method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
15c4c14c-690d-430a-904e-f94db9b71d37
| 2
|
public void swim(int k) {
/**
* Checking for isGreater makes sure that the <= property of MinHeap is
* satisfied.
*/
while (k > 1 && isGreater(k / 2, k)) {
swapArrayValues(k / 2, k);
k = k / 2;
this.arrayAccess += 2;
this.comparisions++;
}
}
|
88007bea-c56c-4216-a511-3b249fd8bc19
| 9
|
public static void startupStreams() {
if (Stella.currentStartupTimePhaseP(0)) {
{ OutputStream self001 = OutputStream.newOutputStream();
self001.nativeStream = new PrintableStringWriter(java.lang.System.out);
Stella.STANDARD_OUTPUT = self001;
}
if (!(Stella.STANDARD_WARNING != null)) {
{ OutputStream self002 = OutputStream.newOutputStream();
self002.nativeStream = new PrintableStringWriter(java.lang.System.err);
Stella.STANDARD_WARNING = self002;
}
}
{ OutputStream self003 = OutputStream.newOutputStream();
self003.nativeStream = new PrintableStringWriter(java.lang.System.err);
Stella.STANDARD_ERROR = self003;
}
}
{ Object old$Module$000 = Stella.$MODULE$.get();
Object old$Context$000 = Stella.$CONTEXT$.get();
try {
Native.setSpecial(Stella.$MODULE$, Stella.$STELLA_MODULE$);
Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get())));
if (Stella.currentStartupTimePhaseP(2)) {
_StartupStreams.helpStartupStreams1();
_StartupStreams.helpStartupStreams2();
}
if (Stella.currentStartupTimePhaseP(4)) {
_StartupStreams.helpStartupStreams3();
}
if (Stella.currentStartupTimePhaseP(5)) {
{ Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("STREAM-ITERATOR", "(DEFCLASS STREAM-ITERATOR (ABSTRACT-ITERATOR) :PUBLIC? TRUE :ABSTRACT? TRUE :DOCUMENTATION \"Iterator that yields tokens from an input stream.\" :SLOTS ((THE-STREAM :TYPE INPUT-STREAM)) :TERMINATOR TERMINATE-STREAM-ITERATOR?)");
renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.stella.StreamIterator", "accessStreamIteratorSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.StreamIterator"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE});
}
{ Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("S-EXPRESSION-ITERATOR", "(DEFCLASS S-EXPRESSION-ITERATOR (STREAM-ITERATOR) :PUBLIC? TRUE :DOCUMENTATION \"Iterator that yields s-expressions from an input stream.\" :PARAMETERS ((ANY-VALUE :TYPE OBJECT)))");
renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.stella.SExpressionIterator", "newSExpressionIterator", new java.lang.Class [] {});
}
{ Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("LINE-ITERATOR", "(DEFCLASS LINE-ITERATOR (STREAM-ITERATOR) :PUBLIC? TRUE :DOCUMENTATION \"Iterator that yields lines with any line terminator sequence from an input stream.\" :PARAMETERS ((ANY-VALUE :TYPE STRING)))");
renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.stella.LineIterator", "newLineIterator", new java.lang.Class [] {});
}
{ Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("NATIVE-LINE-ITERATOR", "(DEFCLASS NATIVE-LINE-ITERATOR (STREAM-ITERATOR) :PUBLIC? TRUE :DOCUMENTATION \"Iterator that yields lines from an input stream.\" :PARAMETERS ((ANY-VALUE :TYPE STRING)))");
renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.stella.NativeLineIterator", "newNativeLineIterator", new java.lang.Class [] {});
}
{ Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("CHARACTER-ITERATOR", "(DEFCLASS CHARACTER-ITERATOR (STREAM-ITERATOR) :PUBLIC? TRUE :DOCUMENTATION \"Iterator that yields characters from an input stream.\" :PARAMETERS ((ANY-VALUE :TYPE CHARACTER)))");
renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.stella.CharacterIterator", "newCharacterIterator", new java.lang.Class [] {});
}
}
if (Stella.currentStartupTimePhaseP(6)) {
Stella.finalizeClasses();
}
if (Stella.currentStartupTimePhaseP(7)) {
_StartupStreams.helpStartupStreams4();
Stella.defineFunctionObject("NATIVE-LINES", "(DEFUN (NATIVE-LINES NATIVE-LINE-ITERATOR) ((STREAM INPUT-STREAM)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.InputStream", "nativeLines", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.InputStream")}), null);
Stella.defineMethodObject("(DEFMETHOD (NEXT? BOOLEAN) ((SELF NATIVE-LINE-ITERATOR)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.NativeLineIterator", "nextP", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null)));
Stella.defineFunctionObject("LINES", "(DEFUN (LINES LINE-ITERATOR) ((STREAM INPUT-STREAM)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.InputStream", "lines", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.InputStream")}), null);
Stella.defineMethodObject("(DEFMETHOD (NEXT? BOOLEAN) ((SELF LINE-ITERATOR)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.LineIterator", "nextP", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null)));
Stella.defineFunctionObject("CHARACTERS", "(DEFUN (CHARACTERS CHARACTER-ITERATOR) ((STREAM INPUT-STREAM)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.InputStream", "characters", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.InputStream")}), null);
Stella.defineMethodObject("(DEFMETHOD (NEXT? BOOLEAN) ((SELF CHARACTER-ITERATOR)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.CharacterIterator", "nextP", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null)));
Stella.defineFunctionObject("LOOKUP-LOGGING-PARAMETER", "(DEFUN (LOOKUP-LOGGING-PARAMETER OBJECT) ((MODULE STRING) (PARAMETER KEYWORD) (DEFAULT OBJECT)) :DOCUMENTATION \"Lookup logging `parameter' for `module'. Use `default' if no\nvalue is defined.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.Stella", "lookupLoggingParameter", new java.lang.Class [] {Native.find_java_class("java.lang.String"), Native.find_java_class("edu.isi.stella.Keyword"), Native.find_java_class("edu.isi.stella.Stella_Object")}), null);
Stella.defineFunctionObject("SET-LOGGING-PARAMETERS", "(DEFUN SET-LOGGING-PARAMETERS ((MODULE STRING) |&REST| (|PARAMS&VALUES| OBJECT)) :DOCUMENTATION \"Set logging parameters for `module'. The supported parameters are:\n :LOG-LEVELS - a cons list of legal levels in ascending log level order;\n for example, (:NONE :LOW :MEDIUM :HIGH) or (0 1 2 3).\n :LEVEL - the current log level for `module'\n :STREAM - the stream or file to log to (defaults to STANDARD-OUTPUT)\n :PREFIX - the prefix to use to identify the module (defaults to `module')\n :MAX-WIDTH - logging output lines will be kept to approximately this width\n (defaults to 10000, minimum width of about 30 is used to\n print line header information).\" :PUBLIC? TRUE :COMMAND? TRUE)", Native.find_java_method("edu.isi.stella.Stella", "setLoggingParameters", new java.lang.Class [] {Native.find_java_class("java.lang.String"), Native.find_java_class("edu.isi.stella.Cons")}), Native.find_java_method("edu.isi.stella.Cons", "setLoggingParametersEvaluatorWrapper", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}));
Stella.defineFunctionObject("SET-LOG-LEVEL", "(DEFUN SET-LOG-LEVEL ((MODULE STRING) (LEVEL OBJECT)) :DOCUMENTATION \"Set the log-level for `module' to `level'. This is a\nconvenience function for this common operation.\" :PUBLIC? TRUE :COMMAND? TRUE)", Native.find_java_method("edu.isi.stella.Stella", "setLogLevel", new java.lang.Class [] {Native.find_java_class("java.lang.String"), Native.find_java_class("edu.isi.stella.Stella_Object")}), Native.find_java_method("edu.isi.stella.Cons", "setLogLevelEvaluatorWrapper", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}));
Stella.defineFunctionObject("LOG-LEVEL<=", "(DEFUN (LOG-LEVEL<= BOOLEAN) ((LEVEL OBJECT) (MODULE STRING)) :DOCUMENTATION \"Return TRUE if `level' is lower than or equal to the current\nlog level of `module'. Return FALSE if any of them are undefined.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.Stella_Object", "logLevelLE", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("java.lang.String")}), null);
Stella.defineFunctionObject("BUMP-LOG-INDENT", "(DEFUN BUMP-LOG-INDENT () :DOCUMENTATION \"Increase the indentation level for subsequent log messages.\" :PUBLIC? TRUE :COMMAND? TRUE)", Native.find_java_method("edu.isi.stella.Stella", "bumpLogIndent", new java.lang.Class [] {}), null);
Stella.defineFunctionObject("UNBUMP-LOG-INDENT", "(DEFUN UNBUMP-LOG-INDENT () :DOCUMENTATION \"Decrease the indentation level for subsequent log messages.\" :PUBLIC? TRUE :COMMAND? TRUE)", Native.find_java_method("edu.isi.stella.Stella", "unbumpLogIndent", new java.lang.Class [] {}), null);
Stella.defineFunctionObject("GET-LOG-STREAM", "(DEFUN (GET-LOG-STREAM OUTPUT-STREAM) ((MODULE STRING)) :DOCUMENTATION \"Return a valid log stream for `module'.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.Stella", "getLogStream", new java.lang.Class [] {Native.find_java_class("java.lang.String")}), null);
Stella.defineFunctionObject("LOG-MESSAGE", "(DEFUN LOG-MESSAGE ((MODULE STRING) (LOGLEVEL OBJECT) (MESSAGE CONS)) :DOCUMENTATION \"Log all elements of `message' to `module's log stream if\n`logLevel' is the same or lower than the `module's log level. Interprets `EOL'\nor :EOL to print a line terminator.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.Stella", "logMessage", new java.lang.Class [] {Native.find_java_class("java.lang.String"), Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineFunctionObject("LOGMSG", "(DEFUN LOGMSG ((MODULE STRING) (LOGLEVEL OBJECT) |&REST| (MESSAGE OBJECT)) :DOCUMENTATION \"Log all elements of `message' to `module's log stream if\n`logLevel' is the same or lower than the `module's log level. Interprets `EOL'\nor :EOL to print a line terminator.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.Stella", "logmsg", new java.lang.Class [] {Native.find_java_class("java.lang.String"), Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineFunctionObject("STARTUP-STREAMS", "(DEFUN STARTUP-STREAMS () :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella._StartupStreams", "startupStreams", new java.lang.Class [] {}), null);
{ MethodSlot function = Symbol.lookupFunction(Stella.SYM_STELLA_STARTUP_STREAMS);
KeyValueList.setDynamicSlotValue(function.dynamicSlots, Stella.SYM_STELLA_METHOD_STARTUP_CLASSNAME, StringWrapper.wrapString("_StartupStreams"), Stella.NULL_STRING_WRAPPER);
}
}
if (Stella.currentStartupTimePhaseP(8)) {
Stella.finalizeSlots();
Stella.cleanupUnfinalizedClasses();
}
if (Stella.currentStartupTimePhaseP(9)) {
Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("/STELLA")))));
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL EOL SYMBOL (QUOTE EOL) :DOCUMENTATION \"Generates a newline character when passed to a stream.\" :PUBLIC? TRUE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL EOL-STRING STRING \"\n\" :DOCUMENTATION \"A string constant containing the character sequence\nnecessary to generate a newline.\" :PUBLIC? TRUE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL STANDARD-INPUT INPUT-STREAM NULL :DOCUMENTATION \"Denotes the standard input stream for the host language.\" :PUBLIC? TRUE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL STANDARD-OUTPUT OUTPUT-STREAM NULL :DOCUMENTATION \"Denotes the standard output stream for the host language.\" :PUBLIC? TRUE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL STANDARD-WARNING OUTPUT-STREAM NULL :DOCUMENTATION \"Denotes the standard warning stream for the host language.\" :PUBLIC? TRUE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL STANDARD-ERROR OUTPUT-STREAM NULL :DOCUMENTATION \"Denotes the standard error stream for the host language.\" :PUBLIC? TRUE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *IGNORETRANSLATIONERRORS?* BOOLEAN TRUE :DOCUMENTATION \"If `true' all passes of a translation will always be performed\nregardless of whether any errors were encountered. Otherwise, translation\nends with the first pass that encountered an error.\" :PUBLIC? TRUE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL SINGLE-QUOTE-STRING STRING-WRAPPER (WRAP-LITERAL \"'\") :DOCUMENTATION \"Holds a string containing the single quote character.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL SINGLE-BQUOTE-STRING STRING-WRAPPER (WRAP-LITERAL \"`\") :DOCUMENTATION \"Holds a string containing the single backquote character.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *OPEN-FILE-STREAMS* (LIST OF STREAM) (NEW (LIST OF STREAM)) :DOCUMENTATION \"List of file streams that are currently open.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *HTML-QUOTED-CHARACTERS* STRING \"><&\\\"\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *HTML-ESCAPE-TABLE* KEY-VALUE-LIST (NEW KEY-VALUE-LIST))");
Stella.$HTML_ESCAPE_TABLE$.insertAt(StringWrapper.wrapString("lt"), CharacterWrapper.wrapCharacter('<'));
Stella.$HTML_ESCAPE_TABLE$.insertAt(StringWrapper.wrapString("gt"), CharacterWrapper.wrapCharacter('>'));
Stella.$HTML_ESCAPE_TABLE$.insertAt(StringWrapper.wrapString("amp"), CharacterWrapper.wrapCharacter('&'));
Stella.$HTML_ESCAPE_TABLE$.insertAt(StringWrapper.wrapString("quot"), CharacterWrapper.wrapCharacter('"'));
Stella.$HTML_ESCAPE_TABLE$.insertAt(StringWrapper.wrapString("apos"), CharacterWrapper.wrapCharacter('\''));
Stella.$HTML_ESCAPE_TABLE$.insertAt(StringWrapper.wrapString("nbsp"), CharacterWrapper.wrapCharacter(' '));
Stella.$HTML_ESCAPE_TABLE$.insertAt(StringWrapper.wrapString("NBSP"), CharacterWrapper.wrapCharacter(' '));
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *LOGGING-REGISTRY* (KEY-VALUE-LIST OF STRING-WRAPPER (PROPERTY-LIST OF KEYWORD OBJECT)) (NEW KEY-VALUE-LIST))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *LOGGING-LOCAL-TIME-ZONE* FLOAT (GET-LOCAL-TIME-ZONE))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *LOG-INDENT-LEVEL* INTEGER 0 :DOCUMENTATION \"The number of spaces to print before the content of a log message.\" :PUBLIC? TRUE)");
}
} finally {
Stella.$CONTEXT$.set(old$Context$000);
Stella.$MODULE$.set(old$Module$000);
}
}
}
|
70102a37-c21b-45db-bb04-fd78d1eaf300
| 6
|
* @param decimalPlaces
* @param a_RoundingMode
* @return e^y where e is the Euler constant. The result is returned correct
* to decimalPlaces decimal place precision.
*/
public static BigDecimal exp(
BigDecimal y,
Generic_BigDecimal a_Generic_BigDecimal,
int decimalPlaces,
RoundingMode a_RoundingMode) {
BigDecimal result;
// Deal with special cases
if (y.compareTo(BigDecimal.ZERO) == 0) {
return BigDecimal.ONE;
}
// Check a_Generic_BigDecimal
if (a_Generic_BigDecimal == null) {
a_Generic_BigDecimal = new Generic_BigDecimal();
}
if (y.compareTo(BigDecimal.ONE) == 0) {
return a_Generic_BigDecimal.getEulerConstantToAFixedDecimalPlacePrecision(
decimalPlaces,
a_RoundingMode);
}
int safeDecimalPlaces;
if (y.compareTo(BigDecimal.ZERO) == -1) {
safeDecimalPlaces = y.scale() + decimalPlaces;
BigDecimal exp = exp(
y.negate(),
a_Generic_BigDecimal,
safeDecimalPlaces,
a_RoundingMode);
result = reciprocal(
exp,
decimalPlaces,
a_RoundingMode);
return result;
}
int divisionDecimalPlaces = decimalPlaces + 3;
result = BigDecimal.ONE.add(y);
// if (a_Generic_BigDecimal._Generic_BigInteger == null) {
// a_Generic_BigDecimal.init_Factorial_Generic_BigInteger(maxite);
// } else {
// a_Generic_BigDecimal._Generic_BigInteger.factorial(maxite);
// }
BigDecimal factorial;
BigDecimal xpow;
BigDecimal xpowOverFactorial;
BigDecimal tollerance = new BigDecimal(
BigInteger.ONE, decimalPlaces + 1);
// Use Taylor Series
BigInteger i_BigInteger = BigInteger.ONE;
Integer factorialKey = 1;
while (true) {
i_BigInteger = i_BigInteger.add(BigInteger.ONE);
factorialKey = factorialKey + 1;
factorial = new BigDecimal(
a_Generic_BigDecimal._Generic_BigInteger.factorial(factorialKey));
xpow = power(
y,
i_BigInteger,
64,
decimalPlaces, // Maybe there is need for more even though the bottom of the Taylor series grows fast
a_RoundingMode);
xpowOverFactorial = divideRoundIfNecessary(
xpow,
factorial,
divisionDecimalPlaces,
a_RoundingMode);
result = result.add(xpowOverFactorial);
if (xpowOverFactorial.compareTo(tollerance) == -1) {
break;
}
}
return roundIfNecessary(result, decimalPlaces, a_RoundingMode);
}
// /**
// * This method was not necessary. However something like it might be
// * useful for none Euler constant based exponentiation so for the time
// * being the code is just commented out rather than deleted. If the power
// * methods are fully operational, this commented code should be deleted.
// * @param y 0 < y < 1
// * @param decimalPlaces
// * @return e^y accurate to decimalPlaces
// */
// private static BigDecimal expLessThanOne(
// BigDecimal y,
// Generic_BigDecimal a_Generic_BigDecimal,
// int decimalPlaces,
// RoundingMode a_RoundingMode) {
// BigDecimal result;
// BigDecimal epsilon_BigDecimal = new BigDecimal(BigInteger.ONE, decimalPlaces);
// BigDecimal x0 = new BigDecimal(a_Generic_BigDecimal._E.toString());
// BigDecimal element;
// BigInteger elementUnscaled;
// BigDecimal elementOne;
// BigInteger elementOneReciprocal;
// BigDecimal rootRoundIfNecessary;
// BigDecimal rootMultiple;
// int maxite = x0.precision();
// result = BigDecimal.ONE;
// while (true) {
// for (int i = 0; i < maxite; i++) {
// element = floorSignificantDigit(x0);
// elementUnscaled = element.unscaledValue();
// System.out.println("element " + element + " elementUnscaled " + elementUnscaled);
// if (elementUnscaled.compareTo(BigInteger.ZERO) == 1) {
// elementOne = divideRoundIfNecessary(
// element,
// elementUnscaled,
// decimalPlaces,
// a_RoundingMode);
// if (elementOne.compareTo(BigDecimal.ZERO) == 0) {
// break;
// }
// System.out.println("element " + element + " elementUnscaled " + elementUnscaled);
// elementOneReciprocal = reciprocalWillBeIntegerReturnBigInteger(elementOne);
// rootRoundIfNecessary = rootRoundIfNecessary(
// y,
// elementOneReciprocal,
// decimalPlaces,
// a_RoundingMode);
// if (rootRoundIfNecessary.compareTo(BigDecimal.ZERO) == 1) {
// rootMultiple = power(
// rootRoundIfNecessary,
// elementUnscaled,
// 64,
// decimalPlaces, // @TODO Is this sufficient?
// a_RoundingMode);
// result = multiplyRoundIfNecessary(
// result,
// rootMultiple,
// decimalPlaces + 3, // @TODO Is this sufficient or ott?
// a_RoundingMode);
// }
// }
// x0 = x0.subtract(element);
// }
|
0257a5aa-2a56-4cd9-bbfc-d6e13a246ac5
| 4
|
public synchronized void sendGamestate(int turnNumber, int dimension, String mapData[][],
AIConnection playerlist[]){
JSONObject root = new JSONObject();
try {
root.put("message", "gamestate");
root.put("turn", turnNumber);
JSONArray players = new JSONArray();
for(AIConnection ai: playerlist){
JSONObject playerObject = new JSONObject();
playerObject.put("name", ai.username);
if(turnNumber != 0){
playerObject.put("health", ai.health);
playerObject.put("score", ai.score);
playerObject.put("position", ai.position.coords.getCompactString());
playerObject.put("alive", ai.isAlive);
JSONObject primaryWeaponObject = new JSONObject();
primaryWeaponObject.put("name", ai.primaryWeapon);
primaryWeaponObject.put("level", ai.primaryWeaponLevel);
playerObject.put("primary-weapon", primaryWeaponObject);
JSONObject secondaryWeaponObject = new JSONObject();
secondaryWeaponObject.put("name", ai.secondaryWeapon);
secondaryWeaponObject.put("level", ai.secondaryWeaponLevel);
playerObject.put("secondary-weapon", secondaryWeaponObject);
}
players.put(playerObject);
}
root.put("players", players);
JSONObject map = new JSONObject();
map.put("j-length", dimension);
map.put("k-length", dimension);
map.put("data", new JSONArray(mapData));
root.put("map", map);
}
catch (JSONException e){}
try {
sendMessage(root);
isDoneProcessing = false;
}
catch (IOException e) {
Debug.error("Error writing to graphics: " + e.getMessage());
}
}
|
f1460515-ea36-4455-b59b-cc8bd0fbdb65
| 2
|
public static byte[] serializeToBytes(Object object) throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
ObjectOutputStream out = new ObjectOutputStream(stream);
try {
out.writeObject(object);
out.flush();
}
finally {
if (out != null) out.close();
}
//..
byte[] array = stream.toByteArray();
return array;
}
finally {
if (stream != null) {stream.close();}
}
}
|
1373d609-f48a-4f1b-be90-108077b10ec0
| 8
|
public String searchAll(String name, String criteria)
{
String result = "";
//loop over entire table from start
for(int i = 0 ; i < hashTableSize -1 ; i ++)
{
//if current data is not null, and equals to search add to result
if(hashtable[i]!= null)
{
if(criteria.equals("First Name"))
if(hashtable[i].getFirstName().toUpperCase().equals(name.toUpperCase()))
result += hashtable[i] + "\n";
if(criteria.equals("Last Name"))
if(hashtable[i].getLastName().toUpperCase().equals(name.toUpperCase()))
result += hashtable[i] + "\n";
if(criteria.equals("Number"))
if(hashtable[i].getPhone().toUpperCase().equals(name.toUpperCase()))
result += hashtable[i] + "\n";
}
}
//return result
return result;
}
|
efe9a58e-5121-45c6-857f-460f164fdf42
| 1
|
public static ResultSet query(String sql,Statement stmt) {
ResultSet rs = null;
try {
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
|
340a6be6-89a7-4762-992b-5435ba756c12
| 8
|
public void mouseDown(MouseEvent e, int x, int y) {
switch (count) {
case 0: {
editor.showStatus("State change: Moving archer to (1,1)");
game.moveUnit(new Position(2, 0), new Position(1, 1));
break;
}
case 1: {
editor.showStatus("State change: Moving archer to (2,2)");
game.moveUnit(new Position(1, 1), new Position(2, 2));
break;
}
case 2: {
editor.showStatus("State change: End of Turn (over to blue)");
game.endOfTurn();
break;
}
case 3: {
editor.showStatus("State change: End of Turn (over to red)");
game.endOfTurn();
break;
}
case 4: {
editor.showStatus("State change: Inspecting red city at (5,5)");
game.setTileFocus(new Position(1, 1));
break;
}
case 5: {
editor.showStatus("State change: Inspecting red archer at (2,2)");
game.setTileFocus(new Position(2, 2));
break;
}
case 6: {
editor.showStatus("State change: Inspecting blue legion at (3,2)");
game.setTileFocus(new Position(3, 2));
break;
}
case 7: {
editor.showStatus("State change: Inspecting blue city at (4,1)");
game.setTileFocus(new Position(4, 1));
break;
}
default: {
editor.showStatus("No more changes in my list...");
}
}
count++;
}
|
079badfc-7553-41a9-8fc7-fc7c1624ce35
| 8
|
@EventHandler
public void onBlockPlace(BlockPlaceEvent e){
Block block = e.getBlock();
Player player = e.getPlayer();
boolean grow = false;
if(GiantTreesRevived.getSettings().allowBlockNearGrow() && GiantTreesRevived.checkPermission(player, "grow")){
if(block.getTypeId() == 6){
grow = TG.nearGrow(block, true, e.getPlayer());
}
if(block.getTypeId() == GiantTreesRevived.getSettings().getBlockNearGrowId()){
grow = TG.nearGrow(block, false, e.getPlayer());
}
}
if(GiantTreesRevived.getSettings().allowRandomChanceGrow() && GiantTreesRevived.checkPermission(player, "grow")){
if(block.getTypeId() == 6 && !grow){
TG.randomGrow(block, GiantTreesRevived.getSettings().getPercentRandomChanceGrow(), e.getPlayer());
}
}
}
|
dafcc63a-bc37-41b7-9075-c86828f77a5c
| 3
|
private void loadTileSheet(String src) {
try {
tileSheet = ImageIO.read(getClass().getResource(src));
tileRows = tileSheet.getHeight() / (tileSize + offset * 2);
tileCols = tileSheet.getWidth() / (tileSize + offset * 2);
BufferedImage tile;
tileSet = new Tile[tileCols][tileRows];
for(int row = 0; row < tileRows; row++) {
for(int col = 0; col < tileCols; col++) {
tile = tileSheet.getSubimage(
(col * tileSize) + (col * 2 + offset),
(row * tileSize) + (row * 2 + offset),
tileSize,
tileSize);
tileSet[col][row] = new Tile(tile);
}
}
}
catch(Exception e) {
e.printStackTrace();
}
}
|
8683892c-d537-432c-9e9c-a6971898f500
| 7
|
protected void addForumJournalsVar(final HTTPRequest httpReq, final String index, final StringBuilder str)
{
final String name=httpReq.getUrlParameter("FORUMJOURNAL_"+index+"_NAME");
if((name!=null)&&(name.trim().length()>0)
&&(!name.trim().equalsIgnoreCase("auction")))
{
if(str.length()>0)
str.append(", ");
str.append(name.trim().replace(',',' ')).append(" ");
for(final JournalsLibrary.ForumJournalFlags flag : JournalsLibrary.ForumJournalFlags.values())
{
final String val=httpReq.getUrlParameter("FORUMJOURNAL_"+index+"_"+flag.name());
if((val!=null)&&(val.trim().length()>0))
str.append(flag.name()).append("=").append(val.trim().replace(',',' ')).append(" ");
}
str.setLength(str.length()-1);
}
}
|
b739d9a7-0aa9-47e7-aabb-f87aee3cedad
| 0
|
public void render(Graphics2D graphics) {
graphics.setColor(Color.BLACK);
graphics.drawRect(screenX, screenY, 15, 15);
graphics.setColor(state.getColor());
graphics.fillRect(screenX + 1, screenY + 1, 14, 14);
}
|
518b18a9-9491-408f-9178-37988ddaae59
| 8
|
private MarkupItem createMarkupItem(
URI id, String gi, URI ns, Collection.Type type, EARMARKNode.Type markupType) {
MarkupItem markup = null;
if (markupType == EARMARKNode.Type.Attribute) {
markup = new Attribute(this, gi, ns, type, id);
} else if (markupType == EARMARKNode.Type.Comment) {
markup = new Comment(this, gi, ns, type, id);
} else {
markup = new Element(this, gi, ns, type, id);
}
idSet.put(id, markup);
String currentGi = (gi == null ? "" : gi);
Set<MarkupItem> associated = giMap.get(currentGi);
if (associated == null) {
associated = new HashSet<MarkupItem>();
giMap.put(currentGi, associated);
}
associated.add(markup);
URI currentNs = (ns == null ? URI.create("") : ns);
Set<String> gies = namespaces.get(currentNs);
if (gies == null) {
gies = new HashSet<String>();
namespaces.put(currentNs,gies);
}
gies.add(currentGi);
Collection children = null;
if (type == Collection.Type.Bag) {
children = new Bag();
} else if (type == Collection.Type.Set) {
children = new it.essepuntato.earmark.core.Set();
} else {
children = new it.essepuntato.earmark.core.List();
}
userData.put(markup, new HashMap<String,Object>());
childMap.put(markup, children);
parentMap.put(markup, new HashSet<EARMARKHierarchicalNode>());
return markup;
}
|
4ae59ef4-2a22-4ed7-a04b-3769308de0c8
| 8
|
@Override
public boolean execute(MOB mob, List<String> commands, int metaFlags)
throws java.io.IOException
{
String commandType="";
if(commands.size()>1)
{
commandType=commands.get(1).toUpperCase();
}
if(commandType.equals("ITEM"))
{
mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("^S<S-NAME> wave(s) <S-HIS-HER> arms...^?"));
items(mob,commands);
}
else
if(commandType.equals("MOB"))
{
mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("^S<S-NAME> wave(s) <S-HIS-HER> arms...^?"));
mobs(mob,commands);
}
else
{
final String allWord=CMParms.combine(commands,1);
final Environmental thang=mob.location().fetchFromMOBRoomFavorsItems(mob,null,allWord,Wearable.FILTER_ANY);
if((thang!=null)&&(thang instanceof Item))
{
commands.add(1,"ITEM");
execute(mob,commands,metaFlags);
}
else
if((thang!=null)&&(thang instanceof MOB))
{
if(((MOB)thang).isMonster())
commands.add(1,"MOB");
else
{
mob.tell(L("@x1 is a player!",thang.name()));
return false;
}
execute(mob,commands,metaFlags);
}
else
{
mob.tell(
L("\n\rYou cannot purge a '@x1'. However, you might try an ITEM or a MOB.",commandType));
}
}
return false;
}
|
18f89ec4-f2f8-4166-af71-b5e2e8f124cd
| 9
|
private int performPeroxyFunctionalReplacement(Element groupToBeModified, Element locantEl, int numberOfAtomsToReplace) throws StructureBuildingException {
List<Atom> oxygenAtoms = findFunctionalOxygenAtomsInApplicableSuffixes(groupToBeModified);
if (oxygenAtoms.size()==0){
oxygenAtoms = findEthericOxygenAtomsInGroup(groupToBeModified);
oxygenAtoms.addAll(findFunctionalOxygenAtomsInGroup(groupToBeModified));
}
if (locantEl !=null){
List<Atom> oxygenWithAppropriateLocants = pickOxygensWithAppropriateLocants(locantEl, oxygenAtoms);
if(oxygenWithAppropriateLocants.size() < numberOfAtomsToReplace){
numberOfAtomsToReplace =1;
}
else{
locantEl.detach();
oxygenAtoms = oxygenWithAppropriateLocants;
}
}
if (numberOfAtomsToReplace >1 && oxygenAtoms.size() < numberOfAtomsToReplace){
numberOfAtomsToReplace=1;
}
int atomsReplaced = 0;
if (oxygenAtoms.size() >=numberOfAtomsToReplace){//check that there atleast as many oxygens as requested replacements
atomsReplaced = numberOfAtomsToReplace;
for (int j = 0; j < numberOfAtomsToReplace; j++) {
Atom oxygenToReplace = oxygenAtoms.get(j);
if (oxygenToReplace.getBondCount()==2){//etheric oxygen
Fragment newOxygen = state.fragManager.buildSMILES("O", SUFFIX_TYPE_VAL, NONE_LABELS_VAL);
Bond bondToRemove = oxygenToReplace.getFirstBond();
Atom atomToAttachTo = bondToRemove.getFromAtom() == oxygenToReplace ? bondToRemove.getToAtom() : bondToRemove.getFromAtom();
state.fragManager.createBond(atomToAttachTo, newOxygen.getFirstAtom(), 1);
state.fragManager.createBond(newOxygen.getFirstAtom(), oxygenToReplace, 1);
state.fragManager.removeBond(bondToRemove);
state.fragManager.incorporateFragment(newOxygen, groupToBeModified.getFrag());
}
else{
Fragment replacementFrag = state.fragManager.buildSMILES("OO", SUFFIX_TYPE_VAL, NONE_LABELS_VAL);
removeOrMoveObsoleteFunctionalAtoms(oxygenToReplace, replacementFrag);
state.fragManager.replaceAtomWithAnotherAtomPreservingConnectivity(oxygenToReplace, replacementFrag.getFirstAtom());
state.fragManager.incorporateFragment(replacementFrag, groupToBeModified.getFrag());
}
}
}
return atomsReplaced;
}
|
6b43ee62-fbb4-4777-b335-02d7668afce5
| 0
|
public void setDateOfJoining(Date dateOfJoining) {
this.dateOfJoining = dateOfJoining;
}
|
97d17917-287d-46b9-90d5-60a41ce52a4c
| 3
|
public void moveToScene(String viewName)
{
Resource res = this.applicationContext.getResource(MessageFormat.format("views/layouts/{0}.fxml", viewName));
try
{
FXMLLoader loader = new FXMLLoader(res.getURL());
loader.setControllerFactory((Class<?> clazz) -> this.applicationContext.getBean(clazz) );
this.sceneCurrent = new Scene((Parent) loader.load());
this.lookup = (Pane) this.sceneCurrent.lookup("#injectPane");
this.stageCurrent.setScene(this.sceneCurrent);
this.stageCurrent.show();
SceneManagerShowable ctrl = loader.getController();
if(ctrl != null)
{
ctrl.showed();
}
}
catch (IOException ex)
{
System.err.println(" View (Main Scene) don't exist: " + res.toString() + " \n" + ex.getMessage() );
}
}
|
80baf8c2-199d-4cf0-ad89-ffbc256ba6c9
| 5
|
@Override
public final void leftRotation() {
int rowLength = WIDTH_FIELDS;
int colLength = HEIGHT_FIELDS;
IField[][] tmpFieldMatrix = new IField[rowLength][colLength];
for (int row = 0; row <= rowLength - 1; row++) {
for (int column = 0; column <= colLength - 1; column++) {
tmpFieldMatrix[row][column] = this.fieldsMatrix[column][2 - row];
}
}
for (int row = 0; row <= rowLength - 1; row++) {
for (int column = 0; column <= colLength - 1; column++) {
this.fieldsMatrix[row][column] = tmpFieldMatrix[row][column];
}
}
for (int i = 0; i < (rowLength * colLength); i++) {
IField field = fieldsMatrix[i / WIDTH_FIELDS][i % WIDTH_FIELDS];
field.rotateLeft();
fieldsMatrix[i / WIDTH_FIELDS][i % WIDTH_FIELDS] = field;
}
rotation = rotation.rotateLeft();
}
|
318b615c-ceec-4091-8de6-5ef4812275a0
| 2
|
public static <T, U> String writeJson(Map<T, U> map, Object[]... typeAdaptors)
{
GsonBuilder gb = new GsonBuilder().setPrettyPrinting();
for(Object[] o : typeAdaptors)
{
if(o.length >= 2)
{
gb.registerTypeAdapter((Type)o[0], o[1]);
}
}
Gson gson = gb.create();
return gson.toJson(map);
}
|
6d9cfcfd-dc1e-4e64-90f2-330920642d1c
| 2
|
public void addDload(int n) {
if (n < 4)
addOpcode(38 + n); // dload_<n>
else if (n < 0x100) {
addOpcode(DLOAD); // dload
add(n);
}
else {
addOpcode(WIDE);
addOpcode(DLOAD);
addIndex(n);
}
}
|
555969f3-2d55-4df9-b6f3-8c8ce97fb125
| 0
|
private void goNext()
{
FalseStartLabel.getInstance().clear();
StateManager.getInstance().setState(new EndRound());
}
|
8387bdb0-6b1c-40d6-90eb-e2bf567c1a04
| 9
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MavenDependency other = (MavenDependency) obj;
if (artifactId == null) {
if (other.artifactId != null)
return false;
} else if (!artifactId.equals(other.artifactId))
return false;
if (groupId == null) {
if (other.groupId != null)
return false;
} else if (!groupId.equals(other.groupId))
return false;
return true;
}
|
46785603-9e54-4e6b-a6fc-52f1da619582
| 9
|
private static void setData(Object obj, Method objMethod, Object param) {
try {
Class []ptt = objMethod.getParameterTypes();
if (ptt == null) {
throw new ASNException(null, "Cannot find parameters in method: " + objMethod.toGenericString());
}
Class pt = ptt[0];
if (pt.isInstance(param)) {
objMethod.invoke(obj, param);
return;
}
if (AsnData.class.equals(param.getClass())) {
objMethod.invoke(obj, ((AsnData) param).getData(pt));
return;
}
if (pt.equals(List.class)) {
objMethod.invoke(obj, Arrays.asList(param));
return;
}
if (List.class.isInstance(param)) {
List lst = (List) param;
if (lst.size() == 1) {
setData(obj, objMethod, lst.get(0));
return;
}
}
throw new ASNException("kfs", "Cannot run set method: " + objMethod.toGenericString() + " but parameter is " + param.getClass().getSimpleName());
} catch (IllegalAccessException ex) {
throw new ASNException("kfs", "Cannot set object " + obj.getClass().getSimpleName() + "." + objMethod.getName() + "( " + param.getClass().getSimpleName() + " )", ex);
} catch (IllegalArgumentException ex) {
throw new ASNException("kfs", "Cannot set object " + obj.getClass().getSimpleName() + "." + objMethod.getName() + "( " + param.getClass().getSimpleName() + " ) - " + objMethod.toGenericString(), ex);
} catch (InvocationTargetException ex) {
throw new ASNException("kfs", "Cannot set object " + obj.getClass().getSimpleName() + "." + objMethod.getName() + "( " + param.getClass().getSimpleName() + " )", ex);
}
}
|
9c454c9f-75d8-4919-9192-e55334ac2902
| 9
|
public void launchNext(final int wexp, final int ah) {
Thread subExpThread;
subExpThread = new Thread() {
public void run() {
m_remoteHostsStatus[ah] = IN_USE;
m_subExpComplete[wexp] = TaskStatusInfo.PROCESSING;
RemoteExperimentSubTask expSubTsk = new RemoteExperimentSubTask();
expSubTsk.setExperiment(m_subExperiments[wexp]);
String subTaskType = (getSplitByDataSet())
? "dataset :" + ((File)m_subExperiments[wexp].getDatasets().
elementAt(0)).getName()
: "run :" + m_subExperiments[wexp].getRunLower();
try {
String name = "//"
+((String)m_remoteHosts.elementAt(ah))
+"/RemoteEngine";
Compute comp = (Compute) Naming.lookup(name);
// assess the status of the sub-exp
notifyListeners(false,true,false,"Starting "
+subTaskType
+" on host "
+((String)m_remoteHosts.elementAt(ah)));
Object subTaskId = comp.executeTask(expSubTsk);
boolean finished = false;
TaskStatusInfo is = null;
while (!finished) {
try {
Thread.sleep(2000);
TaskStatusInfo cs = (TaskStatusInfo)comp.
checkStatus(subTaskId);
if (cs.getExecutionStatus() == TaskStatusInfo.FINISHED) {
// push host back onto queue and try launching any waiting
// sub-experiments
notifyListeners(false, true, false, cs.getStatusMessage());
m_remoteHostsStatus[ah] = AVAILABLE;
incrementFinished();
availableHost(ah);
finished = true;
} else if (cs.getExecutionStatus() == TaskStatusInfo.FAILED) {
// a non connection related error---possibly host doesn't have
// access to data sets or security policy is not set up
// correctly or classifier(s) failed for some reason
notifyListeners(false, true, false, cs.getStatusMessage());
m_remoteHostsStatus[ah] = SOME_OTHER_FAILURE;
m_subExpComplete[wexp] = TaskStatusInfo.FAILED;
notifyListeners(false,true,false,subTaskType
+" "+cs.getStatusMessage()
+". Scheduling for execution on another host.");
incrementFailed(ah);
// push experiment back onto queue
waitingExperiment(wexp);
// push host back onto queue and try launching any waiting
// sub-experiments. Host is pushed back on the queue as the
// failure may be temporary---eg. with InstantDB using the
// RMI bridge, two or more threads may try to create the
// experiment index or results table simultaneously; all but
// one will throw an exception. These hosts are still usable
// however.
availableHost(ah);
finished = true;
} else {
if (is == null) {
is = cs;
notifyListeners(false, true, false, cs.getStatusMessage());
} else {
if (cs.getStatusMessage().
compareTo(is.getStatusMessage()) != 0) {
notifyListeners(false, true, false,
cs.getStatusMessage());
}
is = cs;
}
}
} catch (InterruptedException ie) {
}
}
} catch (Exception ce) {
m_remoteHostsStatus[ah] = CONNECTION_FAILED;
m_subExpComplete[wexp] = TaskStatusInfo.TO_BE_RUN;
System.err.println(ce);
ce.printStackTrace();
notifyListeners(false,true,false,"Connection to "
+((String)m_remoteHosts.elementAt(ah))
+" failed. Scheduling "
+subTaskType
+" for execution on another host.");
checkForAllFailedHosts();
waitingExperiment(wexp);
} finally {
if (isInterrupted()) {
System.err.println("Sub exp Interupted!");
}
}
}
};
subExpThread.setPriority(Thread.MIN_PRIORITY);
subExpThread.start();
}
|
7c224207-672b-4025-9f13-906024b25cb4
| 3
|
private void waitForThread() {
if ((this.thread != null) && this.thread.isAlive()) {
try {
this.thread.join();
} catch (final InterruptedException e) {
plugin.getLogger().log(Level.SEVERE, null, e);
}
}
}
|
0f92a1f4-a991-4de3-a3af-87ba3bf6357c
| 5
|
public static Direction convertActToDir(MovementAction action){
switch(action){
case MOVE_DOWN:
return SOUTH;
case MOVE_LEFT:
return WEST;
case MOVE_RIGHT:
return EAST;
case MOVE_UP:
return NORTH;
case STAND:
return null;
default:
return null;
}
}
|
efc580a1-da24-42c6-b24f-31d3a9d51550
| 6
|
@Override
public void run()
{
if(!running)
return;
try
{
String msg = "";
String line;
while((line = inRead.readLine()) != null)
{
msg += line;
if(line.endsWith("{OP}"))
{
msg = msg.substring(0, line.length() - 4);
List<String> parts = new ArrayList<String>();
parts = Arrays.asList(msg.split(" "));
String name = parts.get(0).toLowerCase();
String[] args = new String[parts.size() - 1];
for(int i = 1; i < parts.size(); i++)
args[i-1] = parts.get(i);
MorgulPlugin.debug("Socket Incoming --" + line + "--");
SocketManager.fireSocketInputEvent(new SocketEvent(this.socket, name, args));
msg = "";
}
MorgulPlugin.debug("Readed");
}
} catch (IOException e) {
MorgulPlugin.log("" + e);
}
try
{
inRead.close();
input.close();
socket.close();
} catch (IOException e) {
MorgulPlugin.log("" + e.toString());
}
MorgulPlugin.debug("SocketHandler " + socket.getRemoteSocketAddress() + " Shutting down.");
}
|
587859df-ea47-4f98-b224-d6263866aa77
| 8
|
@Override
public void executeMsg(final Environmental myHost, final CMMsg msg)
{
super.executeMsg(myHost,msg);
if((msg.othersMajor(CMMsg.MASK_CHANNEL)))
{
final int channelInt=msg.othersMinor()-CMMsg.TYP_CHANNEL;
final ChannelsLibrary.CMChannel chan=CMLib.channels().getChannel(channelInt);
final boolean areareq=chan.flags().contains(ChannelsLibrary.ChannelFlag.SAMEAREA);
if((chan.flags().contains(ChannelsLibrary.ChannelFlag.CLANONLY)
||chan.flags().contains(ChannelsLibrary.ChannelFlag.CLANALLYONLY))
&&(invoker()!=null)
&&((!CMLib.clans().isAnyCommonClan(invoker(),msg.source()))
&&((!chan.flags().contains(ChannelFlag.CLANALLYONLY))
||(!CMLib.clans().findAnyClanRelations(invoker(),msg.source(),Clan.REL_ALLY))))
&&(!CMLib.channels().mayReadThisChannel(msg.source(),areareq,invoker(),channelInt)))
invoker().executeMsg(myHost,msg);
}
}
|
79a1d9c7-3867-4891-a2c1-300e714b9878
| 6
|
@Override
public void removeProgram(Program program) {
Double programFitness = 0.0;
if(program.getFitness() == null) fitnessFunction.computeFitness(program);
programFitness = program.getFitness();
int index = 0;
while (index < this.programs.size() && programFitness > this.fitness.get(index)) {
index++;
}
if (index < this.programs.size() && this.fitness.get(index).equals(programFitness)
&& this.programs.get(index).equals(program)) {
this.programs.remove(index);
this.fitness.remove(index);
}
}
|
e3b8bee1-a52a-465c-9864-32bfb484b56b
| 2
|
public static byte[] toMQttString(String s) {
if (s == null) {
return new byte[0];
}
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(byteOut);
try {
dos.writeUTF(s);
dos.flush();
} catch (IOException e) {
// SHould never happen;
return new byte[0];
}
return byteOut.toByteArray();
}
|
92a6b3ce-457e-4d22-8db6-9d3d84c3ceac
| 9
|
public static Thing lookup(String gType) {
Thing stored, dupe, black;
String bareGType;
/*
* Lookup the type. This will work most of the time...
*/
stored = things.get(gType);
if (stored != null) {
return stored;
}
/*
* ...but not if it needs a const Thing variant, and one hasn't been
* created yet. So strip off the "const-" prefix, and look up the
* type.
*/
if (gType.startsWith("const-")) {
bareGType = gType.substring(6);
stored = things.get(bareGType);
if (stored != null) {
dupe = stored.createConstVariant();
register(dupe);
return dupe;
}
} else if (gType.startsWith("GList-") || gType.startsWith("GSList-")) {
bareGType = gType.split("-")[1];
stored = things.get(bareGType);
if (stored != null) {
dupe = stored.createListVariant(gType);
register(dupe);
return dupe;
}
} else if (gType.endsWith("*")) {
bareGType = gType.substring(0, gType.length() - 1);
stored = things.get(bareGType);
/*
* we don't support arrays of arrays yet. the !(stored instanceof
* ArrayThing) is needed to prevent multiple recursion on the
* pointer star.
*/
if ((stored != null) && !(stored instanceof ArrayThing)) {
dupe = stored.createArrayVariant();
register(dupe);
return dupe;
}
}
/*
* If we're still stuck, then that is would be fatal, except that we
* create a dummy type as a placeholder so we can proceed with the
* bindings generation without total closure.
*/
System.out.println("Warning: no type data for " + gType + ", blacklisting");
black = new BlacklistedThing(gType);
register(black);
return black;
}
|
14c6fefb-6eee-4159-bb56-56faad35f1cb
| 7
|
private void getCPUUsage() {
new Thread() {
@Override
public void run() {
setName("CPU Info Thread");
setPriority(Thread.MIN_PRIORITY);
while (getDeviceInfo) {
// if (debug)
// logger.log(Level.DEBUG, "Loading device CPU info...");
CPU cpu = selectedDevice.getCPU();
String[] load = null;
List<String> usage = null;
ListModel model = cpuUsageList_rootList.getModel();
DefaultListModel _model = new DefaultListModel();
try {
load = cpu.getCPULoad();
usage = cpu.getCPUUsage();
} catch (IOException ex) {
logger.log(Level.ERROR, "An error occurred while loading the CPU load and usage: " + ex.toString() + "\n"
+ "The error stack trace will be printed to the console...");
ex.printStackTrace(System.err);
interrupt();
}
String loadString = "";
for (int i = 0; i < load.length; i++) {
loadString += load[i];
if (i == 0 || i == 1)
loadString += " / ";
}
for (int i = 0; i < model.getSize(); i++)
_model.addElement(model.getElementAt(i));
for (String str : usage)
_model.addElement(str);
cpuUsage_rootLabel.setText(parser.parse("cpuUsageLabel") + loadString);
cpuUsageList_rootList.setModel(_model);
}
}
}.start();
}
|
19c75a58-30bf-472b-a718-a7915c71cabf
| 3
|
public static Vector selectRackID_from_rackCategory(String catname){
Vector v=new Vector();
try {
ResultSet rs1=DB.myConnection().createStatement().executeQuery("select * from category where CategoryName='"+catname+"'");
while(rs1.next()){
String catID=rs1.getString(1);
ResultSet rs2=DB.myConnection().createStatement().executeQuery("select * from rack_category where CategoryID='"+catID+"'");
while(rs2.next()){
v.add(rs2.getString(1));
}
}
} catch (Exception e) {
}
return v;
}
|
199805d4-d6cc-4c2b-a082-abfaf87d9d4c
| 7
|
@Override
public int attack(NPC npc, Entity target) {
final NPCCombatDefinitions defs = npc.getCombatDefinitions();
int distanceX = target.getX() - npc.getX();
int distanceY = target.getY() - npc.getY();
int size = npc.getSize();
int hit = 0;
int attackStyle = Utils.random(2);
if (attackStyle == 0 && (distanceX > size || distanceX < -1 || distanceY > size
|| distanceY < -1)) {
attackStyle = 1;
}
switch(attackStyle) {
case 0:
hit = getRandomMaxHit(npc, defs.getMaxHit() - 36, NPCCombatDefinitions.MELEE, target);
npc.setNextAnimation(new Animation(defs.getAttackEmote()));
delayHit(npc, 0, target, getMeleeHit(npc, hit));
break;
case 1:
hit = getRandomMaxHit(npc, defs.getMaxHit(), NPCCombatDefinitions.MAGE, target);
npc.setNextAnimation(new Animation(16122));
World.sendProjectile(npc, target, 2991, 34, 16, 30, 35, 16, 0);
delayHit(npc, 2, target, getMagicHit(npc, hit));
break;
}
return defs.getAttackDelay();
}
|
d3a9932a-3e6a-49e1-a8a2-206dff92c5cc
| 8
|
private ArrayList<Course> removeClassesWOPre(ArrayList<Course> needed, ArrayList<Course> taken) {
ArrayList<Course> ret = new ArrayList<>();
for (Course course : needed) {
boolean allContained = true;
if (course.getPrereqs() != null && course.getPrereqs().get(0) != null) {
for (ArrayList<Course> prerec : course.getPrereqs()) {
boolean orTaken = false;
for (Course pre : prerec) {
if (taken.contains(pre)) {
orTaken = true;
break;
}
}
if (orTaken == false) allContained = false;
}
}
if (allContained) ret.add(course);
}
return ret;
}
|
0fa7db6a-259e-4c2c-8900-3de919cf0426
| 0
|
public MasterGameThread(NetworkGameScreen screen) throws IOException {
super("MasterGameThread");
this.screen = screen;
String remoteHost = ((PongWindow)screen.parent).RemotePlayer; // formato HRS-GUA-02/169.254.80.80
slaveSocket = new Socket(remoteHost.substring(remoteHost.lastIndexOf('/')+1), 6789);
}
|
b9450e3c-ec91-472d-9b6e-2909cea396da
| 6
|
public static int getHighestLevel(Pokemon party[], Pokemon pc[])
{
int highest=0;
for (Pokemon aParty : party) {
if (aParty != null) {
if (aParty.level > highest)
highest = aParty.level;
} else
break;
}
for (Pokemon aPc : pc) {
if (aPc != null) {
if (aPc.level > highest)
highest = aPc.level;
} else
return highest;
}
return highest;
}
|
e888dd13-0522-4833-8b89-6a3955fb01c8
| 7
|
private void addRule(Document document, Rule rule) throws OutputterException {
Element ele = document.createElement(Tag.RULE.getXmlTag());
if (!rule.getLabel().startsWith(DEFAULT_RULE_LABEL_PREFIX)) ele.setAttribute(Attribute.RULE_LABEL.getAttributeName(), rule.getLabel());
switch (rule.getRuleType()) {
case STRICT:
ele.setAttribute(Attribute.RULE_TYPE_STRICT_RULE.getAttributeName(), Attribute.RULE_TYPE_STRICT_RULE.getAttributeValue());
break;
case DEFEASIBLE:
ele.setAttribute(Attribute.RULE_TYPE_DEFEASIBLE_RULE.getAttributeName(), Attribute.RULE_TYPE_DEFEASIBLE_RULE.getAttributeValue());
break;
case DEFEATER:
ele.setAttribute(Attribute.RULE_TYPE_DEFEATER.getAttributeName(), XmlTag.Attribute.RULE_TYPE_DEFEATER.getAttributeValue());
break;
default:
}
Element modeEle = generateMode(document, rule.getMode());
if (null != modeEle) ele.appendChild(modeEle);
Element headEleList = generateLiteralList(document, rule.getHeadLiterals());
if (null == headEleList) throw new OutputterException("exception throw while generating xml model for rule [" + rule.getLabel()
+ "], head literal is empty");
Element headEle = document.createElement(Tag.HEAD.getXmlTag());
headEle.appendChild(headEleList);
ele.appendChild(headEle);
Element bodyEleList = generateLiteralList(document, rule.getBodyLiterals());
if (null != bodyEleList) {
Element bodyEle = document.createElement(Tag.BODY.getXmlTag());
bodyEle.appendChild(bodyEleList);
ele.appendChild(bodyEle);
}
document.getDocumentElement().appendChild(ele);
}
|
00312d31-d93a-4973-b5e3-bb3762218ab0
| 4
|
public Element generateElement(Document document)
{
Element edge = document.createElement(mxGraphMlConstants.EDGE);
if (!edgeId.equals(""))
{
edge.setAttribute(mxGraphMlConstants.ID, edgeId);
}
edge.setAttribute(mxGraphMlConstants.EDGE_SOURCE, edgeSource);
edge.setAttribute(mxGraphMlConstants.EDGE_TARGET, edgeTarget);
if (!edgeSourcePort.equals(""))
{
edge.setAttribute(mxGraphMlConstants.EDGE_SOURCE_PORT, edgeSourcePort);
}
if (!edgeTargetPort.equals(""))
{
edge.setAttribute(mxGraphMlConstants.EDGE_TARGET_PORT, edgeTargetPort);
}
if (!edgeDirected.equals(""))
{
edge.setAttribute(mxGraphMlConstants.EDGE_DIRECTED, edgeDirected);
}
Element dataElement = edgeData.generateEdgeElement(document);
edge.appendChild(dataElement);
return edge;
}
|
9760fcaa-fb58-46d2-9771-8102c3ef4016
| 2
|
@Override
public int compare(Integer o1, Integer o2) {
return (o1>o2 ? -1 : (o1==o2 ? 0 : 1));
}
|
2f6b864c-a0c3-41fb-bb51-45fbd2cb583e
| 9
|
private void drawPodatek(Graphics g, final ArrayList al)
{
g.setFont(newRomanNormal);
HashMap VatMap = new HashMap(7);
double sumNetto = 0;
double sumBrutto = 0;
double sumVat = 0;
for (int i = 0; i < al.size() ; i++)
{
DataEntry dat = (DataEntry)al.get(i);
String Stawka = dat.getVatStawka();
String VatKwota = DataEntry.rd(dat.getVatKwota());
String WNetto = dat.getWartoscNetto();
String WBrutto = dat.getWartoscBrutto();
if (VatMap.containsKey(Stawka))
{
VatEntry ve = (VatEntry)VatMap.get(Stawka);
try
{
Double dWNetto = new Double(ve.WNetto);
Double dWBrutto = new Double(ve.WBrutto);
Double dVatKwota = new Double(0);
try
{
dVatKwota = new Double(ve.Vat);
}
catch (NumberFormatException e)
{
}
Double vk = new Double(0);
try
{
vk = new Double(VatKwota);
}
catch (NumberFormatException e)
{
}
Double wn = new Double(WNetto);
Double wb = new Double(WBrutto);
sumNetto += wn.doubleValue();
sumBrutto += wb.doubleValue();
sumVat += vk.doubleValue();
VatEntry newEntry = new VatEntry();
newEntry.WNetto = "" + (dWNetto.doubleValue() + wn.doubleValue());
newEntry.WBrutto = "" + (dWBrutto.doubleValue() + wb.doubleValue());
newEntry.Vat = "" + (dVatKwota.doubleValue() + vk.doubleValue());
VatMap.put(Stawka, newEntry);
}
catch(NumberFormatException e)
{
}
}
else
{
VatEntry ve = new VatEntry();
ve.WNetto = WNetto;
ve.WBrutto = WBrutto;
ve.Vat = VatKwota;
try
{
Double vk = new Double(0);
try
{
vk = new Double(VatKwota);
}
catch (NumberFormatException e)
{
}
Double wn = new Double(WNetto);
Double wb = new Double(WBrutto);
sumNetto += wn.doubleValue();
sumBrutto += wb.doubleValue();
sumVat += vk.doubleValue();
}
catch(NumberFormatException e)
{
}
VatMap.put(Stawka, ve);
}
}
TableY += 20;
g.setFont(newRomanSmall);
g.drawString("Netto", 350, TableY);
g.drawString("Brutto", 400, TableY);
g.drawString("Vat", 450, TableY);
TableY += 15;
int k = 0;
while (k < al.size())
{
DataEntry dat = (DataEntry)al.get(k);
VatEntry v = new VatEntry();
if (VatMap.containsKey(dat.getVatStawka()))
{
v = (VatEntry)VatMap.get(dat.getVatStawka());
g.drawString(DataEntry.rd(dat.getVatStawka()), 300, TableY);
g.drawString(DataEntry.rd(v.WNetto), 350, TableY);
g.drawString(DataEntry.rd(v.WBrutto), 400, TableY);
g.drawString(DataEntry.rd(v.Vat), 450, TableY);
TableY += 10;
VatMap.remove(dat.getVatStawka());
}
k++;
}
g.drawString("Razem : ", 300, TableY);
g.drawString(DataEntry.rd("" + sumNetto), 350, TableY);
g.drawString(DataEntry.rd("" + sumBrutto), 400, TableY);
g.drawString(DataEntry.rd("" + sumVat), 450, TableY);
}
|
425c7f46-b991-42b4-9812-66763200935a
| 9
|
public int longestValidParentheses(String s) {
if(s == null || s.length() < 2 || s.indexOf(")") == -1) {
return 0;
}
int ret = 0;
int[] len = new int[s.length() + 1];
len[0] = 0;
len[1] = 0;
for(int i = 2; i <= s.length(); i++) {
if(s.charAt(i-1) == '(') {
len[i] = 0;
} else {
if(s.charAt(i-2) == '(') {
len[i] = len[i-2] + 2;
} else {
if((i - 2 - len[i-1]) >= 0 && s.charAt(i - 2 - len[i-1]) == '(') {
len[i] = len[i - 2 - len[i-1]] + len[i-1] + 2;
} else {
len[i] = 0;
}
}
}
ret = len[i]>ret?len[i]:ret;
}
return ret;
}
|
d93ec099-5500-4993-86f6-00cae5ca71db
| 0
|
public Configuration[] getInitialConfigurations(String input) {
/** The stack should contain the bottom of stack marker. */
Configuration[] configs = new Configuration[1];
CharacterStack stack = new CharacterStack();
stack.push("Z");
configs[0] = new PDAConfiguration(myAutomaton.getInitialState(), null,
input, input, stack, myAcceptance);
return configs;
}
|
c3a5f63c-c83f-40b3-a68c-7bf38d5f8fa7
| 6
|
public boolean checkSize(int min,int max, int size) {
if(size>=min&&size<=max){
return true;
}
if(min==max&&min==UNLIMITED){
return true;
}
if(size<min){
System.out.println(Language.tooFewArguments);
}
if(size>max){
System.out.println(Language.tooManyArguments);
}
return false;
}
|
30b979aa-7150-4ae5-b86c-8a7f14da26a0
| 4
|
Response doSend() throws IOException
{
connection.setRequestMethod(this.verb.name());
if (connectTimeout != null)
{
connection.setConnectTimeout(connectTimeout.intValue());
}
if (readTimeout != null)
{
connection.setReadTimeout(readTimeout.intValue());
}
addHeaders(connection);
if (verb.equals(Verb.PUT) || verb.equals(Verb.POST))
{
addBody(connection, getByteBodyContents());
}
return new Response(connection);
}
|
b25348f0-d232-4d65-a0e9-ca2779e79d50
| 0
|
public Counter(String name)
{
this.name = name;
count = 0;
}
|
b7bdee0a-398a-48c5-ad2e-163d91864f78
| 9
|
private static void reachingDefDataFlow(OptFunctionNode fn, Node[] statementNodes, Block theBlocks[], int[] varTypes)
{
/*
initialize the liveOnEntry and liveOnExit sets, then discover the variables
that are def'd by each function, and those that are used before being def'd
(hence liveOnEntry)
*/
for (int i = 0; i < theBlocks.length; i++) {
theBlocks[i].initLiveOnEntrySets(fn, statementNodes);
}
/*
this visits every block starting at the last, re-adding the predecessors of
any block whose inputs change as a result of the dataflow.
REMIND, better would be to visit in CFG postorder
*/
boolean visit[] = new boolean[theBlocks.length];
boolean doneOnce[] = new boolean[theBlocks.length];
int vIndex = theBlocks.length - 1;
boolean needRescan = false;
visit[vIndex] = true;
while (true) {
if (visit[vIndex] || !doneOnce[vIndex]) {
doneOnce[vIndex] = true;
visit[vIndex] = false;
if (theBlocks[vIndex].doReachedUseDataFlow()) {
Block pred[] = theBlocks[vIndex].itsPredecessors;
if (pred != null) {
for (int i = 0; i < pred.length; i++) {
int index = pred[i].itsBlockID;
visit[index] = true;
needRescan |= (index > vIndex);
}
}
}
}
if (vIndex == 0) {
if (needRescan) {
vIndex = theBlocks.length - 1;
needRescan = false;
}
else
break;
}
else
vIndex--;
}
/*
if any variable is live on entry to block 0, we have to mark it as
not jRegable - since it means that someone is trying to access the
'undefined'-ness of that variable.
*/
theBlocks[0].markAnyTypeVariables(varTypes);
}
|
0c58cf05-c1b9-42d3-8d48-5035ac80781a
| 4
|
private ResGridlet cancel(int gridletId, int userId)
{
ResGridlet rgl = null;
// Find in EXEC List first
int found = gridletInExecList_.indexOf(gridletId, userId);
if (found >= 0)
{
// update the gridlets in execution list up to this point in time
updateGridletProcessing();
// Get the Gridlet from the execution list
rgl = (ResGridlet) gridletInExecList_.remove(found);
// if a Gridlet is finished upon cancelling, then set it to success
// instead.
if (rgl.getRemainingGridletLength() == 0.0) {
rgl.setGridletStatus(Gridlet.SUCCESS);
}
else {
rgl.setGridletStatus(Gridlet.CANCELED);
}
// Set PE on which Gridlet finished to FREE
super.resource_.setStatusPE( PE.FREE, rgl.getMachineID(),
rgl.getPEID() );
allocateQueueGridlet();
return rgl;
}
// Find in QUEUE list
found = gridletQueueList_.indexOf(gridletId, userId);
if (found >= 0)
{
rgl = (ResGridlet) gridletQueueList_.remove(found);
rgl.setGridletStatus(Gridlet.CANCELED);
}
// if not, then find in the Paused list
else
{
found = gridletPausedList_.indexOf(gridletId, userId);
// if found in Paused list
if (found >= 0)
{
rgl = (ResGridlet) gridletPausedList_.remove(found);
rgl.setGridletStatus(Gridlet.CANCELED);
}
}
return rgl;
}
|
0fbc19d1-301e-48f6-82b9-9087ff7d0672
| 0
|
public confirmRemoval()
{
this.requireLogin = true;
this.addRtnCode(405, "not removing");
}
|
51c9a5e6-3d96-408c-9d2f-d5c2e8843408
| 5
|
public static void main(String[] args) {
System.out.println("Building Huffman Tree:");
Byte[] byteArray = new Byte[] { 45, 56, 67, 78, 89, 12, 23, 34, 45, 23,
45, 67, 45 };
HuffmanTree<Byte> hTree = new HuffmanTree<Byte>(byteArray);
System.out.println();
System.out.println("Printing Tree:");
hTree.print();
byte searchByte = (byte) 45;
Bits bits = new Bits();
hTree.fromByte(searchByte, bits);
System.out.println("\nGetting " + searchByte + " from byte: "
+ bits.toString());
System.out.println("\nSending " + bits.toString()
+ " to get the next byte: " + hTree.toByte(bits));
System.out.println("\n Building a Huffman tree based on the image decoding frequencies.");
//The following code builds a huffman tree based on the frequencies provided by the zipped lab page.
HuffmanTree<Byte> imageHuffmanTree = null;
Byte[] imageBytes = null;
byte[] imagebytes = null;
int[] frequenciesOfValues = {423, 116, 145, 136, 130, 165, 179, 197, 148, 125, 954, 156, 143, 145, 164, 241, 107, 149, 176, 153, 121, 164, 144, 166, 100, 138, 157, 140, 119, 138, 178, 289, 360, 120, 961, 195, 139, 147, 129, 192, 119, 146, 138, 184, 137, 196, 163, 331, 115, 160, 127, 172, 176, 181, 149, 194, 138, 154, 163, 167, 196, 174, 250, 354, 142, 169, 170, 209, 205, 179, 147, 245, 108, 179, 148, 186, 131, 160, 112, 219, 118, 204, 164, 154, 154, 175, 189, 239, 126, 145, 185, 179, 149, 167, 152, 244, 189, 257, 234, 208, 179, 170, 171, 178, 184, 189, 203, 184, 204, 208, 187, 163, 335, 326, 206, 189, 210, 204, 230, 202, 415, 240, 275, 295, 375, 308, 401, 608, 2099, 495, 374, 160, 130, 331, 107, 181, 117, 133, 476, 129, 137, 106, 107, 237, 184, 143, 122, 143, 1596, 205, 121, 170, 123, 124, 150, 132, 143, 133, 178, 308, 96, 102, 114, 176, 159, 149, 123, 199, 1156, 119, 144, 237, 131, 155, 143, 225, 92, 125, 117, 138, 135, 154, 124, 137, 121, 143, 149, 141, 177, 159, 247, 384, 302, 120, 95, 140, 87, 1460, 155, 199, 111, 198, 147, 182, 91, 148, 119, 233, 445, 1288, 138, 133, 122, 170, 156, 257, 143, 149, 180, 174, 132, 151, 193, 347, 91, 119, 135, 182, 124, 152, 109, 175, 152, 159, 166, 224, 126, 169, 145, 220, 119, 148, 133, 158, 144, 185, 139, 168, 244, 145, 167, 167, 262, 214, 293, 402};
Queue<Node<Byte>> pQueue = new PriorityQueue<Node<Byte>>();
for(int i = -128; i <= 127; i++){
pQueue.add(new Node<Byte>((byte) i, frequenciesOfValues[i + 128]));
}
imageHuffmanTree = new HuffmanTree(pQueue);
System.out.println("Leaves = " + imageHuffmanTree.leaves);
imageHuffmanTree.print();
//This gets the bytes from the compressed image
try {
File file = new File("compressed.huff");
InputStream is = new FileInputStream(file);
imagebytes = getBytesFromInputStream(is);
imageBytes = new Byte[imagebytes.length];
int i = 0;
for (byte b : imagebytes) {
imageBytes[i++] = b;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
HuffmanCompressor compressor = new HuffmanCompressor();
byte[] decompressedImageBytes = compressor.decompress(imageHuffmanTree, 54679, imageBytes);
//This currenthly throws an exception because I need to finish decompression.
FileOutputStream fos;
try {
String decompressedFilename = "decompressed.huff";
fos = new FileOutputStream("decompressedFilename");
fos.write(decompressedImageBytes);
fos.close();
System.out.println("Decompressed this file & saved as " + decompressedFilename);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
|
d253b154-4f13-422f-9cef-d056ac7d15f6
| 4
|
public List<GPSData> getAccIter(List<GPSData> gpss, List<AccMagn> magns) {
// TODO: add boundary conditions (if arrays.size() < 2...)
long accMagnPreTimestamp = magns.get(0).getTimestamp();
int k = 0;
for (int i = 0; i < gpss.size(); i++) {
GPSData gpsData = gpss.get(i);
long gpsTimestamp = gpsData.getTimestamp();
if (k != magns.size() - 1) {
for (int j = k; j < magns.size(); j++) {
AccMagn accMagnCurr = magns.get(j);
long accMagnCurrTimestamp = accMagnCurr.getTimestamp();
long diffPre = Math.abs(gpsTimestamp - accMagnPreTimestamp);
long diffCurr = Math.abs(accMagnCurrTimestamp - gpsTimestamp);
if (diffPre < diffCurr) {
gpsData.setAcc(magns.get(j - 1).getVectorLength());
System.out.println("i = " + i + " " + gpsData.toString());
k = j;
break;
} else {
accMagnPreTimestamp = accMagnCurrTimestamp;
}
}
} else {
gpsData.setAcc(magns.get(magns.size() - 1).getVectorLength());
System.out.println("i = " + i + " " + gpsData.toString());
}
}
return gpss;
}
|
cf22f2db-83f8-4672-93f3-43f13f6cd95a
| 2
|
public String getDate(){
String day, month, year;
day = Integer.toString(time.get(5));
if (day.length()==1)
day = "0" + day;
month = Integer.toString(time.get(2)+1);
if (month.length()==1)
month = "0" + month;
year = Integer.toString(time.get(1));
return day + "/" + month + "/" + year;
}
|
a3873df1-a731-46aa-b5eb-2b964a254dfe
| 4
|
public static int charge(String ion){
ion = ion.trim();
boolean test0 = true;
boolean test1 = false;
int i = 0;
int charge = 0;
// check entered ion against ion list
while(test0){
if(IonicRadii.compareBare(ion, i)){
test0 = false;
test1 = true;
charge = ionCharge[i];
}
else{
i++;
if(i>=nIons)test0=false;
}
}
// Abort if entered ion was not found in lists
if(!test1){
System.out.println("Class: IonicRadii\nMethod: charge\n"+ion + " was not found in the lists of non-hydrated ions");
System.out.println("0 returned");
}
return charge;
}
|
41de0fbd-1879-4959-8a99-3727dd5d19a4
| 0
|
public void setAvb(Double avb) {
this.avb = avb;
}
|
f7ccce42-4e75-4683-9a67-28df8cedd408
| 6
|
@EventHandler(priority = EventPriority.HIGHEST)
public void onEntityDamageByEntity(final EntityDamageByEntityEvent event) {
if (event.getDamager() instanceof Player) {
final WarPlayer damager = this.war.getHelper().getPlayerExact(((Player) event.getDamager()).getName());
if (!damager.isOnTeam()) {
event.setCancelled(true);
damager.sendMessage(ChatColor.RED + "Join a team first!");
return;
}
if (event.getEntity() instanceof Player) {
final WarPlayer damaged = this.war.getHelper().getPlayerExact(((Player) event.getEntity()).getName());
if (!damaged.isOnTeam()) {
event.setCancelled(true);
damager.getPlayer().damage(1);
return;
}
if (damaged.getTeam() == damager.getTeam()) {
event.setCancelled(true);
return;
}
}
if (PlayerClass.PYRO == damager.getPlayerClass()) {
event.getEntity().setFireTicks(100); // 5s
}
}
}
|
92e1efef-461e-4a31-9bc8-7fd2708bc6a9
| 8
|
public static void reCalculateTFandIDFwithApproxValues(String docContents, String docName, int collectionSize,
double docLength) {
System.out.println("reCalculateTFandIDFwithApproxValues running");
ArrayList<String[]> currentPostingsList;
String[] posting;
for (int k = 0; k < tokens.size(); k++) {
String comparisonToken = tokens.get(k).toString();
Iterator iterator = dictionaryMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry termEntry = (Map.Entry) iterator.next();
String existingToken = (String) termEntry.getKey();
Double levScore = lev.score(existingToken, comparisonToken);
if (levScore.equals(-1.0)) { //we have an approximate match -
currentPostingsList = (ArrayList) dictionaryMap.get(existingToken);
//check if docNames match
Boolean matchRecorded = false;
for (int i = 0; i < currentPostingsList.size(); i++) {
if (currentPostingsList.get(i)[DOC_NAME].equals(docName)) {
posting = currentPostingsList.get(i);
int position = i;
if (posting[MATCH_TYPE].equals("Approximate Match") && posting[TEXT].equals(comparisonToken)) {
//text is the same - increment and break
//iDF doesn't change, just need to change TF
int newFrequency = (Integer.parseInt(posting[FREQ])); //add one to the frequency
newFrequency = newFrequency + 1;
double newTermFrequency = newFrequency / docLength; // calculate a new TF
posting[FREQ] = String.valueOf(newFrequency); //update the posting with the new frequency
posting[TERM_FREQ] = String.valueOf(newTermFrequency);
currentPostingsList.set(position, posting); //update arraylist
dictionaryMap.put(existingToken, currentPostingsList);
matchRecorded = true;
}
}
}
// reached end of postings list, if noMatchRecorded, add new posting (i.e. new approximate match)
if (!matchRecorded) {
// 1) don´t update inverseDocFreqMap for approximate Matches - just get the IDF to calculate TFIDF
Double[] idFArray = (Double[]) inverseDocFreqMap.get(existingToken);
// 2) add new posting(array)
double newTermFrequency = 1.0 / docLength;
double newTFIDFweight = idFArray[IDF] * newTermFrequency;
String[] newPosting = {docName, "1", String.valueOf(newTermFrequency), String.valueOf(newTFIDFweight), "Approximate Match", comparisonToken};
currentPostingsList.add(newPosting);
matchRecorded = true;
}
}
}
}
}
|
e982ab1d-e24d-4cd1-a79f-174df4df69e9
| 0
|
TotalPanel() {
this.setLayout(new GridLayout(3, 2));
this.setBorder(new TitledBorder("总流量"));
getContent();
this.add(totaltitle);
this.add(totalnum);
this.add(tcptitle);
this.add(tcpnum);
this.add(udptitle);
this.add(udpnum);
}
|
e95a18db-6fce-4116-8304-7088cd464094
| 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(Cliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Cliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Cliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Cliente.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 Cliente().setVisible(true);
}
});
}
|
6f93121b-1c3f-45e7-b785-6e444f3362b3
| 0
|
public int getMarker() {
return this.marker;
}
|
a03f540d-023e-4987-8933-b6efd83dddae
| 7
|
public HashMap getInfo(String link){
String sourceName = "挑食网";
String html = GetHTML.getHtml(link, "utf-8");
Document doc = Jsoup.parse(html);
Elements ele = doc.select("script[type]");
Element eleJson = ele.get(7);
String jsonData = eleJson.html().replaceAll("\t","");
String regex = "\\{[^\\{\\}]*\\}";
Pattern pattern = Pattern.compile(regex,Pattern.MULTILINE);
Matcher matcher = pattern.matcher(jsonData);
ArrayList<JSONObject> jsonDataLst = new ArrayList<JSONObject>();
ArrayList<String> bodyPieces = new ArrayList<String>();
while(matcher.find()){
String a = matcher.group();
jsonDataLst.add(JSONObject.fromObject(a));
}
if(jsonDataLst.size()>0){
JSONObject head = jsonDataLst.get(0);
String author = head.get("membernickname").toString();
String title = head.get("title").toString();
head = jsonDataLst.get(1);
String look = head.get("look").toString();
String like = head.get("good").toString();
String pubTime = head.get("date").toString();
String cityId = head.get("cityId").toString();
String city = GetCityById.getCityById(cityId);
for(int i=2;i<jsonDataLst.size();i++){
if(jsonDataLst.get(i).get("type").equals("text")){
bodyPieces.add(jsonDataLst.get(i).get("content").toString());
}
else if(jsonDataLst.get(i).get("type").equals("photo")){
bodyPieces.add(jsonDataLst.get(i).get("url").toString());
}
}
JSONObject end = jsonDataLst.get(jsonDataLst.size()-2);
String shopname="",address="",phone="";
if(end.get("type").equals("end")){
shopname = end.get("shopname").toString();
address = end.get("address").toString();
phone = end.get("phone").toString();
}
ContextUtils contextUtils = new ContextUtils();
HashMap bodyHash = contextUtils.combineBodyText(bodyPieces);
ArrayList<String> bodyTextPieces = (ArrayList<String>)bodyHash.get("bodyText");
ArrayList<String> bodyPicPieces = (ArrayList<String>)bodyHash.get("bodyPic");
String releasetime = FormatTime.getTimeStamp(pubTime,"yyyy-MM-dd");
String smalldesc = bodyTextPieces.size()>0?bodyTextPieces.get(0).split("\n")[0]:"";
HashMap hashMap = new HashMap();
hashMap.put("content",bodyTextPieces);
hashMap.put("releasetime",releasetime);
hashMap.put("bodyPicPieces",bodyPicPieces);
hashMap.put("source",sourceName);
hashMap.put("smalldesc",smalldesc);
return hashMap;
}
return null;
}
|
bf02761f-a3ef-441e-8f0a-52725253083c
| 9
|
public String predict(){
String s;
if(getNext()== 1 || getNext()== 3 || getNext()== 4 || getNext()== 5 || getNext()== 9 || getNext()== 10 || getNext()== 11 || getNext()== 12 || getNext()== 15){
return s = "Head";
}
else {
return s = "Tail";
}
}
|
4a14616e-049a-4a7f-acce-b991bbed5733
| 1
|
public static void main(String[] args) {
String[] names = { "Aman", "Amar", "Himanshu", "Piyush", "Gunjan",
"Ankit", "Shruthi" };
Container nameContainer = new NameContainer(names);
Iterator iterator = nameContainer.getIterator();
for (; iterator.hasNext();) {
System.out.println("Name :" + iterator.next());
}
}
|
0c986ce6-f1d1-4af1-8c6d-576f6bcdd9bb
| 9
|
@Override
boolean canPerform(Creature cc, World w) {
if(cc.canwork && cc.isAlive() && cc.stuntime==0)
{
if(w.getItemcollection().isRecqExist(worldObjectRecquire)==false) return false;
if(this.getTasktype()==TaskEnum.walking)
{
for(int i = -1; i<2; i++)
{
for(int j = -1; j<2; j++)
{
if(w.getPathfinder().findPath(cc.getCy(), cc.getCx(),this.getY()+i, this.getX()+j)!=null)
{
if(w.getMap().isBlockDiag( getY(), getX(), getY()+i, getX()+j)==true) continue;
return true;
}
}
}
return false;
}
return true;
}
return false;
}
|
fcb28adf-e037-40a6-9385-1835725c4f4f
| 3
|
public List<String> getNouns (int idx)
{
List<String> nouns = new ArrayList<String>();
List<TermPos> phrase = phrases.get(idx);
int i = 0;
for (; i < phrase.size() && !phrase.get(i).pos.startsWith("NN"); i++);
for (; i < phrase.size(); i++) {
nouns.add(phrase.get(i).term);
}
return nouns;
}
|
9d28e499-207e-4914-873d-5abb38a63081
| 4
|
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n=in.nextInt();
int m=in.nextInt();
isBlack = new boolean[n][m];
for(int i=0;i<n;i++){
String line = in.next();
for(int j=0;j<m;j++){
isBlack[i][j]=line.charAt(j)=='1';
// System.out.println(isBlack[i][j]);
}
}
for(int i=1;i<400;i*=2){
for(int j=i;j<=i*2;j*=2){
findInRec(i, j);
}
}
System.out.println(count);
}
|
b302215d-0ec5-4fbb-89d3-752a59dddde5
| 7
|
public void calculatePerCapitas() {
popCap = houseNumber * MAXHOUSECAPACITY + 5;
foodPerCapita = ((double) (foodings))/population;
energyPerCapita = energies/population;
popDeriv = (foodPerCapita * energyPerCapita);
if(foodPerCapita <= 0 && energyPerCapita <= 0) {
popDeriv = 0.5;
}
if(population > popCap) {
popDeriv /= 2;
}
if(popDeriv > 5) {
popDeriv = 5;
}
if(population > Math.abs(popDeriv-2)+1)
population += popDeriv - 2;
if(popDeriv >= 2.0 && population <= 5) {
population += popDeriv;
}
}
|
017f93cd-bfa2-4d27-82f9-e5428d554b66
| 8
|
private void extractCircles (Mat mask, List<Circle> balls, List<BallCluster> ballClusters, List<MatOfPoint> contours) {
// clear input
balls.clear();
ballClusters.clear();
contours.clear();
// find the contours
Imgproc.findContours(mask.clone(), contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);
// iterate through the contours, find single balls and clusters of balls touching each other
double minArea = Math.PI * (calib.getBallRadius() * 0.9f) * (calib.getBallRadius() * 0.9f); // minimal ball area
double maxArea = Math.PI * (calib.getBallRadius() * 1.1f) * (calib.getBallRadius() * 1.1f); // maximal ball area
for (int i = 0; i < contours.size(); i++) {
double area = Imgproc.contourArea(contours.get(i));
if (area > minArea) {
if (area < maxArea) {
// we found a ball
float[] radius = new float[1];
Point center = new Point();
Imgproc.minEnclosingCircle(new MatOfPoint2f(contours.get(i).toArray()), center, radius);
balls.add(new Circle(center.x, center.y, calib.getBallRadius()));
} else {
// we found a cluster of balls
int numBalls = (int)(area / (Math.PI * calib.getBallRadius() * calib.getBallRadius() * 0.9));
// draw the contours to a bit mask
Mat hough = Mat.zeros(mask.size(), CvType.CV_8U);
Imgproc.drawContours(hough, contours, i, new Scalar(255, 255, 255), -2);
// detect hough circles, try different params until we hit the number of balls
Mat houghCircles = new Mat();
int hit = 0;
for(int j = 8; j < 20; j++) {
Imgproc.HoughCircles(hough, houghCircles, Imgproc.CV_HOUGH_GRADIENT, 2, calib.getBallRadius() * 0.9 * 2, 255, j, (int)(calib.getBallRadius() * 0.9), (int)(calib.getBallRadius() * 1.1));
if(houghCircles.cols() <= numBalls) {
hit++;
if(hit == 4) break;
}
}
List<Circle> estimatedCircles = new ArrayList<Circle>();
for(int j = 0; j < houghCircles.cols(); j++) {
double[] circle = houghCircles.get(0, j);
if(circle != null) {
estimatedCircles.add(new Circle(circle[0], circle[1], calib.getBallRadius()));
}
}
ballClusters.add(new BallCluster(contours.get(i), numBalls, estimatedCircles));
}
}
}
}
|
a98ea0cb-f1eb-4dab-b931-0866bd354d99
| 0
|
protected boolean test2 () { return true; }
|
85edecb2-8344-42d5-8294-c0f827fe0918
| 7
|
private void parseNodeString(String nodeLine) {
StringTokenizer tokenizer = new StringTokenizer(nodeLine);
// number of node parameters to parse (counts at linestart)
int parameters = 3;
// first test to step to the next parsing-state (edges)
if (nodeLine.contains("Edges:")) {
// Log.printLine("found start of Edges... switch to parse edges!");
state = PARSE_EDGES;
return;
}
// test against an empty line
if (!tokenizer.hasMoreElements()) {
// Log.printLine("this line contains no tokens...");
return;
}
// parse this string-line to read all node-parameters
// NodeID, xpos, ypos, indegree, outdegree, ASid, type(router/AS)
int nodeID = 0;
String nodeLabel = "";
int xPos = 0;
int yPos = 0;
for (int actualParam = 0; tokenizer.hasMoreElements() && actualParam < parameters; actualParam++) {
String token = tokenizer.nextToken();
switch (actualParam) {
case 0: // Log.printLine("nodeID: "+token);
// Log.printLine("nodeLabel: "+token);
nodeID = Integer.valueOf(token);
nodeLabel = Integer.toString(nodeID);
break;
case 1: // Log.printLine("x-Pos: "+token);
xPos = Integer.valueOf(token);
break;
case 2: // Log.printLine("y-Pos: "+token);
yPos = Integer.valueOf(token);
break;
}
}
// instanciate an new node-object with previous parsed parameters
TopologicalNode topoNode = new TopologicalNode(nodeID, nodeLabel, xPos, yPos);
graph.addNode(topoNode);
}// parseNodeString-END
|
b57e020a-f124-4508-a0cd-f73855992eb4
| 4
|
public void SendMessageByGet(){
CloseableHttpClient client=HttpClients.createDefault();
HttpGet get=new HttpGet(url+"?"+"&user="+user+"&key="+key+"&number="+number+"&text="+text);
try {
System.out.println(url+"?"+"&user="+user+"&key="+key+"&number="+number+"&text="+text);
HttpResponse response=client.execute(get);
HttpEntity entity=response.getEntity();
if(entity!=null){
InputStream is=entity.getContent();
BufferedReader in=new BufferedReader(new InputStreamReader(is));
StringBuffer buffer=new StringBuffer();
String line="";
while((line=in.readLine())!=null)
buffer.append(line+"\n");
backContent=buffer.toString();
System.out.println(buffer.toString());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
51c401e8-4833-460a-93e0-f953ff5c271d
| 4
|
private void update(String image) {
switch (TODOManager.backend.getSorting()) {
case TIME:
time.setImage(image);
break;
case PRIO:
prio.setImage(image);
break;
case TITLE:
title.setImage(image);
break;
case CATEGORY:
category.setImage(image);
break;
}
}
|
e79c6fca-5cf2-4651-a6c4-a372b5bcef05
| 5
|
boolean resolve(final MethodWriter owner, final int position,
final byte[] data) {
boolean needUpdate = false;
this.status |= RESOLVED;
this.position = position;
int i = 0;
while (i < referenceCount) {
int source = srcAndRefPositions[i++];
int reference = srcAndRefPositions[i++];
int offset;
if (source >= 0) {
offset = position - source;
if (offset < Short.MIN_VALUE || offset > Short.MAX_VALUE) {
/*
* changes the opcode of the jump instruction, in order to
* be able to find it later (see resizeInstructions in
* MethodWriter). These temporary opcodes are similar to
* jump instruction opcodes, except that the 2 bytes offset
* is unsigned (and can therefore represent values from 0 to
* 65535, which is sufficient since the size of a method is
* limited to 65535 bytes).
*/
int opcode = data[reference - 1] & 0xFF;
if (opcode <= Opcodes.JSR) {
// changes IFEQ ... JSR to opcodes 202 to 217
data[reference - 1] = (byte) (opcode + 49);
} else {
// changes IFNULL and IFNONNULL to opcodes 218 and 219
data[reference - 1] = (byte) (opcode + 20);
}
needUpdate = true;
}
data[reference++] = (byte) (offset >>> 8);
data[reference] = (byte) offset;
} else {
offset = position + source + 1;
data[reference++] = (byte) (offset >>> 24);
data[reference++] = (byte) (offset >>> 16);
data[reference++] = (byte) (offset >>> 8);
data[reference] = (byte) offset;
}
}
return needUpdate;
}
|
c68cd1aa-b22f-4cde-8968-cb22fd406e87
| 3
|
public static int[] sortLogList(int[] logList) {
int i, j, first, temp;
for (i = logList.length - 1; i > 0; i--) {
first = 0; //initialize to subscript of first element
for (j = 1; j <= i; j++) //locate smallest element between positions 1 and i.
{
if (logList[j] < logList[first]) {
first = j;
}
}
temp = logList[first]; //swap smallest found with element in position i.
logList[first] = logList[i];
logList[i] = temp;
}
return logList;
}
|
604d1a5c-2668-46bf-a4c2-4779546f3cb2
| 8
|
private ScoreObject addop(ScoreObject a, ScoreObject b) {
if (a.isNumeric() && b.isNumeric()) {
if (a.isFloat() || b.isFloat())
return new ScoreObject(a.getAsFloat() + b.getAsFloat());
// one is an int?
else if (a.isInt() || b.isInt())
return new ScoreObject(a.getAsInt() + b.getAsInt());
// must both be chars then
else return new ScoreObject(a.getChar() + b.getChar());
} else if (a.isString() || b.isString())
return new ScoreObject(a.getAsString() + b.getAsString());
throw new ScoreException("Cannot add type " + b.getTypeName() + " to type " + a.getTypeName() + ".");
}
|
33fa670c-ed57-4a13-b87b-98a0e734b383
| 8
|
public void keyReleased(KeyEvent w) {
int code = w.getKeyCode();
if (code == KeyEvent.VK_A) {
left = false;
if (right) {
} else {
dx = 0;
}
} else if (code == KeyEvent.VK_D) {
right = false;
if (left) {
} else {
dx = 0;
}
} else if (code == KeyEvent.VK_W) {
up = false;
if (down) {
} else {
dy = 0;
}
} else if (code == KeyEvent.VK_S) {
down = false;
if (up) {
} else {
dy = 0;
}
}
}
|
722ea8b0-1fbe-4876-a122-dd891bed7375
| 3
|
private static String loadSiteUID(){
String uid = DEFAULT_SITE_USER_ID;
try{
FileInputStream fis = new FileInputStream(workingDir + SITE_UID_FILE_NAME);
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
try {
uid = reader.readLine();
} catch (IOException e) {}
reader.close();
}
catch (Exception e){}
fis.close();
} catch (Exception e){}
return uid;
}
|
9a045670-fc73-443a-8190-26c737d3aa99
| 8
|
public static void main(String[] args) {
TreeSet<Integer> products = new TreeSet<Integer>();
int[][] grid = readFile(System.getProperty("user.dir")
+ "/external/problem11.txt");
for (int i = 0; i < 20; i++) {
for (int j = 0; j <= 16; j++) {
products.add(grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3]);
}
}
for (int i = 0; i <= 16; i++) {
for (int j = 0; j < 20; j++) {
products.add(grid[i][j] * grid[i + 1][j] * grid[i + 2][j] * grid[i + 3][j]);
}
}
for (int i = 0; i <= 16; i++) {
for (int j = 0; j <= 16; j++) {
products.add(grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3]);
}
}
for (int i = 3; i < 20; i++) {
for (int j = 0; j <= 16; j++) {
products.add(grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3]);
}
}
System.out.println(products.last());
}
|
1412423d-45ad-4b96-979f-59cfc1cf8dc1
| 3
|
public void changePrice(GraphNode<T> a, GraphNode<T> b, int weight){//T siendo graphNode con elemento de tipo Base, client o hub.
for(int i=0;i<aristas.getLength();i++){//checks coincidence to find link between nodes.
if(((GraphNode) aristas.get(i).getInitial()).equals(a) && ((GraphNode) aristas.get(i).getTerminal()).equals(b)){
aristas.get(i).setWeight(weight);
}
else{}
}
}
|
fa8e478c-e8cf-442f-8376-372f3f5b825e
| 0
|
public boolean isRelativeMouseMode() {
return (robot != null);
}
|
d4cdf86a-b2d2-4743-a588-3e4da93284a1
| 7
|
public void addClassificationAttempt(int trueClass, double[] classVotes,
double weight) {
if (weight > 0.0) {
if (TotalweightObserved == 0) {
reset(classVotes.length > 1 ? classVotes.length : 2);
}
this.TotalweightObserved += weight;
this.weightObserved.add(weight);
int predictedClass = Utils.maxIndex(classVotes);
if (predictedClass == trueClass) {
this.weightCorrect.add(weight);
} else {
this.weightCorrect.add(0);
}
//Add Kappa statistic information
for (int i = 0; i < this.numClasses; i++) {
this.rowKappa[i].add(i == predictedClass ? weight : 0);
this.columnKappa[i].add(i == trueClass ? weight : 0);
}
}
}
|
a116e2fe-53d7-4271-a072-8a0d23a9df94
| 3
|
@Override
public Source getSource(String sId) throws BadResponseException {
Source s = null;
JsonRepresentation representation = null;
Representation repr = serv.getResource("intervention/" + interId
+ "/source", sId);
try {
representation = new JsonRepresentation(repr);
} catch (IOException e) {
e.printStackTrace();
}
try {
s = new Source(representation.getJsonObject());
} catch (InvalidJSONException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return s;
}
|
6c7455b1-e1c2-4801-8a21-9ffca5699488
| 6
|
private static HashMap<String, Holder> getMap(String level) throws Exception
{
HashMap<String, Holder> map = new LinkedHashMap<String, Holder>();
BufferedReader reader = new BufferedReader(new FileReader(new File(
ConfigReader.getRachSachReanalysisDir()
+ File.separator + "rdpAnalysis"
+ File.separator + "pValuesForLine_taxa_Colon content_" + level + ".txt")));
reader.readLine();
for(String s = reader.readLine() ; s != null; s= reader.readLine())
{
String[] splits = s.split("\t");
if( splits.length != 8)
throw new Exception("Parsing error " + s + " " + splits.length);
String key = splits[0].replaceAll("\"","");
if( map.containsKey(key))
throw new Exception("Duplicate");
Holder h = new Holder();
h.pValueColon = getLogValLine(splits);
h.pValueColonCage = getLogValCage(splits);
map.put(key,h);
}
reader = new BufferedReader(new FileReader(new File(
ConfigReader.getRachSachReanalysisDir()
+ File.separator + "rdpAnalysis"
+ File.separator + "pValuesForLine_taxa_Cecal Content_" + level + ".txt")));
reader.readLine();
for(String s = reader.readLine() ; s != null; s= reader.readLine())
{
String[] splits = s.split("\t");
if( splits.length != 8)
throw new Exception("Parsing error");
String key = splits[0].replaceAll("\"","");
Holder h= map.get(key);
if( h== null)
{
h = new Holder();
map.put(key, h);
}
h.pValueCecum = getLogValLine(splits);
h.pValueCecumCage = getLogValCage(splits);
}
return map;
}
|
bcc4521b-54ef-40b9-b6e8-a32d99ac9578
| 9
|
private Node nextIntersectionNode( Node node, K key ) {
if( node == null ) {
return null;
}
while( true ) {
// Check right tree.
Node ret = firstIntersectionNode( node.mRight, key );
if( ret != null ) {
return ret;
}
// Go up until you find a parent to the right.
while( true ) {
if( node.mParent == null ) {
return null;
}
if( node.mParent.mRight == node ) {
node = node.mParent;
} else {
node = node.mParent;
// Found parent to the right. Check node for intersections.
if( mComp.compareMinToMax( key, node.mKey ) < 0 && mComp.compareMinToMax( node.mKey, key ) < 0 ) {
return node;
}
// If mKey is entirely before node, return null.
if( mComp.compareMinToMax( node.mKey, key ) >= 0 ) {
return null;
}
break;
}
}
}
}
|
b7c94ce2-cc6f-4083-b45e-05a8d5c3d990
| 6
|
public void body()
{
// wait for a little while for about 3 seconds.
// This to give a time for GridResource entities to register their
// services to GIS (GridInformationService) entity.
super.gridSimHold(3.0);
LinkedList resList = super.getGridResourceList();
// initialises all the containers
int totalResource = resList.size();
int resourceID[] = new int[totalResource];
String resourceName[] = new String[totalResource];
// a loop to get all the resources available
int i = 0;
for (i = 0; i < totalResource; i++)
{
// Resource list contains list of resource IDs
resourceID[i] = ( (Integer) resList.get(i) ).intValue();
// get their names as well
resourceName[i] = GridSim.getEntityName( resourceID[i] );
}
////////////////////////////////////////////////
// SUBMIT Gridlets
// determines which GridResource to send to
int index = myId_ % totalResource;
if (index >= totalResource) {
index = 0;
}
// sends all the Gridlets
Gridlet gl = null;
boolean success;
for (i = 0; i < list_.size(); i++)
{
gl = (Gridlet) list_.get(i);
write(name_ + "Sending Gridlet #" + i + " to " + resourceName[index]);
// For even number of Gridlets, send without an acknowledgement
// whether a resource has received them or not.
if (i % 2 == 0)
{
// by default - send without an ack
success = super.gridletSubmit(gl, resourceID[index]);
}
// For odd number of Gridlets, send with an acknowledgement
else
{
// this is a blocking call
success = super.gridletSubmit(gl,resourceID[index],0.0,true);
write("ack = " + success + " for Gridlet #" + i);
}
}
////////////////////////////////////////////////////////
// RECEIVES Gridlets back
// hold for few period - few seconds since the Gridlets length are
// quite huge for a small bandwidth
super.gridSimHold(5);
// receives the gridlet back
for (i = 0; i < list_.size(); i++)
{
gl = (Gridlet) super.receiveEventObject(); // gets the Gridlet
receiveList_.add(gl); // add into the received list
write(name_ + ": Receiving Gridlet #" +
gl.getGridletID() + " at time = " + GridSim.clock() );
}
////////////////////////////////////////////////////////
// ping functionality
InfoPacket pkt = null;
int size = 500;
// There are 2 ways to ping an entity:
// a. non-blocking call, i.e.
//super.ping(resourceID[index], size); // (i) ping
//super.gridSimHold(10); // (ii) do something else
//pkt = super.getPingResult(); // (iii) get the result back
// b. blocking call, i.e. ping and wait for a result
pkt = super.pingBlockingCall(resourceID[index], size);
// print the result
write("\n-------- " + name_ + " ----------------");
write(pkt.toString());
write("-------- " + name_ + " ----------------\n");
////////////////////////////////////////////////////////
// shut down I/O ports
shutdownUserEntity();
terminateIOEntities();
// don't forget to close the file
if (report_ != null) {
report_.finalWrite();
}
write(this.name_ + ": sending and receiving of Gridlets" +
" complete at " + GridSim.clock() );
}
|
53d73447-0b08-486e-b547-84282b7b8a35
| 8
|
@Override
public void run() throws IOException, ClassNotFoundException, SQLException {
// let's create output dir
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String ts = df.format(new Date());
Path pathTs = Files.createDirectory(Paths.get(Config.getPathOut() + ts));
System.out.println(pathTs.toString());
List<Page> pages;
pages = new ArrayList<>();
pages.add(new SkUvod());
pages.add(new SkProjekt());
pages.add(new SkNovinky());
pages.add(new SkSluzby());
pages.add(new SkPristupoveSystemy());
pages.add(new SkDEK());
pages.add(new SkBES());
pages.add(new SkRAK());
pages.add(new SkDorozumievacieSystemy());
pages.add(new SkDDS());
pages.add(new SkDDV());
pages.add(new SkSenzoroveOsvetlenie());
pages.add(new SkKovovyroba());
pages.add(new SkElektroinstalacie());
pages.add(new SkRevizie());
pages.add(new SkBleskozvody());
pages.add(new SkNudzoveOsvetlenie());
pages.add(new SkReferencie());
/*
List<Integer> referencie = References.getReferences();
for (Integer idReferencia : referencie) {
pages.add(new SkReferencia(idReferencia));
}
*/
pages.add(new SkCenovaPonuka());
pages.add(new SkProdukty());
pages.add(new SkSteinelRS16L());
pages.add(new SkSteinelDL750S());
pages.add(new SkTelefonElegant());
pages.add(new SkTelefonEso());
pages.add(new SkSteinelIS1());
pages.add(new SkSteinelDL850S());
pages.add(new SkSteinelL870S());
pages.add(new SkSteinelL1());
pages.add(new SkSteinelRSLEDA1());
pages.add(new SkLedus8());
pages.add(new SkMcobLedE27());
pages.add(new SkMcobLedE27Neutralna());
pages.add(new SkLedS2720n());
pages.add(new SkLedS2720());
pages.add(new SkFirmy());
pages.add(new SkSpravcovia());
List<Integer> firmy = Data.getCompanies();
for (Integer idFirma : firmy) {
pages.add(new SkFirma(idFirma));
}
pages.add(new SkKontakt());
pages.add(new SkNaStiahnutie());
pages.add(new Error404());
pages.add(new Error401());
pages.add(new Error403());
pages.add(new Error500());
for (Page page : pages) {
Path file = Files.createDirectory(Paths.get(pathTs.toString() + "/" + page.getUrl()));
if (page.isPHP()) {
file = Paths.get(file.toString() + "/" + "index.php");
} else {
file = Paths.get(file.toString() + "/" + "index.html");
}
file = Files.createFile(file);
BufferedWriter writer = Files.newBufferedWriter(file, Charset.forName("UTF-8"));
writer.append(page.getHtml());
writer.flush();
writer.close();
System.out.println(file.toString());
}
// Main sitemap
DateFormat dfs = new SimpleDateFormat("yyyy-MM-dd");
String tss = dfs.format(new Date());
Path sitemap = Files.createFile(Paths.get(pathTs.toString() + "/sitemap.xml"));
BufferedWriter writer = Files.newBufferedWriter(sitemap, Charset.forName("UTF-8"));
writer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
writer.append("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n");
for (Page page : pages) {
if (page.isInSitemap()) {
writer.append("<url>");
writer.append("<loc>");
writer.append(Config.getBaseUrl());
writer.append(page.getUrl());
writer.append("</loc>");
writer.append("<lastmod>");
writer.append(tss);
writer.append("</lastmod>");
writer.append("<changefreq>");
writer.append(page.getSitemapChangeFreq());
writer.append("</changefreq>");
writer.append("<priority>");
writer.append(page.getSitemapPriority());
writer.append("</priority>");
writer.append("</url>\n");
}
}
writer.append("</urlset>");
writer.flush();
writer.close();
System.out.println(sitemap.toString());
// Image sitemap
Path imgSitemap = Files.createFile(Paths.get(pathTs.toString() + "/image-sitemap.xml"));
writer = Files.newBufferedWriter(imgSitemap, Charset.forName("UTF-8"));
writer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
writer.append("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\n");
writer.append(" xmlns:image=\"http://www.google.com/schemas/sitemap-image/1.1\">\n");
for (Page page : pages) {
List<SitemapImage> images;
images = page.getImages();
if (images.size() > 0) {
writer.append("<url>\n");
writer.append("<loc>");
writer.append(Config.getBaseUrl());
writer.append(page.getUrl());
writer.append("</loc>\n");
for (SitemapImage image : images) {
writer.append("<image:image>");
writer.append("<image:loc>");
writer.append(Config.getBaseUrl());
writer.append(page.getUrl());
writer.append(image.getLoc());
writer.append("</image:loc>");
writer.append("</image:image>\n");
}
writer.append("</url>\n");
}
}
writer.append("</urlset>");
writer.flush();
writer.close();
System.out.println(imgSitemap.toString());
}
|
77e9fc63-2142-4b72-b27d-dcac0b812d67
| 5
|
private boolean won()
{
if (mSweeper.isDied()) return false;
final int width = mField.getWidth(), height = mField.getHeight();
final byte open = mField.getMasks().getOpen().getId(), openBomb = mField.getMasks().getOpenBomb().getId(), bomb = mField.getTiles().getBomb().getId();
for (int tile = 0; tile < width * height; tile++ )
{
final byte mask = mField.getMask(tile);
if (mask != open && mask != openBomb && mField.getTile(tile) != bomb) return false;
}
return true;
}
|
4151c544-0a27-4bed-8d04-4894d180f034
| 6
|
private void sendFiles(Transferable tran) throws UnsupportedFlavorException, IOException {
if (fileList == null) { // If files are drag&dropped filelist will be filled at DragAndDropListener
prtscr = true;
if (tran.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
fileList = (List<File>) tran.getTransferData(DataFlavor.javaFileListFlavor);
} else {
Date date = new Date();
String nimi = date.getTime() + "jpeg";
File tiedosto = new File(date.getTime() + ".jpeg");
BufferedImage kuvaa = (BufferedImage) tran.getTransferData(DataFlavor.imageFlavor);
ImageIO.write(kuvaa, "jpeg", tiedosto);
fileList = new ArrayList<File>();
fileList.add(tiedosto);
}
}
try {
for (File tiedosto : fileList) { //sending files 1 by 1 to neekeri.com then deleting
File file = tiedosto;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://neekeri.com/upscript/uploadify.php");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody bin = new FileBody(file);
reqEntity.addPart("Filename", new StringBody(file.getName()));
reqEntity.addPart("fo8lder", new StringBody("/up"));
reqEntity.addPart("fileext", new StringBody("*.php;*.pdf;*.fla;*.dat;*.ass;*.jar;*.java;*.csv;*.bmp;*.jpg;*.jpeg;*.png;*.gif;*.swf;*.svg;*.txt;*.exe;*.wmv;*.avi;*.mp3;*.nfo;*.mpg;*.naf;*.zip;*.rar;*.7z;*.tif;*.psd;*.doc;*.docx;*.ppt;*.pptx;*.flv;*.mp4;*.mid;*.aac;*.tar.bz2;*.tar.gz;*.tar;*.tif;*.yuv;*.svg;*.db;*.nfo;*.bat;*.sav;*.ttf;*.dll;*.sys;*.deb;*.pkg;*.gz;*.iso;*.toast;*.dmg;*.bak;*.tmp;*.msi;*.torrent;*.flac;*.ogg;*.JPG,*.PNG,*.JPEG;*.TCL;*.tcl"));
reqEntity.addPart("Filedata", bin);
reqEntity.addPart("Upload", new StringBody("Submit Query"));
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
linkkiLeikepoydalle(file.getName());
}
if (!oldFiles) { // Files are screenshots and will be removed
for (File file : fileList) {
file.delete();
}
}
} catch (IOException ex) {
Logger.getLogger(FileSender.class.getName()).log(Level.SEVERE, null, ex);
}
prtscr = false;
isText = false;
fileList = null;
}
|
63f5eb47-cf4f-4957-a128-8be4ad18fee0
| 8
|
@Override
public int[] getInts(int par1, int par2, int par3, int par4)
{
int i1 = par1 - 1;
int j1 = par2 - 1;
int k1 = par3 + 2;
int l1 = par4 + 2;
int[] aint = this.parent.getInts(i1, j1, k1, l1);
int[] aint1 = IntCache.getIntCache(par3 * par4);
for (int i2 = 0; i2 < par4; ++i2)
{
for (int j2 = 0; j2 < par3; ++j2)
{
int k2 = aint[j2 + 1 + (i2 + 1 - 1) * (par3 + 2)];
int l2 = aint[j2 + 1 + 1 + (i2 + 1) * (par3 + 2)];
int i3 = aint[j2 + 1 - 1 + (i2 + 1) * (par3 + 2)];
int j3 = aint[j2 + 1 + (i2 + 1 + 1) * (par3 + 2)];
int k3 = aint[j2 + 1 + (i2 + 1) * k1];
int l3 = 0;
if (k2 == 0)
{
++l3;
}
if (l2 == 0)
{
++l3;
}
if (i3 == 0)
{
++l3;
}
if (j3 == 0)
{
++l3;
}
if (k3 == 0 && l3 > 3)
{
aint1[j2 + i2 * par3] = BiomeGenBase.deepOcean.biomeID;
}
else
{
aint1[j2 + i2 * par3] = k3;
}
}
}
return aint1;
}
|
cc298505-b69d-4f34-b4b4-727cba691f82
| 9
|
public boolean isStillMaintained(Environmental thang, ShopKeeper SK, Item I)
{
if((I==null)||(I.amDestroyed()))
return false;
if(SK!=null)
return SK.getShop().doIHaveThisInStock(I.Name(),null);
if(thang instanceof Area)
{
final Room R=CMLib.map().roomLocation(I);
if(R==null)
return false;
return ((Area)thang).inMyMetroArea(R.getArea());
}
else
if(thang instanceof Room)
return CMLib.map().roomLocation(I)==thang;
else
if(thang instanceof MOB)
return (I.owner()==thang);
else
if(thang instanceof Container)
return (I.owner()==((Container)thang).owner())&&(I.container()==thang);
return I.owner()==CMLib.map().roomLocation(thang);
}
|
4d9aac48-b0b2-40a5-a11c-0c62c1d45488
| 5
|
private void launch() { //The method that kick starts execution of a program and manages it in standard mode
pc.setPC(0); //Initialise PC to 0 for GUI display
if (!pipeliningMode) {
while (active) {
fetchDecodeStage.run();
int opcode = fetchDecodeStage.getOpcodeValue();
if (opcode == -1) { //fetchDecodeStage.getOpcodeValue() returns -1 if interrupted, meaning SwingWorker.cancel()
//has been called from CPUframe ("reset" clicked on GUI). Execution should not continue as a result.
this.active = false;
}
else {
executeStage.setOpcodeValue(opcode);
executeStage.run();//Note that writeBackStage is called from executeStage if necessary
this.active = executeStage.isActive();
}
}
//If interrupted by a "reset" during Stage's accessMemory() method, the lock must be released.
if (((ReentrantLock) Stage.getLock()).isHeldByCurrentThread()) {
Stage.getLock().unlock();
}
}
else if (pipeliningMode) {
/*
* The SwingWorker thread activated from the GUI runs in the executeStage, and
* creates two threads, one to run in the F/D Stage and the other to run in the
* WB Stage. If "reset" is clicked, issuing an interrupt to the SwingWorker thread,
* it interrupts the other two threads (which results in their exiting from their respective
* run() methods asap) prior to terminating itself by exiting its run() method as quickly as possible.
*
* The SwingWorker thread also issues an interrupt to the thread running in the F/D Stage
* if a branch instruction is executed, causing that thread to exit its run() method, before restarting
* it.
*/
executeStage.run(); //This manages the fetch and write back stages
}
}
|
f926480a-1717-41c0-aed5-a5a4fba91f88
| 4
|
public void connectToService() {
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
try {
Remote service = Naming.lookup("//127.0.0.1:1699/quiz");
quizService = (QuizService) service;
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException ex) {
ex.printStackTrace();
}
}
|
acbdc150-3c6c-469f-9c87-8c030e396c6f
| 4
|
protected static String toHtml(String wiki) {
wiki = wiki.replaceAll("<BR>|<br>", " ");
wiki = wiki.replaceAll("\n", " ");
wiki = wiki.replaceAll(" ", " ");
int countBold = 0;
int indexOfApostrophe = wiki.indexOf("'''");
while (indexOfApostrophe != -1) {
if ((countBold % 2) == 0) {
wiki = wiki.replaceFirst("'''", "<b>");
} else {
wiki = wiki.replaceFirst("'''", "</b>");
}
countBold++;
indexOfApostrophe = wiki.indexOf("'''", indexOfApostrophe);
}
int countItalic = 0;
indexOfApostrophe = wiki.indexOf("''");
while (indexOfApostrophe > -1) {
if ((countItalic % 2) == 0) {
wiki = wiki.replaceFirst("''", "<i>");
} else {
wiki = wiki.replaceFirst("''", "</i>");
}
countItalic++;
indexOfApostrophe = wiki.indexOf("''", indexOfApostrophe);
}
wiki = wiki.replace("<\\/b><\\/i>", "</i></b>");
return wiki.trim();
}
|
22df914f-0812-47a6-9935-4a4b1b1eb5f1
| 2
|
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((frequency == null) ? 0 : frequency.hashCode());
result = prime * result + ((symbol == null) ? 0 : symbol.hashCode());
return result;
}
|
3faee16d-3b03-46a7-bdd1-aa1bfed75afd
| 3
|
public OneTangent(Craft craft, double rFinal, double transPoint) {
//Faster but less efficient than a Hohmann transfer
//Decrease transPoint for a shorter transfer time
double grav = craft.parent.mass * Astrophysics.G;
double rInitial = craft.position.clone().subtract(craft.parent.position).magnitude();
double invR = rInitial/rFinal;
boolean isPeriapsis = rInitial < rFinal;
double bigE0 = (isPeriapsis? 0 : Math.PI);
double eTrans = (invR - 1)/(Math.cos(transPoint) + (isPeriapsis? -invR : invR));
double aTrans = rInitial / (1 + (isPeriapsis? -eTrans : eTrans));
double vInitial = Math.sqrt(grav/rInitial);
double vFinal = Math.sqrt(grav/rFinal);
double vTransA = Math.sqrt((2*grav/rInitial) - (grav/aTrans));
double vTransB = Math.sqrt((2*grav/rFinal) - (grav/aTrans));
double deltaVA = vTransA - vInitial;
//Calculate flight-path angle
double thetaTransB = Math.atan2(eTrans*Math.sin(transPoint), 1 + eTrans*Math.cos(transPoint));
double deltaVB = Math.sqrt(vTransB*vTransB + vFinal*vFinal - 2*vTransB*vFinal*Math.cos(thetaTransB));
this.deltaV = Math.abs(deltaVA) + Math.abs(deltaVB);
double bigE = Math.acos((eTrans + Math.cos(transPoint))/(1 + eTrans*Math.cos(transPoint)));
double tTrans = Math.sqrt(aTrans*aTrans*aTrans/grav);
}
|
1279cb73-62e5-4d55-b4d9-05838b7a526a
| 6
|
public void zapImageParts(BufferedImage im, double likelihood)
// change some of the image's pixels to red or yellow
{
if (im == null) {
System.out.println("zapImageParts: input image is null");
return;
}
if ((likelihood < 0) || (likelihood > 1)) {
System.out.println("likelihood must be in the range 0 to 1");
likelihood = 0.5;
}
int redCol = 0xf90000; // nearly full-on red
int yellowCol = 0xf9fd00; // a mix of red and green
int imWidth = im.getWidth();
int imHeight = im.getHeight();
int [] pixels = new int[imWidth * imHeight];
im.getRGB(0, 0, imWidth, imHeight, pixels, 0, imWidth);
double rnd;
for(int i=0; i < pixels.length; i++) {
rnd = Math.random();
if (rnd <= likelihood) {
if (rnd <= 15*likelihood/16 ) // make red more likely then yellow
pixels[i] = pixels[i] | redCol;
else
pixels[i] = pixels[i] | yellowCol;
}
}
im.setRGB(0, 0, imWidth, imHeight, pixels, 0, imWidth);
} // end of eraseImageParts()
|
087e6f9d-dd23-4959-98c6-c0f5f6f3e573
| 9
|
public void setDimensions(){
for(int i=0; i<books.size();i++){
BookNode book = books.get(i);
int x= (int)book.getX();
int y= (int)book.getY();
int radius = (int)book.getPaddedRadius();
if(i==0 || x-radius<minX)
minX=x-radius;
if(i==0 || x+radius>maxX)
maxX=x+radius;
if(i==0 || y-radius<minY)
minY=y-radius;
if(i==0 || y+radius>maxY)
maxY=y+radius;
}
Dimension dim = new Dimension((int)Math.abs(maxX-minX)+3,(int)Math.abs(maxY-minY)+3);
this.setMinimumSize(dim);
this.setPreferredSize(dim);
// this.setMaximumSize(dim);
// lX=minX+1; hX=maxX-1; lY=minY+1; hY=maxY-1;
// xOffset=(-minX);
// yOffset=(-minY);
}
|
61c7f827-4a0b-4f6e-9945-ff9529c34df8
| 6
|
public static void removeConnection(String username, Integer type) {
Client client = getClient(username);
// Check if client target client exists.
if (client != null) {
// Remove from GUI List.
clientListModel.removeElement(username + " (" + client.getSocket().getInetAddress().getHostAddress() + ")");
// Remove stored Client thread.
getConnections().remove(client);
try {
// Attempt to send disconnection packet (if player still exists)
ObjectOutputStream oos = new ObjectOutputStream(client.getSocket().getOutputStream());
oos.writeObject(type);
} catch (Exception ex) {
}
// Stop listening to the player.
client.getConnectionThread().end();
Player p = null;
// Get the target player entity.
for (Entity e : getMap().getEntities()) {
if (e.getType() == EntityType.PLAYER && ((Player) e).getUsername().equalsIgnoreCase(username)) {
p = (Player) e;
break;
}
}
// If player has been found, remove entity.
if (p != null)
getMap().getEntities().remove(p);
}
}
|
60890824-cf87-482d-9734-ef2737f4b8a8
| 9
|
public Matrix decomposeLU(boolean LUP) {
if(rows != cols) {
throw new IllegalArgumentException("Matrica nije kvadratna!");
}
Matrix P = new Matrix(rows);
for(int i = 0; i < rows - 1; i++) {
if(LUP) {
// ako je LUP postupak odabran napravi pivotiranje po stupcima
int pivotIndex = i;
for(int j = pivotIndex + 1; j < rows; j++) {
if(Math.abs(matrix[j][i]) > Math.abs(matrix[pivotIndex][i])) {
pivotIndex = j;
}
}
this.swapRows(i, pivotIndex);
P.swapRows(i, pivotIndex);
}
double pivotValue = matrix[i][i];
if(isZero(pivotValue)) {
System.err.println("Pivot je priblizno nula! Pivot: " + pivotValue);
return null;
}
for(int j = i + 1; j < rows; j++) {
matrix[j][i] /= pivotValue;
for(int k = i + 1; k < cols; k++) {
matrix[j][k] -= matrix[j][i] * matrix[i][k];
}
}
}
double lastPivot = matrix[rows - 1][cols - 1];
if(isZero(lastPivot)) {
System.err.println("LU[N, N] je priblizno nula! Pivot: " + lastPivot);
return null;
}
isDecomposed = true;
return P;
}
|
f1f0b697-a53c-4067-b859-dd9b9cf9d858
| 0
|
public void removeRange(int fromIndex, int toIndex) {
int numMoved = size - toIndex;
System.arraycopy(data, toIndex, data, fromIndex, numMoved);
size = size - (toIndex - fromIndex);
}
|
97ec6a7b-c03a-4f54-974f-39641f7a8ac8
| 4
|
public void aplicarMascarilla() throws InterruptedException {
if (!mascarillaAplicada) {
for (Barrillo barrillo : barrillos) {
barrillo.mascarillaAplicada = true;
}
mascarillaAplicada = true;
repaint();
semaforo.acquire();
Thread th = new Thread() {
public void run() {
try {
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(GranosSimulator.class.getName()).log(Level.SEVERE, null, ex);
}
Thread.sleep(4000);
semaforo.release();
} catch (InterruptedException ex) {
Logger.getLogger(GranosSimulator.class.getName()).log(Level.SEVERE, null, ex);
}
mascarillaAplicada = false;
}
};
th.start();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.