method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
da4e8e01-ef70-413c-94d5-a183f0cbcc5d
| 5
|
private static Population[] generate(){
Population[] h = new Population[GLOBAL_STEPS];
operationCounter = new double[OPERATIONS_NUMBER];
for (int pop = 0; pop < GLOBAL_STEPS; ++pop){
h[pop] = new Population(populationSize, individualSize);
}
resultsRandom = new double[GLOBAL_STEPS];
Arrays.fill(resultsRandom, Double.POSITIVE_INFINITY);
for (int pop = 0; pop < GLOBAL_STEPS; ++pop){
if (pop % 100 == 0){
System.out.println("random pop " + pop);
}
Population randomP = new Population(h[pop]);
Store store = new Store(rng);
CAMO randomAMO = new CAMO(randomP, rng);
CMO randomMO = new CMO(randomP, rng);
CBMO randomCBMO = new CBMO(randomP, rng);
CCO randomCO = new CCO(randomP, rng);
CHO randomCHO = new CHO(randomP, rng);
store.addOperator(randomAMO);
store.addOperator(randomMO);
// store.addOperator(randomCHO);
// store.addOperator(randomCO);
store.addOperator(randomCBMO);
store.initProbabilities();
store.initQ();
for (int steps = 0; steps < MAX_STEPS; ++steps){
// double r;
// synchronized (rng){
// r = rng.nextDouble();
// }
// if (r < 0.2){
// randomAMO.mutate();
// operationCounter[0]++;
// } else if (r < 0.40) {
// randomMO.mutate();
// operationCounter[1]++;
// } else if (r < 0.60) {
// randomCHO.mutate();
// operationCounter[2]++;
// } else if (r < 0.8) {
// randomCO.mutate();
// operationCounter[3]++;
// } else {
// randomCBMO.mutate();
// operationCounter[4]++;
// }
store.chooseOperator().mutate();
operationCounter[store.getChoosen()]++;
if (randomP.getFittest() == OPTIMUM){
resultsRandom[pop] = steps;
break;
}
}
}
Arrays.sort(resultsRandom);
return h;
}
|
e40d0781-7cca-45be-95c3-6c8656903520
| 0
|
@Test
public void runTestActivityLifecycle4() throws IOException {
InfoflowResults res = analyzeAPKFile("Lifecycle_ActivityLifecycle4.apk");
Assert.assertEquals(1, res.size());
}
|
39a49140-7257-4090-983f-c94c598755cd
| 3
|
public List<Integer> returnIntsFromStart (int start) {
List<Integer> listI=new ArrayList<Integer>();
BitSet bset=new BitSet();
int a,bcount=0;
for (a=start;a<totalLength;a++) {
if (this.get(a)==true) bset.set(bcount);
else bset.clear(bcount);
bcount++;
if (bcount==8) {
listI.add(binaryToInt8(bset));
bset.clear();
bcount=0;
}
}
return listI;
}
|
e07fa955-c84d-4540-a269-c7470079cd16
| 7
|
public InsertStatus insertFromBuffer(ItemStack[] buffer) {
if (isFull())
return InsertStatus.FAIL;
for (ItemStack is : buffer) {
if (is == null || is.stackSize == 0)
continue;
InsertStatus i = insert(is, false);
switch (i) {
case FAIL:
case PARTIAL:
return InsertStatus.PARTIAL;
case SUCCESS:
default:
break;
}
}
return InsertStatus.SUCCESS;
}
|
67d96a7d-4946-444e-a087-90dfe51e3a9a
| 6
|
@Override
public int compareTo(Track o) {
int artistcompare = this.get("artist").compareToIgnoreCase(o.get("artist"));
if(artistcompare == 0) {
try {
int albumcompare = this.get("album").compareToIgnoreCase(o.get("album"));
if (albumcompare == 0) {
try {
int that = Integer.parseInt(this.get("track"));
int thing = Integer.parseInt(o.get("track"));
int trackcompare = that - thing;
if (trackcompare == 0) {
return 0;
} else if(trackcompare < 0) {
return -1;
} else {
return 1;
}
} catch(Error e){
//track is null or something
}
} else {
return albumcompare;
}
} catch(Error e){
//album is null or something
}
} else {
return artistcompare;
}
return 0;
}
|
65c32bbb-8be5-4560-8441-346af5cd83a8
| 0
|
public static void main(String[] args) {
RecursionFb fb = new RecursionFb();
System.out.println(fb.fbMethod(4));
}
|
fc578f68-86fb-47bd-8c72-a81ec336e7e3
| 7
|
private void drawChunks(int x0, int y0, int width, int height, Graphics2D gI)
{
for (int x = (int) ((x0-.0)/Chunk.getPixelLength()-0.5); x <= Math.ceil(((double)x0+width)/Chunk.getPixelLength()); ++x)
{
for (int y = (int) ((y0-.0)/Chunk.getPixelLength()-0.5); y <= Math.ceil(((double)y0+height)/Chunk.getPixelLength()); ++y)
{
Chunk c;
try {
c = getChunk(x, y);
} catch (ChunkNotLoadedException e) {
continue;
}
int cScreenX = (int)((x-0.5)*Chunk.getPixelLength()-x0), cScreenY = (int)((y-0.5)*Chunk.getPixelLength()-y0);
if (cScreenX > width || cScreenX+Chunk.getPixelLength() < 0 || cScreenY > height || cScreenY+Chunk.getPixelLength() < 0) //Check that shouldn't fail!
{
System.out.println("WHOOPS! Check src.world.World.drawChunks()!");
}
BufferedImage cI = c.draw();
gI.drawImage(cI, cScreenX, cScreenY, Chunk.getPixelLength(), Chunk.getPixelLength(), null);
}
}
}
|
5d843cfd-4073-42cf-994e-1c4669b189f9
| 3
|
@Override
public void addProduct(Product product) throws SQLException {
Session session=null;
try{
session=HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(product);
session.getTransaction().commit();
}catch(Exception e){
e.printStackTrace();
}finally{
if(session!=null && session.isOpen())
session.close();
}
}
|
cbc30909-3eb9-4c84-80cb-6aa2ac37e534
| 1
|
double tryGetProfit(Match m) {
double total = 0;
if ((total = makeTotalPredict(m)) < 0) {
return 0;
}
return m.betLine.getProfit(total, m.score.total, eps1, eps2);
}
|
bbd69211-cf55-405a-b8e7-c848411d96ba
| 5
|
public Sha1Hash (byte[] bytes) {
if (bytes == null) {
throw new NullPointerException();
}
if (bytes.length != 20) {
throw new IllegalArgumentException();
}
this.bytes = Arrays.copyOf(bytes, bytes.length);
hash = Arrays.hashCode(bytes);
// Hex String
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
int ub = (b) & 0xFF;
if (ub < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(ub).toUpperCase());
}
string = sb.toString();
// URL Encoded String
String str = new String(bytes, Charset.forName("ISO-8859-1"));
try {
urlEncodedString = URLEncoder.encode(str, "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
// Should not happen, as LATIN-1 is always supported...
throw new AssertionError();
}
}
|
03a90a1c-984d-423f-b821-fb7034a961ea
| 9
|
protected void FillBuff() throws java.io.IOException
{
if (maxNextCharInd == available)
{
if (available == bufsize)
{
if (tokenBegin > 2048)
{
bufpos = maxNextCharInd = 0;
available = tokenBegin;
}
else if (tokenBegin < 0)
bufpos = maxNextCharInd = 0;
else
ExpandBuff(false);
}
else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
}
int i;
try {
if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1)
{
inputStream.close();
throw new java.io.IOException();
}
else
maxNextCharInd += i;
return;
}
catch(java.io.IOException e) {
--bufpos;
backup(0);
if (tokenBegin == -1)
tokenBegin = bufpos;
throw e;
}
}
|
cbb1903d-f83e-4e32-af78-8ada6a6a7ea7
| 6
|
public int getImageIndex() {
if (type.equalsIgnoreCase("red")){
return 6;
} else if (type.equalsIgnoreCase("blue")){
return 7;
} else if (type.equalsIgnoreCase("dark")){
return 8;
} else if (type.equalsIgnoreCase("blank")){
return 9;
} else if (type.equalsIgnoreCase("darkRed")){
return 10;
} else if (type.equalsIgnoreCase("darkBlue")){
return 11;
} else {
return 9;
}
}
|
9cdcc03d-cb55-4732-950a-4eb75dfbbfa3
| 2
|
private int MakeThem(Commande data) throws InterruptedException {
int nbRatees = 0, nbFaites = 0;
TypePiece tp = Commande.TypePiece.valueOf(data.GetPiece());
Random r = new Random();
while (nbFaites < data.GetNbrPieces()) {
if (r.nextInt(5) == 3)
nbRatees++;
else
nbFaites++;
}
Thread.sleep(tp.GetTmpFabric() * (nbFaites + nbRatees) * 1000);
return nbRatees;
}
|
fbbeccc1-f035-4095-87b0-3a88ac8bc087
| 1
|
static void tuneAll(Instrument[] e) {
for (Instrument i : e)
tune(i);
}
|
18ea969b-3034-4d15-9de7-d460b7379c92
| 2
|
@Override
public String toString() {
String words = "";
for (Map.Entry<String, Integer> entry : countWords.entrySet()) {
words += entry.getKey() + " - " + entry.getValue() + "\n";
}
String extractedSentences = "";
for (String sentence : sentences) {
extractedSentences += sentence + "\n";
}
return "--------------------"
+ "\n"
+ "URL:" + url + "\n"
+ "Count of character: " + countCharacters
+ "\n"
+ "Count of searching words in url: \n" + words
+ "Extracted sentences or something that looks like sentences. (The number of sentences are not the same as number of found words)"
+ "\n"
+ "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
+ "\n"
+ extractedSentences
+ "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
+ "\n"
+ "--------------------";
}
|
82c94e18-1eb4-42b5-890b-d0826656d7e3
| 3
|
public boolean isEmpty() {
if (hasNoGold() && hasNoWumpus() && hasNoPit())
return true;
return false;
}
|
e3e7569e-614c-452a-92c1-3c27e99d9374
| 8
|
private void checkFormatting(int lineNumber, String line, String[] partsToCheck) throws Exception {
String baseMessage = "On line " + lineNumber + ": Invalid formatting found - ";
String pFound = findIllegalPunctuation(line);
if (pFound != null) {
throw new Exception(baseMessage + "Illegal punctuation: " + pFound);
}
if (partsToCheck.length != 3)
throw new Exception(baseMessage + "punctuation must be in format of \"xCoord,yCoord:propertiesValues\"");
for (int i = 0; i < 3; i++) {
if (partsToCheck[i].toUpperCase().contains("[A-Z]")) {
throw new Exception(baseMessage + " non-numeric characters found in part " + i + ": (" + partsToCheck[i] + ")");
}
int number = Integer.parseInt(partsToCheck[i]);
if (number >= 64 && i < 2) { //IMPLEMENT A WAY TO CHECK FOR MAP SIZE
String message = (baseMessage + " coordinate component (");
if (i == 0) {
message += "x = " + number + ") ";
} else if (i == 1) {
message += "y = " + number + ") ";
}
message += "goes out of bounds of limits (64x64) for this map.";
throw new Exception(message);
}
}
}
|
2017af68-51ba-44db-8620-e31ee649f758
| 3
|
@Override
public void repaint(TextGraphics graphics)
{
border.drawBorder(graphics, new TerminalSize(graphics.getWidth(), graphics.getHeight()), title);
TerminalPosition contentPaneTopLeft = border.getInnerAreaLocation(graphics.getWidth(), graphics.getHeight());
TerminalSize contentPaneSize = border.getInnerAreaSize(graphics.getWidth(), graphics.getHeight());
TextGraphics subGraphics = graphics.subAreaGraphics(contentPaneTopLeft, contentPaneSize);
List<? extends LayoutManager.LaidOutComponent> laidOutComponents = layoutManager.layout(contentPaneSize);
for(LayoutManager.LaidOutComponent laidOutComponent: laidOutComponents) {
TextGraphics subSubGraphics = subGraphics.subAreaGraphics(
laidOutComponent.getTopLeftPosition(), laidOutComponent.getSize());
if(laidOutComponent.getComponent().isVisible())
laidOutComponent.getComponent().repaint(subSubGraphics);
}
}
|
6e4369ea-6a4c-4932-ad82-45ef761baf72
| 3
|
public boolean checkStatus(User user) throws BusinessException {
boolean canAccess = false;
// O usuário foi autenticado com sucesso e se encontra ativo.
if(User.STATUS_ATIVO == user.getStatus()) {
canAccess = true;
} else if(User.STATUS_BLOQUEADO == user.getStatus()) {
// Caso o usuário esteja bloqueado uma mensagem será exibida
if(this.userCanBeReleased(user)) {
this.releasingUser(user);
canAccess = true;
}
}
return canAccess;
}
|
f8af8618-e34d-47a2-8673-8c34901def72
| 6
|
public Movie[] load() throws Exception {
Movie[] finalResult = new Movie[0];
if (!Session.hasKey("LoggedUser")) {
throw new Exception("User is not authorized");
}
if (Session.hasValue("LoggedUser", "admin")) {
XmlDocument xmlMovies = loadXml();
ArrayList<Movie> resultMovies = new ArrayList<Movie>();
for (int i = 0; i < xmlMovies.Elements.size(); i++) {
Movie movie = new Movie(Integer.parseInt(xmlMovies.Elements.get(i).Values[3]));
movie.Rating = Integer.parseInt(xmlMovies.Elements.get(i).Values[2]);
movie.Title = xmlMovies.Elements.get(i).Values[0];
movie.Price = xmlMovies.Elements.get(i).Values[1];
resultMovies.add(movie);
}
Movie[] result = new Movie[resultMovies.size()];
finalResult = resultMovies.toArray(result);
}
else {
if (Session.hasValue("LoggedUser", "user")) {
XmlDocument xmlMovies = loadXml();
ArrayList<Movie> resultMovies = new ArrayList<Movie>();
for (int i = 0; i < xmlMovies.Elements.size(); i++) {
if (Integer.parseInt(xmlMovies.Elements.get(i).Values[2]) <= 14)
{
Movie movie = new Movie(Integer.parseInt(xmlMovies.Elements.get(i).Values[3]));
movie.Rating = Integer.parseInt(xmlMovies.Elements.get(i).Values[2]);
movie.Title = xmlMovies.Elements.get(i).Values[0];
movie.Price = xmlMovies.Elements.get(i).Values[1];
resultMovies.add(movie);
}
}
Movie[] result = new Movie[resultMovies.size()];
finalResult = resultMovies.toArray(result);
}
}
return finalResult;
}
|
bc312e81-ecb2-4526-aa68-7149c0684cc8
| 4
|
public boolean isOnPoint(double mx, double my) {
if (locked) {
mx = (mx - (x - graph.canvas.offX) / graph.canvas.zoom) * Math.sqrt(graph.canvas.zoom)
+ (x - graph.canvas.offX) / graph.canvas.zoom;
my = (my - (y - graph.canvas.offY) / graph.canvas.zoom) * Math.sqrt(graph.canvas.zoom)
+ (y - graph.canvas.offY) / graph.canvas.zoom;
} else {
mx = (mx - x) / Math.sqrt(graph.canvas.zoom) + x;
my = (my - y) / Math.sqrt(graph.canvas.zoom) + y;
}
return dx <= mx && mx <= dx + dw && dy <= my && my <= dy + dh;
}
|
7433c9b7-4351-457e-ae2f-a6184cf49bc9
| 8
|
public void updateTileBar(ArrayList<Integer> pages, Color c, int RedGreenOrBlue){
for(int i = 0;i < pages.size(); i++){
if(pointersToRecolors[pages.get(i) - startingPage] == null){
addPortion(pages.get(i)-startingPage, c);
}
else {
Color currentPanelColor = pointersToRecolors[pages.get(i) - startingPage].getBackground();
if(RedGreenOrBlue == 1){
if(currentPanelColor.getColorComponents(null)[0]+c.getColorComponents(null)[0] < 1){
updatePortion(pages.get(i)-startingPage, new Color(currentPanelColor.getColorComponents(null)[0]+c.getColorComponents(null)[0], currentPanelColor.getColorComponents(null)[1], currentPanelColor.getColorComponents(null)[2]));
}
else {
updatePortion(pages.get(i)-startingPage, new Color((float)1.0, currentPanelColor.getColorComponents(null)[1], currentPanelColor.getColorComponents(null)[2]));
}
}
else if(RedGreenOrBlue == 2){
if(currentPanelColor.getColorComponents(null)[1]+c.getColorComponents(null)[1] < 1){
updatePortion(pages.get(i)-startingPage, new Color(currentPanelColor.getColorComponents(null)[0], currentPanelColor.getColorComponents(null)[1]+c.getColorComponents(null)[1], currentPanelColor.getColorComponents(null)[2]));
}
else {
updatePortion(pages.get(i)-startingPage, new Color(currentPanelColor.getColorComponents(null)[0], (float)1.0, currentPanelColor.getColorComponents(null)[2]));
}
}
else if(RedGreenOrBlue == 3){
if(currentPanelColor.getColorComponents(null)[2]+c.getColorComponents(null)[2] < 1){
updatePortion(pages.get(i)-startingPage, new Color(currentPanelColor.getColorComponents(null)[0], currentPanelColor.getColorComponents(null)[1], currentPanelColor.getColorComponents(null)[2]+c.getColorComponents(null)[2]));
}
else {
updatePortion(pages.get(i)-startingPage, new Color(currentPanelColor.getColorComponents(null)[0], currentPanelColor.getColorComponents(null)[1], (float)1.0));
}
}
}
}
}
|
a33c8dbf-a169-4e87-ae12-c09faec3f8e8
| 4
|
private static String byteToHex(byte[] messageDigest) {
StringBuilder buf = new StringBuilder();
for (byte b : messageDigest) {
int halfbyte = (b >>> 4) & 0x0F;
int two_halfs = 0;
do {
buf.append(
(0 <= halfbyte) && (halfbyte <= 9) ? (char) ('0' + halfbyte) : (char) ('a' + (halfbyte - 10)));
halfbyte = b & 0x0F;
} while (two_halfs++ < 1);
}
return buf.toString();
}
|
55c61bac-7458-4fb2-9752-f4c99f3af184
| 2
|
public synchronized int bytesCompleted(){
int num = 0;
for(Integer k : this.blocks.keySet()){
Block b = this.blocks.get(k);
if(b != null)
num += b.getLength();
}
return num;
}
|
eae2671b-9f7f-4c1c-a674-3dcad1bae701
| 8
|
public void angleDistanceBeforeStarted() {
if (score <= -anglebow.angle*5 || score <= 600 + anglebow.angle*5) {
if (score < -anglebow.angle*5) {
flydot.y += FLYDOT_JUMP_VY;
}
else if (score > -anglebow.angle*5) {
flydot.y += 1;
}
}
if (score <= 600 + anglebow.angle*5 || score <= -anglebow.angle*5) {
if (score < 600 + anglebow.angle*5) {
flydot.x += -vx;
}
else if (score > 600 + anglebow.angle*5) {
flydot.x += 1;
}
}
else {
flydot.update();
}
}
|
761b445e-4645-4978-a444-c7279f4168be
| 9
|
@Override
public String stringify(int level) {
ArrayList<String> strArray = new ArrayList<String>();
int width = 0;
for (int i = 0; i < length; ++i) {
JSON obj = mapArray.get(i);
String strJSON;
if (obj == null)
strJSON = "null";
else
strJSON = obj.stringify(level + 1);
width += strJSON.length() + 2;
strArray.add(strJSON);
}
if (width == 0)
width = 2;
String delim = "";
String indent = LINE_SEPARATOR;
StringBuilder sb = new StringBuilder("[");
int n = strArray.size();
if (widthForIndent >= 0 && width > widthForIndent) {
for (int i = 0; i < level; ++i)
indent += indentString;
delim += indent;
for (String e : strArray) {
sb.append(delim);
sb.append(indentString);
sb.append(e);
delim = "," + indent;
}
if (n > 0)
sb.append(indent);
} else {
for (String e : strArray) {
sb.append(delim);
sb.append(e);
delim = ", ";
}
}
sb.append("]");
return sb.toString();
}
|
2454be3b-d01f-4d54-98c1-8a75d0cda31d
| 9
|
private final void method2333(BufferedStream buffer, int i, int i_8_) {
anInt9517++;
if ((i_8_ ^ 0xffffffff) != -2) {
if ((i_8_ ^ 0xffffffff) == -3) {
int i_9_ = buffer.readUnsignedByte();
anIntArray9522 = new int[i_9_];
for (int i_10_ = 0; (i_10_ ^ 0xffffffff) > (i_9_ ^ 0xffffffff); i_10_++)
anIntArray9522[i_10_] = buffer.readUnsignedShort();
} else if ((i_8_ ^ 0xffffffff) == -4) {
int i_11_ = buffer.readUnsignedByte();
anIntArrayArray9515 = new int[i_11_][];
anIntArray9518 = new int[i_11_];
for (int i_12_ = 0; (i_12_ ^ 0xffffffff) > (i_11_ ^ 0xffffffff); i_12_++) {
int i_13_ = buffer.readUnsignedShort();
Class151 class151 = Class240.method3028((byte) 84, i_13_);
if (class151 != null) {
anIntArray9518[i_12_] = i_13_;
anIntArrayArray9515[i_12_] = new int[class151.anInt1842];
for (int i_14_ = 0; (class151.anInt1842 ^ 0xffffffff) < (i_14_ ^ 0xffffffff); i_14_++)
anIntArrayArray9515[i_12_][i_14_] = buffer.readUnsignedShort();
}
}
} else if (i_8_ == 4) {
aBoolean9521 = false;
}
} else {
aStringArray9529 = Class106.method1120((byte) -102, buffer.readString(), '<');
}
if (i != 0) {
method2326(21, true, -113);
}
}
|
00208511-016d-4a42-aff4-1a263a2b3364
| 7
|
private void checkWater() {
if(this.water >= 10){
this.water = 10;
this.waterStatus = "Fulness";
this.isAlive = true;
}
if(this.water < 10 && this.water >= 7){
this.waterStatus = "Dursty";
this.isAlive = true;
}
if(this.water < 7 && this.water > 2){
this.waterStatus = "Very Hungry";
this.isAlive = true;
}
if(this.water == 2){
this.waterStatus = "Very Very Hungry ";
this.isAlive = true;
}
if(this.water <= 0){
this.water = 0;
this.waterStatus = "Died of Starvation";
this.isAlive = false;
}
this.water = water - 0.0005;
}
|
9ff3531e-9015-44c3-afa9-b41b83f97cd5
| 5
|
@Override
public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) {
if (args.length == 0) {
Main.courier.send(sender, "requires-argument", "message", 0);
return false;
}
final String text = Add.join(args, " ");
if (text == null) return false;
final long set = System.currentTimeMillis();
final String from = ( sender instanceof Player ? ((Player) sender).getDisplayName() : Main.courier.format("console", sender.getName()) );
this.records.add(set, from, ChatColor.translateAlternateColorCodes('&', text));
this.doorman.clearLast();
for (final Player player : Bukkit.getOnlinePlayers()) {
Main.courier.submit(RecipientList.Sender.create(player), this.records.declare(player));
this.doorman.updateLast(player.getName());
}
if (!(sender instanceof Player)) {
Main.courier.submit(RecipientList.Sender.create(sender), this.records.declare(sender));
this.doorman.updateLast(sender.getName());
}
return true;
}
|
3a1f0af1-b192-434e-a4fc-9ae8aa5ba048
| 5
|
private static void updateMaps () {
for (int i = 0; i < mapPanels.size(); i++) {
if (selectedMap == i) {
String packs = "";
if (Map.getMap(getIndex()).getCompatible() != null) {
packs += "<p>This map works with the following packs:</p><ul>";
for (String name : Map.getMap(getIndex()).getCompatible()) {
packs += "<li>" + (ModPack.getPack(name) != null ? ModPack.getPack(name).getName() : name) + "</li>";
}
packs += "</ul>";
}
mapPanels.get(i).setBackground(UIManager.getColor("control").darker().darker());
mapPanels.get(i).setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
LaunchFrame.updateMapInstallLocs(Map.getMap(getIndex()).getCompatible());
File tempDir = new File(OSUtils.getCacheStorageLocation(), "Maps" + File.separator + Map.getMap(getIndex()).getMapName());
mapInfo.setText("<html><img src='file:///" + tempDir.getPath() + File.separator + Map.getMap(getIndex()).getImageName() + "' width=400 height=200></img> <br>"
+ Map.getMap(getIndex()).getInfo() + packs);
mapInfo.setCaretPosition(0);
} else {
mapPanels.get(i).setBackground(UIManager.getColor("control"));
mapPanels.get(i).setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
}
}
|
5a2f4ca3-79b0-4497-87bb-4521cff62540
| 4
|
public boolean addPolyNode(int coefficient, int exponent){
//Check to see if exponent is a positive number(-1 = no exponent)
if(exponent < -1)
throw new IllegalArgumentException("Exponent must be a positive"
+ " integer.");
//Check to see if Polynomial is empty
if(isEmpty()){
firstNode = new PolyNode(coefficient, exponent, null);
return true;//A change was made to the Polynomial
}
else if(!isEmpty()){
PolyNode current = firstNode;
while(current.getNext() != null)
current = current.getNext();
current.setNext(new PolyNode(coefficient, exponent, null));
return true;//A change was made to the Polynomial
}
return false;//No changes where made to the Polynomial
}
|
e2d8158b-3f35-4b04-9842-9a73c20173d7
| 0
|
@Override
public void documentRemoved(DocumentRepositoryEvent e) {}
|
96e8dd1f-21b0-454c-8094-ef6eeb4cbfff
| 5
|
public static byte[] encryptSecretKey(SecretKey sk,PublicKey pk)
{
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pk);
return cipher.doFinal(sk.getEncoded());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}catch (InvalidKeyException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
return null;
}
|
28fc4b78-f732-4462-b53e-0700df0daad3
| 9
|
public static KAryTreeNode<Integer> genRandomIntegerKAryTree(int k, int treeNodeCount, boolean full) {
Random random = new Random();
KAryTreeNode<Integer> root = new KAryTreeNode<Integer>(random.nextInt(1000), k);
int currNodeCount = 0;
Queue<KAryTreeNode<Integer>> queue = new LinkedList<KAryTreeNode<Integer>>();
queue.offer(root);
while(!queue.isEmpty()) {
KAryTreeNode<Integer> node = queue.poll();
int currNodeChildrenCount = full ? k:random.nextInt(k+1);
for(int i=0; i<currNodeChildrenCount&&currNodeCount<treeNodeCount; i++) {
KAryTreeNode<Integer> child = new KAryTreeNode<Integer>(random.nextInt(1000), k);
node.children[i] = child;
queue.offer(child);
currNodeCount++;
}
if(queue.isEmpty() && currNodeCount<treeNodeCount) {
currNodeChildrenCount = random.nextInt(k+1);
while(currNodeChildrenCount == 0) {
currNodeChildrenCount = random.nextInt(k+1);
}
for(int i=0; i<k&&currNodeCount<treeNodeCount; i++) {
KAryTreeNode<Integer> child = new KAryTreeNode<Integer>(random.nextInt(1000), k);
node.children[i] = child;
queue.offer(child);
currNodeCount++;
}
}
}
return root;
}
|
04b4d8ff-53b0-4ac8-b8b0-b0637a06ddad
| 8
|
public static int countNeighbours(boolean[][] world, int col, int row) {
int c = 0;
if (getCell(world, col - 1, row - 1) == true) {
c += 1;
}
if (getCell(world, col, row - 1) == true) {
c += 1;
}
if (getCell(world, col + 1, row - 1) == true) {
c += 1;
}
if (getCell(world, col - 1, row) == true) {
c += 1;
}
if (getCell(world, col + 1, row) == true) {
c += 1;
}
if (getCell(world, col - 1, row + 1) == true) {
c += 1;
}
if (getCell(world, col, row + 1) == true) {
c += 1;
}
if (getCell(world, col + 1, row + 1) == true) {
c += 1;
}
return c;
}
|
e6d78b26-0445-46ed-ae24-52e8a26529e4
| 5
|
private void parseAndAddBiomes(Collection<ParameterNode> nodes) throws Exception {
for (ParameterNode p : nodes) {
if (!p.isGroup()) {
continue;
}
ParameterGroup g = (ParameterGroup) p;
Logger.getLogger(WorldGenerator.class.getName()).log(Level.SEVERE, g.toString());
if (!g.hasChild("color")) {
Logger.getLogger(WorldGenerator.class.getName()).log(Level.SEVERE, "Has no child color");
}
if (!g.hasChild("name")) {
Logger.getLogger(WorldGenerator.class.getName()).log(Level.SEVERE, "Has no child name");
}
if (terrain.getBiomeMap() == null) {
Logger.getLogger(WorldGenerator.class.getName()).log(Level.SEVERE, "Biome map null");
}
terrain.getBiomeMap().addBiomeType((ParameterGroup) p);
}
}
|
7be638e6-7c78-4905-bbf0-bd59df254314
| 9
|
public boolean isPrimitive() {
if (this.type.equals("void")) {
return true;
} else if (this.type.equals("byte")) {
return true;
} else if (this.type.equals("char")) {
return true;
} else if (this.type.equals("double")) {
return true;
} else if (this.type.equals("float")) {
return true;
} else if (this.type.equals("int")) {
return true;
} else if (this.type.equals("long")) {
return true;
} else if (this.type.equals("short")) {
return true;
} else if (this.type.equals("boolean")) {
return true;
} else {
return false;
}
}
|
19d496c3-34fb-494b-97a9-044b19ffacc3
| 6
|
private void setLookAndFeel() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (UnsupportedLookAndFeelException e) {
// handle exception
} catch (ClassNotFoundException e) {
// handle exception
} catch (InstantiationException e) {
// handle exception
} catch (IllegalAccessException e) {
// handle exception
}
}
|
238f4791-d08a-40f7-b9c9-7eadbed61609
| 1
|
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JFrame frame = new JFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
|
82fff00f-684f-4b1e-baea-1ba5615d26a4
| 8
|
public static String rexecute(String command, String success, String failure){
//Queries the data class for login credentials. The data class directly queries
//A local embedded database for the information.
String username = data.getUser();
String hostname = data.getHost();
String password = data.getPass();
int port = data.getPort();
try{
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session=jsch.getSession(username, hostname, port);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
byte[] tmp=new byte[1024];
while(true){
StringBuilder outputVar = new StringBuilder();
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
System.out.print(new String(tmp, 0, i));
// outputVar.append(new String(tmp, 0, i));
// outputVar.append("\n");
}
//String outputVar2 = outputVar.toString();
// General.shellOut(outputVar.toString());
if(channel.isClosed()){
System.out.println("exit-status: "+channel.getExitStatus());
if(channel.getExitStatus() == 0){
General.infoBox(success, "Success!");
}
else{
General.infoBox(failure, "Failure");
}
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
System.out.println("DONE");
} catch (IOException ex) {
java.util.logging.Logger.getLogger(SSH.class.getName()).log(Level.SEVERE, null, ex);
} catch (JSchException ex) {
java.util.logging.Logger.getLogger(SSH.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
|
70720b9a-5561-4b80-b251-5b5785f12c01
| 5
|
public synchronized void unblock() throws IOException {
boolean running = false;
if (state == RUNNING || state == CONFIRMED || state == ERROR) {
running = true;
}
state = CLOSED;
if (socket != null) {
socket.close();
socket = null;
LOGGER.log(Level.INFO, "Successfully closed Sock");
}
if (!running) {
close();
}
}
|
5b47b8a2-deb7-47cd-b655-5b0deb65f798
| 5
|
public void openDoor(String name, InternalDoor door) {
Avatar a = null;
for(Avatar b: avatars){
if(b.getName().equals(name)){
a = b;
}
}
if(a!= null){
String locName = a.getLocationName();
String doorName = door.getName();
Location l = locations.get(locName);
for(GameObject g: l.getAllObjects()){
if(g.getName().equals(doorName)){
InternalDoor d = (InternalDoor) g;
d.setLocked(false);
}
}
}
}
|
9d001093-fb6c-4755-97db-4dee0e3ce8fa
| 1
|
@Override
protected TreeContainerRow clone() {
TreeContainerRow other = (TreeContainerRow) super.clone();
ArrayList<TreeRow> children = new ArrayList<>(mChildren.size());
for (TreeRow row : mChildren) {
row = row.clone();
children.add(row);
row.mParent = other;
}
other.mChildren = children;
other.renumber(0);
return other;
}
|
7cf9f41c-5cd6-4ebd-8ad3-b2fd5d4996dd
| 5
|
public List<ReceiptSaleSummaryBean> getCashOutData(final Long customerGroup, final Long revision) {
List<ReceiptSaleSummaryBean> ret = new ArrayList<ReceiptSaleSummaryBean>();
List<Receipt> receipts = null;
Currency currency = null;
try {
currency = CurrencyApiService.getByNumber(DbReader.getToken(), Long.valueOf(1));
receipts = ReceiptApiService.getPageByCustomerGroup(DbReader.getToken(), Long.valueOf(123456));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (receipts != null) {
for (Receipt receipt : receipts) {
try {
List<Sale> sales = SaleApiService.getAllFromReceipt(DbReader.getToken(), receipt.getUuid());
for (Sale sale : sales) {
Cashier cashier = CashierApiService.getByNumber(DbReader.getToken(),
Long.valueOf(sale.getCashier()));
ret.add(new ReceiptSaleSummaryBean("", "", currency, receipt, cashier, sale));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return ret;
}
|
fcacde1c-12e1-4602-907f-03be2d3585f2
| 2
|
private void validerHeuresTransferees() {
if (declaration.getHeuresTransfereesDuCyclePrecedent() < 0) {
declaration.setHeuresTransfereesDuCyclePrecedent(0);
declaration.ajouterMessageErreur("Nombre d'heures transférées du" +
" cycle précédent est négatif. La valeur 0 sera utilisée.");
} else if (declaration.getHeuresTransfereesDuCyclePrecedent() > 7) {
declaration.setHeuresTransfereesDuCyclePrecedent(7);
declaration.ajouterMessageErreur("Nombre d'heures transférées du" +
" cycle précédent est supérieur à 7. La valeur 7 sera utilisée.");
}
}
|
a2af7a1f-6d95-4b3b-9275-1830a64c5542
| 8
|
@Override
public List<ChessPosition> getTargetPos(ChessPosition current) {
List<ChessPosition> pos = new ArrayList<ChessPosition>();
ChessPosition CpTemp;
int x, y, upBound, lowBound, leftBound, rightBound, value;
int dx[] = { 0, 1, 1, -1, -1 };
int dy[] = { 0, 1, -1, 1, -1 };
// khoi tao gioi han di chuyen cho quan sy
x = current.getCol();
y = current.getRow();
value = board.getTable()[y][x];
if (y <= 2) {
upBound = 0;
lowBound = 2;
} else {
upBound = 7;
lowBound = 9;
}
leftBound = 3;
rightBound = 5;
// Xet 4 o quanh o sy, kiem tra hop le, neu hop le thi cho di
for (int i = 1; i <= 4; i++) {
x = current.getCol() + dx[i];
y = current.getRow() + dy[i];
if (((x >= leftBound) && (x <= rightBound))
&& ((y >= upBound) && (y <= lowBound))) {
if (board.getTable()[y][x] != 0) {
if (board.getTable()[y][x] * value < 0) {
CpTemp = new ChessPosition(x, y, true);
} else {
CpTemp = new ChessPosition(x, y, false);
}
pos.add(CpTemp);
}
}
}
return pos;
}
|
6dcedda8-618f-460a-83d6-f963b40ce546
| 6
|
public boolean validateLocation(Point cellLocation) {
MapObstacle obstacle = getMapObstacle(cellLocation);
if (obstacle != null) {
/* Note that this implementation provide a default obstacle event
* handler "this.obstacleEvent(obstacle)" - see method above - that
* can be overridden if the user of this class passes in another
* class that implements the ObstacleEventHandler interface.
*/
if (getObstacleHandler() != null) {
getObstacleHandler().obstacleEvent(obstacle);
} else {
this.obstacleEvent(obstacle);
}
return false;
}
MapPortal portal = getMapPortal(cellLocation);
if (portal != null) {
if (getPortalHandler() != null){
getPortalHandler().portalEvent(portal);
} else {
this.portalEvent(portal);
}
}
// if (hitTest(cellLocation, getPortalLocations())) {
// System.out.println("Hey... need to go somewhere else!");
// //put an event handler here!
// if (getPortalHandler() != null) {
// //use the getMapPortal method to pass the portal back to the event handler...
// getPortalHandler().MovementEvent(Map.MovementEventType.OBSTACLE);
// }
// }
MapItem mapItem = getMapItem(cellLocation);
if (mapItem != null) {
// System.out.println(getMapItem(cellLocation).getEnemy().getName());
//put an event handler here!
if (getItemHandler() != null) {
getItemHandler().itemEvent(mapItem);
}
}
return true;
}
|
ea3f97d6-8fea-4dd0-808a-c0b2e4cad1dc
| 4
|
private int jjMoveStringLiteralDfa33_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjMoveNfa_0(0, 32);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
return jjMoveNfa_0(0, 32);
}
switch(curChar)
{
case 49:
return jjMoveStringLiteralDfa34_0(active0, 0x800000000000000L);
case 50:
return jjMoveStringLiteralDfa34_0(active0, 0x7ffe00000000000L);
default :
break;
}
return jjMoveNfa_0(0, 33);
}
|
9e387426-2934-4876-aac3-37d37c74c54a
| 0
|
public UserImplXml() throws DaoException {
super("/xml/User.xml", User.class);
}
|
44863a5e-da86-4440-a209-5068b9ddead1
| 6
|
public static void main(String[] args) {
int[][] arr = {{75}, {95, 64}, {17, 47, 82}, {18, 35, 87, 10}, {20, 4, 82, 47, 65}, {19, 1, 23, 75, 3, 34}, {88, 2, 77, 73, 7, 63, 67}, {99, 65, 4, 28, 6, 16, 70, 92}, {41, 41, 26, 56, 83, 40, 80, 70, 33}, {41, 48, 72, 33, 47, 32, 37, 16, 94, 29}, {53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14}, {70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57}, {91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48}, {63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31}, {04, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23}};;
int[][] resArr = new int[15][16];
resArr[0][0] = arr[0][0];
for(int i = 1; i < 15; i++)
{
for(int j = 0; j <= i; j++)
{
if(j != 0)
{
if(resArr[i-1][j-1] < resArr[i-1][j])
resArr[i][j] = arr[i][j] + resArr[i-1][j];
else
resArr[i][j] = arr[i][j] + resArr[i-1][j-1];
}
else
resArr[i][j] = arr[i][j] + resArr[i-1][j];
}
}
int res = 0;
for(int i = 0; i < 15; i++)
{
if(resArr[14][i] > res)
res = resArr[14][i];
}
System.out.println(res);
}
|
26552adb-3cfb-4f08-9be6-4f3d97c5c78e
| 7
|
public static void equateValues(Proposition prop, Stella_Object term1, Stella_Object term2) {
if (Stella_Object.eqlP(term1, term2)) {
}
else if (Logic.skolemP(term1)) {
Skolem.bindSkolemToValue(((Skolem)(term1)), term2, false);
}
else if (Logic.skolemP(term2)) {
Skolem.bindSkolemToValue(((Skolem)(term2)), term1, false);
}
else if (Stella_Object.stellaCollectionP(term1) &&
Stella_Object.stellaCollectionP(term2)) {
Proposition.equateCollections(prop, ((Collection)(term1)), ((Collection)(term2)));
}
else if (Stella_Object.isaP(term1, Logic.SGT_PL_KERNEL_KB_INTERVAL_CACHE) &&
Stella_Object.isaP(term2, Logic.SGT_PL_KERNEL_KB_INTERVAL_CACHE)) {
edu.isi.powerloom.pl_kernel_kb.IntervalCache.unifyIntervalCaches(((edu.isi.powerloom.pl_kernel_kb.IntervalCache)(term1)), ((edu.isi.powerloom.pl_kernel_kb.IntervalCache)(term2)), Logic.SGT_PL_KERNEL_KB_ge);
edu.isi.powerloom.pl_kernel_kb.IntervalCache.unifyIntervalCaches(((edu.isi.powerloom.pl_kernel_kb.IntervalCache)(term2)), ((edu.isi.powerloom.pl_kernel_kb.IntervalCache)(term1)), Logic.SGT_PL_KERNEL_KB_ge);
}
else {
Proposition.signalUnificationClash(prop, term1, term2);
}
}
|
40f4fc29-273d-4813-b65d-839eda6bef98
| 2
|
public static void executeThreads(Runnable... runnables) {
if (exct == null) {
exct = Executors.newCachedThreadPool();
}
for (Runnable r : runnables) {
exct.execute(r);
}
}
|
c5a016da-58e7-477d-8d11-f4d74f63fa8f
| 9
|
public static void main(String[] args) {
File file = null;
if (args.length == 0) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FileFilter() {
public boolean accept(File f) {
if (f.isDirectory())
return true;
String filename = f.getName();
return filename.toLowerCase().endsWith(".ged");
}
public String getDescription() {
return "GEDCOM files";
}
});
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
file = chooser.getSelectedFile();
} else {
file = new File(args[0]);
}
if (file == null) {
System.err.println("No file specified");
System.exit(1);
}
try {
GedcomReader reader = new GedcomReader(file);
FamilyHistoryFactory factory = new FamilyHistoryFactory();
boolean debugging = Boolean.getBoolean("debug");
factory.setDebugging(debugging);
factory.processGedcomFile(reader);
System.out.println("The GEDCOM file contained:");
System.out.println("\t" + factory.getFamilies().size()
+ " families");
System.out.println("\t" + factory.getPeople().size()
+ " individuals");
System.out.println("\t" + factory.getNotes().size() + " notes");
System.out.println("\t" + factory.getSources().size() + " sources");
Set families = factory.getFamilies();
Runtime runtime = Runtime.getRuntime();
System.gc();
long totalmem = runtime.totalMemory() / 1024;
long freemem = runtime.freeMemory() / 1024;
long usedmem = totalmem - freemem;
System.out.println("Memory: total=" + totalmem + "kb, free="
+ freemem + "kb, used=" + usedmem + "kb");
if (!Boolean.getBoolean("list"))
System.exit(0);
for (Iterator iter = families.iterator(); iter.hasNext();) {
System.out.println("\n--- FAMILY ---");
Family family = (Family) iter.next();
showPerson(family.getHusband(), "Husband");
showPerson(family.getWife(), "Wife");
Date marriage = family.getMarriageDate();
if (marriage != null)
System.out.println("\nMarried: " + marriage);
for (int i = 1; i <= family.getChildCount(); i++)
showPerson(family.getChild(i), "Child #" + i);
}
} catch (Exception e) {
e.printStackTrace();
}
}
|
3d030a38-ef2f-4aeb-8e19-e5a1fb6f840c
| 6
|
private void importConfig(){
File configFile = new File("voidCosmos.conf");
try {
configHashMap = SimpleConfig.getHashMap(configFile);
} catch (FileNotFoundException e) {
JFileChooser jf = new JFileChooser();
jf.setFileSelectionMode(JFileChooser.FILES_ONLY); //only files
jf.setMultiSelectionEnabled(false); //only one file
while (!configFile.exists()){
jf.setCurrentDirectory(new File(".")); //start file chooser in the directory of the game jar
if ( jf.showOpenDialog(null) != JFileChooser.APPROVE_OPTION ){
JOptionPane.showMessageDialog(null, "You MUST choose a configuration file.");
continue;
}
configFile = jf.getSelectedFile();
}
try {
configHashMap = SimpleConfig.getHashMap(configFile);
} catch (FileNotFoundException e1) {
// wut?
e1.printStackTrace();
}
}
//=============================
//== Configuration Variables ==
//=============================
try{
gConstant = Double.parseDouble(configHashMap.get("gConstant"));
startFullScreen = Boolean.parseBoolean(configHashMap.get("startFullScreen"));
String displaySizeStr = configHashMap.get("displaySize");
//account for uppercase or lowercase x
int displaySizeXIndex = (displaySizeStr.indexOf("x") != -1) ? displaySizeStr.indexOf("x") : displaySizeStr.indexOf("X");
int displayWidth = Integer.parseInt(displaySizeStr.substring(0, displaySizeXIndex));
int displayHeight = Integer.parseInt(displaySizeStr.substring(displaySizeXIndex + 1));
displaySize = new Dimension(displayWidth, displayHeight);
zNear = Float.parseFloat(configHashMap.get("zNear"));
zFar = Float.parseFloat(configHashMap.get("zFar"));
camSpeed = Float.parseFloat(configHashMap.get("camSpeed"));
}catch(Exception e){
System.err.println("Your configuration file is faulty in some way!");
}
//=============================
}
|
aebd4d32-5b8f-4a1e-a7e3-5f59cd34cc9b
| 0
|
public void desenhar(Graphics2D g2) {
Rectangle2D.Double retangulo = new Rectangle2D.Double(this.getPosX(), this.getPosY(), largura, altura);
g2.draw(retangulo);
}
|
55b57bbd-64c4-4514-ba4d-e474b8e21ae6
| 8
|
private void saveConversionRules(Map<String, Set<String>> conversionRules, //
Map<String, Set<String>> conflictRules, Map<String, Set<String>> exclusionRules) throws IOException {
List<String> modeUsed = new Vector<String>();
modeUsed.addAll(conversionRules.keySet());
for (String m : conflictRules.keySet()) {
if (!modeUsed.contains(m)) modeUsed.add(m);
}
for (String m : exclusionRules.keySet()) {
if (!modeUsed.contains(m)) modeUsed.add(m);
}
for (String mode : modeUsed) {
if (null != conversionRules.get(mode)) {
writer.write(generateConversionRuleStr(mode, conversionRules.get(mode), DflTheoryConst.SYMBOL_MODE_CONVERSION));
writer.write(LINE_SEPARATOR);
}
if (null != conflictRules.get(mode)) {
writer.write(generateConversionRuleStr(mode, conflictRules.get(mode), DflTheoryConst.SYMBOL_MODE_CONFLICT));
writer.write(LINE_SEPARATOR);
}
if (null != exclusionRules.get(mode)) {
writer.write(generateConversionRuleStr(mode, exclusionRules.get(mode), DflTheoryConst.SYMBOL_MODE_EXCLUSION));
writer.write(LINE_SEPARATOR);
}
writer.write(LINE_SEPARATOR);
}
}
|
5488e290-44f8-48a2-801c-4c7d1b1298cd
| 9
|
public void setOptions(String[] options) throws Exception {
String tmpStr;
setRawOutput(Utils.getFlag('D', options));
setRandomizeData(!Utils.getFlag('R', options));
tmpStr = Utils.getOption('O', options);
if (tmpStr.length() != 0)
setOutputFile(new File(tmpStr));
tmpStr = Utils.getOption("dir", options);
if (tmpStr.length() > 0)
setTestsetDir(new File(tmpStr));
else
setTestsetDir(new File(System.getProperty("user.dir")));
tmpStr = Utils.getOption("prefix", options);
if (tmpStr.length() > 0)
setTestsetPrefix(tmpStr);
else
setTestsetPrefix("");
tmpStr = Utils.getOption("suffix", options);
if (tmpStr.length() > 0)
setTestsetSuffix(tmpStr);
else
setTestsetSuffix(DEFAULT_SUFFIX);
tmpStr = Utils.getOption("find", options);
if (tmpStr.length() > 0)
setRelationFind(tmpStr);
else
setRelationFind("");
tmpStr = Utils.getOption("replace", options);
if ((tmpStr.length() > 0) && (getRelationFind().length() > 0))
setRelationReplace(tmpStr);
else
setRelationReplace("");
tmpStr = Utils.getOption('W', options);
if (tmpStr.length() == 0)
throw new Exception("A SplitEvaluator must be specified with the -W option.");
// Do it first without options, so if an exception is thrown during
// the option setting, listOptions will contain options for the actual
// SE.
setSplitEvaluator((SplitEvaluator)Utils.forName(SplitEvaluator.class, tmpStr, null));
if (getSplitEvaluator() instanceof OptionHandler)
((OptionHandler) getSplitEvaluator()).setOptions(Utils.partitionOptions(options));
}
|
66acecda-bf13-4f58-b665-4af59ba2c2e2
| 9
|
@Override
public void run()
{
//streams
BufferedReader bufferedReader = null;
DataOutputStream dataOutputStream = null;
try
{
//create wrapper streams
bufferedReader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
dataOutputStream = new DataOutputStream(this.socket.getOutputStream());
//header and dispatcher
RequestHeader requestHeader = null;
Dispatcher dispatcher = null;
try
{
//read headers
requestHeader = new RequestHeader();
requestHeader.gather(bufferedReader);
requestHeader.sanitise();
//dispatch
dispatcher = new Dispatcher(this.server, requestHeader, dataOutputStream);
dispatcher.dispatch();
//log
if (this.server.getConfiguration().getLogRequests())
this.server.getRequestLogger().logSuccess(this.socket, requestHeader, dispatcher);
}
catch (HttpException httpException)
{
try
{
//http error
dataOutputStream.write(PageGenerator.generatePageCompletelyFor(this.server, httpException).assemble().getBytes());
}
catch (IOException ioException)
{
}
//log
if (this.server.getConfiguration().getLogErrors())
this.server.getErrorLogger().logFailure(this.socket, requestHeader, httpException);
}
catch (Exception exception)
{
try
{
//generic error
dataOutputStream.write(PageGenerator.generatePageCompletelyFor(this.server, "Server Error", exception.getMessage()).assemble().getBytes());
}
catch (IOException ioException)
{
}
//log
if (this.server.getConfiguration().getLogErrors())
this.server.getExceptionLogger().logException(this.socket, requestHeader, exception);
}
}
catch (Exception exception)
{
}
finally
{
try
{
//close
bufferedReader.close();
dataOutputStream.close();
}
catch (IOException ioException)
{
}
}
}
|
2432bd22-96e9-4e89-832d-6bddb68f50a8
| 6
|
public static int maxProduct (int[] seq)
{
int max_product = 1, min_product = 1, max_sofar = 0xFFFFFFFF;
int temp_max_begin = -1;
int temp_min_begin = -1;
for (int i = 0; i < seq.length; i++) {
if (seq[i] > 0) {
max_product *= seq[i];
min_product = min(min_product * seq[i], 1);
if (temp_max_begin == -1)
temp_max_begin = i;
} else if (seq[i] == 0) {
max_product = 1;
min_product = 1;
temp_max_begin = -1;
temp_min_begin = -1;
} else {
int temp = max_product;
int swap = -1;
if (min_product*seq[i] > 1) {
swap = temp_max_begin;
temp_max_begin = temp_min_begin;
max_product = min_product*seq[i];
} else {
temp_max_begin = -1;
max_product = 1;
}
//max_product = max (min_product*seq[i], 1);
temp_min_begin = swap;
min_product = temp * seq[i];
}
if (max_product > max_sofar) {
max_sofar = max_product;
start = temp_max_begin;
end = i;
}
}
return (max_sofar);
}
|
01becc15-48de-458d-8ff4-e52382834a0a
| 1
|
public void draw(Graphics2D g) {
g.drawImage(tileTexture, posX, posY, 16, 16, null);
if(icon != null)
g.drawImage(icon.getSubimage(0, 0, 32, 32), posX, posY, 16, 16, null);
}
|
61f2acc6-0f30-44a3-8382-3d4ab0b49421
| 5
|
public static void addBan(String victim, int type, long length, String mod,
String reason, int display) {
PreparedStatement ps = null;
ResultSet rs = null;
// add player
try {
ps = conn
.prepareStatement(
"INSERT INTO bans (`player_id`, `type`, `length`, `mod`, `date`, `reason`, `display`) VALUES(?,?,?,?,?,?,?);",
Statement.RETURN_GENERATED_KEYS);
ps.setInt(1, HashMaps.getPlayerList(victim.toLowerCase()));
ps.setInt(2, type);
ps.setLong(3, length);
ps.setInt(4, HashMaps.getPlayerList(mod.toLowerCase()));
ps.setObject(5, ArgProcessing.getDateTime());
ps.setString(6, reason);
ps.setInt(7, display);
ps.executeUpdate();
rs = ps.getGeneratedKeys();
if (type == 1 || type == 2) {
if (rs.next()) {
Integer bId = rs.getInt(1);
HashMaps.setBannedPlayers(victim.toLowerCase(), bId);
if (type == 2) {
HashMaps.setTempBannedTime(bId, length);
}
SeruBans.printInfo("Banned: " + victim + " Ban Id: " + bId);
} else {
SeruBans.printInfo("Error adding ban!");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
|
dce5f6df-f7b5-45ff-a7a8-e9399e5bc8ac
| 6
|
public void paintComponent(Graphics g2)
{
final int w = getWidth() / 2 + 1;
final int h = getHeight() / 2 + 1;
if (img == null || img.getWidth(null) != w || img.getHeight(null) != h)
{
img = createImage(w, h);
final Graphics g = img.getGraphics();
for (int x = 0; x <= w / 32; x++)
{
for (int y = 0; y <= h / 32; y++)
{
g.drawImage(bgImage, x * 32, y * 32, null);
}
}
if (g instanceof Graphics2D)
{
final Graphics2D gg = (Graphics2D) g;
int gh = 1;
gg.setPaint(new GradientPaint(new Point2D.Float(0.0F, 0.0F),
new Color(553648127, true),
new Point2D.Float(0.0F, gh), new Color(0, true)));
gg.fillRect(0, 0, w, gh);
gh = h;
gg.setPaint(new GradientPaint(new Point2D.Float(0.0F, 0.0F),
new Color(0, true), new Point2D.Float(0.0F, gh),
new Color(1610612736, true)));
gg.fillRect(0, 0, w, gh);
}
g.dispose();
}
g2.drawImage(img, 0, 0, w * 2, h * 2, null);
}
|
55b08c55-5588-4508-af26-2514682b55dc
| 3
|
public static Database createDatabase(DatabaseConfig config) throws InvalidConfigurationException {
if (!config.isValid())
throw new InvalidConfigurationException(
"The configuration is invalid, you don't have enought parameters for that DB : "
+ config.getType());
switch (config.getType()) {
case MySQL:
return new MySQL(config.getLog(), config.getParameter(Parameter.PREFIX),
config.getParameter(Parameter.HOSTNAME),
Integer.parseInt(config.getParameter(Parameter.PORTNMBR)),
config.getParameter(Parameter.DATABASE),
config.getParameter(Parameter.USERNAME),
config.getParameter(Parameter.PASSWORD));
case SQLite:
return new SQLite(config.getLog(), config.getParameter(Parameter.PREFIX),
config.getParameter(Parameter.FILENAME),
config.getParameter(Parameter.LOCATION));
default:
return null;
}
}
|
e6f11eeb-0f6c-42c4-8b6c-24fa067e944b
| 1
|
public void addErrorMessage(BeamMeUpMQError errorMessage) {
if (this.errorMessages == null) {
this.errorMessages = new ArrayList<BeamMeUpMQError>(2);
}
this.errorMessages.add(errorMessage);
}
|
02a2a2bd-ee18-4a4f-a012-64b125d02694
| 6
|
public void drawState(int x, int y){
/* State Drawing Option
* 0 = Regular drawing
* 1 = Checker Board pattern
* 2 = Randomized
* 3 = Randomized/Checker Board
*/
if(rcflag){if(sdo == 1){ stateCheckDraw(x,y, false);}else{stateAltDraw(x,y);}}
else{
switch(sdo){
case 0: stateDraw(x,y); break;
case 1: stateCheckDraw(x,y, true); break;
case 2: stateRandDraw(x,y); break;
case 3: stateRCDraw(x,y); break;
default: stateDraw(x,y); break;}}
}
|
94ac2a76-e38a-4a37-a642-6d63583df4f4
| 7
|
private void MovieSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MovieSearchButtonActionPerformed
String search = MovieNameTextField.getText();
String movieReturn;
boolean wordSearched;
wordSearched = Pattern.compile("[a-zA-z].*").matcher(search).matches();
if (wordSearched) {
out.println("2!" + search);
int x = 0;
try {
movieReturn = in.readLine();
if (movieReturn.equals("0")) {
throw new noMovieException();
} else {
String columnNames[] = {"Movie", "Genre"};
String[] genreArray = movieReturn.split("!");
Object rows[][] = new Object[(genreArray.length)][2];
for (int i = 0; i < genreArray.length; i++) {
if (i % 2 == 0) {
rows[x][0] = genreArray[i];
} else {
rows[x][1] = genreArray[i];
}
if (i % 2 != 0) {
x++;
}
}
SearchTable = new JTable(rows, columnNames);
SearchScrollPane.getViewport().add(SearchTable);
}
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e, "Error", 0);
} catch (noMovieException e) {
JOptionPane.showMessageDialog(null, "No movie found with entered argument.", "Message", 1);
}
} else {
JOptionPane.showMessageDialog(null, "Text area is empty!!", "Message", 0);
}
}//GEN-LAST:event_MovieSearchButtonActionPerformed
|
9a8ae572-8eba-49fd-adb2-1750a4f1155f
| 8
|
private String convertFileToString(File file) {
final int bufferSize = 1024;
if (file != null && file.exists() && file.canRead() && !file.isDirectory()) {
Writer writer = new StringWriter();
InputStream is = null;
char[] buffer = new char[bufferSize];
try {
is = new FileInputStream(file);
Reader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ignore) {
}
}
}
return writer.toString();
} else {
return "";
}
}
|
208513dc-11d8-46ca-92da-93b0fbce76e6
| 7
|
public static Map<String, String> GetEntityColumnsWithParameters(Class<?> c, boolean hasAutoGenerated) {
Map<String, String> res = new HashMap<String, String>();
for (Field field : Arrays.asList(c.getDeclaredFields())) {
if ((field.isAnnotationPresent(Column.class) && hasAutoGenerated)
|| (field.isAnnotationPresent(Column.class) && !hasAutoGenerated
&& !(field.isAnnotationPresent(AutoIncremented.class)))) {
String name = field.getAnnotation(Column.class).name();
res.put(name, String.format(":%s", name));
}
}
return res;
}
|
45afee7f-002e-4ca7-9763-baeae7dc5f9c
| 4
|
@SuppressWarnings("unchecked")
public void handshake(Byte destination) {
System.out.println("Handshaking initialized");
lock.lock();
byte sequence = (byte) (new Random()).nextInt();
while (sequence == 0)
sequence = (byte) (new Random()).nextInt();
sequencer.setSequenceTo(destination, sequence);
System.out.println("Sequencer aware of new sequencenr: " + sequence);
Entry<Byte, Byte> connection = null;
try {
Object temp = router.getRoute(new Byte(destination));
if (temp instanceof Entry)
connection = (Entry<Byte, Byte>) temp;
} catch (RouteNotFoundException e1) {
System.out
.println("Error finding route. Possibly no route to that host.");
lock.unlock();
return;
}
SmallPacket dp;
try {
dp = new SmallPacket(IntegrationProject.DEVICE, destination,
connection.getValue(), (byte) 0x0, new byte[] { sequence },
false, false, false, false);
send(dp); // We cannot assume
send(dp); // the first packet
send(dp); // actually arrives
// dp = new SmallPacket(IntegrationProject.DEVICE, destination,
// connection.getValue(), (byte) 0x0, eh.getPubKeyPacket(),
// false, false, false, false);
// send(dp); // We cannot assume
// send(dp); // the first packet
// send(dp); // actually arrives
} catch (IOException | BigPacketSentException
| DatagramDataSizeException e) {
System.out.println("BAM JONGÛH!");
e.printStackTrace();
}
lock.unlock();
System.out.println("Handshake finished");
}
|
07ab1b48-f411-4b13-8127-d94d57b4b27b
| 0
|
public void initializeConverter() {
MAP = new HashMap();
UNIQUE_ID = 0;
}
|
5243d32f-9a9d-4029-a03c-836efabe9334
| 8
|
protected Content throwsTagsOutput(ThrowsTag[] throwTags,
TagletWriter writer, Set<String> alreadyDocumented, boolean allowDups) {
Content result = writer.getOutputInstance();
if (throwTags.length > 0) {
for (int i = 0; i < throwTags.length; ++i) {
ThrowsTag tt = throwTags[i];
ClassDoc cd = tt.exception();
if ((!allowDups) && (alreadyDocumented.contains(tt.exceptionName()) ||
(cd != null && alreadyDocumented.contains(cd.qualifiedName())))) {
continue;
}
if (alreadyDocumented.size() == 0) {
result.addContent(writer.getThrowsHeader());
}
result.addContent(writer.throwsTagOutput(tt));
alreadyDocumented.add(cd != null ?
cd.qualifiedName() : tt.exceptionName());
}
}
return result;
}
|
453f2c45-2888-4758-bab9-21006721c30a
| 0
|
@Autowired
@Qualifier("dao") //TODO убрать заглушку, юзать dao
public void setEmployeeDao(EmployeeDao employeeDao) {
this.employeeDao = employeeDao;
}
|
cbfe3bd4-6818-487d-be2f-5cb88b385d8a
| 9
|
public static Component getChild(Component parent, String name) {
parent = getContainer(parent);
if (parent instanceof JSplitPane) {
JSplitPane split = (JSplitPane) parent;
if (JSplitPane.TOP.equals(name)) {
return split.getTopComponent();
} else if (JSplitPane.LEFT.equals(name)) {
return split.getLeftComponent();
} else if (JSplitPane.RIGHT.equals(name)) {
return split.getRightComponent();
} else if (JSplitPane.BOTTOM.equals(name)) {
return split.getBottomComponent();
}
}
Container cont = (Container) parent;
for (int i = 0; i < cont.getComponentCount(); i++) {
Component comp = cont.getComponent(i);
if (name.equals(comp.getName())) {
return comp;
}
}
if (name.endsWith(VIEW_SUFFIX)) {
String subName = name.substring(0, name.length() - VIEW_SUFFIX.length());
if (subName.isEmpty()) {
return parent;
}
return getContainer(getChild(parent, subName));
}
throw new IllegalArgumentException("No component named " + name);
}
|
770c7dd5-3729-4bcd-ab16-ef5ff2ee12b2
| 4
|
@Override
public void componentResized(ComponentEvent e)
{
if(e.getComponent() == null || e.getComponent() instanceof JFrame == false)
return;
JFrame frame = (JFrame)e.getComponent();
Container contentPane = frame.getContentPane();
int newWidth = contentPane.getWidth();
int newHeight = contentPane.getHeight();
FontMetrics fontMetrics = frame.getGraphics().getFontMetrics(appearance.getNormalTextFont());
int consoleWidth = newWidth / fontMetrics.charWidth(' ');
int consoleHeight = newHeight / fontMetrics.getHeight();
if(consoleWidth == lastWidth && consoleHeight == lastHeight)
return;
lastWidth = consoleWidth;
lastHeight = consoleHeight;
resize(consoleWidth, consoleHeight);
}
|
db0886fd-4a63-42c8-bc68-ad7bacd1cd49
| 9
|
protected void calculateMotion() {
boolean fallGlide = gliding && dir.y > 0;
fallSpeed = (fallGlide)?glideFallSpeed:baseFallSpeed;
maxFallSpeed = (fallGlide)?glideMaxFall:baseMaxFall;
super.calculateMotion();
if((sprite.getCurrentState() == SCRATCHING
|| sprite.getCurrentState() == FIREBALL)
&& !(jumping || falling)) {
dir.x = 0;
}
if(jumping && !falling) {
dir.y = jumpStart;
falling = true;
}
}
|
ecd4fe47-cd58-44e3-8211-9ade7149101e
| 8
|
@Override
public void draw(Graphics2D g) {
updateInformation();
if (list.size() == 0)
return;
if (!GUI.controls.get("v_bubble-all-vertices").isActive())
return;
float alpha = transparency * (isOnPoint(graph.mousex, graph.mousey) ? 0.5f : 1.0f);
if (alpha < 0.01)
return;
Composite originalComposite = g.getComposite();
if (alpha < 0.99) {
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
}
AffineTransform at = g.getTransform();
preDraw(g);
g.setColor(new Color(150, 214, 250));
g.fill(new RoundRectangle2D.Double(dx, dy, dw, dh, dr, dr));
g.setColor(Canvas.contrastColor(g.getColor(), Constrast.textbw));
g.draw(new RoundRectangle2D.Double(dx, dy, dw, dh, dr, dr));
int j = 0;
for (String s : lines) {
j += (s.equals("")) ? g.getFontMetrics().getAscent() * 0.25 : g.getFontMetrics()
.getAscent();
g.drawString(s, (float) (dx + dr / 2), (float) (dy + j));
}
g.setTransform(at);
if (alpha < 0.99) {
g.setComposite(originalComposite);
}
}
|
bf97fd79-b70d-4f85-8277-f0b49b58bf6f
| 8
|
public int compareTo(PeptideLocationLine p) {
if(this.chromosomeName < p.getChromosomeName()){
return -1;
}
if(this.chromosomeName > p.getChromosomeName()){
return 1;
}
if(this.startLocation < p.getStartLocation()){
return -1;
}
if(this.startLocation > p.getStartLocation()){
return 1;
}
if(this.stopLocation < p.getStopLocation()){
return -1;
}
if(this.stopLocation < p.getStopLocation()){
return 1;
}
//Sort based on score if all else is equal
if(this.getStartLocType() + this.getStopLocType() > p.getStartLocType() + p.getStopLocType()){
return -1;
}
if(this.getStartLocType() + this.getStopLocType() < p.getStartLocType() + p.getStopLocType()){
return 1;
}
return 0;
}
|
b5390160-a217-4aa7-8c2d-d99244a84df6
| 6
|
private void SetZipChckbx(String project ,JFrame frame){
String projectName="";
if("designer".equals(project)){
projectName="zip_designer";
}else if("res".equals(project)){
projectName="zip_res";
}else if("mobile".equals(project)){
projectName="zip_mobile";
}
zipNameList=GetZipNames(projectName);
int x=10; //checkBox 的x坐标
JCheckBox chckbxNewCheckBox;
for(String item : zipNameList){
if(!(item.trim().isEmpty()||item==null)){
chckbxNewCheckBox = new JCheckBox(item);
chckbxNewCheckBox.setBounds(x, 60, 103, 23);
frame.getContentPane().add(chckbxNewCheckBox);
x+=120;
}
}
}
|
207ae4d0-2de6-4e18-8032-f678052129e3
| 4
|
private void setScrollPaneDefault(Attributes attrs) {
// find the value to be set, then set it
if (attrs.getValue(0).equals("starttime")) {
scrollpaneDef.setStartTime(Integer.valueOf(attrs.getValue(1)));
} else if (attrs.getValue(0).equals("endtime")) {
scrollpaneDef.setEndTime(Integer.valueOf(attrs.getValue(1)));
} else if (attrs.getValue(0).equals("backgroundcolor")) {
scrollpaneDef.setBkCol(new Color(Integer.valueOf(attrs.getValue(1)
.substring(1), 16)));
} else if (attrs.getValue(0).equals("backgroundalpha")) {
scrollpaneDef.setBkAlpha(Float.valueOf(attrs.getValue(1)));
}
}
|
74e5f478-c8cf-423d-9e59-68b808382808
| 0
|
public String getName() {
return Name;
}
|
56caca4e-c36f-4ae3-86eb-b8f513ceb750
| 0
|
public Filter xnor( Filter other )
{
return new Not( xor( other ) );
}
|
4dcc2338-afd2-4bdb-b4b1-ee2b0fd9cba1
| 8
|
protected Instances determineOutputFormat(Instances inputFormat)
throws Exception {
FastVector atts;
FastVector values;
Instances result;
int i;
// attributes must be numeric
m_Attributes.setUpper(inputFormat.numAttributes() - 1);
m_AttributeIndices = m_Attributes.getSelection();
for (i = 0; i < m_AttributeIndices.length; i++) {
// ignore class
if (m_AttributeIndices[i] == inputFormat.classIndex()) {
m_AttributeIndices[i] = NON_NUMERIC;
continue;
}
// not numeric -> ignore it
if (!inputFormat.attribute(m_AttributeIndices[i]).isNumeric())
m_AttributeIndices[i] = NON_NUMERIC;
}
// get old attributes
atts = new FastVector();
for (i = 0; i < inputFormat.numAttributes(); i++)
atts.addElement(inputFormat.attribute(i));
if (!getDetectionPerAttribute()) {
m_OutlierAttributePosition = new int[1];
m_OutlierAttributePosition[0] = atts.size();
// add 2 new attributes
values = new FastVector();
values.addElement("no");
values.addElement("yes");
atts.addElement(new Attribute("Outlier", values));
values = new FastVector();
values.addElement("no");
values.addElement("yes");
atts.addElement(new Attribute("ExtremeValue", values));
}
else {
m_OutlierAttributePosition = new int[m_AttributeIndices.length];
for (i = 0; i < m_AttributeIndices.length; i++) {
if (m_AttributeIndices[i] == NON_NUMERIC)
continue;
m_OutlierAttributePosition[i] = atts.size();
// add new attributes
values = new FastVector();
values.addElement("no");
values.addElement("yes");
atts.addElement(
new Attribute(
inputFormat.attribute(
m_AttributeIndices[i]).name() + "_Outlier", values));
values = new FastVector();
values.addElement("no");
values.addElement("yes");
atts.addElement(
new Attribute(
inputFormat.attribute(
m_AttributeIndices[i]).name() + "_ExtremeValue", values));
if (getOutputOffsetMultiplier())
atts.addElement(
new Attribute(
inputFormat.attribute(
m_AttributeIndices[i]).name() + "_Offset"));
}
}
// generate header
result = new Instances(inputFormat.relationName(), atts, 0);
result.setClassIndex(inputFormat.classIndex());
return result;
}
|
736d30f0-0257-4f2e-a34e-cf2a260a3781
| 2
|
@Override
public void keyTyped(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
try {
// login();
} catch (Throwable e1) {
e1.printStackTrace();
}
}
}
|
067beec2-a643-4a16-b26a-202869ca0cd9
| 6
|
private void quicksort(int low, int high) {
int i = low, j = high;
// Get the pivot element from the middle of the list
int pivot = numbers[low + (high - low) / 2];
// Divide into two lists
while (i <= j) {
// If the current value from the left list is smaller then the pivot
// element then get the next element from the left list
while (numbers[i] < pivot) {
i++;
}
// If the current value from the right list is larger then the pivot
// element then get the next element from the right list
while (numbers[j] > pivot) {
j--;
}
// If we have found a values in the left list which is larger then
// the pivot element and if we have found a value in the right list
// which is smaller then the pivot element then we exchange the
// values.
// As we are done we can increase i and j
if (i <= j) {
exchange(i, j);
i++;
j--;
}
}
// Recursion
if (low < j) quicksort(low, j);
if (i < high) quicksort(i, high);
}
|
0e27b498-cb6d-4546-8348-1957e6235a60
| 5
|
public Tile[][] generateTBlock()
{
Tile[][] piece = new Tile[3][2];
for (int i = 0; i < piece.length; i++)
for (int j = 0; j < piece[i].length; j++)
{
if (j == 0 || (j == 1 && i == 1))
{
piece[i][j] = new Tile(Color.MAGENTA);
piece[i][j].setX(i);
piece[i][j].setY(j);
}
else
{
piece[i][j] = new Tile(Color.white);
piece[i][j].setX(i);
piece[i][j].setY(j);
piece[i][j].setActive(false);
}
}
return piece;
}
|
895e1d36-86c2-49cc-9634-1b9f809428df
| 9
|
public String escapeAttributeValue(String value)
//protected void writeAttributeValue(String value, Writer out) throws IOException
{
int posLt = value.indexOf('<');
int posAmp = value.indexOf('&');
int posQuot = value.indexOf('"');
int posApos = value.indexOf('\'');
if(posLt == -1 && posAmp == -1 && posQuot == -1 && posApos == -1) {
return value;
}
StringBuffer buf = new StringBuffer(value.length() + 10);
// painful loop ...
for(int pos = 0, len = value.length(); pos < len; ++pos) {
char ch = value.charAt(pos);
switch(ch) {
case '<':
buf.append("<");
break;
case '&':
buf.append("&");
break;
case '\'':
buf.append("'");
break;
case '"':
buf.append(""");
break;
default:
buf.append(ch);
}
}
return buf.toString();
}
|
d22a34c8-78c3-4ecb-8495-9e1250a48cd1
| 4
|
private char randChar(boolean numbers)
{
if(numbers)
{
if(ClassParseTests.RANDOM.nextBoolean())
{
if(ClassParseTests.RANDOM.nextBoolean())
{
// 65-90
return (char) (ClassParseTests.RANDOM.nextInt(90 - 65) + 65);
}
else
{
// 97-122
return (char) (ClassParseTests.RANDOM.nextInt(122 - 97) + 97);
}
}
else
{
// 48-57
return (char) (ClassParseTests.RANDOM.nextInt(57 - 48) + 48);
}
}
else
{
if(ClassParseTests.RANDOM.nextBoolean())
{
// 65-90
return (char) (ClassParseTests.RANDOM.nextInt(90 - 65) + 65);
}
else
{
// 97-122
return (char) (ClassParseTests.RANDOM.nextInt(122 - 97) + 97);
}
}
}
|
0bfdf564-613e-4d57-acef-43b8496b0ea7
| 3
|
public void calcPossiblePos(MapScrollPane msp)
{
Tile[][] grid = msp.getGrid();
for (int i = 0; i < grid.length; i++)
{
for (int j = 0; j < grid[i].length; j++)
{
if (Collision.noCollision(grid, new Point(i,j), new Point(i + width - 1,j + height - 1)))
{
this.possiblePos.add(new Rectangle(i,j,width - 1,height - 1));
}
}
}
}
|
9cdc716c-c9e9-491e-892c-b230f7c55209
| 0
|
public void draw() {
System.out.println("Draw Triangle");
}
|
36002c48-7fec-4fbb-a60e-f79488f4b125
| 0
|
void setState(State state) {
this.state = state;
}
|
f3f29bea-35c9-4309-b450-669f90dc3730
| 5
|
public static boolean dismissInvite(String[] args, CommandSender s){
//Various checks
if(Util.isBannedFromGuilds(s) == true){
//Checking if they are banned from the guilds system
s.sendMessage(ChatColor.RED + "You are currently banned from interacting with the Guilds system. Talk to your server admin if you believe this is in error.");
return false;
}
if(args.length > 1){
//Checking if the create command has proper args
s.sendMessage(ChatColor.RED + "Incorrectly formatted cancel invites command! Proper syntax is: \"/guild cancelinvite\"");
return false;
}
if(!s.hasPermission("zguilds.player.dismissinvite")){
//Checking if they have the permission node to proceed
s.sendMessage(ChatColor.RED + "You lack sufficient permissions to cancel your guild invites. Talk to your server admin if you believe this is in error.");
return false;
}
if(Util.isInGuild(s) == true){
//Checking if they're already in a guild
s.sendMessage(ChatColor.RED + "You're in a guild so you don't have any invitations to join a new one.");
return false;
}
if(Util.hasGuildInvite(s) == false){
//Checking if they are even invited to a guild at all.
s.sendMessage(ChatColor.RED + "You are not currently invited to any guild.");
return false;
}
//Setting their current guild invite to blank
sendersPlayerName = s.getName().toLowerCase();
sendersCurrentGuildInvitation = Main.players.getString("Players." + sendersPlayerName + ".Current_Invitation");
Main.players.set("Players." + sendersPlayerName + ".Current_Invitation", "N/A");
s.sendMessage(ChatColor.DARK_GREEN + "You cancelled your pending guild invite with the guild " + ChatColor.RED + sendersCurrentGuildInvitation + ChatColor.DARK_GREEN + ".");
Main.saveYamls();
return true;
}
|
21f2d484-76be-4ab4-ab4f-84b438933106
| 8
|
public void recoveryTokenCheck() {
switch (this.currentToken) {
case TokenNameLBRACE :
RecoveredElement newElement = null;
if(!this.ignoreNextOpeningBrace) {
newElement = this.currentElement.updateOnOpeningBrace(this.scanner.startPosition - 1, this.scanner.currentPosition - 1);
}
this.lastCheckPoint = this.scanner.currentPosition;
if (newElement != null){ // null means nothing happened
this.restartRecovery = true; // opening brace detected
this.currentElement = newElement;
}
break;
case TokenNameRBRACE :
this.rBraceStart = this.scanner.startPosition - 1;
this.rBraceEnd = this.scanner.currentPosition - 1;
this.endPosition = this.flushCommentsDefinedPriorTo(this.rBraceEnd);
newElement =
this.currentElement.updateOnClosingBrace(this.scanner.startPosition, this.rBraceEnd);
this.lastCheckPoint = this.scanner.currentPosition;
if (newElement != this.currentElement){
this.currentElement = newElement;
// if (newElement instanceof RecoveredField && this.dietInt <= 0) {
// if (((RecoveredField)newElement).fieldDeclaration.type == null) { // enum constant
// this.isInsideEnumConstantPart = true; // restore status
// }
// }
}
break;
case TokenNameSEMICOLON :
this.endStatementPosition = this.scanner.currentPosition - 1;
this.endPosition = this.scanner.startPosition - 1;
this.lastCheckPoint=this.scanner.currentPosition;
// RecoveredType currentType = this.currentRecoveryType();
// if(currentType != null) {
// currentType.insideEnumConstantPart = false;
// }
// fall through
default : {
if (this.rBraceEnd > this.rBraceSuccessorStart && this.scanner.currentPosition != this.scanner.startPosition){
this.rBraceSuccessorStart = this.scanner.startPosition;
}
break;
}
}
this.ignoreNextOpeningBrace = false;
}
|
b09cfb99-a825-4b42-8246-0ccc16dbc35d
| 8
|
public List<ACommand.Executor> processClass(Class<?> clazz, Object instance) {
List<ACommand.Executor> cmdList = new ArrayList<ACommand.Executor>();
Method[] methodList = clazz.getMethods();
for(Method method : methodList) {
ACommand acmd = method.getAnnotation(ACommand.class);
// skip it if it doesn't have the annotation
if (acmd == null) {
continue;
}
try {
Method completer = null;
// ensure method has the correct signaure
if (!testCommandSig(method, boolean.class)) {
throw new CommandException("Invalid command signature");
}
if (!acmd.completer().isEmpty()) {
try {
completer = clazz.getMethod(acmd.completer(), CommandContext.class);
if (!testCommandSig(completer, List.class)) {
throw new CommandException("Completer method not found (invalid signature?)");
}
} catch (NoSuchMethodException e) {
throw new CommandException("Completer method not found (invalid signature?)");
}
}
ACommand.Executor cmdExec = new ACommand.Executor(acmd, instance, method, completer);
cmdList.add(cmdExec);
} catch (CommandException e) {
plugin.getLogger().log(Level.WARNING, "@ACommand on method " + clazz.getName() + "."
+ method.getName() + ": " + e.getMessage() + " Please report this to the developer!");
}
}
return cmdList;
}
|
751043a0-06fe-4a3a-94fc-8e404cbe4f1c
| 7
|
public static void dlModlist(File modlist, String dloc) throws InterruptedException, IOException{
FileReader fr = new FileReader(modlist); //Opens the selected modlist
LineNumberReader lnr = new LineNumberReader(fr); //Used to read the modlist
int totalmods = 0; //Start the mod counting at 0 of course
while (lnr.readLine() != null){ //Count the amount of mods in the modlist
totalmods++;
}
lnr.close(); //Closes the line number reader because it is not longer needed
System.out.println("Reading modlist");
System.out.println("Total number of mods to download: " + totalmods);
System.out.println("Directory set to: "+dloc);
MIFU.progress.setMaximum(totalmods); //Set the max of the progressbar to how many mods there are to download
try {
BufferedReader cfgFile = new BufferedReader(new FileReader(modlist)); //Used to read the modlist
String line = null; //The line of the modlist it is on
int currmod = 0; //The current mod it is downloading
new File(MIFU.dlDir.toString()).mkdirs(); //Creates the path to where it will download if it dosen't exist
while ((line = cfgFile.readLine()) != null) { //This loops until it reaches the end of the modlist
line.trim(); //Gets one line at a time
String [] entry = line.split(","); //Splits the line into 2 parts
if (entry[0].equalsIgnoreCase("forge")) { //if the first part says forge
Download.downloadfile("http://files.minecraftforge.net/maven/net/minecraftforge/forge/"+entry[1]+"/forge-"+entry[1]+"-installer.jar", dloc, "/forge-installer-"+entry[1]+".jar");
System.out.println("Downloaded: Minecraft forge version: "+entry[1]); //Downloads the forge installer
}else if(entry[0].equalsIgnoreCase("extract")){
if(entry.length>3){
Extract.ExtractZipFile(dloc, entry[1], dloc+entry[2], entry[3]);
}else{
Extract.ExtractZipFile(dloc, entry[1], dloc+entry[2]);
}
}else{
Download.downloadfile(entry[0], dloc, entry[1]); //Download the mod
}
currmod++; //Go on to the next mod
MIFU.progress.setValue(currmod); //Set the progressbar to how many mods have been downloaded
System.out.println("Downloaded: " + currmod + "/" + totalmods);
MIFU.progress.setString("Downloaded: " + currmod + "/" + totalmods); //Sets the text on the progressbar
if(currmod==totalmods){
MIFU.progress.setString("Done!");
}
}
cfgFile.close(); //Close the file
} catch (IOException e) {
System.out.println("Unexpected File IO Error");
}
}
|
bf96f49a-a3ad-4112-9183-9f32e792d706
| 1
|
@Test
public void diag_test() {
try{
double []mat= {1.0,2.0};
double[][]result = Matrix.diag(mat);
double [][]exp= {{1.0,0.0}, {0.0,2.0}};
Assert.assertArrayEquals(exp, result);
}
catch (Exception e) {
// TODO Auto-generated catch block
fail("Not yet implemented");
}
}
|
ad8a5e10-ee76-4784-b410-4a76bca48855
| 1
|
private Sound(String name) {
try {
clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(
this.getClass().getClassLoader().getResource("sounds/" + name));
clip.open(inputStream);
} catch (Throwable e) {
e.printStackTrace();
}
}
|
ec9a21ec-f6ef-46fc-b37c-90288933e4a9
| 3
|
@Override
public int hashCode() {
int hash = 5;
hash = 23 * hash + (states != null ? states.hashCode() : 0);
hash = 23 * hash + (initialState != null ? initialState.hashCode() : 0);
hash = 23 * hash + (liveStates != null ? liveStates.hashCode() : 0);
return hash;
}
|
f9abd05c-287d-4f0f-bd28-76fe7ea3098a
| 7
|
private void btnIntersectionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIntersectionActionPerformed
JFileChooser saveFile = new JFileChooser();
int selected = saveFile.showOpenDialog(this);
if(selected == JFileChooser.APPROVE_OPTION){
String path = saveFile.getSelectedFile().getAbsolutePath();
File tempFile = new File(path);
if(!tempFile.exists() || tempFile.isDirectory()){
JOptionPane.showMessageDialog(this, "The current selected path is invalid.",
"Invalid Path", JOptionPane.ERROR_MESSAGE);
return;
}
AFProcessing IntersectionAFManager = new AFProcessing();
try {
IntersectionAFManager.processXML(tempFile);
} catch (JAXBException ex) {
invalidAFLoaded("Error parsing xml file.");
}
String error = IntersectionAFManager.validateAF();
if(!error.isEmpty()){
JOptionPane.showMessageDialog(this,error, "Error At parsing XML", JOptionPane.ERROR_MESSAGE);
return;
}
saveFile = new JFileChooser();
selected = saveFile.showSaveDialog(this);
if(selected == JFileChooser.APPROVE_OPTION){
path = saveFile.getSelectedFile().getAbsolutePath();
try {
AFManager.generateIntersectionWithCurrentAndAFContent(IntersectionAFManager.getContent(), path);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}//GEN-LAST:event_btnIntersectionActionPerformed
|
a18992f4-ea60-45f9-8738-683987fbe522
| 9
|
private void talk() {
while (true) {
question();
logWriteUser(question);
if (exit()) {
break;
} else if (stop()) {
answer(MSG_FOR_STOP);
while (true) {
question();
if (start()) {
logWriteUser(question);
answer(MSG_FOR_START);
break;
} else if (exit()) {
logWriteUser(question);
break;
}
}
continue;
} else if (useAnotherFile()) {
setNewFile();
try {
readFile(filename);
} catch (Exception e) {
System.err.println(ERROR_READ_FILE + e);
logWriteComp(ERROR_READ_FILE + e);
continue;
}
answer(NEW_FILE + filename);
continue;
} else if (setGUImode()) {
System.out.println("exit");
this.dispose();
runGuiMode();
return;
}
answer(getAnswer());
}
answer(sayGoodBye());
}
|
b693bcbd-c9a2-4cde-9d7c-2f74e95bc201
| 7
|
public static String task2(String expression) {
int openBrackets = 0;
for(int i=0; i<expression.length(); i++) {
if(expression.charAt(i) == '(') {
openBrackets ++;
}
if(expression.charAt(i) == ')' && openBrackets>0) {
openBrackets --;
}
else if(expression.charAt(i) == ')' && openBrackets==0) {
return "No. You have spare closing bracket in position " + i;
}
}
if(openBrackets>0) {
return "No. You have " + openBrackets + " open bracket(s) in your expression";
}
else {
return "Yes";
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.