method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
7dbf2b74-f282-43a6-b069-9ff8139b6b53 | 8 | public Object nextValue() throws JSONException {
char c = nextClean();
String s;
switch (c) {
case '"':
case '\'':
return nextString(c);
case '{':
back();
return new JSONObject(this);
case '[':
case '(':
back();
return new JSONArray(this);
}
/*
* Handle unquoted text. This could be the values true, false, or
* null, or it can be a number. An implementation (such as this one)
* is allowed to also accept non-standard forms.
*
* Accumulate characters until we reach the end of the text or a
* formatting character.
*/
StringBuffer sb = new StringBuffer();
while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
sb.append(c);
c = next();
}
back();
s = sb.toString().trim();
if (s.equals("")) {
throw syntaxError("Missing value");
}
return JSONObject.stringToValue(s);
} |
6316b228-608e-476e-bac8-59b4066505c4 | 9 | @Override
public boolean tick(Tickable ticking, int tickID)
{
if((tickID==Tickable.TICKID_TRAP_RESET)&&(getReset()>0))
{
if((sprung)
&&(affected!=null)
&&(affected instanceof Room)
&&(!disabled())
&&(tickDown>=0))
{
final Room R=(Room)affected;
if(tickDown>13)
{
R.showHappens(CMMsg.MSG_OK_VISUAL,L("Water is filling up the room!"));
CMLib.utensils().extinguish(invoker(),R,true);
R.recoverPhyStats();
R.recoverRoomStats();
}
else
if(tickDown>2)
{
CMLib.utensils().extinguish(invoker(),R,true);
R.recoverPhyStats();
R.recoverRoomStats();
}
else
{
R.recoverPhyStats();
R.recoverRoomStats();
R.showHappens(CMMsg.MSG_OK_VISUAL,L("The water is draining away..."));
}
}
}
return super.tick(ticking,tickID);
} |
47dcfc3e-3e01-4de2-9083-3f519d18cc67 | 1 | public static void triggerAR(String pin)
{
try
{
URL url;
HttpURLConnection connection = null;
String lResponseMessage = "";
String targetURL = "http://staging.webchat.a-cti.com:8082/js/action/eventToTalkAction.do?";
String urlParameters = "method=sendJSONRequest&open=submitClickToTalkForm&formName=TestScheduleForm&eventToTalkId=3005251315&generatedXML=<?xml version=\"1.0\" encoding=\"UTF-8\"?><form><formfield><label>Phone</label><value>8250000000</value></formfield><formfield><label>uniquepin</label><value>"+pin+"</value></formfield></form>";
System.out.println( "Sending Request to:::::::::" +targetURL);
// Create connection
url = new URL( targetURL );
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod( "POST" );
connection.setRequestProperty( "Content-Type" , "application/x-www-form-urlencoded" );
connection.setRequestProperty( "Content-Length" , "" + Integer.toString( urlParameters.getBytes().length ) );
connection.setRequestProperty( "Content-Language" , "en-US" );
connection.setUseCaches( false );
connection.setDoInput( true );
connection.setDoOutput( true );
// Send request
DataOutputStream wr = new DataOutputStream( connection.getOutputStream() );
wr.writeBytes( urlParameters );
wr.flush();
wr.close();
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader( new InputStreamReader( is ) );
rd.close();
lResponseMessage = connection.getResponseMessage();
System.out.println("lResponseMessage is "+lResponseMessage);
}
catch(Exception e)
{
System.out.println("Problem in the code");
}
} |
d42d71a3-370e-4622-a831-9e318671402c | 7 | private BufferedImage createImage() {
final int boldWidth = 3;
final int sudoHeight = 9 * cellHeight + 2 * yOffset + boldWidth;
final int sudoWidth = 9 * cellWidth + 2 * xOffset + boldWidth;
final EmptyImageBuilder builder = new EmptyImageBuilder(sudoWidth, sudoHeight + textTotalHeight, Color.WHITE);
final BufferedImage im = builder.getBufferedImage();
final Graphics2D g2d = builder.getGraphics2D();
g2d.translate(xOffset, yOffset);
for (int x = 0; x < 9; x++) {
for (int y = 0; y < 9; y++) {
final int num = sudoku.getGiven(x, y);
if (num > 0) {
final TextBlock text = TextBlockUtils.create(Arrays.asList("" + num), new FontConfiguration(
numberFont, HtmlColor.BLACK), HorizontalAlignement.CENTER);
text.drawTOBEREMOVED(new ColorMapperIdentity(), g2d, numberxOffset + x * cellWidth, numberyOffset
+ y * cellHeight);
}
}
}
for (int i = 0; i < 10; i++) {
final boolean bold = i % boldWidth == 0;
final int w = bold ? boldWidth : 1;
g2d.fillRect(0, i * cellHeight, 9 * cellWidth + boldWidth, w);
}
for (int i = 0; i < 10; i++) {
final boolean bold = i % boldWidth == 0;
final int w = bold ? boldWidth : 1;
g2d.fillRect(i * cellWidth, 0, w, 9 * cellHeight + boldWidth);
}
g2d.translate(0, sudoHeight);
final List<String> texts = new ArrayList<String>();
texts.add("http://plantuml.sourceforge.net");
texts.add("Seed " + Long.toString(sudoku.getSeed(), 36));
texts.add("Difficulty " + sudoku.getRatting());
final TextBlock textBlock = TextBlockUtils.create(texts, new FontConfiguration(font, HtmlColor.BLACK),
HorizontalAlignement.LEFT);
textBlock.drawTOBEREMOVED(new ColorMapperIdentity(), g2d, 0, 0);
g2d.dispose();
return im;
} |
fc5840f3-e023-47b9-bebf-44974b6f329e | 9 | private static int editDistanceTranspose(CharSequence cSeq1,
CharSequence cSeq2) {
// cSeq1.length >= cSeq2.length > 1
int xsLength = cSeq1.length() + 1; // > ysLength
int ysLength = cSeq2.length() + 1; // > 2
int[] twoLastSlice = new int[ysLength];
int[] lastSlice = new int[ysLength];
int[] currentSlice = new int[ysLength];
// x=0: first slice is just inserts
for (int y = 0; y < ysLength; ++y)
lastSlice[y] = y; // y inserts down first column of lattice
// x=1:second slice no transpose
currentSlice[0] = 1; // insert x[0]
char cX = cSeq1.charAt(0);
for (int y = 1; y < ysLength; ++y) {
int yMinus1 = y-1;
currentSlice[y] = Math.min(cX == cSeq2.charAt(yMinus1)
? lastSlice[yMinus1] // match
: 1 + lastSlice[yMinus1], // subst
1 + Math.min(lastSlice[y], // delelte
currentSlice[yMinus1])); // insert
}
char cYZero = cSeq2.charAt(0);
// x>1:transpose after first element
for (int x = 2; x < xsLength; ++x) {
char cXMinus1 = cX;
cX = cSeq1.charAt(x-1);
// rotate slices
int[] tmpSlice = twoLastSlice;
twoLastSlice = lastSlice;
lastSlice = currentSlice;
currentSlice = tmpSlice;
currentSlice[0] = x; // x deletes across first row of lattice
// y=1: no transpose here
currentSlice[1] = Math.min(cX == cYZero
? lastSlice[0] // match
: 1 + lastSlice[0], // subst
1 + Math.min(lastSlice[1], // delelte
currentSlice[0])); // insert
// y > 1: transpose
char cY = cYZero;
for (int y = 2; y < ysLength; ++y) {
int yMinus1 = y-1;
char cYMinus1 = cY;
cY = cSeq2.charAt(yMinus1);
currentSlice[y] = Math.min(cX == cY
? lastSlice[yMinus1] // match
: 1 + lastSlice[yMinus1], // subst
1 + Math.min(lastSlice[y], // delelte
currentSlice[yMinus1])); // insert
if (cX == cYMinus1 && cY == cXMinus1)
currentSlice[y] = Math.min(currentSlice[y],1+twoLastSlice[y-2]);
}
}
return currentSlice[currentSlice.length-1];
} |
f41554d5-8575-469e-b62e-dff170786637 | 8 | private int select(int[] data, int start, int end, int k) {
if (start == end) {
return data[k-1];
}
int t = data[start], i = start, j = end + 1;
while (true) {
do {
i++;
} while (i <= end && data[i] < t);
do {
j--;
} while (data[j] > t);
if (i > j) {
break;
}
swap(data, i, j);
}
swap(data, start, j);
if (j<k) {
return select(data, j+1, end, k);
} else if (j > k) {
return select(data, start, j-1, k);
} else {
return data[k-1];
}
} |
be723832-67ad-4d1c-9cc3-9f1922517e2f | 3 | public static void cmd()
{
StringBuilder sb = new StringBuilder();
int c;
System.out.print("SimPL> ");
while(true)
{
try {
c = System.in.read();
if(c=='$')
{
System.out.print("SimPL> ");
System.out.println(run(sb.toString()));
System.out.print("SimPL> ");
sb = new StringBuilder();
}
else
{
sb.append((char)c);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} |
ba9134bd-7c42-4fd8-a6dd-cf45dee67a85 | 3 | private void printItem(String itemName){
Item i = null;
if (((i = bag.getItem(itemName)) != null) || ((i = rooms.get(currentRoom).getItem(itemName)) != null)){
try {
i.printImage();
} catch (FileNotFoundException e) {
System.out.println("Couldn't see " + Phraser.addDeterminer(itemName));
}
}
} |
2e37aea4-4dbd-4dab-a950-41f35ab22558 | 6 | public void run() {
// watch dir
try {
watcher = FileSystems.getDefault().newWatchService();
textsPath = FileSystems.getDefault().getPath(Core.textsDir);
key = textsPath.register(watcher, ENTRY_CREATE, ENTRY_MODIFY);
} catch (IOException e) {
e.printStackTrace();
}
// io loop
for (;;) {
try {
// listen
key = watcher.take();
} catch (InterruptedException x) {
return;
}
for (WatchEvent<?> event : key.pollEvents()) {
// we have new files
WatchEvent<Path> pathEvent = (WatchEvent<Path>) event;
Path filename = pathEvent.context(); // context() is the filename
if (filename != null) {
Path file = textsPath.resolve(filename);
Text text = createTextFromFile(file);
text.update(null);
}
}
key.reset();
}
} |
d3a1d006-2200-4ccd-a298-3044a57087b2 | 7 | public DirectoryTreePanel() {
initDirectoryTree();
/*stop processing the tree if running in applet mode*/
//if(appletCheck())
// return;
initComponents();
jList1.validate();
/*expand the tree to current working directory*/
String curDir = System.getProperty("user.dir");
if((new File(RNALIB + File.separator + "ct")).exists())
curDir = curDir + File.separator + RNALIB + File.separator + "ct" + dir_escape;
/*create path list*/
//String[] pt = this.create_path_list(curDir);
String[] pt = null;
if(winOS){
pt = this.create_path_list(curDir);
pt[0] = pt[0] + "\\";
}
else{
pt = curDir.split(File.separator);
/*get machine name*/
try {
hostname = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException ex) {
Logger.getLogger(FileTreeModel.class.getName()).log(Level.SEVERE, null, ex);
}
pt[0] = hostname;
}
Object root = model.getRoot();
/*build tree path*/
Object parent = root;
jTree1.setSelectionRow(1);
TreePath tp = jTree1.getSelectionPath();
tp = tp.getParentPath();
TreePath curPath = null;
int i = winOS ? 0:1;
for(;i<pt.length;i++){
/*locate the right child*/
Object child = null;
int n = model.getChildCount(parent);
int j=0;
for(j=0;j<n;j++){
child = model.getChild(parent, j);
if(child.toString().equals(pt[i]))
break;
}
/*descend over it */
curPath = tp.pathByAddingChild(child);
tp = curPath;
parent = child;
jTree1.fireTreeExpanded(tp);
jTree1.setSelectionPath(tp);
}
jTree1.scrollPathToVisible(tp);
this.loadDirectoryFiles();
} |
52e7e27a-c3a1-43c0-9097-5ce2bf133e89 | 7 | @Override
public void unInvoke()
{
// undo the affects of this spell
if(!(affected instanceof MOB))
return;
final MOB mob=(MOB)affected;
super.unInvoke();
if(canBeUninvoked())
{
if((!mob.amDead())&&(CMLib.flags().isInTheGame(mob,false)))
{
if(mob==invoker)
{
if(mob.location()!=null)
mob.location().show(mob,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> release(s) <S-HIS-HER> pin."));
else
mob.tell(L("You release your pin."));
}
else
{
if(mob.location()!=null)
mob.location().show(mob,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> <S-IS-ARE> released from the pin"));
else
mob.tell(L("You are released from the pin."));
}
CMLib.commands().postStand(mob,true);
}
}
} |
eb4070b2-44b9-4001-b580-9ef75bdc65b1 | 3 | public String setNick(String nickname) {
if (nickname.length() == 0 || nickname.equals(user.getUsername()))
return null;
if (nickname.length() > 20)
return String.format("Invalid nickname: \"%s\"", nickname);
nickname = nickname.replaceAll("\\s", "_");
getUser().setDisplayName(nickname);
return String.format("Changed nickname to: \"%s\"", nickname);
} |
477af76d-8702-4584-9d08-f06a7a37c0c3 | 5 | @POST
@Timed
@Path("getUserDetails")
@Consumes("application/x-www-form-urlencoded")
@Produces({"application/json"})
public Response verifyUserToken(@HeaderParam("serviceId") @NotNull String serviceToken, @HeaderParam("userSessionId") @NotNull String token) {
String errorMessage = null;
try {
ServiceAccount verifiedService = doVerifyServiceToken(serviceToken);
if (verifiedService == null) {
return Response.status(401).cacheControl(NO_CACHE_CONTROL).entity("Calling service is not authorized").build();
}
if (!verifiedService.hasRole("VerifyToken")) {
return Response.status(401).cacheControl(NO_CACHE_CONTROL).entity("Calling service is not authorized").build();
}
UserToken verifiedUserToken = doVerifyUserToken(token);
if (verifiedUserToken != null) {
UserDetails details = new UserDetails();
details.setName(verifiedUserToken.userAccount.name);
details.setDisplayName(verifiedUserToken.userAccount.displayName);
details.setRoles(new ArrayList<String>());
for (Role role : verifiedUserToken.userAccount.roles) {
details.getRoles().add(role.name);
}
return Response.ok().cacheControl(NO_CACHE_CONTROL).entity(details).build();
}
} catch (Exception e) {
L.error("Error verifying userSessionId: " + token, e);
errorMessage = "An unexpected error occurred";
}
throw new WebApplicationException(Response.status(401).cacheControl(NO_CACHE_CONTROL).entity(errorMessage).build());
} |
aff55371-e810-446d-8276-e97b47f0854b | 3 | private String classSignature() throws UnexpectedTokenException
{
StringBuilder signature = new StringBuilder();
this.expect(PLUS, MINUS, TILDE);
signature.append(this.getToken().data);
this.nextToken();
this.expect(CLASS, INTERFACE, ENUM);
signature.append(this.getToken().data);
this.nextToken();
this.expect(IDENT, LPAREN);
if(this.accept(LPAREN))
{
this.nextToken();
signature.append('(');
while(!this.accept(RPAREN))
{
this.expect(STATIC, FINAL, ABSTRACT);
signature.append(this.getToken().data);
this.nextToken();
if(this.accept(COMMA))
{
signature.append(',');
this.nextToken();
this.expect(STATIC, FINAL, ABSTRACT);
}
}
signature.append(')');
this.nextToken();
}
return signature.toString();
} |
796bca7d-6159-480f-970d-3d04d78e9562 | 4 | public void addSorted(PriorityPair pNew){
ListElement el = head;
if(el == null){
addFirst(pNew);
return;
}
else if (pNew.compareTo((PriorityPair)head.first())>0) {
addFirst(pNew);
}
else {
while(el.rest()!=null && pNew.compareTo((PriorityPair)el.rest().first())<=0){
el = el.rest();
}
el.setRest(new ListElement(pNew, el.rest()));
size++;
}
} |
6f3b7826-6bde-408b-852a-55c3180a473f | 5 | @Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof SaleItem)) {
return false;
}
SaleItem other = (SaleItem) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
} |
803498cf-9c67-4768-b843-e6abb87f0cc0 | 1 | private void downloadVersionTable() {
FileRequest mainRequest = requester.request(255, 255);
while (!mainRequest.isComplete()) {
requester.process();
}
versionTable = new ReferenceTable(mainRequest.getBuffer());
} |
1991d810-f4f6-4bdb-84c7-1c1c97621b71 | 7 | @Override
public void onKeyPress(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_ESCAPE){
GameMain.game.exit();
}
if(key == KeyEvent.VK_ENTER || key == KeyEvent.VK_SPACE){
if(currentSelection == 0){
setCurrentState(new PlayState());
}else if(currentSelection == 1){
GameMain.game.exit();
}
}else if(key == KeyEvent.VK_UP){
currentSelection = 0;
}else if(key == KeyEvent.VK_DOWN){
currentSelection = 1;
}
} |
e3118e9a-f0fb-4fce-b582-9dec087bbf0f | 1 | @Override
public boolean equals(Object other){
if (other instanceof Host){
Host o = (Host)other;
return this.hostName.equals(o.getHostName());
}
return false;
} |
00b2bae2-68a5-46b1-960a-5f3232adb3cb | 6 | public final boolean isPoison() {
switch (sourceid) {
case 2111003:
case 2101005:
case 2111006:
case 2121003:
case 2221003:
case 12111005: // Flame gear
return skill;
}
return false;
} |
1f2e01c8-6b78-4975-b462-e22d7f253efd | 7 | public ArrayList<Integer> suffixTreeSearch(String pattern)
{
ArrayList<Integer> resultList = new ArrayList<Integer>();
boolean found = true;
TreeNode currentNode=root;
while(pattern.length()>0 && found)
{
if(currentNode.getChildHash().get(pattern.charAt(0))!=null)
{
TreeNode currentChild=currentNode.getChildHash().get(pattern.charAt(0));
String alpha= currentChild.getInputEdgeLabe();
for(int i=1;i<Math.min(alpha.length(), pattern.length());i++)
{
if(pattern.charAt(i)!=alpha.charAt(i))
{
found=false;
break;
}
}
if(found)
{
if(pattern.length()<=alpha.length())
{
System.out.println(findAllLeafs(currentChild));
resultList=findAllLeafs(currentChild);
//System.out.println("Juhu gefunden!");
break;
}
else
{
pattern=pattern.substring(alpha.length());
currentNode=currentChild;
}
}
}
else
{
found=false;
System.out.println("Leider nein!");
}
}
return resultList;
} |
8033b921-16e0-4525-83e4-dc0aa63ad65d | 6 | private boolean is_assigned(CPA cpa) throws Exception {
boolean assignmets_constraied=false;
int k=-1;
for(int i=0 ; i<Domain.length ; i++){
k++;
k = find_next_possible_assignment(k);
if(k == -1){
emptyDomain();
return false;
}
Assignment assignment = new Assignment(ID , k);
for(int j=0 ; j<cpa.length() && !assignmets_constraied;j++){
if (constrained(assignment , cpa.getAssignment(j))){
assignmets_constraied=true;
}
}
if(!assignmets_constraied){
Domain[k] =0;
cpa.add_assignment(assignment);
AgentView = cpa;
return true;
}
assignmets_constraied=false;
}
return false;
} |
d1423fc6-b848-441f-b8d2-fe62ef467bc1 | 1 | public void restoreHealth(int value){
health += value;
if(health > maxHealth) health = maxHealth;
} |
c3ff91d8-c3ea-45c8-bc14-4a0fdfc195ae | 1 | public static boolean GetKeyUp(int keyCode)
{
return !GetKey(keyCode) && m_lastKeys[keyCode];
} |
63effb0b-0903-40d6-a599-1989efaa81df | 9 | void breakWall(Coordinates actual, Coordinates target) {
try {
//Porte du haut
if ((target.getX() == actual.getX()) && (target.getY() <= actual.getY())) {
caseArray[actual.getX()][actual.getY()].breakTopWall();
caseArray[target.getX()][target.getY()].breakBottomWall();
}
//Porte de droite
if ((target.getX() >= actual.getX()) && (target.getY() == actual.getY())) {
caseArray[actual.getX()][actual.getY()].breakRightWall();
caseArray[target.getX()][target.getY()].breakLeftWall();
}
//Porte du bas
if ((target.getX() == actual.getX()) && (target.getY() >= actual.getY())) {
caseArray[actual.getX()][actual.getY()].breakBottomWall();
caseArray[target.getX()][target.getY()].breakTopWall();
}
//Porte de gauche
if ((target.getX() <= actual.getX()) && (target.getY() == actual.getY())) {
caseArray[actual.getX()][actual.getY()].breakLeftWall();
caseArray[target.getX()][target.getY()].breakRightWall();
}
} catch (Exception e) {
System.out.println("Unknown Error !");
}
} |
52c95605-9bb7-43c8-b601-e0019d9da943 | 8 | public final ArrayList<Instruction> compileMacros(int offest){
ArrayList<Instruction> program = new ArrayList<>();
ArrayList<InputPin> inPins = new ArrayList<>();
ArrayList<OutputPin> outPins = new ArrayList<>();
macroSize = 0;
for (AbstractUnit unit : units) {
if(unit instanceof InputPin){
inPins.add((InputPin) unit);
}
if(unit instanceof OutputPin){
outPins.add((OutputPin) unit);
}
if(unit instanceof AbstractUnit){
macroSize++;
}
}
initArrays(inPins.size(), outPins.size());
int i = 0;
for (InputPin pin : inPins) {
inLables[i] = pin.name;
i++;
}
i = 0;
for (OutputPin pin : outPins) {
inLables[i] = pin.name;
i++;
}
int comm = 0;
for (AbstractUnit unit : units) {
if(unit instanceof IInstructionUnit){
((IInstructionUnit)unit).getInstruction(unitNumber+comm);
}
}
return program;
} |
7aa69f11-d936-4c53-93e0-8d619d269c85 | 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;
}
} |
8c4be75c-29cd-4b9c-927f-cd78e36e7d52 | 4 | @Override
public boolean equals(Object other) {
if (other == this) { return true; }
if (!(other instanceof GeoPoint)) { return false; }
GeoPoint d = (GeoPoint) other;
return this.referenceEllipsoid.equals(d.referenceEllipsoid)
&& this.latitude.equals(d.latitude) && this.longitude.equals(d.longitude);
} |
a634b1b8-09ba-4fab-bb3b-24acc3663e6e | 6 | private void lu_solve(double a[][], int n, int ipvt[], double b[]) {
int i;
// find first nonzero b element
for (i = 0; i != n; i++) {
int row = ipvt[i];
double swap = b[row];
b[row] = b[i];
b[i] = swap;
if (swap != 0) {
break;
}
}
int bi = i++;
for (; i < n; i++) {
int row = ipvt[i];
int j;
double tot = b[row];
b[row] = b[i];
// forward substitution using the lower triangular matrix
for (j = bi; j < i; j++) {
tot -= a[i][j] * b[j];
}
b[i] = tot;
}
for (i = n - 1; i >= 0; i--) {
double tot = b[i];
// back-substitution using the upper triangular matrix
int j;
for (j = i + 1; j != n; j++) {
tot -= a[i][j] * b[j];
}
b[i] = tot / a[i][i];
}
} |
6e20641a-9258-4f21-8d04-f069b59e9f5d | 8 | private void menuSetDifficulty(int difficultyLevel) {
switch(difficultyLevel) {
case DifficultyLevel.EASY:
this.difficultyLevel = new DifficultyLevel(DifficultyLevel.EASY);
break;
case DifficultyLevel.MEDIUM:
this.difficultyLevel = new DifficultyLevel(DifficultyLevel.MEDIUM);
break;
case DifficultyLevel.HARD:
this.difficultyLevel = new DifficultyLevel(DifficultyLevel.HARD);
break;
case DifficultyLevel.CUSTOM:
String width =
JOptionPane.showInputDialog("Set width (max 40)");
String height =
JOptionPane.showInputDialog("Set height (max 30)");
String mines =
JOptionPane.showInputDialog("Set amount of mines (max half of the minefield size)");
if(width == null || height == null || mines == null) {
JOptionPane.showMessageDialog(this, "Incorrect values",
"Error", JOptionPane.ERROR_MESSAGE);
} else {
try {
int intWidth = new Integer(width);
int intHeight = new Integer(height);
int intMines = new Integer(mines);
this.difficultyLevel = new DifficultyLevel(intHeight, intWidth, intMines);
} catch(NumberFormatException e) {
JOptionPane.showMessageDialog(this, "Incorrect values",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
break;
default:
break;
}
} |
fb1405ec-992a-4258-bafa-6e6ae7c893f9 | 2 | private OBJIndex parseOBJIndex(String token)
{
String[] values = token.split("/");
OBJIndex result = new OBJIndex();
result.vertexIndex = Integer.parseInt(values[0]) - 1;
if(values.length > 1)
{
hasTexCoords = true;
result.texCoordIndex = Integer.parseInt(values[1]) - 1;
if(values.length > 2)
{
hasNormals = true;
result.normalIndex = Integer.parseInt(values[2]) - 1;
}
}
return result;
} |
9ccd1921-9d90-42cd-8af2-1cde934e1958 | 6 | @Override
public void tick(final EntityHandler caller) {
super.tick(caller);
double dx = Math.sin(rotationAngle) * speed;
double dy = -Math.cos(rotationAngle) * speed;
if (rotationAngle > 2 * Math.PI)
rotationAngle -= 2 * Math.PI;
if (rotationAngle < 0)
rotationAngle += 2 * Math.PI;
dir.x = dx;
dir.y = dy;
speed *= deaccl;
if (pos.x > Constants.WIDTH - RADIUS) {
dir.x = 0;
pos.x = Constants.WIDTH - RADIUS;
}
if (pos.y > Constants.HEIGHT - RADIUS) {
dir.y = 0;
pos.y = Constants.HEIGHT - RADIUS;
}
if (pos.x < RADIUS) {
dir.x = 0;
pos.x = RADIUS;
}
if (pos.y < RADIUS) {
dir.y = 0;
pos.y = RADIUS;
}
} |
0ed5efac-49b4-4160-b956-2cfdc6f425f2 | 8 | public double[][] createLattice(int rows, int cols, double rate,
double up, double down, double q)
{
double[][] lattice = new double[rows][cols];
for(int row = 0; row < rows; ++row)
{
for(int col = 0; col < cols; ++col)
{
/*
* Generate the first column and first row with the value
* of the 'rate' constant
*/
if(row == 0 && col == 0)
{
lattice[0][0] = rate;
}
/*
* Generate data for all columns > 0 in row 0
*/
else if(row == 0 && col != 0)
{
lattice[row][col] = down * lattice[row][col - 1];
}
/*
* Where the row number is equal to the column number, multiply
* 'up' constant times the value in lattice[row-1][column-1].
* All other values in this row will be dealt with in the next
* conditional.
*/
else if(row == col)
{
lattice[row][col] = up * lattice[row - 1][col - 1];
}
/*
* Generate data for all columns greater than the row number.
* This will only work where the values have already been
* generated where row number equal column number as set forth
* in the preceding conditional.
*/
else if(row < col)
{
lattice[row][col] = up * lattice[row - 1][col - 1];
}
}
}
return lattice;
} |
1c379534-5739-4e50-8689-3f8f671a9a62 | 8 | private static boolean isUnimportantSpot(BotState state, Region region,
List<RegionAnnotations> regionAnnotationsSoFar) {
if (regionAnnotationsSoFar.contains(RegionAnnotations.ENTRANCE_TO_OWN_SUPERREGION)) {
return false;
}
if (regionAnnotationsSoFar.contains(RegionAnnotations.ENTRANCE_TO_OPPONENT_SUPERREGION)) {
return false;
}
if (regionAnnotationsSoFar.contains(RegionAnnotations.SPOT_IN_OWN_SUPERREGION)) {
return false;
}
if (regionAnnotationsSoFar.contains(RegionAnnotations.SPOT_IN_OPPONENT_SUPERREGION)) {
return false;
}
if (regionAnnotationsSoFar.contains(RegionAnnotations.SUPERREGION_CAN_BE_TAKEN)) {
return false;
}
if (regionAnnotationsSoFar.contains(RegionAnnotations.CAN_TAKE_SUPERREGION)) {
return false;
}
// if the region is part of Australia or South America then it's not
// unimportant.
if (region.getSuperRegion().getId() == 2 || region.getSuperRegion().getId() == 6) {
return false;
}
// in all other cases return true
return true;
} |
a0090195-1d72-462c-bec5-4eeedff88e69 | 3 | protected boolean isElementoEnHechosInferidos(String elemento) {
if (null != hechosInferidos) {
for (String s : hechosInferidos) {
if (elemento.equals(s)) {
return true;
}
}
}
return false;
} |
5d6a8d0d-ec99-4316-bb1c-31909ee1fce8 | 6 | public void dbData(String uName) {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
}
if (uName != null) {
PreparedStatement ps = null;
Connection con = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection("jdbc:mysql://mysql2.cs.stonybrook.edu:3306/mlavina", "mlavina", "108262940");
if (con != null) {
con.setAutoCommit(false);
try {
String sql = "select email,password from customer where email = '"
+ uName + "'";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
rs.next();
dbName = rs.getString("Email");
dbPassword = rs.getString("password");
con.commit();
} catch (Exception e) {
con.rollback();
}
}
} catch (SQLException sqle) {
sqle.printStackTrace();
} finally {
try {
con.setAutoCommit(true);
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} |
0f918523-b01d-404a-9f90-dd64db73fc41 | 0 | public void setY(byte[] value) {
this.y = value;
} |
f78b9e4c-d006-466f-872f-d29488a8fd36 | 0 | public boolean GetVerbose()
{
return verbose;
} |
3f60dabd-cd96-4d96-b151-4c3419008d3b | 8 | public void move(int x, int y){
canAct = false;
//Check for Map Collision
if(map.tileExists(x, y)){
if(map.tileWalkable(x, y)){
if(!getEm().isCreatureAt(this, x,y)){
this.x = x;
this.y = y;
}else if(getEm().isCreatureAt(this, x,y)){
if(getEm().getEntityAt(this, x, y) instanceof Creature && getEm().getEntityAt(this, x, y)!=this){
Creature victim = (Creature)getEm().getEntityAt(this, x, y);
if(name.equals(Molybdenum.settings.PLAYER_NAME) || relationsWith(victim.name)==Creature.RELATION_HATED){
strike(victim);
}
}
}
}else{
getEm().mapCollisionTrigger(this, x, y);
}
}
} |
db260c5d-ac1f-4a85-9a7b-137e0e4654ea | 7 | public QueryHandler(SystemObject querySender, short simulationVariant, ConfigSimulationObject simulationObject) {
_querySender = querySender;
_isRequestFromApplication = _querySender instanceof ClientApplication;
_debug.fine("QueryHandler für " + _querySender + ", isRequestFromApplication: " + _isRequestFromApplication);
_simulationVariant = simulationVariant;
_worker = new Thread(this);
_worker.start();
if(simulationVariant > 0 && simulationObject == null) throw new IllegalStateException("Für eine Simulation wurde kein Simulationsobjekt angegeben");
_simulationObject = simulationObject;
// Die Anfragen müssen identifiziert werden (über ihre Datenidentifikation), aus diesem Grund wird an dieser Stelle
// die erwarteten/unterstützten Identifikationen erzeugt.
if(simulationVariant > 0) {
// Es handelt sich um eine Simulation, also müssen neue Datenidentifikationen erzeut werden
_dataDescriptionReadLocal = new DataDescription(_dataDescriptionRead.getAttributeGroup(), _dataDescriptionRead.getAspect(), simulationVariant);
_dataDescriptionWriteLocal = new DataDescription(
_dataDescriptionWrite.getAttributeGroup(), _dataDescriptionWrite.getAspect(), simulationVariant
);
_dataDescriptionAreaLocal = new DataDescription(_dataDescriptionArea.getAttributeGroup(), _dataDescriptionArea.getAspect(), simulationVariant);
_dataDescriptionUserLocal = new DataDescription(_dataDescriptionUser.getAttributeGroup(), _dataDescriptionUser.getAspect(), simulationVariant);
}
else {
// Es handelt sich um keine Simulation, es können die normalen Datenidentifikationen benutzt werden
_dataDescriptionReadLocal = _dataDescriptionRead;
_dataDescriptionWriteLocal = _dataDescriptionWrite;
_dataDescriptionAreaLocal = _dataDescriptionArea;
_dataDescriptionUserLocal = _dataDescriptionUser;
}
try {
// 4 Kanäle, die Antworten der Konfiguration zurückschicken
// Auf welches Objekt soll sich angemeldet werden (_querySender)
// Wer verschickt diese Nachricht (_localAuthority)
_senderReplyWriteTasks = new ConfigurationAnswerWriteTasks(_connection, _querySender, _localAuthority, simulationVariant);
// Auf welches Objekt soll sich angemeldet werden (_querySender)
// Wer verschickt diese Nachricht (_localAuthority)
_senderReplyReadTasks = new ConfigurationAnswerReadTasks(_connection, _querySender, _localAuthority, simulationVariant);
// Simulationen dürfen weder Benutzer ändern noch Konfigurationsbereiche steuern. Aus diesem Grund werden keine Sender für
// diesen Fall angemeldet.
if(simulationVariant > 0) {
// Auf die nicht initialisierten Objekte wird bei Simulationen nicht Zugegriffen, da die Simulation
// über die Datenidentifikation identifiziert werden kann.
_senderReplyUserAdministrationTask = null;
_senderReplyAreaTasks = null;
}
else {
// Auf welches Objekt soll sich angemeldet werden (_querySender)
// Wer verschickt diese Nachricht (_localAuthority)
_senderReplyUserAdministrationTask = new ConfigurationAnswerUserAdministrationTasks(_connection, _querySender, _localAuthority);
// Auf welches Objekt soll sich angemeldet werden (_querySender)
// Wer verschickt diese Nachricht (_localAuthority)
_senderReplyAreaTasks = new ConfigurationAnswerAreaTasks(_connection, _querySender, _localAuthority);
}
// Die Konfiguration muss alle Änderungen an Objekten propagieren. Dafür werden alle Listener bei allen Typen angemeldet.
// Alle dynamische Typen anfordern
final List<SystemObject> allDynamicTypes = _localConfiguration.getType("typ.dynamischerTyp").getElements();
for(SystemObject objectType : allDynamicTypes) {
final DynamicObjectType dynamicObjectType = (DynamicObjectType)objectType;
// Listener für "Objekte werden ungültig" anmelden
// Änderungen werden über die "atg.konfigurationsAnfrageSchnittstelleLesend" propagiert
final InvalidationListenerForTyps invalidationListenerForTyps = new InvalidationListenerForTyps(_senderReplyReadTasks, dynamicObjectType, _isRequestFromApplication);
dynamicObjectType.addInvalidationListener(invalidationListenerForTyps);
// Damit die Listener wieder entfernt werden können
_invalidationListenerForAllTyps.put(dynamicObjectType, invalidationListenerForTyps);
// Listener für "Der Name ändert sich" anmelden
final NameChangedListenerForTyps nameChangedListenerForTyps = new NameChangedListenerForTyps(_senderReplyReadTasks, dynamicObjectType,
_isRequestFromApplication
);
dynamicObjectType.addNameChangeListener(nameChangedListenerForTyps);
_nameChangedListener.put(dynamicObjectType, nameChangedListenerForTyps);
// Listener für "Neues Objekt" anmelden
final ObjectCreatedListenerForTyps objectCreatedListenerForTyps = new ObjectCreatedListenerForTyps(
_senderReplyReadTasks, dynamicObjectType
);
dynamicObjectType.addObjectCreationListener(objectCreatedListenerForTyps);
_objectCreatedListener.put(dynamicObjectType, objectCreatedListenerForTyps);
}
}
catch(ConfigurationException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
catch(OneSubscriptionPerSendData oneSubscriptionPerSendData) {
oneSubscriptionPerSendData.printStackTrace();
throw new RuntimeException(oneSubscriptionPerSendData);
}
} |
31224c0b-da71-49b9-8a76-a1ce3c7b6391 | 1 | public XPathHelper(Node node)
{
_node = node;
try
{
_xpath = newFactory().newXPath();
}
catch(XPathFactoryConfigurationException xpfce)
{
throw new RuntimeException(xpfce);
}
} |
7fc04a98-a0a5-4a89-965a-0906a0f2202a | 5 | public GenericObject loadFromString(String string) {
final long startTime = System.nanoTime();
//notify about loading
assert debug("Loading from string.", 2);
openStringStream(string);
GenericObject root = null;
try {
root = new GenericObject();
GenericObject curr = readObject(root);
while (tokenType != TokenType.EOF) {
curr = readObject(curr);
}
} catch (ParserException ex) {
if (!settings.isTryToRecover())
root = null;
} finally {
closeInStream();
}
if (m_errors > 0)
System.out.println("There were " + m_errors + " errors during loading.");
if (settings.isPrintTimingInfo())
System.out.println("Loading took " + (System.nanoTime()-startTime) + " ns.\n");
assert debug("The node read was:\n" + root, 6);
return root;
} |
2ec2f728-7941-4d19-b39c-5c0c331d2cd1 | 6 | @Override
public void getDataAttdReport(ClassInfo currentCourse, List<AttdCnt> acList) {
if (acList == null) {
return;
}
acList.clear();
//directory
String crsDirName = getDirName(currentCourse);
File dir = new File(crsDirName);
if (dir.exists() && dir.isDirectory()) {
//read every file in the directory
File[] files = dir.listFiles();
List<AttdRecordInfo> oneDayARList = null;
for (int i = 0; i < files.length; i++) {
String arFileName = files[i].getName();
Date dt = getDate(arFileName);
oneDayARList = new ArrayList<AttdRecordInfo>();
getDataAttdRecord(currentCourse, dt, oneDayARList);
AttdCnt acOneday = new AttdCnt(dt, oneDayARList.size(), 0);
int cnt = 0;
for (AttdRecordInfo ar: oneDayARList) {
if (ar.isAttendant()) {
cnt++;
}
}
acOneday.setAttdNumbers(cnt);
acList.add(acOneday);
}
}
} |
5f6611f7-e6f1-4654-97fb-30b0aa0e99e4 | 2 | public String remover(){
for(int i=0;i<repositorio.atividades.size();i++){
if(atividadeaux.getCodigoatividade() == repositorio.atividades.get(i).getCodigoatividade()){
repositorio.atividades.remove(i);
}
}
return "/atividade/lista?faces-redirect=true";
} |
48db8871-afa2-4460-92ae-0fa8dc155e6f | 4 | private void tick() {
if (state == STATE.MENU) {
menu.tick();
}
if (state == STATE.GAME) {
handler.tick();
cam.tick(handler.object);
if (eventOn) {
evt.tick(handler.object);
}
ui.tick();
}
if (state == STATE.PAUSE) {
pause.tick();
}
} |
a6764781-4a22-4d85-9edb-4d13fbe440ca | 1 | private static SoftValueRef create(Object key, Object val,
ReferenceQueue q) {
if (val == null)
return null;
else
return new SoftValueRef(key, val, q);
} |
17990fa3-bc40-4dfa-b56a-f05f2d2c92a8 | 3 | public void showProfile() throws ProfileNotSetException {
if (this.getEmail() == "" || this.getPhone() == ""
|| this.getDescription() == "") {
System.out.println("User " + this.getName() + " does not have any info set.");
} else {
System.out.println("User " + this.getName() + " has the following info:\n");
System.out.println(" -Email: " + this.getEmail());
System.out.println(" -Telephone nr: " + this.getPhone());
System.out.println(" -Description: " + this.getDescription());
}
} |
bc62ec94-8b63-4e5a-8140-9e89b1c0b793 | 8 | public void reset() {
{ QueryIterator self = this;
if ((Stella.$TRACED_KEYWORDS$ != null) &&
Stella.$TRACED_KEYWORDS$.membP(Logic.KWD_GOAL_CACHES)) {
System.out.println("------------- RESET -------------");
}
{ ControlFrame initialframe = self.baseControlFrame;
if (initialframe.down != null) {
ControlFrame.popFramesUpTo(initialframe.down);
}
{ PatternRecord patternrecord = initialframe.patternRecord;
self.currentPatternRecord = patternrecord;
{ Object old$Context$000 = Stella.$CONTEXT$.get();
Object old$Queryiterator$000 = Logic.$QUERYITERATOR$.get();
try {
Native.setSpecial(Stella.$CONTEXT$, Logic.getQueryContext());
Native.setSpecial(Logic.$QUERYITERATOR$, self);
PatternRecord.unbindVariablesBeginningAt(patternrecord, 0);
if (((Vector)(KeyValueList.dynamicSlotValue(self.dynamicSlots, Logic.SYM_LOGIC_INITIAL_BINDINGS, null))) != null) {
{ PatternVariable arg = null;
Vector vector000 = self.externalVariables;
int index000 = 0;
int length000 = vector000.length();
Stella_Object value = null;
Vector vector001 = ((Vector)(KeyValueList.dynamicSlotValue(self.dynamicSlots, Logic.SYM_LOGIC_INITIAL_BINDINGS, null)));
int index001 = 0;
int length001 = vector001.length();
for (;(index000 < length000) &&
(index001 < length001); index000 = index000 + 1, index001 = index001 + 1) {
arg = ((PatternVariable)((vector000.theArray)[index000]));
value = (vector001.theArray)[index001];
if (value != null) {
if (!(Logic.bindArgumentToValueP(arg, value, false))) {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("reset: binding of `" + arg + "' to `" + value + "' failed.");
throw ((FailException)(FailException.newFailException(stream000.theStringReader()).fillInStackTrace()));
}
}
}
}
}
}
ControlFrame.overlayWithPatternFrameP(initialframe, patternrecord.description, patternrecord.externalArguments);
} finally {
Logic.$QUERYITERATOR$.set(old$Queryiterator$000);
Stella.$CONTEXT$.set(old$Context$000);
}
}
}
self.exhaustedP = false;
self.timeoutP = false;
self.depthCutoffsP = false;
self.solutions.clear();
initialframe.truthValue = null;
self.augmentedGoalCacheP = false;
self.triggeredDepthCutoffP = false;
}
}
} |
da9c2366-364a-4b11-8482-6d93a4d1e64e | 5 | public static void copyCheck(HashMap<String, Integer> printed,
HashMap<String, Integer> toPrint, File outFile) {
try {
FileWriter fw = new FileWriter(outFile);
for(Map.Entry<String, Integer> pair : toPrint.entrySet()) {
String key = pair.getKey();
Integer val = pair.getValue();
if (key.matches("\\s*")) { break; };
if(printed.containsKey(key)) {
Integer numPrinted = printed.get(key);
if(val > numPrinted) {
fw.write((val-numPrinted) + "x " + key + "\n");
} else {
System.out.println("Already printed: " + key);
}
} else {
fw.write(val + "x " + key + "\n");
}
}
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
} |
a3e0c686-c53c-4659-bbf3-61a19c8c024d | 5 | private static String getReducerLogUrl(String reduceTaskDetailsJsp, List<String> countersList) {
Document reduceDetails = HtmlFetcher.getHtml(reduceTaskDetailsJsp);
Element tr = null;
for(Element elem : reduceDetails.getElementsByTag("tbody").first()
.children()) {
if(elem.child(2).text().equals("SUCCEEDED")) {
tr = elem;
break;
}
}
//String taskId = tr.child(0).text();
String countersLink = tr.child(10).child(0).absUrl("href");
Document countersDoc = HtmlFetcher.getHtml(countersLink);
Elements countersTrs = countersDoc.getElementsByTag("tbody").first().children();
for(Element elem : countersTrs) {
if(elem.getElementsByTag("td").size() == 1) {
countersList.add(" ");
String title = elem.text();
countersList.add(title);
countersList.add(" ");
}
if(elem.getElementsByTag("td").size() == 3) {
String valueStr = elem.child(2).text();
String name = elem.child(1).text();
//Long value = Long.parseLong(valueStr.replaceAll(",", ""));
countersList.add(name + "\t" + valueStr);
}
}
String logLink = tr.child(9).child(4).absUrl("href");
return logLink;
} |
4e912a08-b260-4d01-b932-a6f412b4ca2c | 7 | private static String getHexImageFile(HexType hexType)
{
switch (hexType)
{
case WOOD:
return "images/land/forest.gif";
case BRICK:
return "images/land/brick.gif";
case SHEEP:
return "images/land/pasture.gif";
case WHEAT:
return "images/land/wheat.gif";
case ORE:
return "images/land/ore.gif";
case DESERT:
return "images/land/desert.gif";
case WATER:
return "images/land/water.gif";
default:
assert false;
return null;
}
} |
793a3b87-5ba2-4a98-a4c9-5ecdefec0f3d | 6 | public Key next()
{
count++;
Key keyToReturn = null;
while (currentNode != null && !currentNode.isKey1Visited)
{
nodeStack.push(currentNode);
currentNode = currentNode.left; //We continue going left to reach the smallest key
}
//Now we cannot go any further on the left, we found the smallest key which was the last pushed element
currentNode = nodeStack.pop();
if (!currentNode.isKey1Visited)
{
keyToReturn = currentNode.key1;
if (currentNode.key2 != null)
{
currentNode.isKey1Visited = true;
//push this node back, so that next time, we take its key2
nodeStack.push(currentNode);
}
if (currentNode.middle != null)
{
currentNode = currentNode.middle;
}
else if (currentNode.right != null)
{
currentNode = currentNode.right;
}
//else: we don't have middle and right nodes (and we don't have left also because of the while loop), basically this is a leaf.
//we don't need to push it back!
else
{
currentNode = null; //This will pop the parent next time
}
}
else
{
currentNode.isKey1Visited = false;
keyToReturn = currentNode.key2;
currentNode = currentNode.right;
}
return keyToReturn;
}
}
public class Iterator implements Iterable<Key>
{
private Key lo;
private Key hi;
public Iterator()
{
lo = hi = null;
}
public Iterator(Key lo, Key hi)
{
this.lo = lo;
this.hi = hi;
}
public java.util.Iterator<Key> iterator()
{
return new TwoThreeTreeIterator(lo, hi);
}
}
public Iterable<Key> keys()
{
return new Iterator();
} |
74f03c40-08bd-48ac-aa28-a1a6f3e037fe | 1 | public static String[] addStringToArray(String[] array, String str) {
if (SpringObjectUtils.isEmpty(array)) {
return new String[] {str};
}
String[] newArr = new String[array.length + 1];
System.arraycopy(array, 0, newArr, 0, array.length);
newArr[array.length] = str;
return newArr;
} |
6437defe-4bbd-4400-b401-f22759e32279 | 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() );
} |
2a7ed459-1352-4b5c-bbee-73fb34aeab25 | 0 | @XmlTransient
public Collection<Diagnostico> getDiagnosticoCollection() {
return diagnosticoCollection;
} |
59d9e817-e7bd-40e1-8fb1-7fbed068116f | 1 | @Test
public void shouldThrowErrorWhenFileIsEmpty() throws IOException {
//given
File tmpFile = folder.newFile(FILENAME);
String filePathString = tmpFile.getAbsolutePath();
//when
try {
FileParser fileParser = new FileParser(filePathString);
fileParser.parse();
} catch (GOLException e) {
//then
String msg = "Datei darf nicht leer sein.";
assertEquals(msg, e.getMessage());
}
} |
524f4cce-b4e3-438a-a3d7-7c1275aeb589 | 0 | public void stop() {
_motor.set(0);
} |
0aa3c555-4fb2-4273-aae9-24e56dbdde95 | 1 | public static BasicToolbox getInstance() {
if (instance_ == null) instance_ = new BasicToolbox();
return instance_;
} |
2cee5c43-fa77-4396-bc76-78413385fbda | 5 | @Override
public void run() {
long previousTime = System.currentTimeMillis();
long currentTime = previousTime;
if (soundSystem == null) {
errorMessage("SoundSystem was null in method run().", 0);
cleanup();
return;
}
// Start out asleep:
snooze(3600000);
while (!dying()) {
// Perform user-specific source management:
soundSystem.ManageSources();
// Process all queued commands:
soundSystem.CommandQueue(null);
// Remove temporary sources every ten seconds:
currentTime = System.currentTimeMillis();
if ((!dying()) && ((currentTime - previousTime) > 10000)) {
previousTime = currentTime;
soundSystem.removeTemporarySources();
}
// Wait for more commands:
if (!dying())
snooze(3600000);
}
cleanup(); // Important!
} |
b77602fc-b353-40b6-9bb0-adc8af6388c4 | 7 | public Node ceiling(int x){
Node cur = root;
while(true){
if(cur.value==x) return cur;
if(x<cur.value){
if(cur.left==null){
return cur;
}
cur = cur.left;
} else{
if(cur.right==null){
while(cur.parent!=null && cur==cur.parent.right) cur=cur.parent;
return cur.parent;
}
cur = cur.right;
}
}
} |
028221f1-677e-4668-baf7-b520bb5dabc1 | 4 | public void paint(Graphics g) {
super.paint(g);
/*
*store information about current hour, minute and second.
*/
Date myDate = new Date();
currentHour = myDate.getHours();
currentMinute = myDate.getMinutes();
currentSecond = myDate.getSeconds();
if (currentMinute < 10) {
this.minuteCorrection = "0";
}
if (currentSecond < 10) {
this.secondCorrection = "0";
}
if (currentMinute >= 10) {
this.minuteCorrection = "";
}
if (currentSecond >= 10) {
this.secondCorrection = "";
}
//Set font
g.setFont(myFont);
//distance between number in digital clock
fm = g.getFontMetrics();
int hourXCoordinate = 20;
int minuteXCoordinate = hourXCoordinate + (fm.getMaxAdvance() * 2);
int secondXCoordinate = hourXCoordinate + (fm.getMaxAdvance() * 4);
g.drawString(Integer.toString(currentHour), hourXCoordinate, 80);
g.drawString(":", (hourXCoordinate + minuteXCoordinate) / 2, 80);
g.drawString(minuteCorrection + Integer.toString(currentMinute), minuteXCoordinate, 80);
g.drawString(":", (secondXCoordinate + minuteXCoordinate) / 2, 80);
g.drawString(secondCorrection + Integer.toString(currentSecond), secondXCoordinate, 80);
} |
41e3ebf7-ee2f-49d3-b709-3e7c17e24b39 | 7 | private void addVarOp(int op, int varIndex)
{
switch (op) {
case Token.SETCONSTVAR:
if (varIndex < 128) {
addIcode(Icode_SETCONSTVAR1);
addUint8(varIndex);
return;
}
addIndexOp(Icode_SETCONSTVAR, varIndex);
return;
case Token.GETVAR:
case Token.SETVAR:
if (varIndex < 128) {
addIcode(op == Token.GETVAR ? Icode_GETVAR1 : Icode_SETVAR1);
addUint8(varIndex);
return;
}
// fallthrough
case Icode_VAR_INC_DEC:
addIndexOp(op, varIndex);
return;
}
throw Kit.codeBug();
} |
6ccbe177-81c3-469c-9b56-0421bbc1e6d4 | 5 | private void setInitVar(MFStructOrig mforig, InfoSchema info)
{
lstVFVar = new ArrayList<Pair<String, String>>();
for(int i = 0; i != mforig.lst_FV.size(); i ++)
{
int i0 = 0;
if(Character.isDigit(mforig.lst_FV.get(i).charAt(0)))
{
String tmp = mforig.lst_FV.get(i);
for(int j = tmp.length(); j != 0; j--)
{
if(tmp.charAt(j - 1) == '_')
{
i0 = j;
break;
}
}
String name = tmp.substring(i0, tmp.length());
String type = info.getTypeFromColumn(name);
Pair<String, String> pairTypeName = new Pair<String, String>(type, name);
if(lstVFVar.contains(pairTypeName) == false)
{
lstVFVar.add(pairTypeName);
}
}
}
} |
98fe3241-2d41-4b9d-b2a4-4a12670f4de8 | 5 | public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int numberToGuess = (int)Math.abs(1000 * Math.random());
int guessNumber;
int guesses = 1;
boolean guessed = false;
System.out.print("Try to guess my number (integers between 1 and 1000 inclusive): ");
while(!guessed){
guessNumber = s.nextInt();
if(guessNumber < 1 || guessNumber > 1000){
System.out.print("You need to guess between 1 and 1000. Try again: ");
continue;
}
else if(guessNumber > numberToGuess){
System.out.print("No, my number is lower than that. Guess again: ");
}
else if(guessNumber < numberToGuess){
System.out.print("No, my number is higher than that. Guess again: ");
}
else{
System.out.println("CORRECT!");
System.out.println("You needed " + guesses + " guesses.");
guessed = true;
}
guesses++;
}
} |
ab112df3-a0a1-4374-abb6-fe9420f1c1ec | 0 | public EntityListener getEntityListener() {
return entityListener;
} |
72a6ec26-c8f0-46a8-b57f-f286e23422ce | 5 | public void paintComponent(Graphics page) {
//page.drawRect(0,0,50,50);
for (int y1=0;y1<w.HEIGHT;y1++)
for (int x1=0;x1<w.WIDTH;x1++) {
if (w.map[x1][y1].z<=w.WATERLEVEL)
page.setColor(new Color(0,0,64+DELTA*w.map[x1][y1].z));
else if (w.map[x1][y1].river!=-1)
page.setColor(new Color(0,0,Math.min(64+DELTA*w.map[x1][y1].z,255)));
else if (w.map[x1][y1].owner!=null)
page.setColor(Color.RED);
else
page.setColor(new Color(DELTA*w.map[x1][y1].z,DELTA*w.map[x1][y1].z,DELTA*w.map[x1][y1].z));
page.fillRect((int) (x1*SCALE),(int) (y1*SCALE),(int) SCALE,(int) SCALE);
}
} |
a380a371-afc1-4aaa-b379-f48d9181c595 | 7 | static private final void step6()
{ j = k;
if (b[k] == 'e')
{ int a = m();
if (a > 1 || a == 1 && !cvc(k-1)) k--;
}
if (b[k] == 'l' && doublec(k) && m() > 1) k--;
} |
a36d276f-093d-45fc-b37c-356acdf4dd18 | 9 | /* */ public void paint(Graphics g2) {
/* 153 */ if (this.applet != null) return;
/* */
/* 155 */ int w = getWidth() / 2;
/* 156 */ int h = getHeight() / 2;
/* 157 */ if ((this.img == null) || (this.img.getWidth() != w) || (this.img.getHeight() != h)) {
/* 158 */ this.img = createVolatileImage(w, h);
/* */ }
/* */
/* 161 */ Graphics g = this.img.getGraphics();
/* 162 */ for (int x = 0; x <= w / 16; x++) {
/* 163 */ for (int y = 0; y <= h / 16; y++)
/* 164 */ g.drawImage(this.bgImage, x * 16, y * 16, null);
/* */ }
/* 166 */ g.setColor(Color.LIGHT_GRAY);
/* */
/* 168 */ String msg = "Updating Minecraft";
/* 169 */ if (this.gameUpdater.fatalError) {
/* 170 */ msg = "Failed to launch";
/* */ }
/* */
/* 173 */ g.setFont(new Font(null, 1, 20));
/* 174 */ FontMetrics fm = g.getFontMetrics();
/* 175 */ g.drawString(msg, w / 2 - fm.stringWidth(msg) / 2, h / 2 - fm.getHeight() * 2);
/* */
/* 177 */ g.setFont(new Font(null, 0, 12));
/* 178 */ fm = g.getFontMetrics();
/* 179 */ msg = this.gameUpdater.getDescriptionForState();
/* 180 */ if (this.gameUpdater.fatalError) {
/* 181 */ msg = this.gameUpdater.fatalErrorDescription;
/* */ }
/* */
/* 184 */ g.drawString(msg, w / 2 - fm.stringWidth(msg) / 2, h / 2 + fm.getHeight() * 1);
/* 185 */ msg = this.gameUpdater.subtaskMessage;
/* 186 */ g.drawString(msg, w / 2 - fm.stringWidth(msg) / 2, h / 2 + fm.getHeight() * 2);
/* */
/* 188 */ if (!this.gameUpdater.fatalError) {
/* 189 */ g.setColor(Color.black);
/* 190 */ g.fillRect(64, h - 64, w - 128 + 1, 5);
/* 191 */ g.setColor(new Color(32768));
/* 192 */ g.fillRect(64, h - 64, this.gameUpdater.percentage * (w - 128) / 100, 4);
/* 193 */ g.setColor(new Color(2138144));
/* 194 */ g.fillRect(65, h - 64 + 1, this.gameUpdater.percentage * (w - 128) / 100 - 2, 1);
/* */ }
/* */
/* 197 */ g.dispose();
/* */
/* 199 */ g2.drawImage(this.img, 0, 0, w * 2, h * 2, null);
/* */ } |
6fe5569b-2d01-49f8-83c6-2bf2dff77708 | 5 | @AfterGroups("Insertion")
@Test(groups = "Red Black Tree")
public void testRedBlackTreeSearch() throws KeyNotFoundException,
EmptyCollectionException {
Integer count;
Reporter.log("[ ** 2-3 Tree Search ** ]\n");
try {
timeKeeper = System.currentTimeMillis();
for (Integer i = 0; i < seed; i++) {
redblackTree.search(i);
}
Reporter.log("Search -- Passed : "
+ (System.currentTimeMillis() - timeKeeper) + " ms\n");
timeKeeper = System.currentTimeMillis();
count = 0;
for (Integer i = -seed; i < 0; i++) {
try {
redblackTree.search(i);
} catch (KeyNotFoundException e) {
count++;
}
}
if (count == seed) {
Reporter.log("False search -- Passed : "
+ (System.currentTimeMillis() - timeKeeper) + " ms\n");
} else {
throw new KeyNotFoundException();
}
} catch (KeyNotFoundException e) {
Reporter.log("Searching -- Failed!!!\n");
throw e;
}
} |
eba2a976-eb9b-47c2-a7e3-060073040302 | 7 | private void advance() throws IOException {
next = null;
while((next==null)&&(reader!=null)) {
final String line = getLine();
if(line!=null) {
next = burster.parse(line);
if(next!=null) {
if(next.isEmpty()||((!allowPartials)&&(!burster.haveAllFields(next)))) {
next = null;
}
}
}
}
} |
e45632a3-97aa-42c7-a9f2-d476712ee01b | 4 | public int getNumberOfFilesInDirectory(DirectoryInfo info) {
Iterable<EntityInfo> iterator = null;
try {
iterator = listDirectory(info.getFullPath());
} catch (NotADirectoryException e) {
e.printStackTrace();
return 0;
} catch (PathNotFoundException e) {
e.printStackTrace();
return 0;
} catch (AccessDeniedException e) {
e.printStackTrace();
}
int count = 0;
for (@SuppressWarnings("unused")
EntityInfo it : iterator)
count++;
return count;
} |
d1d66001-aa48-45aa-bc99-104d77d062f2 | 3 | public boolean jsFunction_waitEndMove(int timeout) {
deprecated();
int curr = 0; if(timeout == 0) timeout = 10000;
while(JSBotUtils.isMoving())
{
if(curr > timeout)
return false;
Sleep(25);
curr += 25;
}
return true;
} |
1c12202c-148c-40a8-8a6f-b56f5338585c | 0 | public UpdateTask(Region[][] array, int hij, int loj, int hii, int loi,
int threshold, boolean irregular) {
this.array = array;
this.hij = hij;
this.loj = loj;
this.hii = hii;
this.loi = loi;
this.t = threshold;
this.irregular = irregular;
} |
07f63fb1-8059-474f-a00f-fb0af03f42cc | 3 | @Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for(int i = 0; i < width;i++){
for(int j = 0; j < height;j++){
g.drawImage(backTile, i*cellPix, j*cellPix, null);
}
}
for (MapObject obj : objects){
g.drawImage(obj.sprite, obj.x*cellPix, obj.y*cellPix, null);
}
} |
5d30706a-b028-47c6-9e59-42ca270302e8 | 6 | @Override
public Match find(int id) {
Match found = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
pst=this.connect().prepareStatement("select * from Matches where id= ?");
pst.setInt(1, id);
rs=pst.executeQuery();
System.out.println("recherche individuelle réussie");
if (rs.next()) {
found = new Match(rs.getInt("id"), rs.getString("equipeA"), rs.getString("equipeB"),rs.getInt("scoreA"), rs.getInt("scoreB"), rs.getDate("datematch"));
}
} catch (SQLException ex) {
Logger.getLogger(MatchDao.class.getName()).log(Level.SEVERE, "recherche individuelle echoué", ex);
}finally{
try {
if (rs != null)
rs.close();
} catch (SQLException ex) {
Logger.getLogger(MatchDao.class.getName()).log(Level.SEVERE, "liberation result set echoué", ex);
}
try {
if (pst != null)
pst.close();
} catch (SQLException ex) {
Logger.getLogger(MatchDao.class.getName()).log(Level.SEVERE, "liberation prepared statement echoué", ex);
}
}
return found;
} |
7bdc88df-0388-4e64-9548-c05be799317d | 3 | public ArrayList<String> load() throws IOException {
ArrayList<String> words = new ArrayList<String>();
File file = new File(FILE_LOCATION);
Reader r = null;
BufferedReader br = null;
try {
r = new FileReader(file);
br = new BufferedReader(r);
String line = br.readLine();
while (line != null) {
words.add(line);
line = br.readLine();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
br.close();
r.close();
}
}
return words;
} |
0da187d0-c267-428e-90de-dcf572772ba3 | 7 | @Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (label.equalsIgnoreCase("ctf")) {
if (sender instanceof Player) {
Player p = (Player) sender;
if (args.length==0) {
p.sendMessage(CTF.TAG_BLUE + "CTF plugin made by Phantom_64!");
} else if (args[0].equalsIgnoreCase("join")) {
CommandJoin.execute(p, args);
} else if (args[0].equalsIgnoreCase("setspawn")) {
CommandSetSpawn.execute(p, args);
} else if (args[0].equalsIgnoreCase("leave")) {
CommandLeave.execute(p, args);
} else if (args[0].equalsIgnoreCase("setflagspawn")) {
CommandSetFlagSpawn.execute(p, args);
}
} else {
sender.sendMessage(ChatColor.RED + "Only players can use this command.");
}
}
return true;
} |
ef598c0f-315f-4a96-9b1e-1bc2a5a89e6e | 6 | public double weightedMean_as_double() {
if (!weightsSupplied) {
System.out.println("weightedMean_as_double: no weights supplied - unweighted mean returned");
return this.mean_as_double();
} else {
boolean holdW = Stat.weightingOptionS;
if (weightingReset) {
if (weightingOptionI) {
Stat.weightingOptionS = true;
} else {
Stat.weightingOptionS = false;
}
}
double mean = 0.0D;
switch (type) {
case 1:
double[] dd = this.getArray_as_double();
double[] wwd = amWeights.getArray_as_double();
mean = Stat.mean(dd, wwd);
break;
case 12:
BigDecimal[] bd = this.getArray_as_BigDecimal();
BigDecimal[] wwb = amWeights.getArray_as_BigDecimal();
mean = (Stat.mean(bd, wwb)).doubleValue();
bd = null;
wwb = null;
break;
case 14:
throw new IllegalArgumentException("Complex cannot be converted to double");
default:
throw new IllegalArgumentException("This type number, " + type + ", should not be possible here!!!!");
}
Stat.weightingOptionS = holdW;
return mean;
}
} |
01fa8ab2-7c47-4705-9a22-28f2c71dd0c7 | 4 | @Override
public void mouseReleased(MouseEvent e) {
try {
if (renderingColor.equals(Color.GREEN)) {
System.out.println(
inputImage.getContentOfSelectionAsBlock(
mouseRect.x, mouseRect.y,
mouseRect.height, mouseRect.width));
} else if (renderingColor.equals(Color.RED)) {
System.out.println(
inputImage.getContentOfSelectionAsImageBlock(
mouseRect.x, mouseRect.y,
mouseRect.height, mouseRect.width));
} else {
System.out.println(
inputImage.getContentOfSelectionAsPageNumberBlock(
mouseRect.x, mouseRect.y,
mouseRect.height, mouseRect.width));
}
} catch (DoenstFitException ex) {
//Error handling code here
} catch (BadPageNumber pn) {
}
selecting = false;
mouseRect.setBounds(0, 0, 0, 0);
e.getComponent().repaint();
} |
1801c1fe-4751-445f-9701-751c669c0917 | 7 | private String getChar(int tone) {
String out="";
final String C36A[]={"Q" , "X" , "W" , "V" , "E" , "K" , " " , "B" , "R" , "J" , "<*10>" , "G" , "T" ,"F" , "<fs>" , "M" , "Y" , "C" , "cr" , "Z" , "U" , "L" , "<*22>" , "D" , "I" , "H" , "<ls>" , "S" , "O" , "N" , "<*30>" , "A" , "P" , "<*33>"};
final String F36A[]={"1" , "\u0429" , "2" , "=" , "3" , "(" , " " , "?" , "4" , "\u042e" , "<*10>" , "8" , "5" ,"\u042d" , "<fs>" , "." , "6" , ":" , "cr" , "+" , "7" , ")" , "<*22>" , " " , "8" , "\u0449" , "<ls>" , "" , "9" , "," , "<*30>" , "-" , "0" , "<*33>"};
//final String CRY36[]={"\u042f","\u044a","\u0412","\u04c1","\u0415","\u041a"," ","\u0411","\u0420","\u0419","<*10>","\u0490","\u0422","\u0424","<fs>","\u043c","\u042b","\u0426","cr","\u0417","\u0423","\u043b","<*22>","\u0414","\u0418","\u0425","ls","\u0421","\u041e","\041d","<*30>","\u0410","\u041f","<*33>"};
//if (tone==16) figureShift=true;
//else if (tone==28) figureShift=false;
//figureShift=true;
try {
if (tone<0) {
toneLowCount++;
tone=0;
}
else if (tone>33) {
toneHighCount++;
tone=33;
}
else toneCount[tone]++;
if (figureShift==false) out=C36A[tone];
else out=F36A[tone];
if (out.equals("<ls>")) figureShift=false;
else if (out.equals("<fs>")) figureShift=true;
else if (out.equals("cr")) figureShift=false;
}
catch (Exception e) {
JOptionPane.showMessageDialog(null,e.toString(),"Rivet", JOptionPane.INFORMATION_MESSAGE);
return "";
}
return out;
} |
09bff0ba-039c-485c-8b2c-20d4abfb9cba | 0 | @Before
public void setUp() {
} |
feee52e5-7f47-46e1-8309-ffb5878e5233 | 5 | public SimulationMenu(final Simulation model, final MainWindow mainWindow) {
super(new BorderLayout());
setOpaque(false);
this.model = model;// Assigns the model that this menu will control.
this.mainWindow = mainWindow;// Assigns the window this is related to.
// Get the resources (pictures for the buttons):
stepIcon = new ImageIcon(getClass().getResource(STEP_IMAGE_LOCATION));
playIcon = new ImageIcon(getClass().getResource(PLAY_IMAGE_LOCATION));
stopIcon = new ImageIcon(getClass().getResource(STOP_IMAGE_LOCATION));
// The step / play / pause menu:
playMenuHolder = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 2));
playMenu = new JPanel(null);
playMenu.setPreferredSize(new Dimension(125, 25));
playMenu.setBorder(BorderFactory.createTitledBorder(""));
playMenu.setOpaque(false);
step = new JButton(stepIcon);
step.setBounds(25, 3, 20, 20);
step.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
stepModel();
}
});
playMenu.add(step);
play = new JButton(playIcon) {
{
setIcon(playIcon);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (SimulationMenu.this.model.isPlaying()) {
Graphics2D g2d = (Graphics2D) g;
Rectangle toPaint = new Rectangle(2, 2, getWidth() - 4,
getHeight() - 4);
g2d.setColor(new Color(0x33, 0x66, 0x99, 0x66));
g2d.fill(toPaint);
}
}
};
play.setBounds(50, 3, 20, 20);
play.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
play();
}
});
playMenu.add(play);
stop = new JButton(stopIcon);
stop.setBounds(75, 3, 20, 20);
stop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
stop();
}
});
playMenu.add(stop);
playMenuHolder.add(playMenu);
add(playMenuHolder, BorderLayout.NORTH);
// The tabbed pane and everything in it:
menuPane = new JTabbedPane();
menuPane.setPreferredSize(new Dimension(150, 500));
optionsMenu = new WatermarkedPanel(new FlowLayout(FlowLayout.CENTER, 0,
10));
// The speed control:
speedMenu = new JPanel();
speedMenu.setPreferredSize(new Dimension(125, 50));
speedMenu.setBorder(BorderFactory.createTitledBorder("Framerate"));
speedMenu.setOpaque(false);
speedSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 100,
(int) speed);
speedSlider.setPreferredSize(new Dimension(100, 20));
speedSlider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
setSpeed(speedSlider.getValue());
}
});
speedSlider.setOpaque(false);
speedMenu.add(speedSlider);
// The accuracy control:
accuracyMenu = new JPanel();
accuracyMenu.setPreferredSize(new Dimension(125, 50));
accuracyMenu.setBorder(BorderFactory.createTitledBorder("Accuracy"));
accuracyMenu.setOpaque(false);
accuracySlider = new JSlider(SwingConstants.HORIZONTAL, 0, 10,
getAccuracy());
accuracySlider.setPreferredSize(new Dimension(100, 20));
accuracySlider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
setAccuracy(accuracySlider.getValue());
}
});
accuracySlider.setOpaque(false);
accuracyMenu.add(accuracySlider);
gravityMenu = new JPanel();
gravityMenu.setPreferredSize(new Dimension(125, 60));
gravityMenu.setBorder(BorderFactory.createTitledBorder("Gravity"));
gravityMenu.setOpaque(false);
gravitySlider = new JSlider(SwingConstants.HORIZONTAL, -5, 5,
(int) model.getGravity());
gravitySlider.setPreferredSize(new Dimension(100, 30));
gravitySlider.setPaintTicks(true);
gravitySlider.setMajorTickSpacing(5);
gravitySlider.setMinorTickSpacing(1);
gravitySlider.setSnapToTicks(true);
gravitySlider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
model.setGravity(gravitySlider.getValue());
}
});
gravitySlider.setOpaque(false);
gravityMenu.add(gravitySlider);
// Update the gravitySlider properly:
model.addPhysicsListener(new PhysicsListener() {
@Override
public void stateChanged(PhysicsEvent e) {
if (model.getGravity() != gravitySlider.getValue()) {
if (model.getGravity() < gravitySlider.getMinimum()) {
model.setGravity(gravitySlider.getMinimum());
gravitySlider.setValue(gravitySlider.getMinimum());
} else if (model.getGravity() > gravitySlider.getMaximum()) {
model.setGravity(gravitySlider.getMaximum());
gravitySlider.setValue(gravitySlider.getMaximum());
} else {
gravitySlider.setValue((int) model.getGravity());
}
}
setGoing(false);
}
});
optionsMenu.add(speedMenu);
optionsMenu.add(accuracyMenu);
optionsMenu.add(gravityMenu);
menuPane.addTab("Options", optionsMenu);
cameraMenu = new WatermarkedPanel();
mapPanel = new JPanel(new BorderLayout());
mapPanel.setOpaque(false);
mapPanel.setPreferredSize(new Dimension(120, 120));
mapPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
map = new CameraMap(model, this.mainWindow.modelView);
mapPanel.add(map, BorderLayout.CENTER);
cameraMenu.add(mapPanel);
zoomPanel = new JPanel();
zoomPanel.setPreferredSize(new Dimension(125, 50));
zoomPanel.setBorder(BorderFactory.createTitledBorder("Zoom"));
zoomPanel.setOpaque(false);
zoomSlider = new JSlider(-1000, 1000, 0);
zoomSlider.setPreferredSize(new Dimension(100, 20));
zoomSlider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
double zoomFactor = 1.0;
double value;
if (zoomSlider.getValue() >= 0) {
value = ((double) zoomSlider.getValue()) / 1000;
value *= 2;
} else {
value = ((double) zoomSlider.getValue()) / 1200;
}
zoomFactor = 1.01 + value;
mainWindow.modelView.setZoomFactor(zoomFactor);
}
});
zoomSlider.setOpaque(false);
zoomPanel.add(zoomSlider);
cameraMenu.add(zoomPanel);
menuPane.addTab("Camera", cameraMenu);
add(menuPane);
setPreferredSize(new Dimension(160, 650));
} |
b496834f-745c-40b0-8148-d6037c5e2e53 | 2 | public void actionPerformed(ActionEvent e) {
if (e.getSource() == Next) {
}
else if (e.getSource() == Previous) {
}
} |
5fa2ba26-12ba-466b-8e18-f97ee7e2bc56 | 0 | private GuiceInjector() {
} |
53d57bad-2874-4ce1-ac95-8fb90899e990 | 5 | @Override
public void mousePresenceAt(double x, double y) {
for (MenuButton but : _buttons) {
if (but.isMouseWithin(x, y)) {
if (_mouseLastAtButton != but) {
if (_mouseLastAtButton != null)
_mouseLastAtButton.actionOnExit();
but.actionOnEnter();
_mouseLastAtButton = but;
}
return;
}
}
if (_mouseLastAtButton != null) {
_mouseLastAtButton.actionOnExit();
_mouseLastAtButton = null;
}
} |
95e796ef-4640-4ff4-a3a1-0b08125bbede | 3 | public JargonCollection getParentCollection() throws IrodsException {
IRODSFile p;
try {
if (irodsFile.getParent() == null || irodsFile.getParent().isEmpty()) {
return null;
}
p = conn.irodsFileFactory.instanceIRODSFile(irodsFile.getParent());
} catch (JargonException ex) {
throw new IrodsException(ex);
}
return new JargonCollection(conn, p);
} |
125ac11b-c5cf-4e3e-af3b-d7a40360e1c1 | 4 | void accPhiStat(_Doc d) {
double prob;
for(int t=0; t<d.getSenetenceSize(); t++) {
_Stn s = d.getSentence(t);
for(_SparseFeature f:s.getFv()) {
int wid = f.getIndex();
double v = f.getValue();//frequency
for(int i=0; i<number_of_topics; i++) {
prob = this.p_dwzpsi[t][i];
for(int j=1; j<constant; j++)
prob += this.p_dwzpsi[t][i + j*number_of_topics];
this.sstat[i][wid] += v * prob;
}
}
}
} |
a0c6086c-67cf-4ca5-b833-fe42a79079a6 | 8 | public void searchAllClass(HttpServletRequest request)
{
if (bInit)
return;
try
{
// Tools.getClassesFromFileJarFile("jcore.jsonrpc.rpcobj", "/");//
Class[]lst = Tools.getClasses("jcore.jsonrpc.rpcobj");
if(null == lst)return;
String s;
if(Tools.bDebug && 0 == lst.length)System.out.println("没有找到---遗憾吧");
for (int i = 0; i < lst.length; i++) {
s = lst[i].getName();
try {
if(Tools.bDebug)System.out.println("开始初始化:" + s);
JsonRpcRegister.registerObject(request, s.substring(s.lastIndexOf(".") + 1), lst[i]);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
// s = java.net.URLDecoder.decode(s);
// File f = new File(s);
// File[] fs = f.listFiles();
// if (null == fs)
// {
// // System.out.println("Load Errors(" + s + ")");
// int n = s.indexOf(".jar");
// if(-1 < n)
// {
// try
// {
// s = s.substring(0, n + 4);
// int nTomCat = s.lastIndexOf("webapps");
// // if(-1 <
// System.getProperty("java.class.path").toString().toLowerCase().indexOf("weblogic"));
// if(-1 < nTomCat)
// {
// s = "../" + s.substring(nTomCat).replaceAll("\\\\", "/");
// // System.out.println("Load (" + s + ")");
// }
// // else System.out.println("no webapps (" + s + ")");
// JarFile jarFile = new JarFile(s);
// Enumeration myenum = jarFile.entries();
// int k = 0;
// String szPkgTmp = szPkg.substring(1);
// while (myenum.hasMoreElements()) {
// JarEntry entry = (JarEntry)myenum.nextElement();
// String szClassName = entry.getName();
// k = szClassName.lastIndexOf(".class");
// // System.out.println(szClassName);
// if(-1 < k && -1 < szClassName.indexOf(szPkgTmp))
// {
// try {
// szClassName = szClassName.substring(0, k).replaceAll("[/]", ".");
// // System.out.println(szClassName);
// JsonRpcRegister.registerObject(request,
// szClassName.substring(szClassName.lastIndexOf(".") + 1), Class
// .forName(szClassName));
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// }
// } catch (Exception e) {
// System.out.print(s);
// e.printStackTrace();
// }
// }
// // else System.out.print("not find .jar");
// return;
// }
// else
// {
// // System.out.println((null == fs) + "[" + fs.length + "]");
// for (int i = 0; i < fs.length; i++) {
// if (fs[i].isDirectory())
// searchAllClass(request, fs[i].getAbsolutePath());
// else {
// String s1 = fs[i].getAbsolutePath();
// if (-1 < s1.indexOf(".svn"))
// continue;
// s1 = s1.substring(s1.indexOf("jcore"));
// if (-1 < s1.indexOf("\\"))
// s1 = s1.substring(0, s1.indexOf("."));
// s1 = s1.replaceAll("\\\\", ".");
// s1 = s1.replaceAll("/", ".");
// String pknm = "jcore.jsonrpc.rpcobj";
// if(s1.endsWith(".class"))
// s1 = s1.substring(0, s1.length() - 6);
// if (s1.startsWith(pknm))
// try {
// JsonRpcRegister.registerObject(request, s1
// .substring(pknm.length() + 1), Class
// .forName(s1));
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// }
// }
} |
a19516b0-a515-4d08-a58e-e7e8a4b75056 | 5 | private void ConvertOld() {
final File file = new File(extraauth.getDataFolder().getAbsolutePath()
+ File.separator + "PlayerStatusDB.db");
new File(extraauth.getDataFolder().getAbsolutePath() + File.separator
+ "PlayerStatusDB.db.bak");
playerstatus ps;
int method;
extraauth.Log.log(Level.WARNING, "ExtraAuth.Converting");
try {
final ObjectInputStream in = new ObjectInputStream(new FileInputStream(
file));
final int version = in.readInt();
if (version != 1)
throw new Exception("Invalid version");
final int size = in.readInt();
new HashMap<String, Tag>(size);
for (int i = 0; i < size; i++) {
ps = new playerstatus();
ps.Player = in.readUTF();
ps.Authed = in.readBoolean();
ps.LastOnline = in.readLong();
ps.LastIP = in.readUTF();
ps.PrivateKey = in.readUTF();
method = in.readInt();
if (method == 1)
ps.Method = AuthManager.GetAuthMethod("Key");
else if (method == 2)
ps.Method = AuthManager.GetAuthMethod("TOTP");
else
continue;
db.add(ps);
}
in.close();
} catch (final Exception e) {
extraauth.Log.log(Level.SEVERE, e.getMessage(), false);
}
} |
53dcfb27-089b-45e6-8e90-928ccdb40879 | 2 | public static Receipt getById(final String token, final String id) {
JSONArray fetchById = null;
try {
fetchById = fetchById(token, object, id);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<Receipt> formatOutputs = formatOutputs(fetchById);
if (formatOutputs.size() > 0)
return formatOutputs.get(0);
return null;
} |
0c652c7c-93a2-481d-a649-447b0eba8c70 | 4 | public JSInventory[] getInventories() {
ArrayList<JSInventory> items = new ArrayList<JSInventory>();
try {
for (Widget i = wdg().child; i != null; i = i.next) {
if (i instanceof Inventory) {
items.add(new JSInventory(UI.instance.getId(i)));
}
}
} catch (Exception ex) {
// Do nothing
}
JSInventory[] ret = new JSInventory[items.size()];
for (int i = 0; i < items.size(); i++)
ret[i] = items.get(i);
return ret;
} |
d3c357c5-d494-4a8e-b2aa-eb9ce32ef97a | 5 | private void saveLabels() {
// Make sure any labels in the removed blocks are saved.
boolean save = false;
final Iterator iter = method.code().listIterator();
while (iter.hasNext()) {
final Object obj = iter.next();
if (obj instanceof Label) {
final Label label = (Label) obj;
if (label.startsBlock()) {
if (getNode(label) == null) {
save = true;
} else {
save = false;
}
}
if (save) {
label.setStartsBlock(false);
iniBlock.tree().addStmt(new LabelStmt(label));
}
}
}
} |
f71c26c3-3d3f-4ead-a576-65a705961b4f | 2 | private boolean stepInDirectionOfX(int xDestination) {
if (x < xDestination) {
x += Math.min(stepSize, xDestination - x);
} else if (x > xDestination) {
x -= Math.min(x - xDestination, stepSize);
}
return x == xDestination;
} |
234d55b1-da92-43bc-b651-c71d2b3c50b0 | 6 | public static boolean checkIfNoneMatchEtag(HttpServletRequest request, HttpServletResponse response, String etag) {
String headerValue = request.getHeader("If-None-Match");
if (headerValue != null) {
boolean conditionSatisfied = false;
if (!"*".equals(headerValue)) {
StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");
while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
String currentToken = commaTokenizer.nextToken();
if (currentToken.trim().equals(etag)) {
conditionSatisfied = true;
}
}
} else {
conditionSatisfied = true;
}
if (conditionSatisfied) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.setHeader("ETag", etag);
return false;
}
}
return true;
} |
36cb8330-77a9-44bb-8f95-7c734ad62084 | 5 | public Object getLdcValue(int index) {
ConstInfo constInfo = this.getItem(index);
Object value = null;
if (constInfo instanceof StringInfo)
value = this.getStringInfo(index);
else if (constInfo instanceof FloatInfo)
value = new Float(getFloatInfo(index));
else if (constInfo instanceof IntegerInfo)
value = new Integer(getIntegerInfo(index));
else if (constInfo instanceof LongInfo)
value = new Long(getLongInfo(index));
else if (constInfo instanceof DoubleInfo)
value = new Double(getDoubleInfo(index));
else
value = null;
return value;
} |
f4570c59-e818-4b72-896a-170fc604102f | 8 | private void growObstaclesPass() {
// grow obstacles
for (int i = 0; i < userObstacles.size(); i++)
((Obstacle) userObstacles.get(i)).growVertices();
// go through paths and test segments
for (int i = 0; i < workingPaths.size(); i++) {
Path path = (Path) workingPaths.get(i);
for (int e = 0; e < path.excludedObstacles.size(); e++)
((Obstacle) path.excludedObstacles.get(e)).exclude = true;
if (path.grownSegments.size() == 0) {
for (int s = 0; s < path.segments.size(); s++)
testOffsetSegmentForIntersections(
(Segment) path.segments.get(s), -1, path);
} else {
int counter = 0;
List currentSegments = new ArrayList(path.grownSegments);
for (int s = 0; s < currentSegments.size(); s++)
counter += testOffsetSegmentForIntersections(
(Segment) currentSegments.get(s), s + counter, path);
}
for (int e = 0; e < path.excludedObstacles.size(); e++)
((Obstacle) path.excludedObstacles.get(e)).exclude = false;
}
// revert obstacles
for (int i = 0; i < userObstacles.size(); i++)
((Obstacle) userObstacles.get(i)).shrinkVertices();
} |
2222c922-0a60-4b9d-95b2-c903fb865851 | 1 | public void runAnimation(){
index++;
if(index > speed){
index = 0;
nextFrame();
}
} |
c2a44955-6a6f-4b29-933f-ed99b0dff71d | 5 | public boolean searchForElement(String value) {
boolean isFound = false;
ListElement index = head;
if (index != null) {
if (index.next == null && index.value == value) {
isFound = true;
} else {
while (index.next != null) {
if (index.value != value) {
index = index.next;
} else {
isFound = true;
break;
}
}
}
}
return isFound;
} |
27a7d3d1-ef6f-4a26-9b1f-8b0db2e5e7f9 | 5 | public void removeClass(String name){
DragAndDropClassObject obj;
for (int i=0;i<components.size();i++){
obj = components.get(i);
if (obj.name.equals(name)){
for (DragAndDropClassObject classObject:components){
for (int j = 0; j<classObject.links.size(); j++){
Link link = classObject.links.get(i);
if (link.classTwoName.equals(obj.name)){
classObject.links.remove(i);
j--;
}
}
}
components.remove(i);
diagramPanel.repaint();
return;
}
}
} |
f70017dd-1d22-4469-a6bb-913624ceb514 | 3 | public boolean AreXItemsInBag(int ItemID, int Amount) {
int ItemCount = 0;
for (int i = 0; i < playerItems.length; i++) {
if ((playerItems[i] - 1) == ItemID) {
ItemCount++;
}
if (ItemCount == Amount) {
return true;
}
}
return false;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.