method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
297ab629-5b98-4138-afd1-ff442a2d9565 | 0 | public void actionPerformed(ActionEvent arg0) {
Component apane = environment.tabbed.getSelectedComponent();
JComponent c=(JComponent)environment.getActive();
SaveGraphUtility.saveGraph(apane, c,"BMP files", "bmp");
} |
521b73e1-a738-4aa0-a47e-39a8be1c5327 | 1 | protected void calcDIR_NTRes() {
byte[] bTemp = new byte[1];
for (int i = 12;i < 13; i++) {
bTemp[i-12] = bytesOfFAT32Element[i];
}
DIR_NTRes = byteArrayToInt(bTemp);
} |
c01ecc69-5779-4344-8376-77a505af311e | 1 | public static String toString(byte[] data) {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
DataInputStream dis = new DataInputStream(bais);
try {
return dis.readUTF();
} catch (IOException e) {
}
return null;
} |
797e6271-6c81-4f54-919f-182568565671 | 7 | public void setActionEnabled(String type, boolean enabled){
if(type.equals("undo")){
toolBarUndo.setEnabled(enabled);
editUndo.setEnabled(enabled);
}
else if(type.equals("redo")){
toolBarRedo.setEnabled(enabled);
editRedo.setEnabled(enabled);
}
else if(type.equals("cut")){
toolBarCut.setEnabled(enabled);
editCut.setEnabled(enabled);
}
else if(type.equals("copy")){
toolBarCopy.setEnabled(enabled);
editCopy.setEnabled(enabled);
}
else if(type.equals("paste")){
toolBarPaste.setEnabled(enabled);
editPaste.setEnabled(enabled);
}
else if(type.equals("delete")){
toolBarDelete.setEnabled(enabled);
editDelete.setEnabled(enabled);
}
else if(type.equals("new map")){
mapTreeCreateMapButton.setEnabled(enabled);
}
} |
839f77f0-022b-4fe8-9764-d565d2e6feec | 0 | @Override
public LoggerAppender[] getAppenders() {
return (LoggerAppender[])appenders.toArray(new LoggerAppender[appenders.size()]);
} |
b3724054-8160-410c-800a-bdbdbce2409d | 5 | public static double romberg(SingleVarEq f, double a, double b, int steps){
// TODO: Fix this to start at index 0 rather than 1;
// It works as is, but allocates one dimension of extra array space than necessary.
// since the 0th row and column is never used.
double[][] R = new double[3][steps + 1];
double h = (b - a);
R[1][1] = (h / 2.0) * (f.at(a) + f.at(b));
System.out.println("R1,1 = "+R[1][1]);
for(int i = 2; i <= steps; i++){
double tempSum = 0;
int loopSteps = (int) Math.pow(2, i - 2);
for(int k = 1; k <= loopSteps; k++){
tempSum += f.at(a + (k - 0.5)*h);
}
// Aproximation from trapezoidal method
R[2][1] = 0.5 * (R[1][1] + h * tempSum);
for(int j = 2; j <= i; j++){
// Extrapolation
R[2][j] = R[2][j-1] + ( (R[2][j-1] - R[1][j-1]) / (Math.pow(4, j-1) -1) );
}
for(int j = 1; j <= i; j++){
System.out.print("R" + i +","+j+" = " +R[2][j]+ " \t");
}
System.out.println();
h = h/ 2;
// Update row 1
for(int j = 1; j <= i; j++){
R[1][j] = R[2][j];
}
}
return R[1][steps];
} |
caefccca-1d13-425d-bdd4-9b2e48a6e6d6 | 0 | public void reset() {
startTime = System.currentTimeMillis();
} |
f178cc2c-3d85-4296-851c-010d4504a947 | 5 | public void loadConfig(String config){
int configlength = config.length();
for (int i = 0; i < 81; i++){
int[] xy = indexToXY(i);
int x = xy[0];
int y = xy[1];
String cellValue = "";
if (i < configlength){
char configValue = config.charAt(i);
if(Character.isDigit(configValue) && configValue != '0'){
cellValue += configValue;
}
}
SudokuCell sudokuCell = new SudokuCell(this.possibleValues);
if (!cellValue.equals("")){
sudokuCell.setValue(cellValue);
}
this.sudokuField[y][x] = sudokuCell;
}
} |
ccb3fe11-601d-45e1-86a6-74eae07cea66 | 0 | public RouterPacket(byte[] buf, int length, InetAddress address, int port, int time, int sequence)
{
//set the sequence number of the packet
this.sequence = sequence;
//set the time created
timeCreated = time;
//create the packet
dPacket = new DatagramPacket(buf,length,address,port);
} |
90db231a-aea0-4b8e-9750-8b887b9f1e7a | 1 | public void render(Graphics graphics){
for(int i=0;i<object.size();i++){
tempObject = object.get(i);
tempObject.render(graphics);
}
} |
8690278c-102c-4144-9e6e-3169a9db4ff7 | 5 | private int getHeaderEndIdx(byte[] buf)
{
int idx = 0;
while (idx + 3 < buf.length)
{
if (buf[idx] == '\r' && buf[idx + 1] == '\n' && buf[idx + 2] == '\r' && buf[idx + 3] == '\n')
{
return idx + 4;
}
idx++;
}
return 0;
} |
743f8ce8-d65d-4024-84a0-edbf68573437 | 9 | @Override
public final void actionPerformed(final ActionEvent evt) {
if (ePomodoroTime == pomodoroTime) {
ePomodoroTime--; // To ensure progress is not 100% at start
if (isLongBreakNow) {
taskPanel.setStatus(CurrentTaskPanel.WORKING_THEN_LBRK);
} else {
taskPanel.setStatus(CurrentTaskPanel.WORKING_THEN_SBRK);
}
}
if (eBreakTime == 0) {
setString(getElapsedTime(ePomodoroTime));
setValue((int) ePomodoroTime);
ePomodoroTime--;
}
/*
* Counts down to -1 to give an extra second so that 00:00:01 can
* be displayed.
*/
if (ePomodoroTime == -1) {
setString(getElapsedTime(eBreakTime));
setValue((int) eBreakTime);
eBreakTime++;
}
if (eBreakTime == 1) {
playSound();
setMaximum((int) breakTime);
if (breakTime == model.getSettings().getLongBreak() / MILLI_MULT) {
taskPanel.setStatus(CurrentTaskPanel.LONG_BREAK);
} else {
taskPanel.setStatus(CurrentTaskPanel.SHORT_BREAK);
}
}
if (eBreakTime > breakTime) {
timer.stop();
playSound();
setString("Done!");
// Increments the current pomodoro value
taskPanel.incrementPomodoro();
taskPanel.setStatus(CurrentTaskPanel.NULL);
// Enables a long break after an interval
if (model.getSettings().isWillLongBreak()) {
if (currentCycle >= model.getSettings()
.getIncrementInterval() - 1) {
isLongBreakNow = true;
currentCycle = 0; // Reset the cycle
} else {
isLongBreakNow = false;
currentCycle++;
}
}
}
} |
6ac8a8e2-0f39-4f25-99f4-7a2438e930a3 | 8 | protected String toJSONFragment() {
StringBuffer json = new StringBuffer();
boolean first = true;
if (isSetCreditInstrumentId()) {
if (!first) json.append(", ");
json.append(quoteJSON("CreditInstrumentId"));
json.append(" : ");
json.append(quoteJSON(getCreditInstrumentId()));
first = false;
}
if (isSetAdjustmentAmount()) {
if (!first) json.append(", ");
json.append("\"AdjustmentAmount\" : {");
Amount adjustmentAmount = getAdjustmentAmount();
json.append(adjustmentAmount.toJSONFragment());
json.append("}");
first = false;
}
if (isSetCallerReference()) {
if (!first) json.append(", ");
json.append(quoteJSON("CallerReference"));
json.append(" : ");
json.append(quoteJSON(getCallerReference()));
first = false;
}
if (isSetCallerDescription()) {
if (!first) json.append(", ");
json.append(quoteJSON("CallerDescription"));
json.append(" : ");
json.append(quoteJSON(getCallerDescription()));
first = false;
}
return json.toString();
} |
b8cb5809-fa03-4c2c-a9f2-d96d422c0030 | 7 | private void updateBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateBtnActionPerformed
question = questionField.getText();
instructions = instructionField.getText();
// set the match patter of "[]"
Matcher matcher = Pattern.compile("\\[([^\\]]+)").matcher(question);
ArrayList<String> answers = new ArrayList<String>();
int pos = -1;
while (matcher.find(pos+1)){
pos = matcher.start();
// Add the matched word to the Arraylist
answers.add(matcher.group(1));
}
// Find the word with bracket and replace it with blank
String newQuestion = question.replaceAll("\\[.*?]", "_____");
//System.out.println(answers);
System.out.println(newQuestion);
int key = 0;
try {
connectDb();
int QType_ID = 2;
int errors = 0;
// Update the question table
sql1 = "UPDATE fib SET QuestionText='"+question+"',QuestionBlank='"+newQuestion+"', Instructions='"+instructions+"' WHERE QuestionID='"+questionID+"' ";
int rows = st.executeUpdate(sql1);
if(rows == 0) {
errors++;
}
//System.out.println(sql1);
// Delete all the answers
String deleteAnswer = "DELETE FROM fibanswer WHERE QuestionID='"+questionID+"'";
int rows2 = st.executeUpdate(deleteAnswer);
if(rows2 == 0) {
errors++;
}
if (errors == 0) {
JOptionPane.showMessageDialog(null, "Question was successfully updated!");
} else {
JOptionPane.showMessageDialog(null, "ERROR in updating question!!", "error", JOptionPane.ERROR_MESSAGE);
}
//System.out.println(deleteAnswer);
}
catch (Exception exc) {
exc.printStackTrace();
}
// Loop through ArrayList and Insert NEW Answers into DB
for (String answer : answers) {
try {
connectDb();
// Insert answer to DB
sql2 = "INSERT INTO fibanswer (AnswerContentText,QuestionID) VALUES('"+answer+"', '"+questionID+"')";
st.executeUpdate(sql2);
System.out.println(sql2);
}
catch (Exception exc) {
exc.printStackTrace();
}
}
}//GEN-LAST:event_updateBtnActionPerformed |
1a35c518-18b7-447c-8819-d6e64d895f86 | 1 | public IntegerNode pop(){
while (isEmpty() != true){
IntegerNode nextInLine = this.top;
this.top = this.top.getNextTop();
count--;
return nextInLine;
}
return null;
} |
1781ac8c-d8f1-4b79-8fff-621a36b3c6ef | 8 | private void iniReader() throws IOException {
FileReader iniFile = new FileReader("D:\\search.ini");
BufferedReader reader = null;
try {
reader = new BufferedReader(iniFile);
String str = "";
if((str = reader.readLine()) != null ) {
field.setText(str);
}
if((str = reader.readLine()) != null ) {
addressField.setText(str);
}
if((str = reader.readLine()) != null ) {
portField.setText(str);
}
if((str = reader.readLine()) != null ) {
userField.setText(str);
}
if((str = reader.readLine()) != null ) {
passwordField.setText(str);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null){
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} |
318c6c95-827b-4807-9d68-06eb857a2e12 | 1 | void parseAttlistDecl() throws java.lang.Exception
{
String elementName;
requireWhitespace();
elementName = readNmtoken(true);
requireWhitespace();
while (!tryRead('>')) {
parseAttDef(elementName);
skipWhitespace();
}
} |
08e67deb-d57f-4f50-b21f-dde6d65a4089 | 9 | private final int toIndex(Object base, Object property) {
int index = 0;
if (property instanceof Number) {
index = ((Number) property).intValue();
} else if (property instanceof String) {
try {
index = Integer.valueOf((String) property);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Cannot parse array index: " + property);
}
} else if (property instanceof Character) {
index = ((Character) property).charValue();
} else if (property instanceof Boolean) {
index = ((Boolean) property).booleanValue() ? 1 : 0;
} else {
throw new IllegalArgumentException("Cannot coerce property to array index: " + property);
}
if (base != null && (index < 0 || index >= Array.getLength(base))) {
throw new PropertyNotFoundException("Array index out of bounds: " + index);
}
return index;
} |
e710e97c-2c80-43d0-ad16-d3409d8254f2 | 9 | final int method854(int i) {
anInt10827++;
Class259 class259 = method868((byte) -125);
int i_32_ = aClass99_10893.anInt1281;
boolean bool;
if ((class259.anInt3258 ^ 0xffffffff) != -1) {
bool = aClass99_10893.method1089(anInt10889, class259.anInt3283, -21712, class259.anInt3258);
} else {
bool = aClass99_10893.method1089(anInt10889, anInt10890, -21712, anInt10890);
}
if (i < 34) {
return 25;
}
int i_33_ = aClass99_10893.anInt1281 - i_32_;
if (i_33_ != 0) {
anInt10877++;
} else {
anInt10877 = 0;
aClass99_10893.method1088((byte) 61, anInt10889);
}
if (!bool) {
if (class259.anInt3278 != 0) {
aClass99_10898.method1089(0, class259.anInt3284, -21712, class259.anInt3278);
} else {
aClass99_10898.method1088((byte) 73, 0);
}
if ((class259.anInt3272 ^ 0xffffffff) == -1) {
aClass99_10899.method1088((byte) 122, 0);
} else {
aClass99_10899.method1089(0, class259.anInt3289, -21712, class259.anInt3272);
}
} else {
if (class259.anInt3278 != 0) {
if (i_33_ > 0) {
aClass99_10898.method1089(class259.anInt3250, class259.anInt3284, -21712, class259.anInt3278);
} else {
aClass99_10898.method1089(-class259.anInt3250, class259.anInt3284, -21712, class259.anInt3278);
}
}
if ((class259.anInt3272 ^ 0xffffffff) != -1) {
aClass99_10899.method1089(class259.anInt3285, class259.anInt3289, -21712, class259.anInt3272);
}
}
return i_33_;
} |
e01c8dc7-ecd6-4b12-b459-041c6461c321 | 8 | public static long parseLongWithTable(String s, int radix){
boolean negative = false;
if(radix < 2 || radix > 36){
throw new NumberFormatException();
}
char[] chars = s.toUpperCase().toCharArray();
if(chars[0] == 45){
negative = true;
chars = removeChar(chars, (char)45);
}
chars = reverse(chars);
int length = chars.length;
long n = 0;
for(int i = 0; i < length; i++){
char c = chars[i];
int j = 0;
boolean bool = false;
for(; j < radix; j++){
if(c == ACCEPTABLE_DIGITS[j]){
bool = true;
break;
}
}
if(!bool){
throw new NumberFormatException();
}
byte b = ACCEPTABLE_DIGITS_NUMERALS[j];
n += b * Math.pow(radix, i);
}
return negative ? -n : n;
} |
b3aa0b90-91e0-4b06-b5dc-c7548375611a | 5 | public static void main(String[] args) {
long sum = 0;
outer: for (int i = 1; i <= 100_000_000; i++) {
if (!isPrime(i))
continue;
int n = i - 1;
int end = (int) Math.ceil(Math.sqrt(n + 1));
for (int j = 2; j < end; j++)
if (n % j == 0 && !isPrime(j + n / j))
continue outer;
sum += n;
System.out.println("> " + n);
}
System.out.println(">>> " + sum);
} |
3dc695c4-7cc1-41a0-86d7-7c31197986de | 8 | boolean placeDomino(int i) {
if (i == D.length) {
for (int d = 0; d < D.length; d++) {
System.out.println(D[d]);
}
return true;
}
for (int x = 0; x < w; x++)
for (int y = 0; y < h; y++) {
if (tryPlace(i, x, y, x - 1, y) || tryPlace(i, x, y, x + 1, y) || tryPlace(i, x, y, x, y + 1)
|| tryPlace(i, x, y, x, y - 1))
return true;
}
return false;
} |
a71c1518-e296-435a-80f8-9e65348c065e | 7 | public int checaDia(int diaTemp) {
int ultimoDiaMes[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (diaTemp > 0 && diaTemp <= ultimoDiaMes[mes]) {
return diaTemp;
} else if ((mes == 2 && diaTemp == 29) && (ano % 400 == 0) || ((ano % 4 == 0) && (ano % 100 != 0))) {
return diaTemp;
} else {
return -1;
}
} |
89ab7589-4cce-46c2-bfd5-d3044413d813 | 4 | public Writer(String fileName) throws UnsupportedCharsetException {
if (System.getProperty("file.encoding").equalsIgnoreCase("UTF-8") == false) {
String explainString // Chack whether the encoding property is correct
= "\n\tThe system property: \"file.encoding\" should set to \"UTF-8\"."
+ "\n\tSet it, and run the program again."
+ "\n\tYou can set the \"file.encoding\" property by passing -Dfile.encoding=UTF-8 as argument to the JVM.\n";
throw new UnsupportedCharsetException(explainString);
}
try {
this.file = new File(fileName);
if (this.file.exists() == false) {//if file doesnt exists, then create it
this.file.createNewFile();
}
this.fileOutputStream = new FileOutputStream(this.file);
this.outputStreamWriter = new OutputStreamWriter(this.fileOutputStream, Charset.forName("UTF8"));
this.bufferWriter = new BufferedWriter(this.outputStreamWriter);
//<editor-fold defaultstate="collapsed" desc="would you like to test?">
// this.write("<!DOCTYPE html>\n"
// + "<html>\n"
// + " <head>\n"
// + " <title>פלט לבדיקה</title>\n"
// + " <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n"
// + " <META HTTP-EQUIV=\"CACHE-CONTROL\" CONTENT=\"NO-CACHE\">\n"
// + " <link href=\"style.css\" rel=\"stylesheet\" type=\"text/css\" media=\"all\">\n"
// + " </head>\n"
// + " <body>\n");
//</editor-fold>
} catch (IOException ex) {
System.out.println(ex);
for (StackTraceElement el : ex.getStackTrace()) {
System.out.println(el);
}
}
} |
365c0be1-0a4b-4f32-b857-d665b38c56c3 | 8 | public CreateDirectories() {
try {
String binning = "Bins";
boolean success = (new File(binning)).mkdir();
if(success) {
System.out.println("Folder 'bins' created");
}
for(int ab = 0; ab<4; ++ab) { // alpha/beta designation
for(int d=0; d<10; ++d) { // distance
for (int delta=0; delta<3; ++delta) {
for (int theta=0; theta<3; ++theta) {
for(int rho=0; rho<6; ++rho) {
String dirStr = "Bins/" + ab + "/" + d + "/" +
delta + "/" + theta + "/" + rho + "";
success = (new File(dirStr)).mkdirs();
}
}
}
}
}
if(success) {
System.out.println("Folders successfully completed.");
}
}
catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
} |
abc65f7f-09dc-4249-8b7c-0425686ede77 | 5 | public static <A, B> Equal<Either<A, B>> eitherEqual(final Equal<A> ea, final Equal<B> eb) {
return equal(e1 -> e2 -> e1.isLeft() && e2.isLeft() && ea.f.f(e1.left().value()).f(e2.left().value()) ||
e1.isRight() && e2.isRight() && eb.f.f(e1.right().value()).f(e2.right().value()));
} |
b14c8618-b597-4e3f-ae46-dd21cc7b79cd | 4 | public static <A> Equal<List<A>> listEqual(final Equal<A> ea) {
return equal(a1 -> a2 -> {
List<A> x1 = a1;
List<A> x2 = a2;
while (x1.isNotEmpty() && x2.isNotEmpty()) {
if (!ea.eq(x1.head(), x2.head()))
return false;
x1 = x1.tail();
x2 = x2.tail();
}
return x1.isEmpty() && x2.isEmpty();
});
} |
c2c7c754-a4bf-4a89-a3b5-3ae33a1ee1c4 | 7 | private boolean isTrueSNP(VariantCandidate v) {
if (v.val("max.qual.minor") > 59.699 && v.val("total.depth") <= 82.149 && v.val("allele.balance") >= 0.067) {
return true;
} else if(v.val("max.qual.minor") <= 60.101 || v.val("total.depth") > 60.973 || (v.val("allele.balance") > 0.048 && v.val("allele.balance") < 0.930)) {
return false;
} else {
return false;
}
} |
69557252-bd08-4c15-aa23-120129ae58f2 | 7 | private static void writeOperator(Writer output,
AuOperator.Descriptor desc) throws IOException {
if(desc == IntArithmetic.intAdd) {
output.write("ia");
}else if(desc == Products.productType) {
output.write("prt");
}else if(desc == Products.product) {
output.write("prv");
}else if(desc instanceof Lists.List) {
Lists.List list = (Lists.List)desc;
output.write("l");
output.write(Integer.toString(list.getLength()));
}else if(desc == Anys.any) {
output.write("ayv");
}else if(desc == Mutation.mutatorType) {
output.write("mut");
}else if(desc == Io.print) {
output.write("iop");
}else throw new RuntimeException("Unsupported operator " + desc);
} |
e9d33e43-f88b-449b-8d6e-cd1f784d3397 | 8 | public void append(double d[], int n) throws Exception {
double tmp[];
int ln = n * stride;
if (d == null || d.length == 0 || n <= 0) {
throw new Exception("DataSet: Error in append data!");
}
if (data == null)
data = new double[increment];
// Copy the data locally.
if (ln + length < data.length) {
System.arraycopy(d, 0, data, length, ln);
length += ln;
}
else {
tmp = new double[ln + length + increment];
if (length != 0) {
System.arraycopy(data, 0, tmp, 0, length);
}
System.arraycopy(d, 0, tmp, length, ln);
length += ln;
data = tmp;
}
// Calculate the data range.
range(stride);
// Update the range on Axis that this data is attached to
if (xaxis != null)
xaxis.resetRange();
if (yaxis != null)
yaxis.resetRange();
} |
741191e6-c107-4d86-8cac-1efd45ace395 | 7 | private static boolean isCompatible(Class[] paramTypes, Class<?>[] actualTypes) {
if (actualTypes.length != paramTypes.length)
return false;
boolean found = true;
for (int j = 0; j < actualTypes.length; j++) {
if (!actualTypes[j].isAssignableFrom(paramTypes[j])) {
if (actualTypes[j].isPrimitive()) {
found = primitiveMap.get(actualTypes[j]).equals(paramTypes[j]);
} else if (paramTypes[j].isPrimitive()) {
found = primitiveMap.get(paramTypes[j]).equals(actualTypes[j]);
}
}
if (!found)
break;
}
return found;
} |
e3079884-9e6c-4904-a0d7-3bb87de865ca | 1 | public java.security.cert.X509Certificate[] getAcceptedIssuers() {
java.security.cert.X509Certificate[] chain = null;
try {
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
KeyStore tks = KeyStore.getInstance("JKS");
tks.load(this.getClass().getClassLoader().getResourceAsStream("SSL/serverstore.jks"),
SERVER_KEY_STORE_PASSWORD.toCharArray());
tmf.init(tks);
chain = ((X509TrustManager) tmf.getTrustManagers()[0]).getAcceptedIssuers();
} catch (Exception e) {
throw new RuntimeException(e);
}
return chain;
} |
b9deb429-1a08-4c2a-b546-47e863ca8304 | 3 | public static void main(String[] args) {
int a = 10, b = 20;
if( a > b ) {
System.out.println(a + ">" + b);
}
else if ( a < b ) {
System.out.println(a + "<" + b);
}
else if ( a == b ){
System.out.println(a + "==" + b);
}
} |
5d797665-8dd7-425f-be3d-d6328c041f08 | 6 | @Override
public void mouseExited(MouseEvent e) {
if(e.getSource()==recordBut){
recordBut.setIcon(recordIcon);
}else if(e.getSource()==playBut){
playBut.setIcon(playIcon);
}else if(e.getSource()==stopBut){
stopBut.setIcon(stopIcon);
}else if(e.getSource()==saveBut){
saveBut.setIcon(saveIcon);
}else if(e.getSource()==openBut){
openBut.setIcon(openIcon);
}else if(e.getSource()==saveAllBut){
saveAllBut.setIcon(saveIcon);
}
} |
4a33ec80-0846-47f7-a2a1-5087d5799d5f | 4 | public void setProperty(String property, String newvalue){
try {
r = new BufferedReader(new FileReader(config));
} catch (IOException e1) {
}
String temp = "";
try {
p = new PrintWriter(config);
while((temp = r.readLine()) != null){
if(!(temp.startsWith(property))){
p.println(temp);
} else {
p.println(property + ": " + newvalue);
p.close();
return;
}
}
p.println(property + ": " + newvalue);
p.close();
} catch (IOException e) {
}
} |
61b42324-7075-4722-b7d6-3f361cf00c24 | 0 | public int getID() {
return IDNumber;
} |
d384fc2e-b76a-4de4-88fb-890ab3786ad5 | 0 | protected Element createTransitionElement(Document document, Transition transition)
{
Element te = super.createTransitionElement(document, transition);
MealyTransition t = (MealyTransition) transition;
te.appendChild(createElement(document, TRANSITION_READ_NAME, null, t.getLabel()));
te.appendChild(createElement(document, TRANSITION_OUTPUT_NAME, null, t.getOutput()));
return te;
} |
1d35df6b-57cb-4a67-8813-54f6d23b0a31 | 9 | public GuiView() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
setLocationRelativeTo(null);
try {
GuiView.backend.setUserList(GuiView.backend.load());
//System.out.println("LOADED: " + CmdView.backend.getUserList().get("dennisr").getFullName().toString());
} catch (IOException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(new BorderLayout(0, 0));
JPanel northPanel = new JPanel();
northPanel.setPreferredSize(new Dimension(10, 50));
panel.add(northPanel, BorderLayout.NORTH);
northPanel.setLayout(new BorderLayout(0, 0));
JLabel titleLabel = new JLabel("Team 06 Photo Album");
titleLabel.setHorizontalAlignment(SwingConstants.CENTER);
northPanel.add(titleLabel, BorderLayout.CENTER);
JPanel centerPanel = new JPanel();
panel.add(centerPanel, BorderLayout.CENTER);
centerPanel.setLayout(null);
JLabel lblUserId = new JLabel("User ID:");
lblUserId.setBounds(63, 78, 61, 16);
centerPanel.add(lblUserId);
final JLabel errorHandlerLabel = new JLabel("");
errorHandlerLabel.setForeground(Color.RED);
errorHandlerLabel.setHorizontalAlignment(SwingConstants.CENTER);
errorHandlerLabel.setBounds(6, 32, 428, 16);
centerPanel.add(errorHandlerLabel);
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
if (textField.getText().length() == 0)
errorHandlerLabel.setText("Error: Please input a User ID");
else if (textField.getText().toLowerCase().equals("admin")) {
dispose();
AdminLogin al = new AdminLogin();
al.setVisible(true);
al.setEnabled(true);
}
else {
if (GuiView.control.login(textField.getText()) == true) {
dispose();
UserLogin ul = new UserLogin();
ul.setVisible(true);
ul.setEnabled(true);
}
else {
errorHandlerLabel.setText("Error: User '" + textField.getText() + "' does not exist in the User Database");
}
}
}
}
});
textField.setBounds(149, 72, 207, 28);
centerPanel.add(textField);
textField.setColumns(10);
JPanel southPanel = new JPanel();
southPanel.setPreferredSize(new Dimension(10, 50));
panel.add(southPanel, BorderLayout.SOUTH);
southPanel.setLayout(null);
JButton btnConfirm = new JButton("Confirm");
btnConfirm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (textField.getText().length() == 0)
errorHandlerLabel.setText("Error: Please input a User ID");
else if (textField.getText().toLowerCase().equals("admin")) {
dispose();
AdminLogin al = new AdminLogin();
al.setVisible(true);
al.setEnabled(true);
}
else {
if (GuiView.backend.getUserList().containsKey(textField.getText())) {
dispose();
UserLogin ul = new UserLogin();
ul.setVisible(true);
ul.setEnabled(true);
control.login(textField.getText());
}
else {
errorHandlerLabel.setText("Error: User '" + textField.getText() + "' does not exist in the User Database");
}
}
}
});
btnConfirm.setBounds(84, 6, 117, 29);
southPanel.add(btnConfirm);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setBounds(213, 6, 117, 29);
southPanel.add(btnExit);
} |
aba287e0-ebe3-4373-bbf6-6f1ef49eae0b | 4 | public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder out = new StringBuilder();
int nCases = Integer.parseInt(in.readLine().trim());
for (int nCase = 0; nCase < nCases; nCase++) {
String word = in.readLine().trim();
char[] p = new char[word.length()];
char[] t = new char[word.length()];
for (int i = 0; i < word.length(); i++) {
char l = word.charAt(i);
p[i] = l;
t[word.length() - i - 1] = l;
}
preprocess(p);
int len = KMP(p, t);
if (len == 0)
out.append(p[0] + "\n");
else {
for (int i = len - 1; i >= 0; i--)
out.append(p[i]);
out.append('\n');
}
}
System.out.print(out);
} |
f3db1154-4ba1-4b22-885b-7a58969b6a77 | 7 | public synchronized BufferedImage getSample(int width, int height) {
BufferedImage sample = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
Graphics2D sampleEditor = sample.createGraphics();
sampleEditor.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
sampleEditor.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
sampleEditor.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,
RenderingHints.VALUE_COLOR_RENDER_QUALITY);
Point oldPoint = new Point(width / 10, height / 2);
Point point = new Point(width / 10, height / 2);
int i = 0;
int formSize = (int) (int) (Math.pow(Math.log(Math.max(width, height)), this.ratioCircle));
sampleEditor.setColor(new Color(0, 0, 0, 128));
if (this.mouseStops) {
switch (this.typeMS) {
case circles:
sampleEditor.fillOval(
((int) (point.x - ((double) formSize / 2))),
((int) (point.y - ((double) formSize / 2))), formSize,
formSize);
sampleEditor.setColor(this.colorTab[0]);
formSize = (int) (Math.pow(Math.log(Math.max(width, height)), this.ratioDisk));
sampleEditor.fillOval(
((int) (point.x - ((double) formSize / 2))),
((int) (point.y - ((double) formSize / 2))), formSize,
formSize);
break;
case squares:
sampleEditor.fillRect(point.x - (formSize / 2), point.y
- (formSize / 2), formSize, formSize);
sampleEditor.setColor(this.colorTab[0]);
formSize = (int) (Math.pow(Math.log(Math.max(width, height)), this.ratioDisk));
sampleEditor.fillRect(point.x - (formSize / 2), point.y
- (formSize / 2), formSize, formSize);
break;
default:
System.out.println("typeMouseStop : Shape not defined !");
break;
}
}
double quantum = (width - (width / 5))
/ ((double) this.colorTab.length - 1);
while (i < this.colorTab.length) {
point.x = (int) ((width / 10) + (quantum * i));
sampleEditor.setColor(this.colorTab[i]);
sampleEditor.drawLine(oldPoint.x, oldPoint.y, point.x, point.y);
oldPoint.x = point.x;
i++;
}
sampleEditor.setColor(new Color(0, 0, 0, 128));
formSize = (int) (Math.pow(Math.log(Math.max(width, height)), this.ratioCircle));
if (this.mouseStops) {
switch (this.typeMS) {
case circles:
sampleEditor.fillOval(
((int) (point.x - ((double) formSize / 2))),
((int) (point.y - ((double) formSize / 2))), formSize,
formSize);
sampleEditor.setColor(this.colorTab[i - 1]);
formSize = (int) (Math.pow(Math.log(Math.max(width, height)), this.ratioDisk));
sampleEditor.fillOval(
((int) (point.x - ((double) formSize / 2))),
((int) (point.y - ((double) formSize / 2))), formSize,
formSize);
break;
case squares:
sampleEditor.fillRect(
((int) (point.x - ((double) formSize / 2))),
((int) (point.y - ((double) formSize / 2))), formSize,
formSize);
sampleEditor.setColor(this.colorTab[i - 1]);
formSize = (int) (Math.pow(Math.log(Math.max(width, height)), this.ratioDisk));
sampleEditor.fillRect(
((int) (point.x - ((double) formSize / 2))),
((int) (point.y - ((double) formSize / 2))), formSize,
formSize);
break;
default:
System.out.println("typeMouseStop : Shape not defined !");
break;
}
}
return sample;
} |
df8a306f-b8af-4d30-b29c-a06f97c2643b | 7 | public static Rule_DOT parse(ParserContext context)
{
context.push("DOT");
boolean parsed = true;
int s0 = context.index;
ArrayList<Rule> e0 = new ArrayList<Rule>();
Rule rule;
parsed = false;
if (!parsed)
{
{
ArrayList<Rule> e1 = new ArrayList<Rule>();
int s1 = context.index;
parsed = true;
if (parsed)
{
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++)
{
rule = Terminal_NumericValue.parse(context, "%x2e", "[\\x2e]", 1);
if ((f1 = rule != null))
{
e1.add(rule);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed)
e0.addAll(e1);
else
context.index = s1;
}
}
rule = null;
if (parsed)
rule = new Rule_DOT(context.text.substring(s0, context.index), e0);
else
context.index = s0;
context.pop("DOT", parsed);
return (Rule_DOT)rule;
} |
cc08cf0e-0d2d-4dca-be2d-6f007552f5dc | 6 | private void addInvoice() {
Scanner sc = new Scanner(System.in);
int orderID;
boolean success;
int testOrderID;
do {
success = true;
System.out.println("Please enter the order id (enter -1 to exit):");
testOrderID = inputInteger();
if(testOrderID == -1) break;
try {
invoiceManager.checkOrderByID(testOrderID);
} catch (IndexOutOfBoundsException e) {
success = false;
System.out.println("Invalid Order ID");
continue;
}
for (Invoice invoice : invoiceManager.getInvoices()) {
if (testOrderID == invoice.getOrderID()) {
System.out.println("Order already checked out");
success = false;
break;
}
}
} while (!success);
orderID = testOrderID;
if (orderID == -1) {
System.out.println("exit");
return;
}
System.out.println("Enter name of the customer (check membership)");
String name = sc.nextLine();
invoiceManager.createInvoice(orderID, name);
} |
2b4059dc-da61-4b27-b8fd-afc3c31cc9e5 | 7 | public void addAtIndex(int data, int position){
if(position == 1){
addAtBegin(data);
}
int len = size;
if (position>len+1 || position <1){
System.out.println("\nINVALID POSITION");
}
if(position==len+1){
addAtEnd(data);
}
if(position<=len && position >1){
Node n = new Node(data);
Node currNode = head; //so index is already 1
while((position-2)>0){
System.out.println(currNode.data);
currNode=currNode.next;
position--;
}
n.next = currNode.next;
currNode.next = n;
size++;
}
} |
f0792042-304f-4298-aa88-23f047b8b53c | 9 | private void outputTotalsRow( int groupLevel,
ICalculator[] calcForCurrentGroupingLevel){
if(distribOfCalculatorsInDataColsArray.length != dataCols.size()){
//TODO: improve
throw new IllegalArgumentException("dataRows and distributionOfCalculators arrays should have the same length");
}
//if not totals afte each group
if(!getShowTotals() && groupLevel>-1){
return;
}
IReportOutput output = getOutput();
output.startRow(new RowProps(ReportContent.DATA, 0, true));
if(groupCols != null && groupCols.size() > 0){
//prepare and output the Total column
String totalString = getTotalStringForGroupingLevel(groupLevel);
output.output(new CellProps.Builder(totalString)
.horizAlign(HorizontalAlign.LEFT)
.build());
if(groupCols.size() > 1){
//for all others grouping columns put whitespaces
//(groupColumns.length-1 colspan because the first column was already
//filled with the word "Total xxxx"
//if you want a single cell spanning multiple rows decomment this
//output.output(new CellProps.Builder(IReportOutput.WHITESPACE)
// .colspan(groupCols.size()-1)
// .build());
//this is to display an empty cell for every remaining group column
for(int i=1; i<groupCols.size(); i++){
output.output(CellProps.EMPTY_CELL);
}
}
}
String formattedResult = null;
//then iterate over data columns to display the totals for those having calculators
for (int i = 0; i < dataCols.size(); i++) {
IDataColumn column = dataCols.get(i);
if(column.getCalculator() != null){
int calculatorIndex = distribOfCalculatorsInDataColsArray[i];
Object calculatorResult = calcForCurrentGroupingLevel[calculatorIndex].getResult();
//format the computed value
formattedResult = dataCols.get(i).getFormattedValue(calculatorResult);
output.output(new CellProps.Builder(formattedResult)
.horizAlign(dataCols.get(i).getHorizAlign())
.build());
}else{
//if the column doesn't have a calculator asociated
//then display an empty value (whitespace) with colspan 1
output.output(CellProps.EMPTY_CELL);
}
}
output.endRow(new RowProps(ReportContent.DATA, 0, true));
} |
0af6ff46-d4ac-43af-bcd0-ab9e5d5632e4 | 0 | public void setSink(boolean isSink) {
this.isSink = isSink;
} |
c6c08287-cecd-4fc1-a88f-1cfaa0f1e092 | 5 | public void initSoldats() {
// Ajout des Héros
heros = new Armee(NB_HEROS);
for (int i=0; i<=NB_HEROS; i++){
int x, y;
do{
x = (int) (Math.random() * (IConfig.LARGEUR_CARTE / 2));
y = (int) (Math.random() * IConfig.HAUTEUR_CARTE);
}while (!map[x][y].estLibre() || map[x][y].getType() == BackgroundEnum.water);
Heros recrue = new Heros(ISoldat.TypesH.getTypeHAlea(), new Position(x, y));
heros.ajouteSoldat(recrue);
map[x][y].ajouteSoldat(recrue);
}
// Ajout des monstres
monstres = new Armee(NB_MONSTRES);
for (int i=0; i<=NB_MONSTRES; i++){
int x, y;
do{
x = (int) ((Math.random() * (IConfig.LARGEUR_CARTE / 2)) + (LARGEUR_CARTE / 2));
y = (int) (Math.random() * IConfig.HAUTEUR_CARTE);
}while (!map[x][y].estLibre());
Monstre recrue = new Monstre(ISoldat.TypesM.getTypeMAlea(), new Position(x, y));
monstres.ajouteSoldat(recrue);
map[x][y].ajouteSoldat(recrue);
}
} |
f98c27f2-11fc-4ac3-b5b7-4a6233882ccb | 1 | public static boolean userName(String username){
if(username.matches("[a-zA-Z](\\w){8,29}"))
return true;
return false;
} |
bfe611db-9c03-4a49-affb-b1a0c701df5a | 4 | private boolean isSocialNetworkAccountAdded(SocialNetworkAccount socialNetworkAccount)
{
for(int i=0; i<addedSocialNetworkAccountCount; i++)
{
SocialNetworkAccount addedSocialNetworkAct = socialNetworkAccounts[i];
//If they have the same account type ...
if(addedSocialNetworkAct.getSocialNetworkAccountType().equals(socialNetworkAccount.getSocialNetworkAccountType()))
{
//and same ID ...
if(addedSocialNetworkAct.getAccountID() == socialNetworkAccount.getAccountID())
{
return true; //duplicate
}
//and same account name ...
else if (addedSocialNetworkAct.getAccountName().equalsIgnoreCase(socialNetworkAccount.getAccountName()))
{
return true; //also duplicate
}
}
}
return false;
} |
6b3298a2-fa0b-4552-866c-f8bcf524d1ca | 3 | public void test_constructor() {
BaseDateTimeField field = new MockPreciseDurationDateTimeField();
assertEquals(DateTimeFieldType.secondOfMinute(), field.getType());
try {
field = new MockPreciseDurationDateTimeField(null, null);
fail();
} catch (IllegalArgumentException ex) {}
try {
field = new MockPreciseDurationDateTimeField(
DateTimeFieldType.minuteOfHour(),
new MockImpreciseDurationField(DurationFieldType.minutes()));
fail();
} catch (IllegalArgumentException ex) {}
try {
field = new MockPreciseDurationDateTimeField(
DateTimeFieldType.minuteOfHour(),
new MockZeroDurationField(DurationFieldType.minutes()));
fail();
} catch (IllegalArgumentException ex) {}
} |
600093bf-6e0b-4548-ac53-764ddd5fba20 | 8 | protected void onSelectionChanged(DiagramFieldPanel field)
{
if(field.isSelected())
queryBuilderPane.sqlBrowserViewPanel.addSelectList(field.getQueryTokenColumn());
else
queryBuilderPane.sqlBrowserViewPanel.removeSelectList(field.getQueryTokenColumn());
packFields();
if(queryItem instanceof BrowserItems.DiagramQueryTreeItem)
{
DiagramQuery entityUp = ((BrowserItems.DiagramQueryTreeItem) queryItem).getDiagramObject();
if (entityUp == null)
return;
if(field.isSelected())
{
final DiagramFieldPanel existinField = entityUp.getField(
field.getQueryTokenColumn().getAlias() != null ? field.getQueryTokenColumn().getAlias()
: field.getQueryTokenColumn().getName());
if (existinField == null)
{
if (field.getQueryTokenColumn().getAlias() == null)
entityUp.addField(field.getQueryTokenColumn().getName());
else
entityUp.addField(field.getQueryTokenColumn().getAlias());
}
}
else
{
entityUp.removeField(field.getQueryTokenColumn().getAlias());
if (field.getQueryTokenColumn().getAlias() == null)
entityUp.removeField(field.getQueryTokenColumn().getName());
else
entityUp.removeField(field.getQueryTokenColumn().getAlias());
}
entityUp.pack();
}
} |
bfb55c62-f5db-40a7-8259-46986542e3e6 | 1 | public boolean exists() {
return question != null && answer != null;
} |
b44c3767-632f-4ceb-ad19-4915881cdd8c | 0 | @Override
public boolean supportsComments() {return true;} |
b34bfa3d-b482-4a5b-976f-828928f7ab17 | 7 | private void handleExitButton(ExitButton button) {
// Check input
if (button == null)
throw new IllegalArgumentException("ExitButton can't be null");
// Check a tile is currently selected
if (selectedTileButton != null) {
Point2D from = selectedTileButton.getBoardPosition();
// Calculate the destination x/y based on which button was clicked
int toX = (int) from.getX();
int toY = (int) from.getY();
// Make destination one square off the board in the relevant direction
switch (button.getDirection()) {
case Directional.BIG_X:
toX = boardSize;
break;
case Directional.BIG_Y:
toY = boardSize;
break;
case Directional.SMALL_X:
toX = -1;
break;
case Directional.SMALL_Y:
toY = -1;
break;
default:
throw new IllegalStateException(
"Invalid direction: " + button.getDirection());
}
try {
Player movingPlayer = game.getActivePlayer();
game.getBoard().moveTile(movingPlayer, from, new Point(toX, toY));
// The move succeeded
}
catch (IllegalMoveException ex) {
// The move was invalid
rejectMove(ex.getMessage());
}
}
} |
90316a90-1e8f-44d2-b780-4f57ea0df940 | 3 | private static void caratInputValidator(){
while (!validInput) {
try {
System.out.print("You selected to search by carat. Please enter a carat: ");
caratInput = actionInput.nextDouble();
System.out.println("You entered: " + caratInput);
validInput = true;
if(data1.isEmpty()) {
data1 = caratInput.toString();
} else {
data2 = caratInput.toString();
}
} catch (InputMismatchException e) {
System.out.println("Invalid data type input. Please try again: ");
actionInput.nextLine();
}
}
validInput = false;
} |
b35cb12b-90c3-4235-9ffd-79b39e22dafa | 7 | public static void main(String[] args) {
try {
File file = new File("C:\\Users\\Collin\\Downloads\\words.txt");
Scanner readFile = new Scanner(file);
int maxLines = 0;
int answer = 0;
String wordList = readFile.nextLine();
String[] words;
words = wordList.replace("\"","").split(",");
for (int count = 0; count < words.length; count++) {
if (words[count].length() > maxLines) {
maxLines = words[count].length();
}
}
maxLines *= 26;
ArrayList triangles = new ArrayList();
for (double count = 1; .5*count*(count+1) < maxLines; count++) {
triangles.add((int)(.5*count*(count+1)));
}
for (int count = 0; count < words.length; count++) {
char[] letters = words[count].toLowerCase().toCharArray();
int lineValue = 0;
for (int insideCount = 0; insideCount < letters.length; insideCount++) {
lineValue += (int)letters[insideCount] - 96;
}
if (triangles.contains(lineValue)) {
answer++;
}
}
System.out.println(answer);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} |
62046310-4fd7-470f-b163-59fc2780f059 | 9 | @Override
protected void updateDefinition(final JeksCell cell,
final String cellAddress, final String value)
{
if (currentTierOneHeader == TIER_ONE_HEADERS.FIELDS)
{
if (columnHeaderMapping.get(CodecUtils
.getColumnFromString(cellAddress)) == TIER_TWO_HEADERS.LABELS)
{
if (parameterInfo.getLabel() != null)
{
type.addParameter(parameterInfo);
parameterInfo = type.new FieldInfo();
}
parameterInfo.addLabel(value);
} else if (columnHeaderMapping.get(CodecUtils
.getColumnFromString(cellAddress)) == TIER_TWO_HEADERS.DEFAULT)
{
parameterInfo.addDefault(model.getValueAt(cell.getRow(), cell.getColumn()));
} else if (columnHeaderMapping.get(CodecUtils
.getColumnFromString(cellAddress)) == TIER_TWO_HEADERS.ACCESS)
{
parameterInfo.addAccess(value);
}
} else if (currentTierOneHeader == TIER_ONE_HEADERS.FUN_NAME)
{
currentDefinition.setName(value);
completeTypeDefinition();
} else if (currentTierOneHeader == TIER_ONE_HEADERS.ARGS)
{
if (columnHeaderMapping.get(CodecUtils
.getColumnFromString(cellAddress)) == TIER_TWO_HEADERS.NAME)
{
paramHolder.name = value;
String col = CodecUtils.getColumnFromHeader(
columnHeaderMapping.entrySet(),
TIER_TWO_HEADERS.TEST_VALUE);
if (col != null)
{
String testAddress = col
+ CodecUtils.getRowFromString(cellAddress);
paramHolder.testCell = savedExpressionSyntax
.getCellAt(testAddress);
currentDefinition.addParameter(new FunctionSheetParameter(
paramHolder.name, paramHolder.testCell));
paramHolder = new FunctionParamHolder();
}
}
}
} |
101c3c2f-9df1-4e52-a0dd-e4e290892137 | 4 | public void update(Game game)
{
super.update(game);
if(age == 2)
{
for(Vector2d u : Types.BASEDIRS)
{
if(game.getRandomGenerator().nextDouble() < spreadprob)
{
int newType = (itype == -1) ? this.getType() : itype;
game.addSprite(newType, new Vector2d(this.lastrect.x + u.x*this.lastrect.width,
this.lastrect.y + u.y*this.lastrect.height));
}
}
}
} |
e6b8649d-fec8-44e4-9754-965331c32848 | 9 | private void drawTableGrid() {
Object[][] cellData = new Object[0][headers.length];
tableGridModel = new DefaultTableModel(cellData, headers) {
private static final long serialVersionUID = 880033063879582590L;
public boolean isCellEditable(int row, int column) {
if (column == 2 || column == 7 || column == 9) {
return true;
} else return false;
}
};
tableGridModel.addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
if (e.getType() == TableModelEvent.UPDATE && e.getLastRow() >= 0) {
String columnName = tableGrid.getValueAt(e.getLastRow(), 0).toString();
String value = tableGrid.getValueAt(e.getLastRow(), e.getColumn()).toString();
Column column = tableModel.getColumn(columnName);
if (column != null) {
if (e.getColumn() == 2) {
column.setJavaType(value);
} else if (e.getColumn() == 7) {
column.setNullable(Boolean.parseBoolean(value));
} else if (e.getColumn() == 9) {
column.setRemarks(value);
}
}
}
}
});
tableGrid.setModel(tableGridModel);
tableGrid.setRowHeight(22);
((EditableTable) tableGrid).setComboCell(2, new ComboBoxEditor(typeMapping.getAllJavaTypes()));// 第2列为下拉
resizeTableGrid(true);
} |
43eca06a-b02b-4c69-9666-9e681a9f755d | 6 | @Override
public void emettre() throws InformationNonConforme {
Float[] tabFloat = new Float[informationRecue.nbElements() * nbEch];
for (int i = 0; i < informationRecue.nbElements(); i++) {
if (informationRecue.iemeElement(i)) {
for (int j = i * nbEch; j < (i + 1) * nbEch; j++)
tabFloat[j] = ampMax;
} else {
for (int j = i * nbEch; j < (i + 1) * nbEch; j++)
tabFloat[j] = ampMin;
}
}
Information<Float> sigAnalog = new Information<Float>(tabFloat);
informationEmise = sigAnalog;
if (utilisationSondes) {
SondeAnalogique sa1 = new SondeAnalogique("Sortie Emetteur NRZ");
sa1.recevoir(informationEmise);
}
for (DestinationInterface<Float> dest : destinationsConnectees)
dest.recevoir(informationEmise);
} |
8bf1104d-83a7-45b1-a776-0a4bed3c3d0b | 8 | public static void matchListings(List<Listing> listings, final Map<String, Product> productMap, final ManufacturerLookup manufacturerLookup) {
System.out.println("Matching listings...");
// // single threaded implementation
// for(Listing listing : listings) {
//
// // match product name
// String productName = manufacturerLookup.lookupProductName(listing);
// if(productName == null) {
// continue;
// }
//
// // add to the product's listings
// Product product = productMap.get(productName);
// if(product == null) {
// continue;
// }
//
// product.listings.add(listing);
// }
// mutli-threaded mostly because it was easy to implement for this algorithm
// and does speed up the matching a lot for multi-core machines.
// make a thread safe copy to use as the source (linked list since we are removing from the front)
final List<Listing> source = Collections.synchronizedList(new LinkedList<Listing>(listings));
// objects used to signal that all threads are done
final Object signal = new Object();
final AtomicInteger remainingThreads = new AtomicInteger();
for(int i = 0; i < Challenge.THREADS; ++i) {
// another thread added
remainingThreads.incrementAndGet();
// very simple threads implementation of the above code
Runnable runner = new Runnable() {
public void run() {
while(true) {
// remove head items until collection is empty
Listing listing;
try {
listing = source.remove(0);
} catch (IndexOutOfBoundsException e) {
// lists throw IndexOutOfBoundsException when remove is called on an empty list
// we will use that as a signal for done
break;
}
// match product name
String productName = manufacturerLookup.lookupProductName(listing);
if(productName == null) {
continue;
}
Product product = productMap.get(productName);
if(product == null) {
continue;
}
// add to the product's listings
// product.listings collection is thread safe
product.listings.add(listing);
}
// signal when all threads are done
int remaining = remainingThreads.decrementAndGet();
if(remaining <= 0) {
synchronized (signal) {
signal.notify();
}
}
}
};
// run the matcher
Thread thread = new Thread(runner);
thread.start();
}
// wait for all threads to finish
while(remainingThreads.get() > 0) {
try {
synchronized (signal) {
signal.wait();
}
} catch (InterruptedException e) {
// dont care, try again
}
}
} |
a3134209-5fca-4a1d-b5fa-b9945a40e6b2 | 0 | public void set(String key, Object value) {
datas.put(key, value);
} |
f570c86d-4004-457c-b52b-5aa82e2dfe95 | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Agregar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Agregar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Agregar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Agregar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Agregar().setVisible(true);
}
});
} |
667bc4d5-3217-4e42-9223-42aa5687efae | 5 | private void checkSymbols(char[] symbols) {
if (symbols.length != this.numTapes) {
throw new InvalidTransitionException("Specified " + symbols.length + " symbols for " + this.numTapes + " tapes.");
}
//Check that the symbol is valid
for (char symbol : symbols) {
boolean isContained = false;
for (char alpha : this.getAlphabet()) {
if (alpha == symbol) {
isContained = true;
break;
}
}
isContained |= symbol == DEFAULT_TAPE_SYMBOL;
if (!isContained) {
throw new SymbolNotInAlphabetException(symbol + " is not in " + Arrays.toString(this.getAlphabet()));
}
}
} |
c0258a79-b96a-4f24-88ac-fb2ddbec896d | 3 | public static void main(String[] args) throws IOException, TechnicalException {
MPSConnector mps = new MPSConnector(9302);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Write to test, f.e. \"0\". \"q\" to quit.");
String s =in.readLine();
while (! s.equals("q")) {
try {
AuftragsNr nr = mps.erstelleAuftrag(angebotsNr(parseInt(s)));
System.out.println("Response: AuftragsNr: " + nr);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (TechnicalException e) {
e.printStackTrace();
}
System.out.println("Write to test, f.e. \"0\". \"q\" to quit.");
s = in.readLine();
}
} |
78fdd675-79fd-485d-bf64-0e8aa9a29a47 | 8 | private MethodST method() throws UnexpectedTokenException
{
StringBuilder signature = new StringBuilder();
this.expect(PLUS, MINUS, TILDE);
signature.append(this.getToken().data);
this.nextToken();
this.expect(IDENT);
String type = this.type();
signature.append(type);
this.expect(LPAREN, IDENT);
if(this.accept(LPAREN))
{
signature.append('(');
this.nextToken();
while(!this.accept(RPAREN))
{
this.expect(NATIVE, SYNC, STATIC, FINAL, ABSTRACT);
signature.append(this.getToken().data);
this.nextToken();
this.expect(COMMA, RPAREN);
if(this.accept(COMMA))
{
signature.append(',');
this.nextToken();
this.expect(NATIVE, SYNC, STATIC, FINAL, ABSTRACT);
}
}
signature.append(')');
this.nextToken();
}
this.expect(IDENT);
String name = this.getToken().data;
this.nextToken();
this.expect(LPAREN, LBRACE);
List<ArgumentPair> args = new ArrayList<ArgumentPair>();
if(this.accept(LPAREN))
{
this.nextToken();
while(!this.accept(RPAREN))
{
this.expect(IDENT);
String atype = this.type();
this.nextToken();
this.expect(IDENT);
String aname = this.getToken().data;
args.add(new ArgumentPair(aname, atype));
this.nextToken();
this.expect(COMMA, RPAREN);
if(this.accept(COMMA))
{
this.nextToken();
this.expect(IDENT);
}
}
this.nextToken();
}
MethodST method = new MethodST(ACC.parse(signature.toString()), name, type);
for(ArgumentPair arg : args)
method.arguments.add(arg);
this.expect(LBRACE);
while(!this.accept(RBRACE))
{
// TODO
this.nextToken();
}
return method;
} |
cfc47b15-2ab0-4c96-881d-0a8719a47088 | 7 | public javax.sound.midi.Sequence createMidiSequence() {
javax.sound.midi.Sequence s = null;
try {
s = new javax.sound.midi.Sequence(javax.sound.midi.Sequence.PPQ, 16);
int channelNum = 0;
for (Track t : tracks) {
int tickCount = 0;
javax.sound.midi.Track javaTrack = s.createTrack();
javaTrack.add(new MidiEvent(sequenceTempo(), tickCount)); // set tempo
ShortMessage setInst = new ShortMessage();
setInst.setMessage(ShortMessage.PROGRAM_CHANGE, channelNum,
t.getInstrument().getInstrumentNumber(), 0);
javaTrack.add(new MidiEvent(setInst, tickCount)); // set instrument for track
for (int i = 0; i < t.getNumElements(); i++) {
if (t.getElement(i) instanceof Note) {
Note currentNote = (Note) t.getElement(i);
ShortMessage onMessage = new ShortMessage();
onMessage.setMessage(ShortMessage.NOTE_ON, channelNum,
currentNote.getPitch(), currentNote.getVelocity());
javaTrack.add(new MidiEvent(onMessage, tickCount));
tickCount += currentNote.getDuration();
ShortMessage offMessage = new ShortMessage();
offMessage.setMessage(ShortMessage.NOTE_OFF, channelNum,
currentNote.getPitch(), 0);
javaTrack.add(new MidiEvent(offMessage, tickCount));
}
else if (t.getElement(i) instanceof Chord) {
Chord currentChord = (Chord) t.getElement(i);
Note[] noteList = currentChord.getNotes();
for (int j = 0; j < noteList.length; j++) {
ShortMessage onMessage = new ShortMessage();
onMessage.setMessage(ShortMessage.NOTE_ON, channelNum,
noteList[j].getPitch(), noteList[j].getVelocity());
javaTrack.add(new MidiEvent(onMessage, tickCount));
}
tickCount += currentChord.getDuration();
for (int j = 0; j < noteList.length; j++) {
ShortMessage offMessage = new ShortMessage();
offMessage.setMessage(ShortMessage.NOTE_OFF, channelNum,
noteList[j].getPitch(), 0);
javaTrack.add(new MidiEvent(offMessage, tickCount));
}
}
}
channelNum++;
}
} catch (InvalidMidiDataException e) {
System.err.println("Error: (Sequence) failure to generate Java midi sequence");
//e.printStackTrace();
}
return s;
} |
99bd1f11-43a8-4e9a-8d7f-69bc516dba47 | 0 | public void setSeatType(long value) {
this._seatType = value;
} |
44de807c-1868-4cbc-b8a0-89f61727542a | 3 | @Override
public void actionPerformed(ActionEvent e) {
String s = promptUserForDirectory();
if (s == null) {
return; //if user pressed cancel or close do nothing.
}
try {
//todo tidify?
//das magic
registryHandler.setPathEnvironmentVariable(verify.verifyAndCleanPath(registryHandler.getPathEnvironmentVariable()+verify.cleanString(s)));
} catch (IOException | InterruptedException | InvocationTargetException err) {
jopDependency.showInputDialog(null, "Error Error", "https://www.youtube.com/watch?v=4aMD4uy-QGc&t=2m44s", jopDependency.ERROR_MESSAGE);
err.printStackTrace();
} catch (IllegalAccessException iae) {
jopDependency.showMessageDialog(null, "Something is up with your rights!");
iae.printStackTrace();
}
} |
2eae5daa-f197-41e9-9b81-763ade346c42 | 2 | protected void notifyObservers() {
if(observers != null)
for(PositionChangedObserver o : observers) {
o.update(this);
}
} |
a1ab38fe-9a56-49d8-a353-775e75073fb4 | 9 | public static void main(String[] args) throws Exception {
processConfigFile(args[1]);
try {
maxFiles = Integer.parseInt(args[2]);
} catch (Exception e) {
maxFiles = Integer.MAX_VALUE;
}
try {
SpotSigs.minIdf = Double.parseDouble(args[3]);
System.out.println("minIdf=" + SpotSigs.minIdf);
} catch (Exception e) {
try {
SpotSigs.dupsFile = args[3];
System.out.println("dumping duplicates to dupsFile = " + SpotSigs.dupsFile);
} catch (Exception ex) {
}
}
try {
SpotSigs.maxIdf = Double.parseDouble(args[4]);
System.out.println("maxIdf=" + SpotSigs.maxIdf);
} catch (Exception e) {
try {
SpotSigs.caseName = args[4];
System.out.println("Case name = " + SpotSigs.caseName);
} catch (Exception ex) {
}
}
try {
SpotSigs.confidenceThreshold = Double.parseDouble(args[5]);
System.out.println("conf=" + SpotSigs.confidenceThreshold);
} catch (Exception e) {
try {
SpotSigs.resultsFile = args[5];
System.out.println("results file = " + SpotSigs.resultsFile);
} catch (Exception ex) {
}
}
try {
SpotSigs.k = Integer.parseInt(args[6]);
System.out.println("k=" + SpotSigs.k);
} catch (Exception e) {
}
try {
SpotSigs.l = Integer.parseInt(args[7]);
System.out.println("l=" + SpotSigs.l);
} catch (Exception e) {
}
keys = new HashMap<String, Integer>(1000000);
invKeys = new HashMap<Integer, String>(1000000);
files = new ArrayList<File>();
scanDirs(new File(args[0]));
numFiles = files.size();
new SpotSigsIndexer(files).work();
} |
c98f4ccb-8308-4f9a-9d59-32ea5ea9bee4 | 5 | public void run() {
int seconds = 0;
while(connected) {
try {
Thread.sleep(1000);
}
catch(InterruptedException e) {
// nah
}
seconds = (seconds + 1) % idleTimeout;
if(seconds == 0) {
if(idle) {
try {
disconnect();
}
catch(IOException e) {
connected = false;
}
}
else {
idle = true;
}
}
}
} |
bfdd9f78-4aed-4eca-9156-e9ca4147691a | 7 | private static boolean isValid(int m, int d, int y) {
if (m < 1 || m > 12) return false;
if (d < 1 || d > DAYS[m]) return false;
if (m == 2 && d == 29 && !isLeapYear(y)) return false;
return true;
} |
ae1af086-6aa0-40c4-ac7a-2b04253f4674 | 8 | @Override
public boolean apply(Course course) {
final int startTime = (startHours.getSelectedIndex() % 12) * 60 + startMinutes.getSelectedIndex() * 10 + startAmPm.getSelectedIndex() * 12 * 60;
final int endTime = (endHours.getSelectedIndex() % 12) * 60 + endtMinutes.getSelectedIndex() * 10 + endAmPm.getSelectedIndex() * 12 * 60;
if(startTime != 0 || endTime != 0) {
if(course.Time.length() > 10) {
String[] data = course.Time.split("-");
final int dataStartTime = getTime(data[0]);
final int dataEndTime = getTime(data[1]);
if(course.CRN == 75122) {
System.out.println("Start: " + startTime);
System.out.println("End: " + endTime);
System.out.println("dataStartTime: " + dataStartTime);
System.out.println("dataEndTime: " + dataEndTime);
}
if(startTime != 0 && startTime > dataStartTime) {
return false;
}
if(endTime != 0 && endTime < dataEndTime) {
return false;
}
return true;
}
return false;
}
return true;
} |
cca2e8cd-b3a1-451c-8a01-51905240b14a | 8 | private static Trajectory secondOrderFilter(
int f1_length,
int f2_length,
double dt,
double start_vel,
double max_vel,
double total_impulse,
int length,
IntegrationMethod integration) {
if (length <= 0) {
return null;
}
Trajectory traj = new Trajectory(length);
Trajectory.Segment last = new Trajectory.Segment();
// First segment is easy
last.pos = 0;
last.vel = start_vel;
last.acc = 0;
last.jerk = 0;
last.dt = dt;
// f2 is the average of the last f2_length samples from f1, so while we
// can recursively compute f2's sum, we need to keep a buffer for f1.
double[] f1 = new double[length];
f1[0] = (start_vel / max_vel) * f1_length;
double f2;
for (int i = 0; i < length; ++i) {
// Apply input
double input = Math.min(total_impulse, 1);
if (input < 1) {
// The impulse is over, so decelerate
input -= 1;
total_impulse = 0;
} else {
total_impulse -= input;
}
// Filter through F1
double f1_last;
if (i > 0) {
f1_last = f1[i - 1];
} else {
f1_last = f1[0];
}
f1[i] = Math.max(0.0, Math.min(f1_length, f1_last + input));
f2 = 0;
// Filter through F2
for (int j = 0; j < f2_length; ++j) {
if (i - j < 0) {
break;
}
f2 += f1[i - j];
}
f2 = f2 / f1_length;
// Velocity is the normalized sum of f2 * the max velocity
traj.segments_[i].vel = f2 / f2_length * max_vel;
if (integration == RectangularIntegration) {
traj.segments_[i].pos = traj.segments_[i].vel * dt + last.pos;
} else if (integration == TrapezoidalIntegration) {
traj.segments_[i].pos = (last.vel
+ traj.segments_[i].vel) / 2.0 * dt + last.pos;
}
traj.segments_[i].x = traj.segments_[i].pos;
traj.segments_[i].y = 0;
// Acceleration and jerk are the differences in velocity and
// acceleration, respectively.
traj.segments_[i].acc = (traj.segments_[i].vel - last.vel) / dt;
traj.segments_[i].jerk = (traj.segments_[i].acc - last.acc) / dt;
traj.segments_[i].dt = dt;
last = traj.segments_[i];
}
return traj;
} |
e6149326-e01f-4e1e-a859-f608f0cfe10f | 0 | public int numberSelected() {
return selected.size();
} |
3bc809fe-9160-480e-af7c-c535be495830 | 6 | public void remove(Integer start, Integer end){
Interval toRemove = new Interval(start,end);
List<Interval> affected = new LinkedList<Interval>();
for (Interval currInterval : sched){
if (!currInterval.isDisjoint(toRemove))
affected.add(currInterval);
if (currInterval.start > toRemove.end)
break;
}
for (Interval interval : affected){
sched.remove(interval);
Interval aux = interval.subtract(toRemove);
if (interval.isEmpty() == false){
sched.add(interval);
if (aux.isEmpty() == false)
sched.add(aux);
}
}
} |
cb3c9d83-f664-4144-afb2-5767452fdbf0 | 6 | public Graph randCreator(){
int p = 0,q = 0;
g = new Graph(true);
g.addColumn("id", int.class);
g.addColumn("value", String.class);
g.addColumn("source", String.class);
g.addColumn("Edgetype", String.class);
//This loop is used to create the nodes of the random graph.
//We ensure same number of same type of nodes as in the given data.
for(int i =0;i<1490;i++){
Node hook = g.addNode();
hook.set("id", i);
if(p<732 && q <758){
int n = rand.nextInt(1);
hook.set("value",lol[n]);
if(n == 0){
p++;
}
else q++;
}
else if(p>731){
hook.set("value", "0");
}
else{
hook.set("value", "1");
}
}
//This for loop creates edges between all the nodes of the random graph.
for(int j=0;j<19090;j++){
int x = rand.nextInt(1490);
int y = rand.nextInt(1490);
int apple = g.addEdge(x, y);
Edge abc = g.getEdge(apple);
String mango = (String) (g.getNode(x)).get("value");
String banana = (String) (g.getNode(y)).get("value");
abc.set("Edgetype", mango+banana );
abc.set("source", x);
}
return g;
} |
7beb18d1-09ea-43c2-b985-0ff7dc618a24 | 9 | private static int diff_commonOverlap(String text1, String text2)
{
// Cache the text lengths to prevent multiple calls.
final int text1_length = text1.length();
final int text2_length = text2.length();
// Eliminate the null case.
if (text1_length == 0 || text2_length == 0)
{
return 0;
}
// Truncate the longer string.
if (text1_length > text2_length)
{
text1 = text1.substring(text1_length - text2_length);
}
else
if (text1_length < text2_length)
{
text2 = text2.substring(0, text1_length);
}
final int text_length = Math.min(text1_length, text2_length);
// Quick check for the worst case.
if (text1.equals(text2))
{
return text_length;
}
// Start by looking for a single character match
// and increase length until no match is found.
// Performance analysis: http://neil.fraser.name/news/2010/11/04/
int best = 0;
int length = 1;
while (true)
{
final String pattern = text1.substring(text_length - length);
final int found = text2.indexOf(pattern);
if (found == -1)
{
return best;
}
length += found;
if (found == 0 || text1.substring(text_length - length).equals(text2.substring(0, length)))
{
best = length;
length++;
}
}
} |
b963cc66-9c2b-4604-a093-d1ea58b94bdc | 8 | @Override
public String getColumnName(int column) {
switch(column) {
case 0 : return "Nota";
case 1 : return "Nama";
case 2 : return "Pewangi";
case 3 : return "Berat";
case 4 : return "Masuk";
case 5 : return "Ambil";
case 6 : return "Harga";
case 7 : return "Ket";
default : return null;
}
} |
e76c0982-b03c-407a-9988-79a431db5ffc | 0 | public void resume_egress() {
++resume_egress_count;
} |
c95602e6-9c64-422a-83f5-7c7fc1259d9c | 7 | void addMapChanges(PropertyMapImpl propertyMap, ConstMap mapChanges) {
HashMap map = (HashMap) changes.get(propertyMap);
if (map == null) {
map = new HashMap();
changes.put(propertyMap, map);
}
for (ConstMapIterator iterator = mapChanges.constIterator(); iterator.atEntry(); iterator.next()) {
ValueChange vc = (ValueChange) iterator.getValue();
Object key = iterator.getKey();
Object newValue = vc.getNewValue() == null ?
null : ((PropertyValue) vc.getNewValue()).getWithDefault(propertyMap);
Object value = map.get(key);
Object oldValue = value == null ?
vc.getOldValue() == null ?
null : ((PropertyValue) vc.getOldValue()).getWithDefault(propertyMap) :
((ValueChange) value).getOldValue();
if (!Utils.equals(oldValue, newValue))
map.put(iterator.getKey(), new ValueChange(oldValue, newValue));
else if (value != null)
map.remove(key);
}
} |
06e201de-ffeb-4045-a569-c161576db712 | 2 | public static void main(String[] args) throws JFAuthenticationException, JFVersionException, Exception {
final ITesterClient client = TesterFactory.getDefaultInstance();
client.setSystemListener(new ISystemListener() {
@Override
public void onStart(long processId) {
LOGGER.info("onStart");
}
@Override
public void onStop(long processId) {
LOGGER.info("Strategy stopped: " + processId);
File reportFile = new File(filepath);
try {
client.createReport(processId, reportFile);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
if (client.getStartedStrategies().size() == 0) {
System.exit(0);
}
}
@Override
public void onConnect() {
LOGGER.info("onConnect");
}
@Override
public void onDisconnect() {
LOGGER.info("onDisconnect");
}
});
// 接続
client.connect(Constants.JNLP_URL, Constants.USER_NAME, Constants.PASSWORD);
LOGGER.info("setSubscribedInstruments");
Set<Instrument> instruments = new HashSet<Instrument>();
// ドル円
instruments.add(Instrument.USDJPY);
client.setSubscribedInstruments(instruments);
// setting initial deposit
LOGGER.info("setInitialDeposit");
// 日本円で10万円
client.setInitialDeposit(Instrument.USDJPY.getSecondaryCurrency(), 100000);
// タイムゾーン
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss SSS");
Long from = dateFormat.parse("2010/01/01 00:00:00 000").getTime();
Long to = dateFormat.parse("2011/01/01 00:00:00 000").getTime();
// バックテスト期間設定
LOGGER.info("setDataInterval");
client.setDataInterval(
Period.THIRTY_MINS,
OfferSide.ASK,
InterpolationMethod.CLOSE_TICK,
from,
to);
// // 過去データを先に全てキャッシュに保存+アルファする
// LOGGER.info("downloadData");
// LoadingProgressListener loadingProgressListener = new LoadingProgressListener() {
// @Override
// public void dataLoaded(long startTime, long endTime, long currentTime, String information) {
// LOGGER.info("dataLoaded: " + startTime + ":" + endTime + ":" + currentTime + ":" + information);
// }
// @Override
// public void loadingFinished(boolean allDataLoaded, long startTime, long endTime, long currentTime) {
// LOGGER.info("loadingFinished: " + allDataLoaded + "_" + startTime + "_" + endTime + "_" + currentTime);
// }
// @Override
// public boolean stopJob() {
// return false;
// }
// };
// Future<?> future = client.downloadData(loadingProgressListener);
// future.get();
// ストラテジースタート
LOGGER.info("startStrategy");
client.startStrategy(new MyStrategy());
} |
e9942c68-9064-4d50-8b70-b36e72c9114d | 8 | private void externalReflection(Atom a) {
double x0 = getX();
double x1 = getX() + getWidth();
double y0 = getY();
double y1 = getY() + getHeight();
double radius = a.sigma * 0.5;
if (a.rx - radius < x1 && a.rx + radius > x0 && a.ry - radius < y1 && a.ry + radius > y0) {
switch (RectangularObstacle.borderCross(getBounds().getBounds2D(), radius, a.rx, a.ry, a.dx, a.dy, x0, y0, x1, y1)) {
case RectangularObstacle.EAST:
a.vx = Math.abs(a.vx);
break;
case RectangularObstacle.WEST:
a.vx = -Math.abs(a.vx);
break;
case RectangularObstacle.SOUTH:
a.vy = Math.abs(a.vy);
break;
case RectangularObstacle.NORTH:
a.vy = -Math.abs(a.vy);
break;
}
}
} |
b113fbfd-820e-4842-895c-eedf4f12d09b | 7 | public void setInstalledDirectory(File targetDirectory) {
if (installedDirectory != null && installedDirectory.exists()) {
try {
FileUtils.copyDirectory(installedDirectory, targetDirectory);
FileUtils.cleanDirectory(installedDirectory);
} catch (IOException ex) {
Utils.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
return;
}
}
installedDirectory = targetDirectory;
String path = installedDirectory.getAbsolutePath();
if (path.equals(directories.getModpacksDirectory().getAbsolutePath())) {
installedPack.setDirectory(InstalledPack.MODPACKS_DIR);
} else if (path.equals(directories.getLauncherDirectory().getAbsolutePath())) {
installedPack.setDirectory(InstalledPack.LAUNCHER_DIR);
} else if (path.startsWith(directories.getModpacksDirectory().getAbsolutePath())) {
installedPack.setDirectory(InstalledPack.MODPACKS_DIR + path.substring(directories.getModpacksDirectory().getAbsolutePath().length() + 1));
} else if (path.startsWith(directories.getLauncherDirectory().getAbsolutePath())) {
installedPack.setDirectory(InstalledPack.LAUNCHER_DIR + path.substring(directories.getLauncherDirectory().getAbsolutePath().length() + 1));
} else
installedPack.setDirectory(path);
save();
} |
bf20ced3-ffa2-4e86-8678-6beb7a4db105 | 6 | public boolean isComplete() {
int size = board.length;
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
if (x == size - 1 && y == size - 1 && board[x][y] == -1) return true;
if (board[x][y] != y * size + x + 1) return false; // Bail early
}
}
return false;
} |
c2034b7a-e14f-477e-b067-4b44b719d3b4 | 2 | public void Render() {
for(int x = 0 ; x < this.mapImageWidth ; x++ ) {
for(int y = 0 ; y < this.mapImageHeight ; y++) {
this.tileMap[x + y * this.mapImageWidth].render((x << this.shiftCount) + xOffset , (y << this.shiftCount) + yOffset);
}
}
} |
1f018696-5425-4f41-824b-6afcad6a2de9 | 4 | private boolean checkFieldLineWinn(int lineNumber, char cellValue){
boolean checkLine = true;
for (int i = 0; i <= fieldSize - WIN_NUMBER_OF_CELLS ; i++){
checkLine = true;
for(int j = i; j < i + WIN_NUMBER_OF_CELLS; j++){
if( field[j][lineNumber] != cellValue) checkLine = false;
}
if(checkLine){
return true;
}
}
return false;
} |
807c86ed-a015-4815-ab94-f15095034cfb | 7 | public static void combineMonomeConfigurations() {
Configuration configuration = Main.main.configuration;
if (configuration.getMonomeConfigurations() == null) {
return;
}
@SuppressWarnings("unchecked")
HashMap<Integer, MonomeConfiguration> tmpMonomeConfigurations = (HashMap<Integer, MonomeConfiguration>) configuration.getMonomeConfigurations().clone();
Iterator<Integer> it = tmpMonomeConfigurations.keySet().iterator();
while (it.hasNext()) {
Integer key = it.next();
MonomeConfiguration mainMonomeConfig = configuration.getMonomeConfigurations().get(key);
if (mainMonomeConfig == null) {
continue;
}
Iterator<Integer> it2 = tmpMonomeConfigurations.keySet().iterator();
while (it2.hasNext()) {
Integer key2 = it2.next();
MonomeConfiguration checkMonomeConfig = configuration.getMonomeConfigurations().get(key2);
if (checkMonomeConfig == null) {
continue;
}
if (checkMonomeConfig.prefix.compareTo(mainMonomeConfig.prefix) == 0 && checkMonomeConfig.index != mainMonomeConfig.index) {
mainMonomeConfig.sizeX += checkMonomeConfig.offsetX;
mainMonomeConfig.sizeY += checkMonomeConfig.offsetY;
mainMonomeConfig.setFrameTitle();
removeMonomeConfiguration(key2);
}
}
}
} |
fbda5267-820f-4a04-867b-055f17fd68a7 | 5 | public boolean setParallelJobProbabilities(
double uLow, double uMed, double uHi, double uProb) {
if (uLow > uHi) {
return false;
} else if (uMed > uHi-1.5 || uMed < uHi-3.5) {
return false;
} else if(uProb < 0.7 || uProb > 0.95) {
return false;
}
this.uLow = uLow;
this.uMed = uMed;
this.uHi = uHi;
this.uProb = uProb;
return true;
} |
9f9f6269-1f26-4913-83e0-e20127c8214a | 9 | private static void createFoldSVM(String[] args) throws FileNotFoundException, IOException {
String orgDataFile = args[1];
int noFolds = Integer.parseInt(args[2]);
BufferedReader br1 = new BufferedReader(new FileReader(orgDataFile));
ArrayList<String> posData = new ArrayList<String>();
ArrayList<String> negData = new ArrayList<String>();
while (br1.ready()) {
String Y = br1.readLine().trim();
String[] X = Y.split(" ");
if (X[0].contains("+1")) {
posData.add(Y);
} else {
negData.add(Y);
}
}
int testposSize = posData.size() / noFolds;
int testnegSize = negData.size() / noFolds;
Random generator = new Random();
ArrayList<String> posTrainData = new ArrayList<String>();
ArrayList<String> negTrainData = new ArrayList<String>();
ArrayList<String> posTestData = new ArrayList<String>();
ArrayList<String> negTestData = new ArrayList<String>();
for (int fold = 0; fold < noFolds; fold++) {
posTrainData.clear();
posTrainData.addAll(posData);
posTestData.clear();
negTrainData.clear();
negTrainData.addAll(negData);
negTestData.clear();
while (posTestData.size() < testposSize) {
posTestData.add(posTrainData.remove(generator.nextInt(posTrainData.size())));
}
while (negTestData.size() < testnegSize) {
negTestData.add(negTrainData.remove(generator.nextInt(negTrainData.size())));
}
// open test file
String fileName = orgDataFile + "test" + Integer.toString(fold);
FileWriter fstream = new FileWriter(fileName);
BufferedWriter out = new BufferedWriter(fstream);
for (String pos : posTestData) {
out.write(pos + "\n");
}
for (String neg : negTestData) {
out.write(neg + "\n");
}
out.close();
//opentrainfile
fileName = orgDataFile + "train" + Integer.toString(fold);
fstream = new FileWriter(fileName);
out = new BufferedWriter(fstream);
for (String pos : posTrainData) {
out.write(pos + "\n");
}
for (String neg : negTrainData) {
out.write(neg + "\n");
}
out.close();
}
} |
76a553a9-9ac1-4bda-8dfd-571bf73c26c0 | 9 | @SuppressWarnings("rawtypes")
public List<Claim> getClaims(String actionType, String team) {
List<Claim> claimList = new ArrayList<Claim>();
Element claimE;
Claim claim;
if (actionType.equals(CLAIMSUBCLAIM)) {
List<Claim> claimList1 = getClaims("claim", team);
List<Claim> subclaimList = getClaims("subclaim", team);
for (int i = 0; i < claimList1.size(); i++) {
claimList.add(claimList1.get(i));
}
for (int i = 0; i < subclaimList.size(); i++) {
claimList.add(subclaimList.get(i));
}
} else if (team.equals(TEAMAB)) {
// Public claims, read all claims Team A and Team B
for (Iterator i = root.elementIterator(actionType); i.hasNext();) {
claimE = (Element)i.next();
if (claimE.element("isDeleted").getText().equals("false")) {
String id = claimE.element("id").getText()
, title = claimE.element("title").getText()
, description = claimE.element("description").getText()
, type = claimE.element("type").getText()
, timeAdded = claimE.element("timeAdded").getText()
, name = claimE.element("name").getText()
, debateId = claimE.element("debateId").getText()
, dialogType = claimE.elementText("dialogType")
, parentId = claimE.elementText("parentId")
, teams = claimE.attributeValue("team");
claim = new Claim(id, title, description, type
, timeAdded, parentId, name, debateId, dialogType, teams);
claimList.add(claim);
}
}
} else {
for (Iterator i = root.elementIterator(actionType); i.hasNext();) {
claimE = (Element)i.next();
if (claimE.element("isDeleted").getText().equals("false")
&& claimE.attributeValue("team").equals(team)) {
String id = claimE.element("id").getText()
, title = claimE.element("title").getText()
, description = claimE.element("description").getText()
, type = claimE.element("type").getText()
, timeAdded = claimE.element("timeAdded").getText()
, name = claimE.element("name").getText()
, debateId = claimE.element("debateId").getText()
, dialogType = claimE.elementText("dialogType")
, parentId = claimE.elementText("parentId")
, teams = claimE.attributeValue("team");
claim = new Claim(id, title, description, type
, timeAdded, parentId, name, debateId, dialogType, teams);
claimList.add(claim);
}
}
}
return claimList;
} |
bb6e1a40-ffb1-43a5-9d52-57953b092576 | 5 | int multiply(int a, int b) {
boolean negative = false; // Sign
if (a < 0) {
negative = !negative;
a = sub(0, a);
}
if (b < 0) {
negative = !negative;
b = sub(0, b);
}
int res = 0;
while (b != 0) {
if ((b & 1) == 1) {
res = add(res, a);
}
a <<= 1;
b >>= 1; // 算术移位
}
return negative ? sub(0, res) : res;
} |
01d41db1-1ede-4a4a-8dfa-4acff940f798 | 2 | void send(String data) {
if (socket == null) {
println("Cannot operate with a null socket");
return;
}
PrintStream output;
try {
output = new PrintStream(socket.getOutputStream());
output.println(data);
} catch (IOException e) {
println("An exception has occured while sending to the socket");
}
} |
eeb9ccb0-f942-4cea-b884-0f354042a859 | 3 | public ChannelEvent nextEvent()
throws ChannelError, InterruptedException {
ChannelEvent event;
ChannelError error;
if ((error = resetError()) != null) {
throw error;
}
if ((event = resetEndEvent()) != null) {
return event;
}
event = m_eventQueue.poll();
if (event == null) {
m_waitLock.acquire();
return nextEvent();
}
return event;
} |
5d333a61-7406-4c2a-92b9-2474d684268f | 1 | public Bitstream(InputStream in)
{
if (in==null) throw new NullPointerException("in");
in = new BufferedInputStream(in);
loadID3v2(in);
firstframe = true;
//source = new PushbackInputStream(in, 1024);
source = new PushbackInputStream(in, BUFFER_INT_SIZE*4);
closeFrame();
//current_frame_number = -1;
//last_frame_number = -1;
} |
124ed261-38cf-4340-9771-2b2a877641ed | 3 | private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
Transferable clipboardContent = getToolkit().getSystemClipboard().getContents(this);
if ((clipboardContent != null)
&& (clipboardContent.isDataFlavorSupported(DataFlavor.stringFlavor))) {
try {
String tempString;
tempString = (String) clipboardContent.getTransferData(DataFlavor.stringFlavor);
jTextArea1.setText(tempString);
} catch (Exception e) {
e.printStackTrace();
}
}
}//GEN-LAST:event_jButton2ActionPerformed |
e090bd3c-589a-45e0-96a3-ec28e41d3463 | 9 | public static boolean writeWikiSample(BookmarkReader reader, List<UserData> userSample, String filename, List<int[]> catPredictions) {
try {
FileWriter writer = new FileWriter(new File("./data/csv/" + filename + ".txt"));
BufferedWriter bw = new BufferedWriter(writer);
int userCount = 0;
// TODO: check encoding
for (UserData userData : userSample) {
bw.write("\"" + reader.getUsers().get(userData.getUserID()).replace("\"", "") + "\";");
bw.write("\"" + reader.getResources().get(userData.getWikiID()).replace("\"", "") + "\";");
bw.write("\"" + userData.getTimestamp().replace("\"", "") + "\";\"");
int i = 0;
for (int tag : userData.getTags()) {
bw.write(URLEncoder.encode(reader.getTags().get(tag).replace("\"", ""), "UTF-8"));
if (++i < userData.getTags().size()) {
bw.write(',');
}
}
bw.write("\";\"");
List<Integer> userCats = (catPredictions == null ?
userData.getCategories() : Ints.asList(catPredictions.get(userCount++)));
i = 0;
for (int cat : userCats) {
bw.write(URLEncoder.encode((catPredictions == null ? reader.getCategories().get(cat).replace("\"", "") : reader.getTags().get(cat)).replace("\"", ""), "UTF-8"));
if (++i < userCats.size()) {
bw.write(',');
}
}
bw.write("\"");
if (userData.getRating() != -2) {
bw.write(";\"" + userData.getRating() + "\"");
}
bw.write("\n");
}
bw.flush();
bw.close();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
} |
c4e902ab-8771-432a-a47a-8c3c440967c6 | 3 | private static <T> List<T> filterToList( Iterable<T> source, Filter<T>... filters )
{
List<T> dest = new ArrayList<T>();
for ( T each : source ) {
filter_loop:
for ( Filter<T> filter : filters ) {
if ( filter.accept( each ) ) {
dest.add( each );
break filter_loop;
}
}
}
return dest;
} |
c228cad8-a2ab-4dca-bad1-634b076e1cd7 | 2 | public static int getIndexSelectedValue(String name){
switch(name){
case "USD":
System.out.println("USD");
return 2;
case "CLP":
System.out.println("CLP");
return 1;
}
return 0;
} |
66c1debd-5263-478d-9cea-b1c7bd3a26d8 | 8 | public Node getEntrance(Node head){
if(head == null || head.next == null) return null;
Node slow = head.next;
Node fast = head.next.next;
while(slow !=null && fast.next != null && fast != slow){
slow = slow.next;
fast = fast.next.next;
}
if(slow == null || fast.next == null)
return null;
Node r1 = head;
Node r2 = fast;
System.out.println("OK");
while(r1 != r2){
r1 = r1.next;
r2 = r2.next;
}
return r1;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.