method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
1d81532d-bd5d-421f-8a84-744d01a6a58c | 7 | private void expTypeChanged() {
if (m_Exp == null) return;
// update parameter ui
if (m_ExperimentTypeCBox.getSelectedItem() == TYPE_CROSSVALIDATION_TEXT) {
m_ExperimentParameterLabel.setText("Number of folds:");
m_ExperimentParameterTField.setText("" + m_numFolds);
} else {
m_ExperimentParameterLabel.setText("Train percentage:");
m_ExperimentParameterTField.setText("" + m_trainPercent);
}
// update iteration ui
if (m_ExperimentTypeCBox.getSelectedItem() == TYPE_FIXEDSPLIT_TEXT) {
m_NumberOfRepetitionsTField.setEnabled(false);
m_NumberOfRepetitionsTField.setText("1");
m_Exp.setRunLower(1);
m_Exp.setRunUpper(1);
} else {
m_NumberOfRepetitionsTField.setText("" + m_numRepetitions);
m_NumberOfRepetitionsTField.setEnabled(true);
m_Exp.setRunLower(1);
m_Exp.setRunUpper(m_numRepetitions);
}
SplitEvaluator se = null;
Classifier sec = null;
if (m_ExpClassificationRBut.isSelected()) {
se = new ClassifierSplitEvaluator();
sec = ((ClassifierSplitEvaluator)se).getClassifier();
} else {
se = new RegressionSplitEvaluator();
sec = ((RegressionSplitEvaluator)se).getClassifier();
}
// build new ResultProducer
if (m_ExperimentTypeCBox.getSelectedItem() == TYPE_CROSSVALIDATION_TEXT) {
CrossValidationResultProducer cvrp = new CrossValidationResultProducer();
cvrp.setNumFolds(m_numFolds);
cvrp.setSplitEvaluator(se);
PropertyNode[] propertyPath = new PropertyNode[2];
try {
propertyPath[0] = new PropertyNode(se, new PropertyDescriptor("splitEvaluator",
CrossValidationResultProducer.class),
CrossValidationResultProducer.class);
propertyPath[1] = new PropertyNode(sec, new PropertyDescriptor("classifier",
se.getClass()),
se.getClass());
} catch (IntrospectionException e) {
e.printStackTrace();
}
m_Exp.setResultProducer(cvrp);
m_Exp.setPropertyPath(propertyPath);
} else {
RandomSplitResultProducer rsrp = new RandomSplitResultProducer();
rsrp.setRandomizeData(m_ExperimentTypeCBox.getSelectedItem() == TYPE_RANDOMSPLIT_TEXT);
rsrp.setTrainPercent(m_trainPercent);
rsrp.setSplitEvaluator(se);
PropertyNode[] propertyPath = new PropertyNode[2];
try {
propertyPath[0] = new PropertyNode(se, new PropertyDescriptor("splitEvaluator",
RandomSplitResultProducer.class),
RandomSplitResultProducer.class);
propertyPath[1] = new PropertyNode(sec, new PropertyDescriptor("classifier",
se.getClass()),
se.getClass());
} catch (IntrospectionException e) {
e.printStackTrace();
}
m_Exp.setResultProducer(rsrp);
m_Exp.setPropertyPath(propertyPath);
}
m_Exp.setUsePropertyIterator(true);
m_Support.firePropertyChange("", null, null);
} |
1ee4b01e-6722-4c9d-9422-bb737c9b7bd1 | 2 | private double[] charToDouble(char[] responses){
int n = responses.length;
double[] converted = new double[n];
for(int i=0; i<n; i++){
double holdi = (double)((int)responses[i]);
if(holdi>96.0){
converted[i] = holdi-96.0;
}
else{
converted[i] = holdi-64.0;
}
}
return converted;
} |
7acc0b09-c0e3-4b1c-93de-bae6eecfa63a | 3 | public void drawCities(){
for ( int r = 0; r < GameConstants.WORLDSIZE; r++ ) {
for ( int c = 0; c < GameConstants.WORLDSIZE; c++ ) {
City city = game.getCityAt(new Position(r, c));
if (city != null){
CityFigure cf = new CityFigure(city,
new Point( GfxConstants.getXFromColumn(c),
GfxConstants.getYFromRow(r)));
cityFigures.put(new Position(r, c), cf);
editor.drawing().add(cf);
}
}
}
} |
23058936-834f-4cc9-b4bb-95ec1fcd30ac | 8 | @Override
public boolean equals(Object obj) {
if (!(obj instanceof LabelBlock)) {
return false;
}
LabelBlock that = (LabelBlock) obj;
if (!this.text.equals(that.text)) {
return false;
}
if (!this.font.equals(that.font)) {
return false;
}
if (!PaintUtilities.equal(this.paint, that.paint)) {
return false;
}
if (!ObjectUtilities.equal(this.toolTipText, that.toolTipText)) {
return false;
}
if (!ObjectUtilities.equal(this.urlText, that.urlText)) {
return false;
}
if (!this.contentAlignmentPoint.equals(that.contentAlignmentPoint)) {
return false;
}
if (!this.textAnchor.equals(that.textAnchor)) {
return false;
}
return super.equals(obj);
} |
59d1c2f2-b424-4c6f-a337-ef0469c27d18 | 1 | private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
currentRound++;
jLabel7.setText(g.makeThrow(2));
jLabel3.setText(g.getScore());
jLabel6.setText(g.getPredictedThrow());
if(currentRound == numberOfThrows) {
JOptionPane.showMessageDialog(this, "Final Score: " + g.getScore());
System.exit(1);
}
} |
4a7bb636-317c-49d6-98d1-c483d88a48b9 | 3 | public char skipTo(char to) throws JSONException {
char c;
try {
int startIndex = this.index;
int startCharacter = this.character;
int startLine = this.line;
reader.mark(Integer.MAX_VALUE);
do {
c = next();
if (c == 0) {
reader.reset();
this.index = startIndex;
this.character = startCharacter;
this.line = startLine;
return c;
}
} while (c != to);
} catch (IOException exc) {
throw new JSONException(exc);
}
back();
return c;
} |
fe8668f1-4b68-4c02-b43d-808c45908378 | 4 | private static void doArchive() throws MVDException
{
try
{
MVD mvd = loadMVD();
File m = new File( mvdFile );
File archiveDir;
XMLGuideFile guideFile = new XMLGuideFile( mvd );
// create default archive name
if ( archiveName == null )
{
archiveName = m.getName();
int index = archiveName.lastIndexOf(".");
archiveName = archiveName.substring( 0, index );
archiveDir = new File( m.getParentFile(), archiveName );
}
else
archiveDir = new File( archiveName );
if ( !archiveDir.exists() )
archiveDir.mkdir();
int nVersions = mvd.numVersions();
for ( short i=1;i<=nVersions;i++ )
{
char[] data = mvd.getVersion( i );
// use the short name as the file name
String vName = mvd.getVersionShortName( i );
File versionFile = new File( archiveDir, vName );
FileOutputStream fos = new FileOutputStream( versionFile );
OutputStreamWriter osw = new OutputStreamWriter( fos, mvd.getEncoding() );
osw.write( data );
osw.close();
guideFile.setVersionFile( i, vName );
}
guideFile.externalise( new File(archiveDir,XMLGuideFile.GUIDE_FILE) );
}
catch ( Exception e )
{
throw new MVDToolException( e );
}
} |
13b627b3-eb27-489a-9fc8-2a58370b5c85 | 0 | int getId()
{
return id;
} |
9e62e4e7-ee12-4e7b-9447-83dcbef00e1e | 8 | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Note note = (Note) o;
if (id != note.id) return false;
if (headLine != null ? !headLine.equals(note.headLine) : note.headLine != null) return false;
if (text != null ? !text.equals(note.text) : note.text != null) return false;
return true;
} |
96409357-5450-46e8-a5d8-7b7d0f3f9b60 | 2 | public Deck() {
cards = new ArrayList<DevCard>(25);
for (int i = 0; i < 14; i++)
cards.add(new DevCard("Knight"));
cards.add(new DevCard("Progress", "Road building"));
cards.add(new DevCard("Progress", "Road building"));
cards.add(new DevCard("Progress", "Year of plenty"));
cards.add(new DevCard("Progress", "Year of plenty"));
cards.add(new DevCard("Progress", "Monopoly"));
cards.add(new DevCard("Progress", "Monopoly"));
for (int i = 0; i < 5; i++)
cards.add(new DevCard("Victory Point"));
Collections.shuffle(cards);
} |
03e31afa-5d34-4f7c-98e1-ea2bba950a44 | 2 | public static int nextSequenceNumber(int sequenceNumber) {
if(sequenceNumber == Packet.SEQUENCE_NUMBER_NOT_APPLICABLE || sequenceNumber == Packet.MAXIMUM_SEQUENCE_NUMBER)
return Packet.MINIMUM_SEQUENCE_NUMBER;
return sequenceNumber + 1;
} |
095e1e8d-71d5-4ebf-b4a3-dbaa884e6a57 | 0 | public Quicksort(int[] values) {
this.numbers = values;
} |
8ec015b8-0b81-4ecc-9d6a-fb13656e75ee | 2 | public void addItem(Item item) {
for(int x = 0; x<size; x++) {
if(items.get(x).getID() == 0) {
items.set(x, item);
break;
}
}
} |
138fb613-9016-4068-9fbd-9a1413cd194c | 4 | public String toString()
{
String rankStr = null;
if(rank == 11)
{
rankStr = "jack";
String str = rankStr+suit;
return str;
}
else if(rank == 12)
{
rankStr = "queen";
String str = rankStr+suit;
return str;
}
else if(rank == 13)
{
rankStr = "king";
String str = rankStr+suit;
return str;
}
else if(rank == 14)
{
rankStr = "ace";
String str = rankStr+suit;
return str;
}
else
{
String str = rank + "" + suit;
return str;
}
} |
35cdd763-30f5-41a8-a545-23c8efa9d8d7 | 7 | @Override
public int read(char cbuf[], int off, int len) throws IOException {
// System.out.println("read() off:" + off + " len:" + len);
// Fetch new line if necessary
if (curLine == null) {
getNextLine();
}
// Return characters from current line
if (curLine != null) {
int num = Math.min(len, Math.min(cbuf.length - off,
curLine.length() - curLineIx));
// Copy characters from curLine to cbuf
for (int i = 0; i < num; i++) {
cbuf[off++] = curLine.charAt(curLineIx++);
}
// No more characters in curLine
if (curLineIx == curLine.length()) {
curLine = null;
// Is there room for the newline?
if (num < len && off < cbuf.length) {
cbuf[off++] = '\n';
num++;
}
}
// Return number of character read
// System.out.println("read " + num);
return num;
} else if (len > 0) {
// No more characters left in input reader
return -1;
} else {
// Client did not ask for any characters
return 0;
}
} |
88834f4f-d3ff-458c-ae5e-41aa6dd60d0c | 1 | @Override
public void run() {
try {
String dur=null;
int[][] A = new int[cnt][cnt],B=new int[cnt][cnt],C=new int[cnt][cnt];
int_mat(A);
int_mat(B);
long start=System.currentTimeMillis();
integer_operation(A, B, C);
long end=System.currentTimeMillis();
dur=end-start+"";
System.out.println("running time is"+dur);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("exception");
}
// TODO Auto-generated method stub
} |
8510e628-772e-460c-8230-ca1641638a8f | 6 | @Override
public void actionPerformed(ActionEvent event) {
String userkey = projectName.getText().toString();
String mess = p_dao.saveProject(userkey);
if(event.getActionCommand().equals("Add")){
if(!userkey.equals("")) {
message.setText(mess);
projectName.setText("");
if(mess.contains("SAVE_PROJECT_SUCCESS"))
model.addRow(new Object[]{userkey});
}
}
else if(event.getActionCommand().equals("Delete")){
message.setText(mess);
projectName.setText("");
int length = model.getRowCount();
for(int i=0;i<length;i++){
if(model.getValueAt(i, 0).toString().equals(userkey)){
model.removeRow(i);
break;
}
}
}
} |
7be59751-eb30-4ebf-9d78-166ac35f91c3 | 7 | private void buildTranslationTable(BufferedReader buf) throws IOException {
translationTable = new Hashtable<String, String>();
String line = buf.readLine();
while(line!=null && ! line.contains(";")) {
String[] parts = line.split("\\s+");
if (parts.length>2) {
int index = 0;
while(index<parts.length && parts[index].trim().length()==0)
index++;
if (index<parts.length-1) {
parts[index+1] = parts[index+1].replaceAll(",", "");
translationTable.put(parts[index], parts[index+1]);
//System.out.println("Associating key " + parts[index] + " with value : " + parts[index+1]);
}
}
line = buf.readLine();
}
if (treeReader != null)
treeReader.setTranslationTable(translationTable);
} |
720b599e-1ab9-481a-a29e-6b0f14001ba5 | 3 | public static void main(String [] args){
String path = new String("/home/elblonko/Desktop/DICOMFiles/BRAINIX/sequence/IM-0001-0001.dcm");
//Number of files in the path
File fileDir = new File("/home/elblonko/Desktop/DICOMFiles/BRAINIX/sequence");
int numFiles = fileDir.listFiles().length;
//Check to see if num files is correct
System.out.println("Number of Files: " + numFiles);
DICOM dcm = new DICOM();
dcm.open(path);
if (dcm.getWidth()==0)
IJ.log("Error opening '" + path + "'");
/*
else
dcm.show();
*/
//create a image stack of DICOM files PROOF OF SINGLE CASE
/*
ImageStack dcmStack = new ImageStack(dcm.getWidth(),dcm.getHeight(),numFiles);
dcmStack.addSlice(dcm.getProcessor());
*/
ImageStack dcmStack = new ImageStack(dcm.getWidth(),dcm.getHeight());
File[] directoryListing = fileDir.listFiles();
//Sort the file alphabetically
Arrays.sort(directoryListing);
if(directoryListing != null){
for(File child: directoryListing){
//open DICOM
dcm.open(child.getAbsolutePath());
//Add DICOM to DicomStack
dcmStack.addSlice(dcm.getProcessor());
//System.out.println(child.toString());
}
}
//Now sort the stack
//Generate the DicomTool
DicomTools dTools = new DicomTools();
dTools.sort(dcmStack);
//Pass in the stack to the sorted
ImageStack sortedDcmStack = dTools.sort(dcmStack);
//Get and print the Voxel Depth of the DicomStack
/*
double voxelDepth = dTools.getVoxelDepth(dcmStack);
System.out.println("Voxel Depth of Stack: " + voxelDepth +
" Times Loop ran: " + " Size of Stack: " +
dcmStack.getSize());
*/
//now we construct an image plus from the image stack
/*
The first argument will be used as the title of the window that displays the image
the second is the imagestack.
*/
ImagePlus dicomStackImage = new ImagePlus("BRAINX",sortedDcmStack);
//trying to save the image as tiff file types
FileSaver saveFile = new FileSaver(dicomStackImage);
//BOTH OF THESE FILE SAVES WORKS. THOUGH jpeg only works for a single slice
saveFile.saveAsJpeg("/home/elblonko/Desktop/ExportedDICOM/BrainXjpg");
saveFile.saveAsTiffStack("/home/elblonko/Desktop/ExportedDICOM/BrainXtiff");
//Allows for opening a Stack of DICOM images saved as a Tif file.
//Opener openStuff = new Opener();
//openStuff.open();
} |
900910c2-5f61-49d1-abd1-7301efdb28c1 | 8 | public int compare(Object d1, Object d2) {
//put non display modes at bottom
if(!(d1 instanceof DisplayMode)) {
return 1;
}
if(!(d2 instanceof DisplayMode)) {
return 1;
}
//now compare bit depth and resolution
DisplayMode mode1 = (DisplayMode)d1;
DisplayMode mode2 = (DisplayMode)d2;
int w1 = mode1.getWidth();
int w2 = mode2.getWidth();
if(w1<w2) return -1;
if(w1>w2) return 1;
int h1 = mode1.getHeight();
int h2 = mode2.getHeight();
if(h1<h2) return -1;
if(h1>h2) return 1;
int bitd1 = mode1.getBitDepth();
int bitd2 = mode2.getBitDepth();
if(bitd1<bitd2) return -1;
if(bitd1>bitd2) return 1;
return 0;
} |
932222bc-c029-4ad3-8ae6-724ad10a0cda | 7 | public boolean SetBusActiveStatus(int busNumber, int inputBufferNumber, int packetSequence, int TIME, ConfigFile cfg)
{
//REMOVE IN CROSSBAR FABRIC TYPE
//only one bus present in this fabric type,
busNumber = 0;
//ensure valid busNumber chosen
//if(((busNumber+1)<= VERTICALBUSES) && ((busNumber+1) > 0) &&
// (busActiveStatus[busNumber] == false))
if(((busNumber+1)<= VERTICALBUSES) && ((busNumber+1) >0) &&
(busActiveStatus[busNumber] == false))
{
//check if bus free, or already used by a buffer
if ((currentInputBufferUsingTheBus[busNumber] == -1) ||
(currentInputBufferUsingTheBus[busNumber] == inputBufferNumber))
{
//System.out.println("busNumber :- "+(busNumber+1)+ " SIZE of currentInputBufferUsingTheBus: "+currentInputBufferUsingTheBus.length);
//set the status of the bus
busActiveStatus[busNumber] = true;
//remove the bus from available buses
availableBuses.remove(busNumber);
//add input buffer connected to a bus
inputConnectedToBus.add((Object)inputBufferNumber);
//keep track of the buffer using the bus
currentInputBufferUsingTheBus[busNumber] = inputBufferNumber;
//keep track of the packet sequence using the bus
sequence[busNumber] = packetSequence;
//set the recently used bus
recentBus = busNumber;
if(((String)cfg.GetConfig("GENERAL","Verbose")).compareToIgnoreCase("True") == 0)
{
Print(true, busNumber,packetSequence,true,TIME);
}
//successfully controlled the bus
return true;
}
}
if(((String)cfg.GetConfig("GENERAL","Verbose")).compareToIgnoreCase("True") == 0)
{
Print(false, busNumber,packetSequence,true,TIME);
}
//was unable to control the bus
return false;
} |
b07edf03-69d7-4a80-a5be-846fda322eec | 3 | public boolean estVoisin(Region r)
{
int i = 0;
while ((r.nom != voisins[i].nom) && (i != voisins.length))
{
i++;
}
if (!(r.nom == voisins[i].nom))
return false;
return true;
} |
0b122052-282c-44de-83fb-7bae5b7dcde3 | 6 | private String[] getEnabled() {
enabledMods.clear();
if(folder.exists()) {
for(String name : folder.list()) {
if(name.toLowerCase().endsWith(".zip")) {
enabledMods.add(name);
} else if(name.toLowerCase().endsWith(".jar")) {
enabledMods.add(name);
} else if(name.toLowerCase().endsWith(".litemod")) {
enabledMods.add(name);
}
}
}
String[] enabledList = new String[enabledMods.size()];
for(int i = 0; i < enabledMods.size(); i++) {
enabledList[i] = enabledMods.get(i).replace(".zip", "").replace(".jar", "").replace(".litemod", "");
}
return enabledList;
} |
15f7ed5a-d0f1-42e6-9bc7-eb5f0f56c4b4 | 3 | public ManaCrystal getClosestCrystal(Point point) {
double min = Double.POSITIVE_INFINITY;
ManaCrystal closestManaCrystal = null;
for(ManaCrystal manaCrystal : manaCrystals) {
if(manaCrystal instanceof ManaCrystal) {
if(Geometry.squareDistance(point, manaCrystal.getPoint()) < min) {
min = Geometry.squareDistance(point, manaCrystal.getPoint());
closestManaCrystal = manaCrystal;
}
}
}
return closestManaCrystal;
} |
fd8e3003-6291-4db7-8340-6d5035b5a938 | 0 | public static String getSig() {
StackTraceElement st = (new Throwable()).getStackTrace()[1];
return st.getClassName() + "#" + st.getMethodName();
} |
542a7f2d-53f7-4ce1-bc7a-85f14494e4fa | 6 | @Override
public String toString()
{
String result = "\tHandicap Situation:";
if(problemWithFontSize)
result = result + "\n\t\tPROBLEM WITH FONT SIZE!";
if(problemWithMagnification)
result = result + "\n\t\tPROBLEM WITH MAGNIFICATION!";
if(problemWithForegroundAndBackgroundColor)
result = result + "\n\t\tPROBLEM WITH FOREGROUND AND BACKGROUND COLOR!";
if(problemWithScreenReaderAndGnome)
result = result + "\n\t\tPROBLEM WITH SCREEN READER AND GNOME!";
if(problemWithHighContrast)
result = result + "\n\t\tPROBLEM WITH HIGH CONTRAST!";
if(problemWithMagnifierFullScreen)
result = result + "\n\t\tPROBLEM WITH MAGNIFIER FULL SCREEN!";
return result;
} |
3067ebf7-ba52-4db7-aeff-4d9ed1803d83 | 9 | private RequirementElement parseReqElementInfo(List<String> factors) {
/*
* this part is exclusively for requirement elements 0)notation,element;
* 1)id,51670; 2)shape,Hexagon; 3)name,Calculate price;
* 4)layer,Business; 5)thickness, 1.0; 6)double stroke; 7)size:
* 117.945899963379 43.817626953125; 8)no fill; 9)0.0 corner radius 10)
* stroke pattern: 0 11) origin: 87.234039306641 1084.06665039062
* 12) owner: xx 13) Canvas, Model
*/
//TODO: pre-process all numbers fields, don't know why so far...
factors.set(5, factors.get(5).replaceAll(",", "."));
factors.set(7, factors.get(7).replaceAll(",", "."));
factors.set(9, factors.get(9).replaceAll(",", "."));
factors.set(11, factors.get(11).replaceAll(",", "."));
RequirementElement new_elem;
//security goals
if (factors.get(3).startsWith("(S)") & factors.get(2).equals("Cloud")) {
new_elem = new SecurityGoal();
new_elem.setId(factors.get(1));
new_elem.setType(InfoEnum.RequirementElementType.SECURITY_GOAL.name());
String sg_name = factors.get(3);
// remove"(S)" at the first beginning
sg_name = sg_name.replaceAll("\\(S\\)", "");
new_elem.setName(sg_name.trim());
new_elem.setLayer(factors.get(4));
// get value for security-specific attributes
if (Float.valueOf(factors.get(5)) > 1) {
((SecurityGoal) new_elem).setCriticality(true);
;
} else {
((SecurityGoal) new_elem).setCriticality(false);
;
}
//this value can be useful in the following analysis
new_elem.owner_text=factors.get(12);
((SecurityGoal) new_elem).extractInfoFromName();
}
//actors
else if (checkCircle(factors.get(7))) {
new_elem = new Actor();
new_elem.setId(factors.get(1));
new_elem.setName(factors.get(3));
new_elem.setLayer(factors.get(4));
new_elem.setType(InfoEnum.RequirementElementType.ACTOR.name());
}
//all others
else {
new_elem = new RequirementElement();
new_elem.setId(factors.get(1));
if (factors.get(3).startsWith("(S)") & factors.get(2).equals("Hexagon")) {
new_elem.setType(InfoEnum.RequirementElementType.SECURITY_MECHANISM.name());
} else if (factors.get(3).equals("empty") & factors.get(2).equals("Circle") & factors.get(10).equals("0")) {
new_elem.setType(InfoEnum.RequirementElementType.MIDDLE_POINT.name());
// new_elem.setRemark(InfoEnum.ElementRemark.REFINEUM.name());
} else if (factors.get(3).equals("empty") & factors.get(2).equals("Circle") & factors.get(10).equals("1")) {
new_elem.setType(InfoEnum.RequirementElementType.ACTOR_BOUNDARY.name());
new_elem.setRemark(InfoEnum.ElementRemark.BOUNDARY.name());
} else if (factors.get(2).equals("AndGate")
|| (factors.get(2).equals("Rectangle") & factors.get(9).equals("0.0"))) {//Why rectangle?
new_elem.setType(InfoEnum.RequirementElementType.LABEL.name());
} else {
new_elem.setType(InfoEnum.req_elem_type_map.get(factors.get(2)));
}
if (factors.get(3).startsWith("(S)")) {
String sm_name = factors.get(3);
// remove"(S)" at the first beginning
sm_name = sm_name.replaceAll("\\(S\\)", "");
new_elem.setName(sm_name.trim());
} else {
new_elem.setName(factors.get(3));
}
new_elem.setLayer(factors.get(4));
}
// The layout related information is applicable for all types of elements
String[] temp = factors.get(7).split(" ");
new_elem.width = Double.parseDouble(temp[0]);
new_elem.height = Double.parseDouble(temp[1]);
String[] temp2 = factors.get(11).split(" ");
new_elem.origin_x = Double.parseDouble(temp2[0]);
new_elem.origin_y = Double.parseDouble(temp2[1]);
return new_elem;
} |
25a23568-30fe-46ab-8786-f20bd4508c25 | 4 | public void mouseWheelMoved (MouseWheelEvent event)
{
if (!(doorgaan_thread) && (doorgaan_wheel)) // deze methode alleen uitvoeren als de thread uitstaat EN
{ // 'het verplaatsen mbv het wieltje' aan
int ticks = event.getWheelRotation(); // wat levert dit op?
if ((bal.getY() < valhoogte) && (bal.getT() > 0) ){ // waarom deze conditie?
// pas de bal aan en gebruik 'ticks' en 'dt'
bal.adjust(dt * ticks);
}
else
return;
view.repaint(); // niet vergeten opnieuw ... ?
}
} |
ff9598bf-0360-42e7-9e82-3640b3c62603 | 3 | @Override
public WriteMsg write(long txnID, long msgSeqNum, FileContent data)
throws RemoteException, IOException {
String fileName = data.getFileName();
// if this is the first message, we obtain a lock on file first
if (msgSeqNum == 1) {
Semaphore lock = null;
if (!fileLock.containsKey(fileName)) {
lock = new Semaphore(1);
fileLock.put(fileName, lock);
} else {
lock = fileLock.get(fileName);
}
try {
lock.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
fileNameTransaction.put(txnID, fileName);
cache.put(fileName, data);
} else {
cache.get(fileName).appendData(data.getData());
}
return null;
} |
82b109a7-0cb2-423c-a62e-f3dedacb75ef | 0 | public boolean hasNext() { return current != null; } |
5cbd6c23-4ed3-4260-a91e-4a7d2c095ce9 | 1 | static void mergeTryCatch(FlowBlock tryFlow, FlowBlock catchFlow) {
if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_ANALYZE) != 0)
GlobalOptions.err.println("mergeTryCatch(" + tryFlow.getAddr()
+ ", " + catchFlow.getAddr() + ")");
tryFlow.updateInOutCatch(catchFlow);
tryFlow.mergeSuccessors(catchFlow);
tryFlow.mergeAddr(catchFlow);
} |
f790ca78-c719-456d-a3cf-d44506aa7fe5 | 9 | @POST
@Path("/{algorithm}/{provider}/list")
@Consumes(APPLICATION_JSON)
public String list(@PathParam("algorithm") String algorithm, @PathParam("provider") String provider,
String keystoreAndPassword) {
InputStream inputStream = null;
try {
KeyStore keyStore = KeyStore.getInstance(algorithm, provider);
Gson gson = new Gson();
PathAndPassword pathAndPassword = gson.fromJson(keystoreAndPassword, PathAndPassword.class);
if (pathAndPassword.path == null) {
inputStream = null;
} else {
inputStream = new FileInputStream(pathAndPassword.path);
}
char[] password;
if (pathAndPassword.password == null) {
password = null;
} else {
password = pathAndPassword.password.toCharArray();
}
keyStore.load(inputStream, password);
List<Map<String, String>> aliases = newLinkedList();
Enumeration<String> aliasesEnumeration = keyStore.aliases();
while (aliasesEnumeration.hasMoreElements()) {
String alias = aliasesEnumeration.nextElement();
aliases.add(ImmutableMap.of(
"alias", alias,
"isKey", Boolean.toString(keyStore.isKeyEntry(alias)),
"isCert", Boolean.toString(keyStore.isCertificateEntry(alias))));
}
return gson.toJson(aliases);
} catch (KeyStoreException e) {
throw new WebApplicationException(status(NOT_FOUND).entity(e.getMessage()).build());
} catch (NoSuchProviderException e) {
throw new WebApplicationException(status(NOT_FOUND).entity(e.getMessage()).build());
} catch (FileNotFoundException e) {
throw new WebApplicationException(status(NOT_FOUND).entity("KeyStore not found").build());
} catch (CertificateException e) {
throw new WebApplicationException(status(NOT_FOUND).entity("Certificate not readable").build());
} catch (NoSuchAlgorithmException e) {
throw new WebApplicationException(status(NOT_FOUND).entity(e.getMessage()).build());
} catch (IOException e) {
throw new WebApplicationException(status(NOT_FOUND).entity("KeyStore not readable or bad password").build());
} finally {
Closeables.closeQuietly(inputStream);
}
} |
ba4a6344-9ac0-49bd-a74f-6f24fca97525 | 5 | @Override
public void selectElement() {
assert isInitialized : "Menu not initialized";
Choice pointedChoice = Choice.values()[getPointedElementId()];
switch (pointedChoice) {
case RETURN:
close();
break;
case USE:
setChanged();
notifyObservers(new UseItem(item));
break;
case INSPECT:
setChanged();
notifyObservers(new ShowMessage(new Message(item.getDescription())));
break;
case THROW:
setChanged();
if (item.isThrowable()) {
List<String> possibleAnswers = new ArrayList<String>();
possibleAnswers.add(UserInterface.getLang().getString("yes"));
possibleAnswers.add(UserInterface.getLang().getString("no"));
List<List<IAction>> actionLists = new ArrayList<List<IAction>>();
List<IAction> throwActionList = new ArrayList<IAction>();
throwActionList.add(new ThrowItem(item, bag));
throwActionList.add(new ShowMessage(new Message(UserInterface.getLang().getString("thrown") + item.getName())));
throwActionList.add(new CloseMenu(this));
List<IAction> cancelActionList = new ArrayList<IAction>();
cancelActionList.add(new CloseMenu(MenuID.messageBox));
actionLists.add(throwActionList);
actionLists.add(cancelActionList);
Question q = new Question(UserInterface.getLang().getString("confirmThrow"), possibleAnswers, actionLists);
notifyObservers(new ShowMessage(q));
}
else {
notifyObservers(new ShowMessage(new Message(UserInterface.getLang().getString("notThrowable"))));
}
break;
default:
break;
}
} |
fb98c9f5-a1d0-41d7-85b3-a00815862a54 | 7 | @Test
public void getBeansWithObjectAndAnyQualifierShouldReturnGenericBeans() {
final Collection<Object> beans = beanLoader.getBeans(Object.class, "any");
assertNotNull(beans);
assertEquals(BeanCount.SCANNED.getNumberOfBeans(), beans.size());
boolean foundListOfOneStuffBean = false;
// A bit more complicated than I had hoped for, but "bean instanceof List<OneStuffBean>" does not work.
for (final Object bean : beans) {
if (bean instanceof List<?>) {
final List<?> listBean = (List<?>) bean;
if (listBean.size() == 1) {
final Object firstListBeanObject = listBean.get(0);
if (firstListBeanObject instanceof OneStuffBean) {
foundListOfOneStuffBean = true;
break;
}
}
}
}
assertTrue(foundListOfOneStuffBean);
} |
d600f42e-e9cf-4292-ad7c-ed8d58f6f6ad | 0 | public NotFunc() {
setLayout(new BorderLayout(0, 0));
JButton btnSorrynotImplementedYet = new JButton("sorry,not implemented yet (not enough time ; < )");
btnSorrynotImplementedYet.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainFrame.cardLayout.show(getParent(), "startScreen");
}
});
add(btnSorrynotImplementedYet, BorderLayout.CENTER);
} |
36c04f93-2ad5-4fe0-8793-a85e890f2456 | 8 | private void flushFlags(int totalFields, int[] fieldNums) throws IOException {
// check if fields always have the same flags
boolean nonChangingFlags = true;
int[] fieldFlags = new int[fieldNums.length];
Arrays.fill(fieldFlags, -1);
outer:
for (DocData dd : pendingDocs) {
for (FieldData fd : dd.fields) {
final int fieldNumOff = Arrays.binarySearch(fieldNums, fd.fieldNum);
assert fieldNumOff >= 0;
if (fieldFlags[fieldNumOff] == -1) {
fieldFlags[fieldNumOff] = fd.flags;
} else if (fieldFlags[fieldNumOff] != fd.flags) {
nonChangingFlags = false;
break outer;
}
}
}
if (nonChangingFlags) {
// write one flag per field num
vectorsStream.writeVInt(0);
final PackedInts.Writer writer = PackedInts.getWriterNoHeader(vectorsStream, PackedInts.Format.PACKED, fieldFlags.length, FLAGS_BITS, 1);
for (int flags : fieldFlags) {
assert flags >= 0;
writer.add(flags);
}
assert writer.ord() == fieldFlags.length - 1;
writer.finish();
} else {
// write one flag for every field instance
vectorsStream.writeVInt(1);
final PackedInts.Writer writer = PackedInts.getWriterNoHeader(vectorsStream, PackedInts.Format.PACKED, totalFields, FLAGS_BITS, 1);
for (DocData dd : pendingDocs) {
for (FieldData fd : dd.fields) {
writer.add(fd.flags);
}
}
assert writer.ord() == totalFields - 1;
writer.finish();
}
} |
2f003a34-8fe8-4417-aba9-fa8aec7c3354 | 6 | private int get() throws IOException {
if (start > end) {
if (end > BACK) {
int len = Math.min(BACK, end - BACK + 1);
System.arraycopy(buf, end + 1 - len, buf, BACK - len, len);
back = BACK - len;
}
if (in != null) {
if (!in.markSupported()) in = new BufferedInputStream(in);
this.reader = new InputStreamReader(in, determineEncoding(in));
this.in = null;
}
int size = reader.read(buf, BACK, buf.length-BACK);
if (size != -1) {
mark = (mark > end - BACK) ? BACK - (end - mark + 1) : -1;
start = BACK;
end = BACK + size - 1;
} else {
start++;
return -1;
}
}
return buf[start++];
} |
5ef091a1-c327-4891-8c72-12e66e6bf8df | 3 | public Node<Integer> findKthToLastElemItr(Node<Integer> head, int k) {
Node<Integer> p = head;
for (int i = 0; i < k - 1; i++) {
if (p == null)
return null;
p = p.next;
}
Node<Integer> q = head;
while (p.next != null) {
p = p.next;
q = q.next;
}
return q;
} |
96af6d69-a792-4e7a-ba62-f8b766c3f7da | 7 | public static boolean createContactAccount(int index, String contactID, String label, String nymID, String acctID, String assetID, String serverID, String serverType, String publickey, String memo) {
System.out.println("createContactAccount contactID:"+contactID);
boolean status = false;
AddressBook addressBook = Helpers.getAddressBook();
if (addressBook == null) {
System.out.println("createContactAccount - addressBook returns null");
return false;
}
int count = (int) addressBook.GetContactCount();
for (int i = 0; i < count; i++) {
Contact contact = addressBook.GetContact(i);
if (contact == null) {
continue;
}
if (contactID.equals(contact.getContact_id())) {
System.out.println("createContactAccount - contactID matches, index="+index);
ContactAcct contactAcct = null;
if (index == -1) {
System.out.println("createContactAccount new obj");
Storable storable = otapi.CreateObject(StoredObjectType.STORED_OBJ_CONTACT_ACCT);
if (storable != null) {
contactAcct = ContactAcct.ot_dynamic_cast(storable);
}
} else {
contactAcct = contact.GetContactAcct(index);
System.out.println("createContactAccount old obj, contactAcct :"+contactAcct);
}
if (contactAcct != null) {
contactAcct.setGui_label(label);
contactAcct.setMemo(memo);
contactAcct.setNym_id(nymID);
contactAcct.setAcct_id(acctID);
contactAcct.setAsset_type_id(assetID);
contactAcct.setPublic_key(publickey);
contactAcct.setServer_id(serverID);
contactAcct.setServer_type(serverType);
contact.AddContactAcct(contactAcct);
status = otapi.StoreObject(addressBook, "moneychanger", "gui_contacts.dat");
System.out.println("createContactAccount status addressBook otapi.StoreObject:" + status);
// Set other values here
}
break;
}
}
return status;
} |
b472fcc3-4b06-49b3-a2e0-466dacfc67ea | 2 | public void create( int subdivisions, Vector3f p1, Vector3f p2, Vector3f p3, Vector3f p4 )
{
if ( subdivisions <= 0 )
{
if ( pok % 2 == 0 )
{
triangles.add( new Triangle( p3, p1, p4 ) );
triangles.add( new Triangle( p4, p1, p2 ) );
}
else
{
triangles.add( new Triangle( p1, p2, p3 ) );
triangles.add( new Triangle( p3, p2, p4 ) );
}
pok++;
}
else
subDiv( --subdivisions, p1, p2, p3, p4 );
} |
42b0d3f1-edd6-42b2-bff0-54ff2ef09c46 | 1 | public ArrayList<Molecule> split(int[] MoleculeID){
ArrayList<Molecule> fragments = new ArrayList<Molecule>();
int len = (Arrays.equals(MoleculeID, new int[0])) ? 0 : MoleculeID.length;
Molecule splitPoint = getFromMoleculeID(MoleculeID, MoleculeID.length, 0);
//System.out.println("Split point is at "+Arrays.toString(MoleculeID));
//System.out.println("Molecule at split point: "+splitPoint.toStringf());
splitPoint.flag();
splitPoint.flagChildren();
flagAncestors(MoleculeID, MoleculeID.length, 0);
findUnflaggedChildren(fragments);
return fragments;
} |
f63dffae-eb01-447e-ac7a-47aa09d552b9 | 9 | public static int value(tile input) {
int output = 0;
for (int y = -1; y < 2; y++) {
for (int x = -1; x < 2; x++) {
if (x != 0 || y != 0) {
if (input.getX() + x >= 0 && input.getX() + x <= 9
&& input.getY() + y >= 0 && input.getY() + y <= 9) {
if (board[input.getX() + x][input.getY() + y].getMine()) {
output++;
}
}
}
}
}
return output;
} |
0337cd8e-d172-4f41-b581-d070cb9916e4 | 2 | public void update(GameContainer gc, StateBasedGame sbg, int delta)throws SlickException
{
if(!isGameOver)
{
if(!isPause)
{
}
else
{
}
}
else
{
}
} |
e67edd37-22bd-4fbe-98e6-35a5265bd957 | 0 | public List<Partner> findPartnersByHallEventIdAndRoleName(
final Long hallEventId, final String partnerRoleName
) throws WrongTypeNameException {
return new ArrayList<Partner>();
} |
450b4431-0855-47e7-a7ba-a017255ade7b | 6 | public int move(int d, boolean findChange) {
if (d == 0) return moveDown(findChange);
if (d == 1) return moveLeft(findChange);
if (d == 2) return moveUp(findChange);
if (d == 3) return moveRight(findChange);
if (d > 3 || d < 0) System.err.println("Invalid move");
return -100;
} |
ccf2bf0f-a49c-42d8-ac90-349058dfcccd | 5 | private Object readBinding(Object source) {
try {
if (source == null) {
return null;
}
if (this.pathName == ".") {
return source;
} else {
return source.getClass().getMethod("get" + this.pathName).invoke(source);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return null;
} |
dd7e5964-2c07-48f5-80cb-29b79c700d2a | 8 | @Override
public Object getValueAt(Object object, int row, int col) {
Prestamo prestamo = (Prestamo) object;
try {
if (col == 0) {
return prestamo.getUsuario().getDNI();
} else if (col == 1) {
return prestamo.getUsuario().getNombre();
} else if (col == 2) {
return prestamo.getUsuario().getApellido();
} else if (col == 3) {
return prestamo.getRecurso().getID();
} else if (col == 4) {
return prestamo.getRecurso().getTitulo();
} else if (col == 5) {
Calendar fecha =
prestamo.getFechaEntrega();
Integer dia = fecha.get(Calendar.DAY_OF_MONTH);
Integer mes = fecha.get(Calendar.MONTH) + 1;
Integer anio = fecha.get(Calendar.YEAR);
return dia.toString() + "/"
+ mes.toString() + "/" + anio.toString();
} else if (col == 6) {
Calendar fecha =
prestamo.getFechaLimite();
Integer dia = fecha.get(Calendar.DAY_OF_MONTH);
Integer mes = fecha.get(Calendar.MONTH) + 1;
Integer anio = fecha.get(Calendar.YEAR);
return dia.toString() + "/"
+ mes.toString() + "/" + anio.toString();
} else {
return null;
}
} catch (UsuarioException |
RecursoException |
PrestamoException e) {
return e.getMessage();
}
} |
c4664e65-f0e5-4d94-baad-404652e09c57 | 4 | public int[] returnInts () {
int itotal=totalLength/8;
int out[]=new int[itotal];
BitSet bset=new BitSet();
int a,tc=counter,bcount=0,ocount=0;
for (a=0;a<totalLength;a++) {
if (this.get(tc)==true) bset.set(bcount);
else bset.clear(bcount);
bcount++;
if (bcount==8) {
out[ocount]=binaryToInt8(bset);
ocount++;
bset.clear();
bcount=0;
}
tc++;
if (tc==totalLength) tc=0;
}
return out;
} |
8a406f95-0000-4355-9e0a-841bc4b7f9b8 | 8 | public static void markText(JTextComponent pane, int start, int end, SimpleMarker marker) {
try {
Highlighter hiliter = pane.getHighlighter();
int selStart = pane.getSelectionStart();
int selEnd = pane.getSelectionEnd();
// if there is no selection or selection does not overlap
if(selStart == selEnd || end < selStart || start > selStart) {
hiliter.addHighlight(start, end, marker);
return;
}
// selection starts within the highlight, highlight before slection
if(selStart > start && selStart < end ) {
hiliter.addHighlight(start, selStart, marker);
}
// selection ends within the highlight, highlight remaining
if(selEnd > start && selEnd < end ) {
hiliter.addHighlight(selEnd, end, marker);
}
} catch (BadLocationException ex) {
// nothing we can do if the request is out of bound
LOG.log(Level.SEVERE, null, ex);
}
} |
acc5be32-df1b-48a3-a26b-146e6e0bedc8 | 2 | @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((base == null) ? 0 : base.hashCode());
result = prime * result + ((seed == null) ? 0 : seed.hashCode());
return result;
} |
c655174e-05a0-4d97-98a8-bd006431d283 | 8 | @Override
public boolean tick(Tickable ticking, int tickID)
{
if(!(affected instanceof MOB))
return super.tick(ticking,tickID);
final MOB mob=(MOB)affected;
if(tickID!=Tickable.TICKID_MOB)
return true;
if(!proficiencyCheck(null,0,false))
return true;
if((mob.curState().getHunger()<=0)
||(mob.curState().getThirst()<=0))
{
if(mob.curState().getThirst()<=0)
mob.tell(L("Your mouth is dry!"));
else
mob.tell(L("Your stomach growls!"));
unInvoke();
return false;
}
if((!mob.isInCombat())
&&(CMLib.flags().isSitting(mob)))
{
final double man=((mob.charStats().getStat(CharStats.STAT_INTELLIGENCE)
+(2*getXLEVELLevel(mob))
+mob.charStats().getStat(CharStats.STAT_WISDOM)));
mob.curState().adjMana( (int)Math.round( ( man * .1 ) + ( ( mob.phyStats().level() + ( 2.0 * getXLEVELLevel( mob ) ) ) / 2.0 ) ),
mob.maxState() );
}
else
{
unInvoke();
return false;
}
return super.tick(ticking,tickID);
} |
53ec3d25-c6d6-47dd-af66-2fe44e121b5e | 4 | protected Behaviour getNextStep() {
if (lead == null) findLead() ;
if (expired()) {
//I.say(actor+" performance has expired...") ;
return null ;
}
if (client != null) {
final Recreation r = new Recreation(client, venue, type) ;
if (client.matchFor(r) == null) {
final Action attend = new Action(
actor, venue,
this, "actionAttend",
Action.TALK, "Attending"
) ;
return attend ;
}
}
final Action perform = new Action(
actor, venue,
this, "actionPerform",
Action.TALK, "Performing"
) ;
return perform ;
} |
cce23613-db9c-4ae5-9212-f85d67dd66c7 | 4 | public void treatBackstageOnly(Item item){
if (item.isLessSellInThan(11) && item.isLessQualityThan(50)) {
item.increaseQuality();
}
if (item.isLessSellInThan(6) && item.isLessQualityThan(50)) {
item.increaseQuality();
}
} |
b7bd1520-b242-4069-8e91-472d0175680d | 6 | public static RepNotification GET_NOTIFICATIONS(OVNotification oVNotification) throws SQLException {
RepNotification rep = new RepNotification();
Connection connexion = GET_CONNECTION();
try {
int distance = oVNotification.getDistance();
int major = oVNotification.getOvBeacon().getMajor();
Statement statement = connexion.createStatement();
ResultSet resultat = statement.executeQuery("SELECT notification.id,"
+ "notification.distance, notification.reponseNeeded, notification.texte, notification.idPromotion "
+ "FROM notification\n"
+ "INNER JOIN beacon on (notification.idBeacon = beacon.id)\n"
+ "WHERE distance = " + distance + " and major = " + major);
while (resultat.next()) {
OVNotification ovNotif = new OVNotification(
resultat.getInt("notification.id"),
resultat.getInt("notification.distance"),
resultat.getInt("notification.reponseNeeded"),
resultat.getString("notification.texte"),
resultat.getInt("notification.idPromotion")
);
rep.getListeNotification().add(ovNotif);
}
// Traitement des notifications qui ont besoin d'une réponse
if (rep.getListeNotification().size() > 0 && rep.getListeNotification().get(0).isResponseNeeded() == 1) {
statement.close();
statement = connexion.createStatement();
OVReponse ovReponse = new OVReponse();
ovReponse.setEtat(0);
int resultatInsert = statement.executeUpdate("INSERT intO reponse (etat, idNotification) VALUES (0, " + rep.getListeNotification().get(0).getId() + ");", Statement.RETURN_GENERATED_KEYS);
if (resultatInsert == 0) {
rep.erreur = true;
rep.messageErreur = "Aucune ligne inséré!";
} else {
ResultSet gk = statement.getGeneratedKeys();
if (gk.next()) {
ovReponse.setId(gk.getInt(1));
} else {
rep.messageErreur = "Creating user failed, no ID obtained.";
}
}
rep.getListeNotification().get(0).setReponseEnvoye(ovReponse);
rep.getListeNotification().get(0).setOvPromotion(GET_PROMOTIONS_BY_ID(rep.getListeNotification().get(0).getIdPromotion()).getListePromotion().get((0)));
}
} catch (SQLException ex) {
rep.erreur = true;
rep.messageErreur = ex.getMessage();
}
return rep;
} |
13cf75cd-0f9e-49f3-92fc-4f0e34384f89 | 5 | private String keyToString(JsonElement keyElement) {
if (keyElement.isJsonPrimitive()) {
JsonPrimitive primitive = keyElement.getAsJsonPrimitive();
if (primitive.isNumber()) {
return String.valueOf(primitive.getAsNumber());
} else if (primitive.isBoolean()) {
return Boolean.toString(primitive.getAsBoolean());
} else if (primitive.isString()) {
return primitive.getAsString();
} else {
throw new AssertionError();
}
} else if (keyElement.isJsonNull()) {
return "null";
} else {
throw new AssertionError();
}
} |
50de1e20-2ca4-4792-8567-3dfbb31d68ac | 2 | void copyIso8859_1ReadBuffer(int count)
{
int i, j;
for (i = 0, j = readBufferPos; i < count; i++, j++) {
readBuffer[j] = (char) (rawReadBuffer[i] & 0xff);
if (readBuffer[j] == '\r') {
sawCR = true;
}
}
readBufferLength = j;
} |
fe8e59ad-2d5c-4cb1-9ab4-351325f6613d | 9 | public void build () throws ExceptionInvalidParam
{
if ( upperXBound <= lowerXBound
|| upperZBound <= lowerZBound
|| destWidth <= 0
|| destHeight <= 0
|| sourceModule == null
|| destNoiseMap == null)
throw new ExceptionInvalidParam ("Invalid parameter in NoiseMapBuilderPlane");
// Resize the destination noise map so that it can store the new output
// values from the source model.
destNoiseMap.setSize (destWidth, destHeight);
// Create the plane model.
Plane planeModel = new Plane();
planeModel.setModule (sourceModule);
double xExtent = upperXBound - lowerXBound;
double zExtent = upperZBound - lowerZBound;
double xDelta = xExtent / (double)destWidth ;
double zDelta = zExtent / (double)destHeight;
double xCur = lowerXBound;
double zCur = lowerZBound;
// Fill every point in the noise map with the output values from the model.
for (int z = 0; z < destHeight; z++)
{
xCur = lowerXBound;
for (int x = 0; x < destWidth; x++)
{
double finalValue;
if (!isSeamlessEnabled)
finalValue = planeModel.getValue (xCur, zCur);
else
{
double swValue, seValue, nwValue, neValue;
swValue = planeModel.getValue (xCur, zCur);
seValue = planeModel.getValue (xCur + xExtent, zCur);
nwValue = planeModel.getValue (xCur, zCur + zExtent);
neValue = planeModel.getValue (xCur + xExtent, zCur + zExtent);
double xBlend = 1.0 - ((xCur - lowerXBound) / xExtent);
double zBlend = 1.0 - ((zCur - lowerZBound) / zExtent);
double z0 = Interp.linearInterp (swValue, seValue, xBlend);
double z1 = Interp.linearInterp (nwValue, neValue, xBlend);
finalValue = Interp.linearInterp (z0, z1, zBlend);
}
destNoiseMap.setValue(x, z, finalValue);
xCur += xDelta;
}
zCur += zDelta;
setCallback (z);
}
} |
f90a098b-fc4a-4458-b41d-58dedb873d90 | 4 | public static void move(int d) {
if (d == 0) {
System.out.println("down");
Main.fenrir.pressKey(40);
} else if (d == 1) {
System.out.println("left");
Main.fenrir.pressKey(37);
} else if (d == 2) {
System.out.println("up");
Main.fenrir.pressKey(38);
} else if (d == 3) {
System.out.println("right");
Main.fenrir.pressKey(39);
} else {
System.err.println("Not a valid direction");
}
} |
31a126b1-cc4a-4077-88ae-af82d935625a | 7 | public void updateInterventionForce() {
Specification spec = getSpecification();
int interventionTurns = spec.getInteger("model.option.interventionTurns");
if (interventionTurns > 0) {
int updates = getGame().getTurn().getNumber() / interventionTurns;
for (AbstractUnit unit : interventionForce.getLandUnits()) {
// add units depending on current turn
int value = unit.getNumber() + updates;
unit.setNumber(value);
}
interventionForce.updateSpaceAndCapacity();
while (interventionForce.getCapacity() < interventionForce.getSpaceRequired()) {
boolean progress = false;
for (AbstractUnit ship : interventionForce.getNavalUnits()) {
// add ships until all units can be transported at once
if (ship.getUnitType(spec).canCarryUnits()
&& ship.getUnitType(spec).getSpace() > 0) {
int value = ship.getNumber() + 1;
ship.setNumber(value);
progress = true;
}
}
if (!progress) break;
interventionForce.updateSpaceAndCapacity();
}
}
} |
fb425a4a-bf47-48b6-963e-ce54c3683a0f | 3 | private void deleteSelected() {
if (JOptionPane.showConfirmDialog(frmDictionaryEditor, Localization.getInstance().get("messageConfirmEntryDelete")) != JOptionPane.OK_OPTION) {
return;
}
try {
for (Long id : getSelectedIDs()) {
dic.deleteEntry(id);
}
} catch (Exception ex) {
showError(Localization.getInstance().get("deletionError"), ex);
}
} |
cc29204c-90c6-4eb0-9d54-d8faf43518ad | 5 | private void render() {
if (this.world != null) {
Iterable<Chunk> chunks = this.world.getLoadedChunks();
for (Chunk chunk : chunks) {
for (int section = 0; section < 8; section++) {
if (chunk.getVboId(section) == 0) {
int vboId = glGenBuffersARB();
chunk.setVboId(section, vboId);
chunk.setVboUpdateRequired(section, true);
}
if (chunk.getVboUpdateRequired(section)) {
FloatBuffer buffer = BufferUtils.createFloatBuffer(16*16*16*24); // TODO: Load from config
int numElements = this.chunkSectionRenderer.renderChunkSection(buffer, this.world, chunk, section);
buffer.flip();
glBindBufferARB(GL_ARRAY_BUFFER_ARB, chunk.getVboId(section));
glBufferDataARB(GL_ARRAY_BUFFER_ARB, buffer, GL_STATIC_DRAW_ARB);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
chunk.setVboUpdateRequired(section, false);
chunk.setNumVboElements(section, numElements);
}
glPushMatrix();
glEnableClientState(GL_VERTEX_ARRAY);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, chunk.getVboId(section));
glVertexPointer(3, GL_FLOAT, 0, 0L);
glDrawArrays(GL_TRIANGLES, 0, chunk.getNumVboElements(section));
glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
glDisableClientState(GL_VERTEX_ARRAY);
glPopMatrix();
}
}
}
} |
21af392a-7736-4e8e-bd13-983ff51a0c0e | 0 | public ListenerThread(ActiveMQConnectionFactory factory,
ConcurrentMap<String, MessageAdaptor> messageResponse, String topic) {
this.factory = factory;
this.messageResponse = messageResponse;
this.topic = topic;
} |
738250a8-159a-4f71-9fd9-d6d38b2f4fbc | 2 | private int swim(int i)
{
Key t = pq[i]; // Save key for later restoring
while (i > 1 && greater(pq[i / 2], pq[i]))
{
// exch(pq, i / 2, i);
pq[i] = pq[i / 2]; // half exchanges
i = i / 2;
}
pq[i] = t; // restore key
return i;
} |
51465807-730d-4564-8321-071c58e58d5d | 2 | public Map load(String path, Sprite sprite)
{
try
{
inputStream = new FileInputStream(new File(getClass().getResource(path).toURI())); //Some crap to read file
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
byte[] data = Files.readAllBytes(Paths.get(getClass().getResource(path).toURI()));
return new Map(data, sprite, br);
}
catch (FileNotFoundException ex)
{
System.out.println(ex.getMessage());
}
catch (IOException | URISyntaxException ex)
{
System.out.println(ex.getMessage());
}
return null;
} |
31cd4122-1da1-4db0-a235-b1e8d24af9b8 | 1 | public boolean isWide() {
return (desc.charAt(0) == Type.LONG_CHAR)
|| (desc.charAt(0) == Type.DOUBLE_CHAR);
} |
eca57659-4170-47a5-9b9f-5fc7bb3bd847 | 4 | Subject[] generateSubjectGroup(int size, int[] code, int[] slot, String[] name){
Subject[] s = new Subject[size];
ArrayList<Subject> arr = new ArrayList<>(size);
int t = 1;
for(int i=0; i<size; i++){
int k = (int)(size * Math.random());
arr.add(new Subject(code[k % code.length], slot[k % slot.length], t, name[k % name.length]));
s[i] = arr.get(i);
}
for(int i=0; i<size; i++){
if(arr.get(i).getCode() == arr.get(size-1).getCode()){
s[i].setGroup(t+1);
} if(arr.get(i).getCode() == 0){
s[i].setMaxStudents(0);
}
} return s;
} |
502259ec-5283-409f-b32b-4ad66dcce212 | 9 | @Override
public void iterate() {
try {
if (isAllyControlled()) {
targets = renderer.getEnemyShips();
} else {
targets = renderer.getAllyShips();
}
} catch (NullPointerException ex) {
this.setRemovable();
}
try {
int closest = 999999;
double closestDistance = 999999;
for (int i = 0; i < targets.size(); i++) {
// If target is closer than previous ones, and the target isn't destroyed already...
if ((getDistanceTo(targets.get(i)) < closestDistance) && (!targets.get(i).isDestroyed())) {
closestDistance = getDistanceTo(targets.get(i));
closest = i;
}
}
if (closestDistance != 999999) {
double angle = -getRelativeAngleTo(targets.get(closest)) / Math.PI * 180;
if (angle < -2) {
turn(-2);
} else if (angle > 2) {
turn(2);
}
}
} catch (Exception e) {
}
super.iterate();
} |
6a36ae7d-6647-473b-b630-e52e4c8ac5a5 | 5 | @Override
// KEY LISTENER FUNCTIONS
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_LEFT){
mainPlayer.setLeft(true);
}
if(keyCode == KeyEvent.VK_RIGHT){
mainPlayer.setRight(true);
}
if(keyCode == KeyEvent.VK_UP){
mainPlayer.setUp(true);
}
if(keyCode == KeyEvent.VK_DOWN){
mainPlayer.setDown(true);
}
if(keyCode == KeyEvent.VK_SHIFT){
mainPlayer.setSpeedUp(true);
}
} |
42e9e800-b99d-4e6b-9d2f-293a3c543620 | 7 | private void printEntitiesInNary(ORASSNode node, String naryRelName, List<String> entities, int currEntityIndex, int numOfTabs) {
String entityName = node.getName();
writer.println(getTabs(numOfTabs) + "<xs:element name=\""+entityName+"\" minOccurs=\"0\" maxOccurs=\"unbounded\">");
writer.println(getTabs(numOfTabs + 1) + "<xs:complexType>");
writer.println(getTabs(numOfTabs + 2) + "<xs:attribute name=\""+entityName+"_Ref\" type=\"xs:string\" use=\"required\"/>");
List<ColumnDetail> naryRelAttrs = new ArrayList<ColumnDetail>();
if (currEntityIndex == entities.size()-1) {
List<ColumnDetail> relAttrs = node.getRelAttributes();
if (relAttrs.size() > 0) {
Iterator<ColumnDetail> relAttrsItr = relAttrs.iterator();
while (relAttrsItr.hasNext()) {
ColumnDetail relAttr = relAttrsItr.next();
if (relAttr.getTableName().equals(naryRelName))
naryRelAttrs.add(relAttr);
}
}
if (naryRelAttrs.size() > 0) {
writer.println(getTabs(numOfTabs + 2) + "<xs:all>");
printColumns(naryRelAttrs, numOfTabs + 3);
writer.println(getTabs(numOfTabs + 2) + "</xs:all>");
}
}
else {
List<ORASSNode> children = node.getChildren();
Iterator<ORASSNode> childrenItr = children.iterator();
String nextEntityNameInNary = entities.get(currEntityIndex + 1);
while (childrenItr.hasNext()) {
ORASSNode child = childrenItr.next();
if (child.getName().equals(nextEntityNameInNary)) {
printEntitiesInNary(child, naryRelName, entities, currEntityIndex + 1, numOfTabs+2);
break;
}
}
}
writer.println(getTabs(numOfTabs + 1) + "</xs:complexType>");
writer.println(getTabs(numOfTabs) + "</xs:element>");
} |
bcbb5d14-488d-4730-b2bc-b56b47da259d | 8 | protected void initDefaultStyle() {
if(this.styleMap == null) {
this.styleMap = DefaultStyle.getDefaults();
}
//background
if(!styleMap.containsKey(BACKGROUND_KEY))
styleMap.put(BACKGROUND_KEY, new Color(209,215,226));
//header title font
if(!styleMap.containsKey(HEADER_TITLE_FONT_KEY))
styleMap.put(HEADER_TITLE_FONT_KEY, styleMap.getFont(DefaultStyle.LABEL_FONT_KEY));
//header title color
if(!styleMap.containsKey(HEADER_TITLE_COLOR_KEY))
styleMap.put(HEADER_TITLE_COLOR_KEY, new Color(40,40,40));
//header title bevel color
if(!styleMap.containsKey(HEADER_TITLE_BEVEL_COLOR_KEY))
styleMap.put(HEADER_TITLE_BEVEL_COLOR_KEY, new Color(196,196,196));
//header border color
if(!styleMap.containsKey(HEADER_BORDER_COLOR_KEY))
styleMap.put(HEADER_BORDER_COLOR_KEY, styleMap.getFont(DefaultStyle.CTRL_BORDER_COLOR_KEY));
//header top gradient
if(!styleMap.containsKey(HEADER_TOP_GRADIENT_KEY))
styleMap.put(HEADER_TOP_GRADIENT_KEY, new Color(196,196,196));
//header bottom gradient
if(!styleMap.containsKey(HEADER_BOTTOM_GRADIENT_KEY))
styleMap.put(HEADER_BOTTOM_GRADIENT_KEY, new Color(153,153,153));
} |
8e18ddcc-60db-4133-9a87-c26757e9faa5 | 4 | public static void filledEllipse(double x, double y, double semiMajorAxis, double semiMinorAxis) {
if (semiMajorAxis < 0) throw new RuntimeException("ellipse semimajor axis can't be negative");
if (semiMinorAxis < 0) throw new RuntimeException("ellipse semiminor axis can't be negative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*semiMajorAxis);
double hs = factorY(2*semiMinorAxis);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.fill(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
} |
50ccf6f5-6c55-47e1-9ab2-25367fbfbf6a | 2 | public State[] getUnreachableStates() {
ArrayList list = new ArrayList();
State[] states = myAutomaton.getStates();
/** Create nodes for DFS. */
initializeNodes(states);
Node initialNode = getNodeForState(myAutomaton.getInitialState());
/** Start DFS at node representing initial state. */
visit(initialNode);
/**
* DFS has completed. Add all non-visited (white) nodes to list of
* unreachable states.
*/
for (int k = 0; k < myNodes.length; k++) {
if (myNodes[k].isWhite()) {
list.add(myNodes[k].getState());
}
}
return (State[]) list.toArray(new State[0]);
} |
9cebc22c-3134-46b7-95c9-c4ad22697697 | 2 | public static synchronized void updateDynmapVersion(String dynmapVersion) {
if (Main.dynmapVersion != null) {
if (!Main.dynmapVersion.equals(dynmapVersion)) {
logger.error("You use different Versions of Dynmaps");
System.exit(-1);
}
} else {
Main.dynmapVersion = dynmapVersion;
}
} |
6e391879-b2d4-4e92-b959-4c02fd607434 | 7 | public void doINTERPRET(){
try{
System.out.print("> ");
in.readLine();
String curWord = null;
while((curWord = in.getNextWord()) != null){
int word = dict.find(curWord);
if(word != -1){
if(state == STATE_INTERP){
dict.runWord(word, this);
}else{
if(dict.isWordImmediate(word)){
dict.runWord(word, this);
}else{
dict.compileWord(word);
}
}
}else{
try{
//Parse as an int and add to stack
int num = Integer.parseInt(curWord);
if(state == STATE_INTERP){
pushDataStack(num);
}else{
dict.compileNamedWord("LIT");
dict.compileInt(num);
}
}catch(NumberFormatException ex){
throw new ForthException("Word not found: " + curWord);
}
}
//System.out.format("Word: %s -- Found: %d\n", curWord, dict.find(curWord));
}
System.out.println("ok");
}catch(ForthException ex){
System.out.println("----Forth Exception ---");
ex.printStackTrace();
System.out.println("-----------------------");
}
} |
53fa1d91-20c6-4542-afc7-320c0c3ef096 | 7 | private int yy_advance ()
throws java.io.IOException {
int next_read;
int i;
int j;
if (yy_buffer_index < yy_buffer_read) {
return yy_buffer[yy_buffer_index++];
}
if (0 != yy_buffer_start) {
i = yy_buffer_start;
j = 0;
while (i < yy_buffer_read) {
yy_buffer[j] = yy_buffer[i];
++i;
++j;
}
yy_buffer_end = yy_buffer_end - yy_buffer_start;
yy_buffer_start = 0;
yy_buffer_read = j;
yy_buffer_index = j;
next_read = yy_reader.read(yy_buffer,
yy_buffer_read,
yy_buffer.length - yy_buffer_read);
if (-1 == next_read) {
return YY_EOF;
}
yy_buffer_read = yy_buffer_read + next_read;
}
while (yy_buffer_index >= yy_buffer_read) {
if (yy_buffer_index >= yy_buffer.length) {
yy_buffer = yy_double(yy_buffer);
}
next_read = yy_reader.read(yy_buffer,
yy_buffer_read,
yy_buffer.length - yy_buffer_read);
if (-1 == next_read) {
return YY_EOF;
}
yy_buffer_read = yy_buffer_read + next_read;
}
return yy_buffer[yy_buffer_index++];
} |
2e03d9f2-3853-4469-9542-fa137fca933e | 9 | public DotBracketNotation(Sequence aSequence, String aDotBracketNotation)
throws InvalidDotBracketNotationException {
if (aSequence.getLength() != aDotBracketNotation.length()) {
throw new InvalidDotBracketNotationException(
"Sequence and dot bracket notation are not the same length.");
}
if (!this.isNested(aSequence, aDotBracketNotation)) {
throw new InvalidDotBracketNotationException(
"The dot bracket notation contains non properly nested characters");
}
this.sequence = aSequence;
this.dotBracketNotation = aDotBracketNotation;
this.interactions = new LinkedHashSet<NucleotideInteraction>();
this.dotBracketMap = new LinkedHashMap<Nucleotide, Character>();
Iterator<Nucleotide> itr = this.sequence.iterator();
LinkedHashMap<Character, Stack<Nucleotide>> openingStacks = new LinkedHashMap<Character, Stack<Nucleotide>>();
// iterate over the sequence, ensure that dbn is nested and create base
// pairs and add them to the interactions set
int i = 0;
while (itr.hasNext()) {
Nucleotide currentNucleotide = itr.next();
char dotBracket = this.dotBracketNotation.charAt(i++);
dotBracketMap.put(currentNucleotide, dotBracket);
if (this.isOpeningCharacter(dotBracket)) {
if (!openingStacks.containsKey(dotBracket)) {
openingStacks.put(dotBracket, new Stack<Nucleotide>());
}
openingStacks.get(dotBracket).push(currentNucleotide);
} else if (this.isClosingCharacter(dotBracket)) {
Stack<Nucleotide> openingStack = openingStacks
.get(DotBracketNotationConstants.CLOSING_CHARACTERS
.get(dotBracket));
BasePair bp = new BasePair(openingStack.pop(),
currentNucleotide);
this.interactions.add(bp);
} else {
continue;
}
}
for (int j = 0; j < this.sequence.getLength() - 1; j++) {
Nucleotide curr = this.sequence.getNucleotideAtPosition(j + 1);
Nucleotide next = this.sequence.getNucleotideAtPosition(j + 2);
// check if the two nucleotides have a difference of one in their
// positions
int check = next.getResiduePosition() - curr.getResiduePosition();
if (check == 1) {
PhosphodiesterBond pdb = null;
try {
pdb = new PhosphodiesterBond(curr, next);
} catch (NonConsecutiveNucleotideException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.interactions.add(pdb);
}
}
} |
30a8ccb1-dbf6-4469-b895-237ca56ac88c | 8 | StructInfo(Class<?> clz)
{
this.clz = clz;
Field[] fields = clz.getDeclaredFields();
List<FieldMarshal> required = new ArrayList<FieldMarshal>();
for (Field i : fields)
{
boolean ignore = Modifier.isStatic(i.getModifiers()) ||
null != i.getAnnotation(Ignore.class);
if (ignore)
{
continue;
}
Counted ctd = i.getAnnotation(Counted.class);
Counter ctr = i.getAnnotation(Counter.class);
if (null != ctd)
{
counted.put(i, ctd.counter());
}
else if (null != ctr)
{
counters.put(ctr.id(), i);
}
required.add(fieldMarshal(this, i));
}
Counted struct = clz.getAnnotation(Counted.class);
if (null != struct)
{
if (!counters.containsKey(struct.counter()))
{
throw new IllegalArgumentException();
}
length = counters.get(struct.counter());
}
else
{
length = null;
}
sequence = required.toArray(new FieldMarshal[required.size()]);
} |
0b91d66f-e4b2-4ed3-8ce7-def5a995fd3f | 2 | public String getSqlStatement() throws ParseException, IOException {
StringBuilder sb = new StringBuilder();
// for (int k = 1; k <= 1; k++) {
for (int k = 1; k <= 66; k++) {
for (int chapter = 1; chapter <= CHAPTER_COUNT_1TO66[k]; chapter++) {
String str = getVersesSql(k, chapter);
sb.append(str);
}
}
return sb.toString();
} |
a82d367e-705f-48fa-aa98-4a1313cb9e16 | 4 | public static AutomatonTable getConnections(Map<Integer, ZState> states){
List<Connection> connections = new ArrayList<>(states.size());
List<String> ids = new ArrayList<>();
List<boolean []> codes = new ArrayList<>();
AutomatonTable table = new AutomatonTable();
table.connections = connections;
table.ids = ids;
table.codes = codes;
for (Map.Entry<Integer, ZState> entry : states.entrySet()) {
ZState zState = entry.getValue();
if(zState.signalId != null){
ids.add(zState.signalId);
}else{
ids.add("0");
}
boolean[] code =SynchroState.intToCode(zState.code, getPower(states)[0]);
codes.add(code);
for(Connection conn : zState.fromConnections){
if(!connections.contains(conn)){
connections.add(conn);
}
}
}
return table;
} |
25fb1c78-b471-4bb7-895c-73cc15698954 | 0 | @Override
public String getSex() {
return super.getSex();
} |
9755165b-a3b9-4160-8945-b3ddf0b79c80 | 3 | public synchronized void update(long timePassed) {
if (scenes.size() > 1) {
movieTime += timePassed;
if (movieTime >= totalTime) {
movieTime = 0;
sceneIndex = 0;
}
if(movieTime > getScene(sceneIndex).endTime) {
sceneIndex++;
}
}
} |
d2137ae0-877f-4f56-840e-f3696c4e6850 | 8 | public static void main(String args[]) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
for (int circle = 1; ; circle++) {
int number = Integer.parseInt(reader.readLine());
if (number != 0) {
String currentStr = reader.readLine();
System.out.println("Test case #" + circle);
int repeatIndex = -1; //重复串的尾部位置
for (int currentIndex = 1; currentIndex<number ; currentIndex++) {
if (repeatIndex == -1) {
if (currentIndex%2==1
&& currentStr.substring(0, (currentIndex+1)/2).equals(currentStr.substring((currentIndex+1)/2, currentIndex+1))) {
System.out.println(currentIndex+1 + " " + 2);
repeatIndex = (currentIndex-1)/2;
}
} else {
if ((currentIndex+1)%(repeatIndex+1) == 0) {
if (currentStr.substring(0, repeatIndex+1).equals(currentStr.substring(currentIndex-repeatIndex, currentIndex+1))) {
System.out.println(currentIndex+1 + " " + (currentIndex+1)/(repeatIndex+1));
} else {
repeatIndex = currentIndex;
}
}
}
}
System.out.println();
} else {
break;
}
}
} |
d578a495-f743-4f97-94a6-4c83e8623ee3 | 4 | protected Script createAddScript(Path resourcefile, List<ResourceVO> resources, Path resHackerLog) {
assert (resourcefile != null) && (resHackerLog != null);
assert (resources != null) && !resources.isEmpty();
List<String> sb = new LinkedList<>();
Iterator<ResourceVO> i = resources.listIterator(0);
sb.add(this.RES_SCRIPTHEADER1 + resourcefile + this.newLine);
sb.add(this.RES_SCRIPTHEADER2 + resourcefile + this.newLine);
sb.add(this.RES_SCRIPTHEADER3 + resHackerLog + this.newLine + this.newLine);
sb.add(this.RES_SCRIPTHEADER4);
while (i.hasNext()) {
ResourceVO tmp = i.next();
sb.add(this.CMD_ADDOVERWRITE + tmp.getPath() + ", " + tmp.getType() + ", " + tmp.getResourceNumber() + "," + this.newLine);
}
if (!FileUtil.writeTextFile(this.scriptPath, sb, false)) {
return null;
}
assert FileUtil.control(this.scriptPath);
return new Script(this.scriptPath);
} |
97ab6d4e-c6e4-4139-b512-23c8515d1dd2 | 6 | public void move()
{
switch(direction)
{
//1 Up/Left
case 1:
{
TLY -= DY * localG.delta;
TRY -= DY * localG.delta;
BLY -= DY * localG.delta;
BRY -= DY * localG.delta;
TLX -= DX * localG.delta;
BLX -= DX * localG.delta;
TRX -= DX * localG.delta;
BRX -= DX * localG.delta;
}
break;
//4 Up/Right
case 2:
{
TLY -= DY * localG.delta;
TRY -= DY * localG.delta;
BLY -= DY * localG.delta;
BRY -= DY * localG.delta;
TLX += DX * localG.delta;
BLX += DX * localG.delta;
TRX += DX * localG.delta;
BRX += DX * localG.delta;
}
break;
//3 Low/Right
case 3:
{
TLY += DY * localG.delta;
TRY += DY * localG.delta;
BLY += DY * localG.delta;
BRY += DY * localG.delta;
TLX += DX * localG.delta;
BLX += DX * localG.delta;
TRX += DX * localG.delta;
BRX += DX * localG.delta;
}
break;
//4 Low/Left
case 4:
{
TLY += DY * localG.delta;
TRY += DY * localG.delta;
BLY += DY * localG.delta;
BRY += DY * localG.delta;
TLX -= DX * localG.delta;
BLX -= DX * localG.delta;
TRX -= DX * localG.delta;
BRX -= DX * localG.delta;
}
break;
case 5:
{
TLX -= DX * localG.delta;
BLX -= DX * localG.delta;
TRX -= DX * localG.delta;
BRX -= DX * localG.delta;
}
break;
case 6:
{
TLX += DX * localG.delta;
BLX += DX * localG.delta;
TRX += DX * localG.delta;
BRX += DX * localG.delta;
}
break;
}
} |
45e80a8c-aa82-4bd2-a32f-7dfcf49b9730 | 8 | public void makeMatrix(boolean andriodOnly) throws Exception{
ASTClassNode acn=(ASTClassNode)this.beginNode;
PrintWriter pwOut=new PrintWriter(new FileOutputStream(jarName+".txt"));
// this.json=new PrintWriter(new FileOutputStream(this.jarName+"_json.txt"));
for(ASTNode tempHead:acn.getChild()){
ASTClassNode classLevel=(ASTClassNode)tempHead;
for(ASTNode tempClass:classLevel.getChild()){
ASTFunctionNode functionLevel=(ASTFunctionNode)tempClass;
for(ASTNode tempFunction:functionLevel.getChild()){
if(tempFunction.getASTKind().equals("ASTMethodNode")){
ASTMethodNode amn=(ASTMethodNode)tempFunction;
if(andriodOnly==true){
String rowName=amn.getOwner()+" "+amn.getName();
if(rowName.length()>7){
if(this.androidAPI.get(rowName)!=null){
if(this.recordCount.get(rowName)!=null){
int methodCount=this.recordCount.get(rowName);
this.currentKey=this.jarName+"-"+rowName+"-"+methodCount;
this.recordCount.put(rowName,methodCount+1);
}else{
this.currentKey=this.jarName+"-"+rowName+"-0";
this.recordCount.put(rowName, 1);
}
ArrayList<ASTNode> callingRecord=new ArrayList<ASTNode>();
// this.json.println(this.currentKey+"{");
// this.json.println("return:{");
getRelatedAPI(pwOut,amn,callingRecord);
// this.json.println("}");
callingRecord.remove(amn);
currentChecking=amn;
// this.json.println("argument:{");
getArgumentAPI(pwOut,amn,callingRecord);
// this.json.println("}");
// this.json.println("}");
}
}
}else{
String rowName=classLevel.getName()+" "+functionLevel.getName()+" "+amn.getOwner()+" "+amn.getName();
pwOut.println(rowName);
}
}
}
}
}
// this.json.close();
pwOut.close();
} |
decec109-f96b-4fb7-9a19-e9918dc36a8b | 4 | public void executeQuery(String query) throws ExecutorException
{
Connection connection = null;
Statement statement = null;
try
{
connection = DriverManager.getConnection(url, user, password);
statement = connection.createStatement();
statement.executeUpdate(query);
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
try
{
if (statement != null)
{
statement.close();
}
if (connection != null)
{
connection.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
} |
eafb32db-7ff4-48d7-8719-62df6793cb7f | 0 | private void txtNomActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNomActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtNomActionPerformed |
aebd9890-0ace-45c9-9606-76cd0d66b415 | 9 | @Override
public String toString() {
String result;
switch(type) {
case CLASS_LABEL:
boolean firstLabel = true;
result = "";
for(String val : values) {
if(!firstLabel) { result += ", "; }
else { firstLabel = false; }
result += val;
}
break;
case INPUT_CONTINUOUS:
result = name+": continuous.";
break;
case INPUT_DISCRETE:
result = name+": ";
boolean first = true;
for(String val : values) {
if(!first) { result += ", "; }
else { first = false; }
result += val;
}
result += ".";
break;
case INPUT_TEXT:
result = name+": text.";
break;
case INPUT_SCOREDTEXT:
result = name+": scoredtext.";
break;
default:
result= name;
}
return result;
} |
2cd0f8e6-417b-4d72-b2d3-66a0dc6aba6b | 8 | private byte[] findError(DatagramPacket packet) {
byte temp[] = new byte[2];
System.arraycopy(packet.getData(), 2, temp, 0, 2);
if(this.packetType == 1 || this.packetType == 2) {
for (int i = 0; i < 4; i++) {
if(packet.getData()[i] != this.comparitorA[i]) return packet.getData();
}
return makeError(packet);
} else if (this.packetType == 3) {
if(packet.getData()[0]==0 && (packet.getData()[1]==1 || packet.getData()[1]==2)) return makeError(packet);
}
return packet.getData();
} |
d6edb211-f1ed-44e6-8a10-8098993d26fb | 6 | protected JTable createTable(final Transition transition) {
TableModel model = createModel(transition);
final TipLambdaCellRenderer[] renders = new TipLambdaCellRenderer[model
.getColumnCount()];
for (int i = 0; i < model.getColumnCount(); i++)
renders[i] = transition instanceof TMTransition ? new TipLambdaCellRenderer(
"" + Tape.BLANK, model.getColumnName(i))
: new TipLambdaCellRenderer(model.getColumnName(i));
JTable table = new JTable(createModel(transition)) {
public TableCellRenderer getCellRenderer(int r, int c) {
return renders[c];
}
protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,
int condition, boolean pressed) {
if (ks.getKeyCode() == KeyEvent.VK_ENTER
&& !ks.isOnKeyRelease()) {
stopEditing(false);
if (e.isShiftDown()) {
createTransition(transition.getFromState(), transition
.getToState());
}
return true;
} else if (ks.getKeyCode() == KeyEvent.VK_ESCAPE) {
stopEditing(true);
return true;
}
return super.processKeyBinding(ks, e, condition, pressed);
}
};
table.setGridColor(Color.gray);
table.setBorder(new javax.swing.border.EtchedBorder());
return table;
} |
a8aeeded-0b90-4b8c-8f27-7dee15ac9861 | 6 | public static void main(String[] args) {
System.out.println("Hello World!");
FileInputStream ml_file = null;
String parent_path = "I:\\JetBrains\\PsychoCompiler\\src\\main\\resources\\MyLang_code\\";
String file_name = "MyLang_simple_1.ml";
File file = new File(parent_path + file_name);
if (file.isFile() && file.exists()) {
System.out.println("find file success");
} else {
System.out.println("not find file");
}
try {
ml_file = new FileInputStream(file);
}
catch (FileNotFoundException e) {
System.out.print("src file open failed.");
}
MyLangTree parser = new MyLangTree(ml_file);
try {
// Token test
String temp = null;
while(!(temp = parser.getNextToken().toString()).equals("")) {
System.out.print(temp + " ");
}
System.out.println(" ");
// Parser test
file = new File(parent_path + file_name);
ml_file = new FileInputStream(file);
parser = new MyLangTree(ml_file);
SimpleNode root = parser.Start();
//root.dump("");
analyse(root);
System.out.println("Format true!");
} catch (Exception e){
System.out.println("Parser Exception:");
System.out.println(e.getMessage());
}
catch (Error e){
System.out.println("Token Error:");
System.out.println(e.getMessage());
}
} |
5a1cc773-5d71-4431-bd2a-380a59c1a63d | 5 | public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
if (triangle == null || triangle.size() == 0) {
return 0;
}
int n = triangle.size();
int[][] sum = new int[n][n];
for (int i = 0; i < n; i++) {
sum[n - 1][i] = triangle.get(n - 1).get(i);
}
for (int i = n - 2; i >= 0; i--) {
for (int j = 0; j <= i; j++) {
sum[i][j] = Math.min(sum[i + 1][j], sum[i + 1][j + 1])
+ triangle.get(i).get(j);
}
}
return sum[0][0];
} |
b70a76b9-652c-4e39-aa02-7b4bdce6a934 | 5 | static final boolean method245(int i, int i_2_, int i_3_, byte i_4_) {
if (i_4_ < 38)
return false;
anInt8619++;
Interface10 interface10
= (Interface10) r_Sub2.method3297(i, i_2_, i_3_);
boolean bool = true;
if (interface10 != null)
bool &= Class55.method520(interface10, -1);
interface10 = ((Interface10)
Class177.method1353(i, i_2_, i_3_,
(aClass8623 != null ? aClass8623
: (aClass8623
= method246("Interface10")))));
if (interface10 != null)
bool &= Class55.method520(interface10, -1);
interface10
= (Interface10) Class348_Sub16_Sub3.method2878(i, i_2_, i_3_);
if (interface10 != null)
bool &= Class55.method520(interface10, -1);
return bool;
} |
c8f0665d-e0c4-463d-86d6-74d9cd44c116 | 1 | @Override
public List<ValidateException> validate(String parameter) {
List<ValidateException> validateExceptionList = new LinkedList<>();
final int identificationNumberLength = 10;
if (!ValidateUtils.stringLengthValidation(parameter, identificationNumberLength)) {
String exMsg = "entered wrong length identification number";
validateExceptionList.add(new ValidateException(String.format("You %s!", exMsg)));
logger.warn("User {}={}. Identification number length={}", exMsg, parameter, identificationNumberLength);
}
return validateExceptionList;
} |
8b6bb239-73b9-4723-91e0-fcb2ab7baff0 | 2 | @Override
public void doLogic() {
if (inputList[0] == true || inputList[1] == true){
power = false;
} else {
power = true;
}
// Resets power if not still pressed
inputList[0] = false;
inputList[1] = false;
} |
36204ee4-4e2b-4ddc-977d-b4bbd3c285e2 | 7 | private void insert_recursive(LUSTree node){
build_id = node.index+1;
//The new card cannot be inserted here (wouldn't be sorted)
if (node.card < card)
build_result = false;
else{
build_result = false;
//Check to see if it can be inserted somewhere further
for (LUSTree n: branches){
//This node has already been visited
if (n.build_id == build_id){
if (n.build_result)
build_result = true;
}
else{
n.insert_recursive(node);
if (n.build_result)
build_result = true;
}
}
//If not, we'll insert it here
//Make sure there is enough usable in between the cards
if (!build_result && (node.card-card >= node.index-index)){
branches.add(node);
build_result = true;
}
}
} |
8849d23d-a2d9-4cf8-ad15-57a064418fd1 | 1 | public DLLResource(Path script) {
if (script == null) {
IllegalArgumentException iae = new IllegalArgumentException("The scriptfile path must not be null!");
Main.handleUnhandableProblem(iae);
}
this.packer = new ResourcePacker(RESOURCE_HACKER);
this.script = new Script(script);
} |
8d851a17-a5b9-4dd6-8a15-44dcc2ef15bf | 2 | public int getTimeout() {
if (socket != null)
try {
return socket.getSoTimeout();
} catch (IOException exc) {
exc.printStackTrace();
return -1;
}
else
return timeout;
} |
0d6b89c3-df30-4245-a2f0-c1f071586ed6 | 4 | public List<Survivor> getSurvivorsNotPicked() {
List<Survivor> res = new LinkedList<Survivor>();
for (Survivor s : game.getSurvivors()) {
boolean alreadyChosen = false;
for (RaidSettings raid : this.raids) {
if (raid.getTeam().contains(s)) {
alreadyChosen = true;
}
}
if (!alreadyChosen) {
res.add(s);
}
}
return res;
} |
91c9709b-b1e4-4930-a9a0-4626035952d6 | 8 | private SGFLeaf readLeaf( StreamTokenizer st )
throws IOException, SGFException
{
SGFLeaf leaf = null;
SGFToken sgfToken;
int token;
// Keep reading in tokens until the end of the file, the start of a new
// leaf, start of a new tree, or end of the current tree/game. These
// are a semi-colon, open parenthesis, and close parenthesis respectively.
//
while( ((token = st.nextToken()) != StreamTokenizer.TT_EOF) &&
(token != (int)';') &&
(token != (int)'(') &&
(token != (int)')') )
{
if( token == StreamTokenizer.TT_WORD )
if( (sgfToken = readToken( st )) != null )
{
// Since we found a token that belongs to the "information"
// class, it gets a special place in habitat.
//
if( sgfToken instanceof InfoToken )
myGameInfoTokens.add( sgfToken );
else
{
if( leaf == null )
leaf = new SGFLeaf( sgfToken );
else
leaf.addToken( sgfToken );
}
}
}
// We found something that couldn't be an SGFToken, so let the calling
// method handle whatever we read. (End of game/variation/leaf, etc.)
//
st.pushBack();
return leaf;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.