method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
31fa9b8c-a752-407d-a6c0-95c6b297c02c | 3 | @Override
public AuthorModel addAuthor(AuthorModel author) throws WebshopAppException {
int generatedId = AuthorModel.DEFAULT_ID;
if (isValidAuthor(author, "ADD_AUTHOR")) {
try (Connection conn = getConnection()) {
String sql = "INSERT INTO author (firstname, lastname, dob, country)"
+ "VALUES (?, ?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql,
Statement.RETURN_GENERATED_KEYS)) {
prepareStatementFromModel(pstmt, author);
pstmt.executeUpdate();
try (ResultSet rs = pstmt.getGeneratedKeys()) {
if (rs.next()) {
generatedId = rs.getInt(1);
}
}
}
LOGGER.trace(String.format("%s.ADD_AUTHOR - %s %s", this
.getClass().getSimpleName(), "Author added: ", author));
} catch (SQLException e) {
WebshopAppException excep = new WebshopAppException(
e.getMessage(), this.getClass().getSimpleName(),
"ADD_AUTHOR");
LOGGER.error(excep);
throw excep;
}
} else {
LOGGER.error("Add author: Author is null.");
}
return new AuthorModel.Builder(generatedId, author.getFirstname(),
author.getLastname()).dob(author.getDob())
.country(author.getCountry()).build();
} |
6dc1551c-357a-4351-a506-3365c4ac635a | 8 | @SuppressWarnings("rawtypes")
public String getUsoDestinoMasArea() {
// Si hay destinos cogemos el de mayor area
if (destinos != null && !destinos.isEmpty()) {
String destino = "";
double area = 0;
Iterator<Entry<String, Double>> it = destinos.entrySet().iterator();
// Comparamos las areas de los destinos (son mas especificos)
while (it.hasNext()) {
Map.Entry e = (Map.Entry) it.next();
if ((Double) e.getValue() > area) {
area = (Double) e.getValue();
destino = (String) e.getKey();
}
}
return destino;
}
// Si no lo hay, pasamos a usos que son mas generales y con menos nivel
// de detalle
else if (usos != null && !usos.isEmpty()) {
String uso = "";
double area = 0;
Iterator<Entry<String, Double>> it = usos.entrySet().iterator();
// Comparamos las areas de los destinos (son mas especificos)
while (it.hasNext()) {
Map.Entry e = (Map.Entry) it.next();
if ((Double) e.getValue() > area) {
area = (Double) e.getValue();
uso = (String) e.getKey();
}
}
return uso;
}
return "";
} |
3f903e2a-4666-4b21-8594-522549db14cd | 2 | public boolean estaEmS(String transacao) {
boolean res = false;
for (String s : lockS) {
if (s.equals(transacao)) {
res = true;
}
}
return res;
} |
76c140c9-e938-4baa-bf5d-ca98773e6dbf | 1 | public static void createTrees(ResearchScreen rs) {
Collection<ResearchItem> items = Application.get().getLogic().getGame().getResearch().getRoots();
int indx = 0;
for(ResearchItem ri : items) {
createTree(rs, ri, 100+indx*180, 100);
indx++;
}
} |
51cf0848-4d63-4bc6-9b9d-a0fc32b4ba95 | 7 | public static void commandMute(CommandSender sender, String player, String duration){
if (player == null || duration == null) {
sender.sendMessage(Msg.$("mute-usage"));
return;
}
int mute;
try {
mute = Integer.parseInt(duration);
} catch (Exception e){
if (!duration.equals("forever")){
sender.sendMessage(Msg.$("not-valid-num"));
return;
} else {
mute = -1;
}
}
Long mutelong = Long.parseLong(Integer.toString(mute));
MuteManager.Mute(sender, player, mutelong);
List perms = config.getList("add-permissions.list", null);
if (perms != null)
for (int i = 0; i < perms.size(); i++) {
Access.addNode(player, (String) perms.get(i));
}
if (config.getString("set-group", "") != ""){
String group = config.getString("set-group", "");
Log.info(group);
Access.addGroup(player, group);
}
} |
2ce4579e-8083-4530-9a53-1602a4c809bf | 7 | private Boolean isPresent(String FileOrDirectoryName, Boolean includeProxy)
{
for(DistributedFile f: files)
if(f.getFileName().equals(FileOrDirectoryName) )
return true;
for(Directory d: childDirectories)
if(d.getName().equals(FileOrDirectoryName))
return true;
if(includeProxy)
for(String s: fileProxies)
if(s.equals(FileOrDirectoryName))
return true;
return false;
} |
6fc2297e-90cc-403e-a4e5-a8bfff2cf576 | 2 | @Override
public void add(CreditProgram element) {
//Добавляем запись в список
getList().add(element);
Statement statement = null;
ResultSet result = null;
try {
//Создаем изменяемую выборку
statement = getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
//Получаем набор данных
result = statement.executeQuery(allQuery);
//Позиционируемся на добавление новой записи
result.moveToInsertRow();
//Заполняем поля
result.updateString("CREDITNAME", element.getName());
result.updateLong("CREDITMINAMOUNT", element.getMinAmount());
result.updateLong("CREDITMAXAMOUNT", element.getMaxAmount());
result.updateInt("CREDITDURATION", element.getDuration());
result.updateDouble("CREDITSTARTPAY", element.getStartPay());
result.updateDouble("CREDITPERCENT", element.getPercent());
result.updateString("CREDITDESCRIPTION", element.getDescription());
result.updateInt("CREDITPROGSTATUS", element.getCreditProgStatus());
//Фиксируем изменения
result.insertRow();
} catch (SQLException ex) {
System.out.println("Ошибка при изменении таблицы");
} finally {
try {
//Закрываем открытые соединения
statement.close();
result.close();
} catch (SQLException ex) {
System.out.println("Ошибка при закрытии соединения");
}
}
} |
65918841-8600-4e98-b79a-c7bda17f20c0 | 4 | public static boolean dragDraggable(final Draggable d, final int slot) {
return d != null
&& (SlotData.getDraggableId(slot) == d.getId() || d.show() && dragChild(d.getChild(), slot)
&& new TimedCondition(700) {
@Override
public boolean isDone() {
return d.getId() == SlotData.getDraggableId(slot);
}
}.waitStop());
} |
396511a7-7da5-482a-8c6a-6c450c03b94a | 5 | private final void method735(AbstractToolkit var_ha, Class72 class72_19_) {
method738(var_ha);
method732(var_ha);
var_ha.getDimensions(anIntArray1226);
var_ha.setDimensions(0, 0, anInt1220, anInt1220);
var_ha.ya();
var_ha.drawQuad(0, 0, anInt1220, anInt1220, ~0xffffff | anInt1222, 0);
int i = 0;
int i_20_ = 0;
int i_21_ = 256;
if (class72_19_ != null) {
if (class72_19_.aBoolean1223) {
i = -class72_19_.anInt1225;
i_20_ = -class72_19_.anInt1216;
i_21_ = -class72_19_.anInt1229;
} else {
i = class72_19_.anInt1225 - anInt1225;
i_20_ = class72_19_.anInt1216 - anInt1216;
i_21_ = class72_19_.anInt1229 - anInt1229;
}
}
if (anInt1231 != 0) {
int i_22_ = Class70.sineTable[anInt1231];
int i_23_ = Class70.cosineTable[anInt1231];
int i_24_ = i_20_ * i_23_ - i_21_ * i_22_ >> 14;
i_21_ = i_20_ * i_22_ + i_21_ * i_23_ >> 14;
i_20_ = i_24_;
}
if (anInt1219 != 0) {
int i_25_ = Class70.sineTable[anInt1219];
int i_26_ = Class70.cosineTable[anInt1219];
int i_27_ = i_21_ * i_25_ + i * i_26_ >> 14;
i_21_ = i_21_ * i_26_ - i * i_25_ >> 14;
i = i_27_;
}
AnimatableToolkit class64 = aClass64_1227.method614((byte) 0, 51200, true);
class64.aa((short) 0, (short) anInt1224);
var_ha.xa(1.0F);
var_ha.ZA(16777215, 1.0F, 1.0F, (float) i, (float) i_20_,
(float) i_21_);
int i_28_ = 1024 * anInt1220 / (class64.RA() - class64.V());
if (anInt1222 != 0)
i_28_ = i_28_ * 13 / 16;
var_ha.DA(anInt1220 / 2, anInt1220 / 2, i_28_, i_28_);
var_ha.method3638(var_ha.method3654());
Class101 class101 = var_ha.method3654();
class101.method894(0, 0, var_ha.i() - class64.HA());
class64.method608(class101, null, 1024, 1);
int i_29_ = anInt1220 * 13 / 16;
int i_30_ = (anInt1220 - i_29_) / 2;
aClass105_1215.method970(i_30_, i_30_, i_29_, i_29_, 0,
~0xffffff | anInt1222, 1);
aClass105_1221 = var_ha.createRaster(0, 0, anInt1220, anInt1220, true);
var_ha.ya();
var_ha.drawQuad(0, 0, anInt1220, anInt1220, 0, 0);
aClass105_1228.method970(0, 0, anInt1220, anInt1220, 1, 0, 0);
aClass105_1221.method968(0, 0, 0);
var_ha.setDimensions(anIntArray1226[0], anIntArray1226[1], anIntArray1226[2],
anIntArray1226[3]);
} |
4f6ba1e0-874d-4845-a095-864fd859fd35 | 9 | public boolean validarContato(Contato contato){
List<Contato> listaContatos = fachada.FachadaSistema.getInstance().listarContatos();
for (Contato contatoBusca : listaContatos) {
if(contatoBusca.getNome().equals(contato.getNome())){
JOptionPane.showMessageDialog(null, "Já existe um contato com o nome: " + contato.getNome());
return false;
}
}
if(contato.getNome().isEmpty()){
JOptionPane.showMessageDialog(null, "O campo nome deve ser preenchido");
return false;
}
if(contato.getTelefone1() == 0){
JOptionPane.showMessageDialog(null, "O campo telefone 1 deve ser preenchido");
return false;
}
// if(!soContemNumeros(String.valueOf(contato.getTelefone1()))){
// JOptionPane.showMessageDialog(null, "O campo telefone 1 deve ser preenchido apenas com numeros");
// return false;
// }
//
// if(!soContemNumeros(String.valueOf(contato.getTelefone3()))){
// JOptionPane.showMessageDialog(null, "O campo telefone 3 deve ser preenchido apenas com numeros");
// return false;
// }
//
// if(!soContemNumeros(String.valueOf(contato.getTelefone2()))){
// JOptionPane.showMessageDialog(null, "O campo telefone 2 deve ser preenchido apenas com numeros");
// return false;
// }
if(String.valueOf(contato.getTelefone1()).length() > 9){
JOptionPane.showMessageDialog(null, "O telefone de conter no máximo 9 dígitos");
return false;
}
if(String.valueOf(contato.getTelefone2()).length() > 9){
JOptionPane.showMessageDialog(null, "O telefone de conter no máximo 9 dígitos");
return false;
}
if(String.valueOf(contato.getTelefone3()).length() > 9){
JOptionPane.showMessageDialog(null, "O telefone de conter no máximo 9 dígitos");
return false;
}
if(!contato.getEmail().isEmpty()){
if(!contato.getEmail().contains("@")){
JOptionPane.showMessageDialog(null, "Este não é um email válido");
return false;
}
}
return true;
} |
9cf64987-5dbe-4fd8-94cb-40704cdb29bc | 1 | public SampleBuffer(int sample_frequency, int number_of_channels)
{
buffer = new short[OBUFFERSIZE];
bufferp = new int[MAXCHANNELS];
channels = number_of_channels;
frequency = sample_frequency;
for (int i = 0; i < number_of_channels; ++i)
bufferp[i] = (short)i;
} |
90c677e5-b725-4947-ab9e-e41a0ebea067 | 8 | public Msg read()
{
if (!in_active || (state != State.active && state != State.pending))
return null;
Msg msg_ = inpipe.read ();
if (msg_ == null) {
in_active = false;
return null;
}
// If delimiter was read, start termination process of the pipe.
if (msg_.is_delimiter ()) {
delimit ();
return null;
}
if (!msg_.has_more())
msgs_read++;
if (lwm > 0 && msgs_read % lwm == 0)
send_activate_write (peer, msgs_read);
return msg_;
} |
e284f509-035f-41b9-b31b-e053206d3b38 | 8 | public String readCStr() throws IOException {
boolean isAscii = true;
// short circuit 1 byte strings
_random[0] = read();
if (_random[0] == 0) {
return "";
}
_random[1] = read();
if (_random[1] == 0) {
final String out = ONE_BYTE_STRINGS[_random[0]];
return (out != null) ? out : new String(_random, 0, 1, DEFAULT_ENCODING);
}
_stringBuffer.reset();
_stringBuffer.write(_random, 0, 2);
isAscii = _isAscii(_random[0]) && _isAscii(_random[1]);
byte b;
while ((b = read()) != 0) {
_stringBuffer.write( b );
isAscii = isAscii && _isAscii( b );
}
String out = null;
if ( isAscii ){
out = _stringBuffer.asAscii();
}
else {
try {
out = _stringBuffer.asString( DEFAULT_ENCODING );
}
catch ( UnsupportedOperationException e ){
throw new BSONException( "impossible" , e );
}
}
_stringBuffer.reset();
return out;
} |
f95944f4-0174-48dd-bf2f-57212ad9a478 | 6 | public static void main(String[] args) {
Scanner cal = new Scanner(System.in);
System.out.println("Enter number of units for calculating the bill : \n");
double Bill = cal.nextDouble();
double B = 1;
if (Bill < 100) {
System.out.println("Calculated Bill is : $ " + B);
} else if (Bill > 100 || Bill < 300) {
B = (99 * B) + ((Bill - 99) * 0.75);
System.out.println("Calculated Bill is : $" + B);
} else if (Bill < 300 || Bill > 500) {
B = (99 * B) + ((Bill - 99) * 0.50);
System.out.println("Calculated Bill is : $" + B);
} else if (Bill > 500) {
B = (99 * B) + ((Bill - 99) * 0.25);
System.out.println("Calculated Bill is : $" + B);
}
} |
8f3abd30-bc7a-49e6-baa5-8f4b156230c8 | 8 | public static <Z> Aggregator<Z> createAggregator(Class<?> returnType) throws AggregationException {
if (returnType.equals(Integer.TYPE) || returnType.equals(Integer.class)) {
return (Sum<Z>) new IntegerSum();
} else if (returnType.equals(Double.TYPE) || returnType.equals(Double.class)) {
return (Sum<Z>) new DoubleSum();
} else if (returnType.equals(Float.TYPE) || returnType.equals(Float.class)) {
return (Sum<Z>) new FloatSum();
} else if (returnType.equals(String.class)) {
return (Sum<Z>) new StringSum();
}
throw new AggregationException("Unsupported type: " + returnType.getSimpleName());
} |
c0fa4bfd-f7e7-43c8-8866-e7156a2ead28 | 5 | public void setGridletStatus(int newStatus) throws Exception
{
// if the new status is same as current one, then ignore the rest
if (status_ == newStatus) {
return;
}
// throws an exception if the new status is outside the range
if (newStatus < Gridlet.CREATED || newStatus > Gridlet.FAILED_RESOURCE_UNAVAILABLE)
{
throw new Exception("Gridlet.setGridletStatus() : Error - " +
"Invalid integer range for Gridlet status.");
}
if (newStatus == Gridlet.SUCCESS) {
finishTime_ = GridSim.clock();
}
if (record_)
{
String obj = "Sets Gridlet status from " + getGridletStatusString();
write( obj + " to " + Gridlet.getStatusString(newStatus) );
}
this.status_ = newStatus;
} |
663573af-c41d-4aa4-9e80-c72e603395b1 | 7 | @Override
public void initialize(JSONObject dataMixinValue) throws JSONException,
DataFormatException {
JSONArray dataMixinArray = dataMixinValue.getJSONArray("mixins");
this.regularTileMixins = new RegularTileMixin[dataMixinArray.length()];
this.firstEventMixins = new FirstEventMixin[dataMixinArray.length()];
for (int i = 0; i < dataMixinArray.length(); i++) {
JSONObject dataChildMixinValue = dataMixinArray.getJSONObject(i);
try {
this.regularTileMixins[i] = ClassUtils
.makeMixin(dataChildMixinValue);
} catch (DataFormatException e) {
if (!(e.getCause() instanceof ClassCastException)) {
throw e;
}
}
try {
this.firstEventMixins[i] = ClassUtils
.makeFirstEventMixin(dataChildMixinValue);
} catch (DataFormatException e) {
if (!(e.getCause() instanceof ClassCastException)) {
throw e;
}
}
if (this.regularTileMixins[i] == null
&& this.firstEventMixins[i] == null) {
// Since we've reached here, it must be a ClassCastException.
throw new DataFormatException("Mixin with unknown type: "
+ dataChildMixinValue.getString("class"));
}
}
} |
51f37380-8707-440a-af27-4d1e9e98c285 | 6 | private MemoryNode encontrarHojaDondeEstaQ(MemoryNode node, double[] q) throws IOException {
comparaciones++;
node.setVisitado(1);
if (node.getLeft() == null || node.getRight() == null) {
double distNueva = Math
.sqrt((Math.pow((q[0] - node.getX()), 2) + Math.pow(
(q[1] - node.getY()), 2)));
distActual = distNueva;
mejorActual[0] = node.getX();
mejorActual[1] = node.getY();
return node;
} else {
if ((node.getX() == 0 && q[1] > node.getY())
|| (node.getY() == 0 && q[0] > node.getX())) {
return encontrarHojaDondeEstaQ(node.getRight(), q);
} else {
return encontrarHojaDondeEstaQ(node.getLeft(), q);
}
}
} |
55764680-ec50-45b2-9a02-93697311b75b | 4 | public double getStrength(ArrayList<Card> holeCards) throws Exception {
if (holeCards.size() != 2) {
throw new Exception("Not correct amount of hole cards");
}
if (holeCards.get(0).sign == holeCards.get(1).sign) { // suited
// in cause of a triangular matrix you have to look on the right sight
if (holeCards.get(0).value.ordinal() < holeCards.get(1).value
.ordinal()) {
return suitedPreFlop[holeCards.get(0).value.ordinal()][holeCards
.get(1).value.ordinal()];
} else {
return suitedPreFlop[holeCards.get(1).value.ordinal()][holeCards
.get(0).value.ordinal()];
}
} else { // unsuited
// in cause of a triangular matrix you have to look on the right sight
if (holeCards.get(0).value.ordinal() <= holeCards.get(1).value
.ordinal()) {
return unsuitedPreFlop[holeCards.get(0).value.ordinal()][holeCards
.get(1).value.ordinal()];
} else {
return unsuitedPreFlop[holeCards.get(1).value.ordinal()][holeCards
.get(0).value.ordinal()];
}
}
} |
f328a241-e3d3-493d-90f8-0929ddc40f18 | 3 | public static void main(String[] args) {
BLPSystem sys = new BLPSystem();
SecurityLevel low = SecurityLevel.low;
SecurityLevel high = SecurityLevel.high;
// We add two subjects, one high and one low.
sys.createSubject("Lyle", low);
sys.createSubject("Hal", high);
// We add two objects, one high and one low.
sys.getReferenceMonitor().createNewObject("Lobj", low);
sys.getReferenceMonitor().createNewObject("Hobj", high);
BufferedReader reader = null;
try {
String currentInstruction;
reader = new BufferedReader(new FileReader(args[0]));
while ((currentInstruction = reader.readLine()) != null) {
System.out.println(currentInstruction);
sys.runInstruction(currentInstruction);
sys.getReferenceMonitor().printState();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
} |
88a35849-6be0-4611-bfcc-b88a9de179c8 | 8 | private static String initialise(Token currentToken,
int[][] expectedTokenSequences,
String[] tokenImage) {
String eol = System.getProperty("line.separator", "\n");
StringBuffer expected = new StringBuffer();
int maxSize = 0;
for (int i = 0; i < expectedTokenSequences.length; i++) {
if (maxSize < expectedTokenSequences[i].length) {
maxSize = expectedTokenSequences[i].length;
}
for (int j = 0; j < expectedTokenSequences[i].length; j++) {
expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');
}
if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
expected.append("...");
}
expected.append(eol).append(" ");
}
String retval = "Encountered \"";
Token tok = currentToken.next;
for (int i = 0; i < maxSize; i++) {
if (i != 0) retval += " ";
if (tok.kind == 0) {
retval += tokenImage[0];
break;
}
retval += " " + tokenImage[tok.kind];
retval += " \"";
retval += add_escapes(tok.image);
retval += " \"";
tok = tok.next;
}
retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
retval += "." + eol;
if (expectedTokenSequences.length == 1) {
retval += "Was expecting:" + eol + " ";
} else {
retval += "Was expecting one of:" + eol + " ";
}
retval += expected.toString();
return retval;
} |
26648957-bb4a-4e8f-aab0-f37781aa183b | 7 | private String useElementVariables(String s) {
if (!(model instanceof AtomicModel))
return s;
int lb = s.indexOf("%element[");
int rb = s.indexOf("].", lb);
int lb0 = -1;
String v;
int i;
while (lb != -1 && rb != -1) {
v = s.substring(lb + 9, rb);
double x = parseMathExpression(v);
if (Double.isNaN(x))
break;
i = (int) Math.round(x);
if (i < 0 || i >= 4) {
out(ScriptEvent.FAILED, i + " is an invalid index: must be between 0 and 3 (inclusive).");
break;
}
v = escapeMetaCharacters(v);
Element e = ((AtomicModel) model).getElement(i);
s = replaceAll(s, "%element\\[" + v + "\\]\\.mass", e.getMass() * M_CONVERTER);
s = replaceAll(s, "%element\\[" + v + "\\]\\.sigma", e.getSigma() * R_CONVERTER);
s = replaceAll(s, "%element\\[" + v + "\\]\\.epsilon", e.getEpsilon());
lb0 = lb;
lb = s.indexOf("%element[");
if (lb0 == lb) // infinite loop
break;
rb = s.indexOf("].", lb);
}
return s;
} |
e0fbf911-d763-42e0-8953-306e3e5d7948 | 7 | Point3i adjustedTemporaryScreenPoint() {
float z = (point3fScreenTemp.z - perspectiveOffset.z);
if (z < cameraDistance) {
if (Float.isNaN(point3fScreenTemp.z)) {
// removed for extending pmesh to points and lines BH 2/25/06
if (!haveNotifiedNaN)
Logger.debug("NaN seen in TransformPoint");
haveNotifiedNaN = true;
z = 1;
}
else if (z <= 0) {
// just don't let z go past 1 BH 11/15/06
z = 1;
}
}
point3fScreenTemp.z = z;
if (perspectiveDepth) {
float perspectiveFactor = perspectiveFactor(z);
point3fScreenTemp.x *= perspectiveFactor;
point3fScreenTemp.y *= perspectiveFactor;
}
// higher resolution here for spin control.
point3fScreenTemp.x += perspectiveOffset.x;
point3fScreenTemp.y += perspectiveOffset.y;
if (Float.isNaN(point3fScreenTemp.x) && !haveNotifiedNaN) {
Logger.debug("NaN found in transformPoint ");
haveNotifiedNaN = true;
}
point3iScreenTemp.x = (int) point3fScreenTemp.x;
point3iScreenTemp.y = (int) point3fScreenTemp.y;
point3iScreenTemp.z = (int) point3fScreenTemp.z;
return point3iScreenTemp;
} |
763cde11-322b-4ac3-bd8d-33890b379a9e | 6 | static public void adjustBeginLineColumn(int newLine, int newCol)
{
int start = tokenBegin;
int len;
if (bufpos >= tokenBegin)
{
len = bufpos - tokenBegin + inBuf + 1;
}
else
{
len = bufsize - tokenBegin + bufpos + 1 + inBuf;
}
int i = 0, j = 0, k = 0;
int nextColDiff = 0, columnDiff = 0;
while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize])
{
bufline[j] = newLine;
nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];
bufcolumn[j] = newCol + columnDiff;
columnDiff = nextColDiff;
i++;
}
if (i < len)
{
bufline[j] = newLine++;
bufcolumn[j] = newCol + columnDiff;
while (i++ < len)
{
if (bufline[j = start % bufsize] != bufline[++start % bufsize])
bufline[j] = newLine++;
else
bufline[j] = newLine;
}
}
line = bufline[j];
column = bufcolumn[j];
} |
b321e1b9-76b4-4108-b997-6956e5a789b9 | 0 | public static void addSuccessMessage(String msg) {
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg);
FacesContext.getCurrentInstance().addMessage("successInfo", facesMsg);
} |
9325ec48-99d9-4580-a9bd-11372c5e6412 | 2 | public String login(String vCloudUrl, String username, String orgName, String password) throws Exception
{
String loginString = Utils.CLOUD_URL_PREFIX + vCloudUrl + Utils.CLOUD_URL_SUFFIX;
String creds;
if(username.contains("@")) {
creds = username +":" + password;
} else {
creds = username + "@" + orgName + ":" + password;
}
creds = new String(Base64.encodeBase64(creds.getBytes()));
HashMap<String, String> headers = new HashMap<String, String>();
headers.put(Utils.AUTHORIZATION_HEADER, Utils.CRED_PREFIX + creds);
headers.put(Utils.ACCEPT_HEADER, Constants.XML_CONTENT_TYPE);
HttpResponse response = RestClient.doPost(loginString, null, headers);
StatusLine status = response.getStatusLine();
if( status.getStatusCode() == 401) {
throw new Exception("Unauthorized credentials. Please check username and password");
}
HttpClient httpClient = RestClient.getHttpClient();
authToken = RestClient.getAuthToken(response);
return RestClient.getResponseString(httpClient, response);
} |
4e5a77bf-2cd2-4578-8d60-b03edfdf0acd | 3 | public static void renderBlank(Graphics2D g, boolean blue) {
try {
SVGDiagram diagram = universe.getDiagram(ImageManager.class.getResource(urlBase + (blue ? "blue.svg" : "red.svg")).toURI());
diagram.setIgnoringClipHeuristic(true);
diagram.render(g);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (SVGException e) {
e.printStackTrace();
}
} |
eb4c537b-1798-4aa7-9c0a-34515a384088 | 3 | public static void main(String[] args) {
String path = System.getProperty("user.dir") + FILE_PATH;
Dictionary dictionary = new Dictionary(path);
System.out.println("initializing dictionary...");
dictionary.preprocess();
Scanner userInputScanner = new Scanner(System.in);
System.out.print("Enter a word or % to quit: ");
String input = userInputScanner.nextLine();
if (input.equals("%"))
return;
while (!input.equals("%")) {
long startTime = System.currentTimeMillis();
try {
validate(input);
input = input.toLowerCase();
List<String> findings = dictionary.find(input);
System.out.println("Found: " + findings);
System.out.println(String.format("%d words found in %d seconds", findings.size(),
TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime)));
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.print("Enter a word or % to quit: ");
input = userInputScanner.nextLine();
}
System.out.println("Game over");
} |
33e206ad-313c-4000-aa47-1780c8721752 | 0 | public Piirtaja(Pelaaja pelaaja, Kamera kamera) {
this.pelaaja = pelaaja;
this.kamera = kamera;
} |
910b25b7-3fc0-42cc-bb4f-036ba31e0021 | 3 | public VariableStack mapStackToLocal(VariableStack stack) {
StructuredBlock[] subBlocks = getSubBlocks();
VariableStack after;
if (subBlocks.length == 0)
after = stack;
else {
after = null;
for (int i = 0; i < subBlocks.length; i++) {
after = VariableStack.merge(after,
subBlocks[i].mapStackToLocal(stack));
}
}
if (jump != null) {
/* assert(after != null) */
jump.stackMap = after;
return null;
}
return after;
} |
0806a589-0531-4182-8d4b-710cf359c54c | 8 | public static Book parseBook(String data) throws IOException {
Book book = new Book();
try {
String tokens[] = data.split("[=]|[\\{]|[\\}]|[,]");
if(data.indexOf("Book") != -1 || tokens.length > 0) {
for( int i = 0; i < tokens.length ; i++) {
if(tokens[i].indexOf("title") != -1)
book.setTitle(tokens[i+1]);
else if(tokens[i].indexOf("author") != -1)
book.setAuthor(tokens[i+1]);
else if(tokens[i].indexOf("releaseDate") != -1)
book.setReleaseDate(tokens[i+1]);
else if(tokens[i].indexOf("language") != -1)
book.setLanguage(tokens[i+1]);
}
}
else{
logger.warn("Book:Invalid Record read " + data);
}
}
catch(Exception ex) {
logger.error("Book:Error Record read " + data);
ex.printStackTrace();
}
return book;
} |
f461057d-8957-4017-b38f-eb6009903720 | 2 | public MethodVisitor visitMethod(final int access, final String name,
final String desc, final String signature, final String[] exceptions) {
MethodVisitor mv;
if ("<clinit>".equals(name)) {
int a = Opcodes.ACC_PRIVATE + Opcodes.ACC_STATIC;
String n = prefix + counter++;
mv = cv.visitMethod(a, n, desc, signature, exceptions);
if (clinit == null) {
clinit = cv.visitMethod(a, name, desc, null, null);
}
clinit.visitMethodInsn(Opcodes.INVOKESTATIC, this.name, n, desc);
} else {
mv = cv.visitMethod(access, name, desc, signature, exceptions);
}
return mv;
} |
f51f5368-f474-4887-a4ba-9cee1a718b7c | 8 | public void buildClassifier(Instances data) throws Exception{
//heuristic to avoid cross-validating the number of LogitBoost iterations
//at every node: build standalone logistic model and take its optimum number
//of iteration everywhere in the tree.
if (m_fastRegression && (m_fixedNumIterations < 0)) m_fixedNumIterations = tryLogistic(data);
//Need to cross-validate alpha-parameter for CART-pruning
Instances cvData = new Instances(data);
cvData.stratify(m_numFoldsPruning);
double[][] alphas = new double[m_numFoldsPruning][];
double[][] errors = new double[m_numFoldsPruning][];
for (int i = 0; i < m_numFoldsPruning; i++) {
//for every fold, grow tree on training set...
Instances train = cvData.trainCV(m_numFoldsPruning, i);
Instances test = cvData.testCV(m_numFoldsPruning, i);
buildTree(train, null, train.numInstances() , 0);
int numNodes = getNumInnerNodes();
alphas[i] = new double[numNodes + 2];
errors[i] = new double[numNodes + 2];
//... then prune back and log alpha-values and errors on test set
prune(alphas[i], errors[i], test);
}
//build tree using all the data
buildTree(data, null, data.numInstances(), 0);
int numNodes = getNumInnerNodes();
double[] treeAlphas = new double[numNodes + 2];
//prune back and log alpha-values
int iterations = prune(treeAlphas, null, null);
double[] treeErrors = new double[numNodes + 2];
for (int i = 0; i <= iterations; i++){
//compute midpoint alphas
double alpha = Math.sqrt(treeAlphas[i] * treeAlphas[i+1]);
double error = 0;
//compute error estimate for final trees from the midpoint-alphas and the error estimates gotten in
//the cross-validation
for (int k = 0; k < m_numFoldsPruning; k++) {
int l = 0;
while (alphas[k][l] <= alpha) l++;
error += errors[k][l - 1];
}
treeErrors[i] = error;
}
//find best alpha
int best = -1;
double bestError = Double.MAX_VALUE;
for (int i = iterations; i >= 0; i--) {
if (treeErrors[i] < bestError) {
bestError = treeErrors[i];
best = i;
}
}
double bestAlpha = Math.sqrt(treeAlphas[best] * treeAlphas[best + 1]);
//"unprune" final tree (faster than regrowing it)
unprune();
//CART-prune it with best alpha
prune(bestAlpha);
cleanup();
} |
aaf737e4-47f4-4492-8419-104f09dae859 | 6 | private static boolean addToZip(String absolutePath, String relativePath, String fileName, ZipOutputStream out) {
File file = new File(absolutePath + File.separator + fileName);
DebugUtils.info("Adding \"" + absolutePath + File.separator + fileName + "\" file");
if (file.isHidden())
return true;
if (file.isDirectory()) {
absolutePath = absolutePath + File.separator + file.getName();
relativePath = relativePath + File.separator + file.getName();
for (String child : file.list()) {
if (!addToZip(absolutePath, relativePath, child, out)) {
return false;
}
}
return true;
}
try {
byte[] data = new byte[2048];
FileInputStream fi = new FileInputStream(file);
BufferedInputStream origin = new BufferedInputStream(fi, 2048);
ZipEntry entry = new ZipEntry(relativePath + File.separator + fileName);
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, 2048)) != -1) {
out.write(data, 0, count);
}
origin.close();
} catch (Exception ex) {
DebugUtils.error(ex.getMessage());
ex.printStackTrace();
return false;
}
return true;
} |
bf70087b-ba98-4651-a2f9-0b1ae27bcd07 | 5 | public static List<List<ICard>> getPrese(ICard card, List<ICard> tableCards){
List<List<ICard>> retPrese = new ArrayList<List<ICard>>();
//singola presa
for(ICard c : tableCards)
if(card.getNumber() == c.getNumber())
{
ArrayList<ICard> spresa = new ArrayList<ICard>();
spresa.add(c);
spresa.add(card); //aggiungo carta giocata alla presa
retPrese.add(spresa);
return retPrese; //singola presa
}
//prese multiple
List<List<ICard>> allSubSets = Lists.powerset(tableCards);
for(List<ICard> set : allSubSets)
{
int sum = 0;
for(ICard tablec : set)
sum+=tablec.getNumber();
if(sum == card.getNumber()){
set.add(card); //aggiungo la carta giocata alla presa
retPrese.add(set); //aggiungo il set alle prese
}
}
return retPrese;
} |
2f67913f-fe7e-417b-8cc6-d821a342833f | 4 | public static void main(String [] args) throws SocketException, NoSuchAlgorithmException {
if(args.length < 2) {
System.out.println("Invalid number of arguments to start server. Needs <port> <shared secret>");
return;
}
try {
UDPServer server = new UDPServer(Integer.parseInt(args[0]), args[1]);
while(server.isRunning) {
byte[] receiveData = new byte[4096];
DatagramPacket packet = new DatagramPacket(receiveData, receiveData.length);
server.socket.receive(packet);
Runnable worker = new UDPServerThread(server.socket, packet, server.sharedSecret);
server.service.execute(worker);
}
} catch (SocketException ex) {
System.out.println("Socket could not be bound to port " + args[0] + " please try again with another port.");
ex.printStackTrace();
} catch (IOException ex) {
System.out.println("Package could not be received.");
ex.printStackTrace();
}
} |
3323f54e-14bc-49bb-873d-35b4e4a63d66 | 7 | protected void saveBest() {
try {
if (runBestIndividual == null)
throw new IOException("No run best individual");
List<Individual> bestIndividuals = new ArrayList<Individual>();
File inputFolder = new File("results/input");
File outputFolder = new File("results/output");
if (!inputFolder.exists()) inputFolder.mkdirs();
if (!outputFolder.exists()) outputFolder.mkdirs();
for (File file : inputFolder.listFiles()) {
Individual individual = new Individual();
individual.readInputFile(file.getPath());
individual.calculateFitness();
bestIndividuals.add(individual);
}
runBestIndividual.calculateFitness();
runBestIndividual.writeInputFile(
"results/input/HMO-projekt-input-last.txt"
);
runBestIndividual.writeOutputFile(
"results/output/HMO-projekt-output-last.txt"
);
bestIndividuals.add(runBestIndividual);
Collections.sort(bestIndividuals);
int rank = 1;
for (Individual individual : bestIndividuals) {
if (rank <= 5) {
individual.writeInputFile(
"results/input/HMO-projekt-input-"+rank+".txt"
);
individual.writeOutputFile(
"results/output/HMO-projekt-output-"+rank+".txt"
);
rank++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
} |
d8f11f89-064d-4aef-9a1e-9e9a1d87b044 | 3 | public void actionPerformed(ActionEvent e) {
if (e.getSource() == kilobutton) {
kilotext.setEnabled(true);
kbytes.enable();
}
else {
kilotext.setEnabled(false);
kbytes.disable();
}
if (e.getSource() == megabutton) {
megatext.setEnabled(true);
mbytes.enable();
}
else {
megatext.setEnabled(false);
mbytes.disable();
}
if (e.getSource() == numbutton) {
numtext.setEnabled(true);
numreqs.enable();
}
else {
numtext.setEnabled(false);
numreqs.disable();
}
} |
f4d02a88-db35-4885-8e27-6c4fe1d43441 | 2 | public static JPanel makePanel(int orientation) {
JPanel p = new JPanel();
switch (orientation) {
case HORIZONTAL:
p.setLayout(new GridLayout(1, 0));
break;
case VERTICAL:
p.setLayout(new GridLayout(0, 1));
break;
default:
break;
}
return p;
} |
93c1f24e-14d7-43ef-8dc9-b7ee9cee7c52 | 9 | private static int method503(char ac[], char ac1[], int j)
{
if(j == 0)
return 2;
for(int k = j - 1; k >= 0; k--)
{
if(!method517(ac[k]))
break;
if(ac[k] == '@')
return 3;
}
int l = 0;
for(int i1 = j - 1; i1 >= 0; i1--)
{
if(!method517(ac1[i1]))
break;
if(ac1[i1] == '*')
l++;
}
if(l >= 3)
return 4;
return !method517(ac[j - 1]) ? 0 : 1;
} |
448be902-e4c6-49f9-97f5-59d73fc0ceb9 | 6 | public boolean getBoolean(int index) throws JSONException {
Object object = get(index);
if (object.equals(Boolean.FALSE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONArray[" + index + "] is not a boolean.");
} |
c5a8b4ef-9ef2-46be-a099-2be5484601e0 | 8 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Category other = (Category) obj;
if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) {
return false;
}
if ((this.title == null) ? (other.title != null) : !this.title.equals(other.title)) {
return false;
}
return (this.uriTag == null) ? other.uriTag == null : this.uriTag.equals(other.uriTag);
} |
b62e7c83-3643-4191-b89c-301211b09e62 | 6 | private void loadCoffers(){
File cofferFile = new File(getDataFolder(),cofferFileName);
if(!cofferFile.exists()){
logMessage("Coffer file does not exist");
return;
}
FileConfiguration config = YamlConfiguration.loadConfiguration(cofferFile);
Iterator<String> citr = config.getConfigurationSection("coffers").getKeys(false).iterator();
while(citr.hasNext()){
try{
String key = citr.next();
String wName = config.getString("coffers."+key+".world");
World world = getServer().getWorld(wName);
String pName = config.getString("coffers."+key+".player");
Location chestLoc = new Location(world,Double.parseDouble(key.split("x")[1]),Double.parseDouble(key.split("x")[2]),Double.parseDouble(key.split("x")[3]));
//The chest was some how missing since we last loaded, don't add it
if(!(world.getBlockAt(chestLoc).getState() instanceof Chest))
continue;
Chest chest = (Chest) world.getBlockAt(chestLoc).getState();
OfflinePlayer player = getServer().getOfflinePlayer(pName);
//No offline player by that name, can't add it
if(player==null)
continue;
if(!addCoffer(player,chest))
logWarning("Unable to add a coffer to the list for "+player.getName()+"!");
}catch(NullPointerException e){
logWarning("The coffer file has been improperly modified!");
continue;
}
}
} |
0468a499-df07-4441-8075-e6d1cf6290f4 | 6 | private void logOutput() throws VehicleException, SimulationException, IOException {
// reset text area
logText.setText("");
Log log = new Log();
// update log
if(valid()){
log.initialEntry(cp, s);
for (int time=0; time<=Constants.CLOSING_TIME; time++) {
//queue elements exceed max waiting time
if (!cp.queueEmpty()) {
cp.archiveQueueFailures(time);
}
//vehicles whose time has expired
if (!cp.carParkEmpty()) {
//force exit at closing time, otherwise normal
boolean force = (time == Constants.CLOSING_TIME);
cp.archiveDepartingVehicles(time, force);
}
//attempt to clear the queue
if (!cp.carParkFull()) {
cp.processQueue(time,s);
}
// new vehicles from minute 1 until the last hour
if (newVehiclesAllowed(time)) {
cp.tryProcessNewVehicles(time,s);
}
String status = cp.getStatus(time);
log.writer.write(status);
logText.append(status);
}
log.finalise(cp);
}
} |
1031ce93-bef1-46cc-8d6f-a03930089597 | 2 | public ArrayList<String> readTestData() throws IOException{
ArrayList<String> candAttr = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String str = "";
while (!(str = reader.readLine()).equals("")) {
StringTokenizer tokenizer = new StringTokenizer(str);
while (tokenizer.hasMoreTokens()) {
candAttr.add(tokenizer.nextToken());
}
}
return candAttr;
} |
220ef6e9-cc2f-4004-add4-4d43efe26d13 | 3 | private long consumeCurrentToken()
throws IOException {
if( this.currentToken == null )
return -1L;
byte[] buff = new byte[256];
int len;
long totalLength = 0;
if( !this.currentToken.isClosed() ) {
while( (len = this.currentToken.read(buff)) > 0 )
totalLength += len;
}
this.currentToken.close();
this.currentToken = null;
return totalLength;
} |
fda5892d-f24c-4057-9c47-93f3f6efb15e | 6 | private static void filterMapper(String realJvmCostDir, String mapperJvmCost,
String filteredMapper) {
File input = new File(realJvmCostDir + mapperJvmCost);
File output = new File(realJvmCostDir + filteredMapper);
if(!output.exists())
output.getParentFile().mkdirs();
try {
BufferedReader reader = new BufferedReader(new FileReader(input));
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(output)));
String titles = reader.readLine();
String[] title = titles.split("\t");
writer.println("XMS" + "\t" + titles);
String line;
while((line = reader.readLine()) != null) {
String[] value = line.split("\t");
SplitMapperRealJvmCost jvmCost = new SplitMapperRealJvmCost(title, value);
int xms = 0;
if(jvmCost.getXms() == jvmCost.getXmx())
xms = 1;
if(jvmCost.getBytes() == jvmCost.getSplit())
writer.println(xms + "\t" + line);
}
reader.close();
writer.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
66960203-e6fe-40c9-aa11-d2fcd757a609 | 0 | public Validator<T> getValidatorRHS() {
return validatorRHS;
} |
407118c1-881b-40f0-b3d2-e027a073d863 | 8 | public boolean setParallelJobProbabilities(int jobType,
double uLow, double uMed, double uHi, double uProb) {
if(jobType > BATCH_JOBS || jobType < INTERACTIVE_JOBS) {
return false;
} else 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;
}
if(useJobType_) {
this.uLow[jobType] = uLow;
this.uMed[jobType] = uMed;
this.uHi[jobType] = uHi;
this.uProb[jobType] = uProb;
}
else {
this.uLow[INTERACTIVE_JOBS] = this.uLow[BATCH_JOBS] = uLow;
this.uMed[INTERACTIVE_JOBS] = this.uMed[BATCH_JOBS] = uMed;
this.uHi[INTERACTIVE_JOBS] = this.uHi[BATCH_JOBS] = uHi;
this.uProb[INTERACTIVE_JOBS] = this.uProb[BATCH_JOBS] = uProb;
}
return true;
} |
84b9f7d8-d3bf-40cf-9bf3-b8e2d6aa86cb | 2 | private StructureFile readRoot(Node root) throws SyntaxException {
StructureFile structure = new StructureFile();
NodeList children = root.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child instanceof Element)
readChunkDec(structure, (Element) child);
}
return structure;
} |
0be32a17-f047-492d-bc4c-dad06de88173 | 0 | void vouting(Object obj, final String userid) {
vote.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
Map<String, Object> m = new HashMap<String, Object>();
m.put("action", "vote");
m.put("userfrom",View._model.user_id );
m.put("userto", userid );
Main.c.enableVoteButtons(false);
}
});
} |
bb7b043d-6e52-41d5-af76-ba72cc5377bc | 3 | public Habitat getHabitatByTenant(String tenant) {
for (Habitat h : getHabitats().values()) {
if (h != null)
if (h.getTenant().equalsIgnoreCase(tenant)) return h;
}
return null;
} |
4a787d41-6156-40a7-8dd9-bf71880400fc | 9 | public long uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
if(m<1||n<1) return 0;
if(m==1 && n==1) return obstacleGrid[0][0]^1;
long count[][] = new long[m+1][n+1];
for(int i=0;i<=m;i++) count[i][0] = 0;
for(int i=0;i<=n;i++) count[0][i] = 0;
count[0][1] = 1;
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
if(obstacleGrid[i-1][j-1]==1) count[i][j]=0;
else count[i][j] =count[i-1][j]+ count[i][j-1];
}
}
return count[m][n];
} |
f8516c5c-5a4a-473e-8993-81661a064c68 | 6 | public boolean twoOpt555(){
int pathLength=tour.length();
boolean better=false;
for(int currentVerticeIndex=0; currentVerticeIndex<pathLength;currentVerticeIndex++){
int nextVerticeIndex=(currentVerticeIndex+1)%pathLength;
//skip the current and the nextVerticeIndex
int toVerticeIndex=(currentVerticeIndex+2)%pathLength;
int distOldEdge=tour.indexDistance(currentVerticeIndex, nextVerticeIndex);/*ug.dist(current,nextVerticeIndex);*/
//goes through all other edges
for(int iters=0;iters<pathLength-3;iters++){
int distNewEdge=tour.indexDistance(currentVerticeIndex,toVerticeIndex);/*ug.dist(current,swapWith);*/
//check if edge to swapwith is better than edge from current to next
if(distNewEdge < distOldEdge ){
// System.out.println("before " +tourLength(dist,tour));
//check if second edge swap if it really is an improvement
if(swapIfBetterTwoOpt(nextVerticeIndex,toVerticeIndex)){
//it was better so complete the reversing
int innerFrom=(nextVerticeIndex+1)%pathLength;
int innerTo= toVerticeIndex==0 ? pathLength-1 : toVerticeIndex-1;
// reverse(path, innerFrom, innerTo);
tour.reverseSubPath(innerFrom, innerTo);
// System.out.println("after " +tourLength(dist,tour));
better=true;
}
}
//increment the index, but do a wraparound if it reaches the end
toVerticeIndex++; if(toVerticeIndex>=pathLength){ toVerticeIndex=0; }
}
}
return better;
} |
fad2756e-96ad-4863-a44f-cdba0fc567f8 | 4 | public void removeWalls(int wallsToRemove){
ArrayList<MazeNode> walls = new ArrayList<MazeNode>();
for(int row = 1; row < this.rows - 1; row++){
for(int column = 1; column < this.columns - 1; column++){
if(getNode(column, row).isWall()){
walls.add(getNode(column, row));
}
}
}
Collections.shuffle(walls);
for(int i = 0; i < wallsToRemove; i++){
walls.get(i).setWall(false);
}
} |
22f2a2a3-d1ad-466b-abdf-cddcc6bafd21 | 8 | private static List<SubFileParser> getCompletedWorkers( File rdpFile, int numCPUs)
throws Exception
{
BlockingQueue<String> blockingQueue = new LinkedBlockingQueue<String>();
List<SubFileParser> subList = new ArrayList<SubFileParser>();
int numAdded = 0;
List<Thread> startedThreads = new ArrayList<Thread>();
for( int x=0; x < numCPUs; x++)
{
SubFileParser sfp = new SubFileParser(blockingQueue);
subList.add(sfp);
Thread t = new Thread(sfp);
t.start();
startedThreads.add(t);
}
BufferedReader reader = new BufferedReader(new FileReader(rdpFile));
String nextLine = reader.readLine();
while(nextLine != null)
{
blockingQueue.add(nextLine);
nextLine = reader.readLine();
numAdded++;
}
reader.close();
while(! blockingQueue.isEmpty())
Thread.yield();
boolean keepLooping = true;
while(keepLooping)
{
int assignedCount =0;
for( SubFileParser sfp : subList )
assignedCount += sfp.listSize;
if( assignedCount > numAdded )
throw new Exception("Threading error");
if( assignedCount == numAdded)
{
keepLooping = false;
}
else
{
Thread.yield();
}
}
for( Thread t : startedThreads)
t.interrupt();
return subList;
} |
adec0da9-3339-453e-bc70-a30d7effdcab | 0 | public void setPassword(String password) {
this.password = password;
} |
4a96c1ab-5a54-4a01-b1a8-5f107a858c87 | 2 | private void renewASL(){
ASL_model.removeAllElements();
for (int i = 0; i<logAc.getDoctorSize(); i++){
ASL_model.add(i, logAc.getDoctor(i).getName());
}
ASL_adminmodel.removeAllElements();
for (int i = 0; i<logAc.getAdminSize(); i++){
ASL_adminmodel.add(i, logAc.getAdmin(i).getName());
}
ASR_doctor.setEnabled(true);
ASR_admin.setEnabled(true);
AST_password.setEnabled(true);
AST_name.setText("");
AST_userName.setText("");
AST_password.setText("");
AST_room.setText("");
} |
7dffa6b6-70b1-493b-833f-eeb4ea639cb6 | 5 | void loadTile(String[] split)
{
setExplored(Boolean.valueOf(split[1]));
setTilehealth(Integer.valueOf(split[2]));
if(!split[3].equals("null"))
setDesignate(TaskEnum.valueOf(split[3]));
setActualTask(Integer.valueOf(split[4]));
/*
* TODO: split[5] creatures ints and split[6]item ints has to be added
*/
if(split[5].equals("@")==false)
{
String[] splitint = split[5].split("@");
for(int i=0; i<splitint.length; i++)
{
this.creature.add(Integer.valueOf(splitint[i]));
}
}
if(split[6].equals("@")==false)
{
String[] splitint = split[6].split("@");
for(int i=0; i<splitint.length; i++)
{
this.item.add(Integer.valueOf(splitint[i]));
}
}
} |
ee9c6267-b995-4e97-9b70-76930489c86a | 7 | public Map<String, List<Map<String, String>>> readLocators(List<String> locAppIDs){
Map<String, List<Map<String, String>>> locatorSets= new LinkedHashMap<String, List<Map<String, String>>>();
if(locAppIDs.size()>0){
EnvironmentVariables ev = EnvironmentVariables.getInstance();
for (String appID : locAppIDs) {
Connection conn1 = null;
Statement stmnt = null;
String locsheetName= ev.getFieldDefnSheetName();
String locfilePath= ev.getFieldDefnFilePathPrefix()+appID+ ev.getFileExtension();
try
{
ResultSet locTable = null;
conn1 = DriverManager.getConnection( "jdbc:odbc:Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ="+locfilePath+"");
stmnt = conn1.createStatement();
String locQuery = "select * from ["+locsheetName+"$];";
locTable = stmnt.executeQuery(locQuery);
List<Map<String, String>> locset = new ArrayList<Map<String, String>>();
while(locTable.next()){
if(locatorSets.get(appID)== null){
logger.info("reading LOCATORS- adding locators records to a new applicationID:"+appID);
Map<String, String> locRecord = new HashMap<String, String>();
locRecord.put("ScreenName", locTable.getString("ScreenName").trim());
locRecord.put("FieldName", locTable.getString("FieldName").trim());
locRecord.put("FieldDefinition", locTable.getString("FieldDefinition").trim());
locset.add(locRecord);
locatorSets.put(appID, locset);
}else{
logger.info("reading LOCATORS - Updating locators records to a new applicationID:"+appID);
Map<String, String> locRecord = new HashMap<String, String>();
locRecord.put("ScreenName", locTable.getString("ScreenName").trim());
locRecord.put("FieldName", locTable.getString("FieldName").trim());
locRecord.put("FieldDefinition", locTable.getString("FieldDefinition").trim());
locatorSets.get(appID).add(locRecord);
}
}
}catch(Exception e){
logger.error("Exception in reading locators \n stacktraceInfo::"+e.getMessage());
}finally{
try {
stmnt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
try {
conn1.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
}
}
}else{
logger.error("Error in reading Locators - appIDs List contains"+ locAppIDs.size() + " appIDs");
}
return locatorSets;
} |
34dacc55-4ecb-4a7d-b139-f9e6ce779415 | 3 | public void actionPerformed(ActionEvent e) {
Grammar g = environment.getGrammar(UnrestrictedGrammar.class);
myGrammar=g;
if (g == null)
return;
if (g.getTerminals().length==0)
{
JOptionPane.showMessageDialog(environment,
"Error : This grammar does not accept any Strings. ",
"Cannot Proceed with CYK", JOptionPane.ERROR_MESSAGE);
myErrorInTransform=true;
return;
}
hypothesizeLambda(environment, g);
if (!myErrorInTransform)
{
MultipleCYKSimulateAction mult = new MultipleCYKSimulateAction(g, myGrammar, environment);
mult.performAction((Component)e.getSource());
}
} |
376d4651-c522-4858-9072-2cd3beddfc09 | 8 | public void analyzeShots(RoomAnalysis ra) {
double closest_shot_distance2 = Double.MAX_VALUE;
for (Shot shot : current_room.getShots()) {
double shot_distance2 = MapUtils.distance2(bound_object, shot);
if (shot.getType().equals(ObjectType.MegaMissile) &&
MapUtils.distance2(bound_object, shot) < MEGA_MISSILE_MIN_DISTANCE2 &&
// Is the Pyro facing the MegaMissile?
Math.abs(MapUtils.angleTo(bound_object, shot)) < MapUtils.PI_OVER_TWO &&
// Is the MegaMissile facing away from the Pyro?
Math.abs(MapUtils.angleTo(shot, bound_object)) > MapUtils.PI_OVER_TWO) {
ra.is_close_behind_mega = true;
}
if (shot.getSource().equals(bound_object) || shot_distance2 > closest_shot_distance2) {
continue;
}
StrafeDirection strafe = findReactionToShot(shot);
if (!strafe.equals(StrafeDirection.NONE)) {
ra.shot_reaction = strafe;
closest_shot_distance2 = MapUtils.distance2(bound_object, shot);
}
}
} |
8df5f42a-01d8-450c-914a-2c612239097e | 3 | @Override
public boolean remove(int codigo) {
boolean status = false;
Connection con = null;
PreparedStatement pstm = null;
try{
con = ConnectionFactory.getConnection();
pstm = con.prepareStatement(REMOVE);
pstm.setInt(1, codigo);
pstm.execute();
status = true;
}catch(Exception e){
String var = "com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`agendamento_medico`.`paciente`, CONSTRAINT `convenio_fk` FOREIGN KEY (`codigo_convenio`) REFERENCES `convenio` (`codigo`) ON DELETE NO ACTION ON UPDATE NO ACTION)";
if(e.toString().equals(var)){
JOptionPane.showMessageDialog(null, "Erro ao remover, ele está sendo usado em algum paciente");
} else {
JOptionPane.showMessageDialog(null, "Erro ao excluir convenio: " + e.getMessage());
System.out.println("Erro ao remover:" + e + ":");
}
}finally{
try{
ConnectionFactory.closeConnection(con, pstm);
}catch(Exception ex){
JOptionPane.showMessageDialog(null, "Erro ao fechar a conexão do remove:"+ex.getMessage());
}
}
return status;
} |
56d0e076-858e-4a83-94e2-965c6e979d3e | 8 | private void graphToPS(File psOutputFile, Rectangle boundingBox, PositionTransformation pt){
EPSOutputPrintStream pw = null;
try {
pw = new EPSOutputPrintStream(psOutputFile);
} catch (FileNotFoundException e) {
Main.minorError("Could not open the file to write the ps to.");
}
pw.setBoundingBox((int)boundingBox.getX()-2, (int)boundingBox.getY()-2, boundingBox.width+2, boundingBox.height+2);
pw.writeHeader();
//add the default macros.
pw.println("%default Macros");
pw.addMacro("line", "newpath moveto lineto stroke");
pw.addMacro("filledCircle", "newpath 0 360 arc fill stroke");
pw.addMacro("filled4Polygon", "newpath moveto lineto lineto lineto closepath fill stroke");
pw.addMacro("filledArrowHead", "newpath moveto lineto lineto closepath fill stroke");
pw.println();
// print the map prior to the background (such that the border is on top of the map
if(Configuration.useMap) {
Runtime.map.drawToPostScript(pw,pt);
}
//draw the background
if(Configuration.epsDrawDeploymentAreaBoundingBox) {
pt.drawBackgroundToPostScript(pw);
}
//draw the edges
if(Configuration.drawEdges) {
Enumeration<Node> nodeEnumer = Runtime.nodes.getSortedNodeEnumeration(true);
while(nodeEnumer.hasMoreElements()){
Node n = nodeEnumer.nextElement();
for(Edge e: n.outgoingConnections){
e.drawToPostScript(pw, pt);
}
}
}
if(Configuration.drawNodes) {
// draw the nodes
for(Node n: Runtime.nodes){
n.drawToPostScript(pw, pt);
}
}
pw.writeEOF();
pw.close();
} |
a0d1cd1a-9e4e-4790-8ca5-dcbcc3030d70 | 9 | public static void main(String[] args) {
//首先获取一个path
Path path = FileSystems.getDefault().getPath("D:/a.txt");
final ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
//打开一个通道
try(AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ,
StandardOpenOption.WRITE,StandardOpenOption.SYNC)) {
//进行调用它的功能函数
System.out.println(fileChannel.size());
if (fileChannel.isOpen()) {
Future<Integer> future = fileChannel.read(byteBuffer, 0);
//等待接受消息
while (!future.isDone()) {
System.out.println("echo waiting............");
}
Thread.sleep(1000);
//接受到消息以后
Integer count = future.get();
if (count != -1) {
//说明已经读取到了数据
byteBuffer.flip();
System.out.println(Charset.forName("utf-8").decode(byteBuffer).toString());
byteBuffer.clear();
}
//second
fileChannel.read(byteBuffer,0,null,new CompletionHandler<Integer, Object>() {
@Override
public void completed(Integer result, Object attachment) {
if (result != null && result != -1) {
byteBuffer.flip();
System.out.println(Charset.defaultCharset().decode(byteBuffer).toString());
byteBuffer.clear();
}else{
System.out.println("end of file ");
}
}
@Override
public void failed(Throwable exc, Object attachment) {
System.out.println(exc.getStackTrace());
}
});
Future<Integer> future1 = fileChannel.write(ByteBuffer.wrap("last line this is future".getBytes()), fileChannel.size());
if (future1.isDone()) {
Integer integer = future1.get();
System.out.println(integer);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} |
1140ed34-78f1-419c-9b3c-10d45e2a4869 | 4 | public Card getNextUntappedPerm(String permName, Player controller) {
for (Card perm : this.permanents) {
if (perm.getName().equals(permName)
&& perm.getController().equals(controller)
&& !perm.isTapped()) {
return perm;
}
}
return null;
} |
1f7df96a-0e17-4354-823b-ca32e61988ad | 9 | private void populateFilters() {
//Populate gym filter
getGyms().clear();
//get all gyms
Iterable<Entry> gymResultSet = MongoHelper.query("{id:{$gte:0}}", Gym.class, "gyms");
if (gymResultSet != null) {
//Iterate through gyms matching query
for (Entry entry : gymResultSet) {
//add gym name to name list and gym to gym list
getGyms().add(((Gym) entry).getNickName());
getGymList().add((Gym) entry);
}
//remove duplicates using hash
HashSet hs = new HashSet();
hs.addAll(getGyms());
getGyms().clear();
getGyms().addAll(hs);
//sort gym names
Collections.sort(getGyms());
//add gyms to filter combo box
locationjComboBox.addItem("Any");
for (String gym : getGyms()) {
if (UserSession.getDebug()) {
System.out.println("Adding gym to list: " + gym);
}
locationjComboBox.addItem(gym);
}
}
else {
//No gyms exits
locationjComboBox.addItem("No Gyms Available");
}
//add trainers
//get all trainers from db
Iterable<Entry> classRS = MongoHelper.query("{id:{$gte:0}}", TrainingClass.class, "trainingClasses");
//get trainer from each class
for (Entry trainingClass1 : classRS) {
getTrainers().add(((TrainingClass) trainingClass1).getTrainer().getFirstName() + " " + ((TrainingClass) trainingClass1).getTrainer().getLastName());
if (UserSession.getDebug()) {
System.out.println(((TrainingClass) trainingClass1).getTrainer().getLastName());
}
}
//remove duplicates using hash
HashSet hs = new HashSet();
hs.addAll(getTrainers());
getTrainers().clear();
getTrainers().addAll(hs);
//sort trainers
Collections.sort(getTrainers());
if (UserSession.getDebug()) {
System.out.println(getTrainers());
}
//Add default of any
trainerjComboBox.addItem("Any");
//fill combo box
for (String trainer : getTrainers()) {
if (trainer.equals(" ")) {
//Compensate for empty trainer
trainerjComboBox.addItem("Trainer TBD");
}
else {
trainerjComboBox.addItem(trainer);
}
}
} |
3ffcd849-6e82-4363-af4d-ca41b7efdb81 | 3 | public void drawStateLabel(Graphics g, State state, Point point, Color color) {
String[] labels = state.getLabels();
if (labels.length == 0)
return;
int ascent = g.getFontMetrics().getAscent();
int heights = 0;
int textWidth = 0;
for (int i = 0; i < labels.length; i++) {
Rectangle2D bounds = g.getFontMetrics().getStringBounds(labels[i],
g);
textWidth = Math.max((int) bounds.getWidth(), textWidth);
heights += ascent + STATE_LABEL_PAD;
}
heights -= STATE_LABEL_PAD;
// Width of the box.
int width = textWidth + (STATE_LABEL_PAD << 1);
int height = heights + (STATE_LABEL_PAD << 1);
// Upper corner of the box.
int x = point.x - (width >> 1);
int y = point.y + STATE_RADIUS - STATE_LABEL_PAD;
// Where the y point of the baseline is.
int baseline = y;
g.setColor(color);
g.fillRect(x, y, width, height);
g.setColor(Color.black);
for (int i = 0; i < labels.length; i++) {
baseline += ascent + STATE_LABEL_PAD;
g.drawString(labels[i], x + STATE_LABEL_PAD, baseline);
}
g.drawRect(x, y, width, height);
} |
3347fa4e-6ffd-461d-9d0d-20feab6c2674 | 1 | public String getOptions(Request request) {
try {
return String.join(",", getRoutesMap(request).get(request.getURI()).keySet());
} catch (NullPointerException e) {
return "GET";
}
} |
9ae2ca84-91c5-49dd-9027-1feb7a11c88f | 3 | @Override
public Class getColumnClass(int column) {
Class returnValue;
if ((column >= 0) && (column < getColumnCount())) {
if(getValueAt(0, column)==null)
return String.class;
returnValue = getValueAt(0, column).getClass();
} else {
returnValue = Object.class;
}
return returnValue;
} |
b13688f8-9905-4233-b0a3-b27fdf5712a5 | 5 | public void menuTextSym() {
int choice;
do {
System.out.println("\n");
System.out.println("Text Cryption Menu");
System.out.println("Select Symmetric Cryption Methode");
System.out.println("---------------------------------\n");
System.out.println("1 - AES");
System.out.println("2 - Back");
System.out.print("Enter Number: ");
while (!scanner.hasNextInt()) {
System.out.print("That's not a number! Enter 1 or 2: ");
scanner.next();
}
choice = scanner.nextInt();
} while (choice < 1 || choice > 2);
switch (choice) {
case 1:
AesUI.aesCrypterText(this);
break;
case 2:
this.menuTextCrypt();
break;
default:
this.menuTextSym();
}
} |
5ad08120-cf27-4133-829c-8bb0a1954f0e | 9 | protected void spawnLettersNEW_OLD(int amount) {
char[] randomCharacters = new char[amount];
char temp;
int generatedVowels;
int bonusVowels;
final int MINIMUM_VOWELS = 6; // (6 for 40%)
bonusVowels = rand.nextInt(((2 - 0) + 1) + 0);
bonusVowels--; // TODO: this is lame, just fix it by fixing the line above
System.out.println("\nVowel Modifier: "+ bonusVowels);
generatedVowels = 0;
// check the letter inventory
if (vowelCount < MINIMUM_VOWELS) {
// get vowels first
// add random factor so it is not always fixed amount of vowels
// random bw. 0-2
generatedVowels = MINIMUM_VOWELS - vowelCount + bonusVowels;
for (int i = 0; i < (generatedVowels); i++) {
do {
temp = getRandomVowel();
} while (letterCount[temp - 65] > 2); // THIS CONTROLS THE MAX AMOUNT PER LETTER
randomCharacters[i] = temp;
this.letterCount[temp - 65]++;
System.out.print("" + randomCharacters[i] + " ");
}
// get consonants (the rest)
temp = 0;
for (int i = 0; i < (amount - generatedVowels); i++) {
do {
temp = getRandomConsonant();
} while (letterCount[temp - 65] > 1);
randomCharacters[i + generatedVowels] = temp;
this.letterCount[temp - 65]++;
System.out.print("" + randomCharacters[i] + " ");
}
} else {
// get consonants
for (int i = 0; i < amount; i++) {
do {
temp = getRandomConsonant();
} while (letterCount[temp - 65] > 1);
randomCharacters[i + generatedVowels] = temp;
this.letterCount[temp - 65]++;
System.out.print("" + randomCharacters[i] + " ");
}
}
char value;
String newLetters = "";
Element randomElement;
if (this.letterInventory.size() < this.maxLetterAmount) {
for (int i = 0; i < amount; i++) {
value = randomCharacters[i];
randomElement = getRandomElement();
Letter letter = new Letter(value, randomElement);
this.addLetter(letter);
newLetters += letter.getValue() + " ";
}
}
CombatLog.println("New letters: " + newLetters);
System.out.println();
// printLetterCount();
} |
d41ed5fe-6bb8-4b74-a5f7-a4ba2fe56698 | 7 | @SuppressWarnings("unchecked")
private T createEntity(T entity) {
try {
return (T) entity.getClass()
.getConstructor(new Class<?>[] { entity.getClass() })
.newInstance(entity);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return null;
} |
cd1507bc-f5f7-4e7a-be58-9e82a1bdfef9 | 1 | Object value() {
return (idx == null) ? val : Util.accessArray(name, val, idx);
} |
eca116d5-fdc0-4527-8f37-6fe038292ebd | 0 | public void setFirst(T newValue) { first = newValue; } |
45d6bb2a-65d0-40d8-9a55-9a5e6527e30b | 6 | public void setImgPath_SliderArrowUp(Path img, Imagetype type) {
switch (type) {
case DEFAULT:
this.imgSliderArrowUp_Def = handleImage(img, UIResNumbers.SLIDER_UP_DEF.getNum());
if (this.imgSliderArrowUp_Def == null) {
this.imgSliderArrowUp_Def = UIDefaultImagePaths.SLIDER_UP_DEF.getPath();
deleteImage(UIResNumbers.SLIDER_UP_DEF.getNum());
}
break;
case FOCUS:
this.imgSliderArrowUp_Foc = handleImage(img, UIResNumbers.SLIDER_UP_FOC.getNum());
if (this.imgSliderArrowUp_Foc == null) {
this.imgSliderArrowUp_Foc = UIDefaultImagePaths.SLIDER_UP_FOC.getPath();
deleteImage(UIResNumbers.SLIDER_UP_FOC.getNum());
}
break;
case PRESSED:
this.imgSliderArrowUp_Pre = handleImage(img, UIResNumbers.SLIDER_UP_PRE.getNum());
if (this.imgSliderArrowUp_Pre == null) {
this.imgSliderArrowUp_Pre = UIDefaultImagePaths.SLIDER_UP_PRE.getPath();
deleteImage(UIResNumbers.SLIDER_UP_PRE.getNum());
}
break;
default:
throw new IllegalArgumentException();
}
somethingChanged();
} |
e9fdf30e-7f0a-4e7a-990c-d0c3ccb48a14 | 8 | private void updateRankCap(String Rank, String RankCap, JComboBox rankcapComboBox) {
oldRankCap = RankCap;
rankcapComboBox.setActionCommand("other");
rankcapComboBox.removeItem("12");
rankcapComboBox.removeItem("11");
rankcapComboBox.removeItem("10");
rankcapComboBox.removeItem("9");
rankcapComboBox.removeItem("6");
rankcapComboBox.removeItem("3");
rankcapComboBox.setEnabled(true);
rankcapComboBox.setActionCommand("RankCap");
Vector<String> rankcapVector = new gen.Rank(Rank).getRankcapVector();
for (int i=0; i <rankcapVector.size() ; i++)
{
rankcapComboBox.addItem(rankcapVector.elementAt(i));
}
int rankInt = Integer.parseInt(Rank);
if (rankInt==11 || rankInt==12)
{
rankcapComboBox.setEnabled(false);
}
for(int i=0; i<rankcapComboBox.getItemCount();i++)
{
if (oldRankCap !=null && oldRankCap.compareTo((String) rankcapComboBox.getItemAt(i))==0)
{
rankcapComboBox.setSelectedItem(rankcapComboBox.getItemAt(i));
}
}
//if old rank is less than 6 and new rank is greater than old rank and oldrankcap is 6 then
if(oldRankCap!=null && Integer.parseInt(Rank)>Integer.parseInt(oldRankCap))
{
rankcapComboBox.setSelectedItem(rankcapComboBox.getItemAt(rankcapComboBox.getItemCount()-1));
}
} |
271e3bf5-3bd4-4ec4-a83c-2ee8a79cef78 | 7 | public void visitFrame(
final int type,
final int nLocal,
final Object[] local,
final int nStack,
final Object[] stack)
{
buf.setLength(0);
switch (type) {
case Opcodes.F_NEW:
case Opcodes.F_FULL:
declareFrameTypes(nLocal, local);
declareFrameTypes(nStack, stack);
if (type == Opcodes.F_NEW) {
buf.append("mv.visitFrame(Opcodes.F_NEW, ");
} else {
buf.append("mv.visitFrame(Opcodes.F_FULL, ");
}
buf.append(nLocal).append(", new Object[] {");
appendFrameTypes(nLocal, local);
buf.append("}, ").append(nStack).append(", new Object[] {");
appendFrameTypes(nStack, stack);
buf.append('}');
break;
case Opcodes.F_APPEND:
declareFrameTypes(nLocal, local);
buf.append("mv.visitFrame(Opcodes.F_APPEND,")
.append(nLocal)
.append(", new Object[] {");
appendFrameTypes(nLocal, local);
buf.append("}, 0, null");
break;
case Opcodes.F_CHOP:
buf.append("mv.visitFrame(Opcodes.F_CHOP,")
.append(nLocal)
.append(", null, 0, null");
break;
case Opcodes.F_SAME:
buf.append("mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null");
break;
case Opcodes.F_SAME1:
declareFrameTypes(1, stack);
buf.append("mv.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] {");
appendFrameTypes(1, stack);
buf.append('}');
break;
}
buf.append(");\n");
text.add(buf.toString());
} |
5376c961-7be2-4fa6-b306-1c2b012e7d3a | 7 | public void transferHeadFiles(BufferedReader consoleInput) throws IOException {
directory.setWorkingDir(ProjectDirectory);
if (HEAD != null) {
for(int i=0; i<HEAD.files.size(); i++) {
String headpath = HeadFilesDirectory + File.separator + HEAD.files.get(i);
String projectpath = ProjectDirectory + File.separator + HEAD.files.get(i);
File headfile = new File(headpath);
File projectfile = new File(projectpath);
if (projectfile.isFile()) {
SHA1 headfileHash = new SHA1(Utilities.FileToByteArray(headfile));
SHA1 projectfileHash = new SHA1(Utilities.FileToByteArray(projectfile));
if (!headfileHash.getSHA1().equals(projectfileHash.getSHA1())) {
boolean validAnswer = false;
System.out.println("#Conflict: \"" + projectfile.getName() + "\" exists already in your project and isn't equal as the file on the server. \n Do you want to override the file with the file from the server or keep the file unmodified? \n Write \"o\" to override or \"u\" to keep the file unmodified");
while (!validAnswer) {
System.out.print("> ");
String answer = consoleInput.readLine();
if (answer.equals("o")) {
validAnswer = true;
directory.putFile(headpath);
} else if (answer.equals("u")) {
validAnswer = true;
} else {
System.out.println(" Please give a valid answer");
}
}
}
} else {
directory.putFile(headpath);
}
}
}
} |
174dda15-82b8-4924-9141-a9b079c58c8b | 9 | public String getEnding(Number aNumber, Case aCase)
{
//Exception for Dat/Abl/Loc pl for filia/dea
if ( (getStem().equalsIgnoreCase("fili") || getStem().equalsIgnoreCase("de") || getStem().equalsIgnoreCase("lup") ||
getStem().equalsIgnoreCase("equ") || getStem().equalsIgnoreCase("simi")) &&
(aCase == Noun.Case.DAT || aCase == Noun.Case.ABL || aCase == Noun.Case.LOC) &&
(aNumber == Noun.Number.PLURAL) )
{
return ALTERNATE_ENDING1;
}
return getEnding(ENDINGS, aNumber, aCase);
} |
51b8f47f-4992-4e6d-a3c2-cf19b3ebd8bb | 1 | public void upkeep(){
for(Creature c : p1.getCritters())
c.setSumSick(false);
} |
918f4e71-9d11-41eb-9055-451235770558 | 5 | private void check_connection(){
Statement stmt;
ResultSet mysql_result;
try{
//Execute Query
stmt = mysql_connection.createStatement();
mysql_result = stmt.executeQuery("SELECT 1 from DUAL WHERE 1=0");
mysql_result.close();
}
catch(NullPointerException e){
System.err.println("MySQL Database not connected!");
}
catch(SQLTransientConnectionException e){
System.err.println("Database connection problem");
if(auto_reconnect){auto_reconnect();}
}
catch(SQLException e){
System.err.println("Database Communications Error");
if(auto_reconnect){auto_reconnect();}
}
finally{
mysql_result = null;
}
} |
4c88af9d-0221-4cb9-9317-ea4a1cd53c90 | 8 | void output( int code, OutputStream outs ) throws IOException
{
cur_accum &= masks[cur_bits];
if ( cur_bits > 0 )
cur_accum |= ( code << cur_bits );
else
cur_accum = code;
cur_bits += n_bits;
while ( cur_bits >= 8 )
{
char_out( (byte) ( cur_accum & 0xff ), outs );
cur_accum >>= 8;
cur_bits -= 8;
}
// If the next entry is going to be too big for the code size,
// then increase it, if possible.
if ( free_ent > maxcode || clear_flg )
{
if ( clear_flg )
{
maxcode = MAXCODE(n_bits = g_init_bits);
clear_flg = false;
}
else
{
++n_bits;
if ( n_bits == maxbits )
maxcode = maxmaxcode;
else
maxcode = MAXCODE(n_bits);
}
}
if ( code == EOFCode )
{
// At EOF, write the rest of the buffer.
while ( cur_bits > 0 )
{
char_out( (byte) ( cur_accum & 0xff ), outs );
cur_accum >>= 8;
cur_bits -= 8;
}
flush_char( outs );
}
} |
82cb15d9-514e-40eb-96b5-edc2aefc9d6f | 3 | private void btnFinalizarPagaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFinalizarPagaActionPerformed
if(JOptionPane.showConfirmDialog(rootPane, "Deseja Salvar?") == 0){
try{
Pagamento paga = new Pagamento();
//Setando os dados e convertendo de text para seus respectivos tipos.
paga.setNome(txtCadNomePaga.getText());
paga.setJuros(Double.parseDouble(txtCadJurosPaga.getText()));
//Criando variavel dao para salvar os dados no BD.
PagamentoDao dao = new PagamentoDao();
//mandando prod para dao.Salvar.
//Mensagem de confirmação!
if(dao.Salvar(paga)){
JOptionPane.showMessageDialog(rootPane, "Salvo com sucesso");
}else{
JOptionPane.showMessageDialog(rootPane, "Erro ao salvar! Consulte o administrador do sistema");
}
//Limpando campos do formularios para o usuarios nao inserir os mesmos dados novamente.
txtCadNomePaga.setText(null);
txtCadJurosPaga.setText(null);
}catch (ExceptionInInitializerError ex) {
Logger.getLogger(frmPagamentoCad.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
JOptionPane.showMessageDialog(rootPane,"Operação Não cancelada!");
}
}//GEN-LAST:event_btnFinalizarPagaActionPerformed |
e4aeca63-3f86-4496-8d14-2167bd9f3a00 | 3 | public T getRandomObject(Random rand)
{
if(!list.isEmpty())
{
int r = rand.nextInt(totalWeight);
Iterator<WeightEntry> i = list.iterator();
while(i.hasNext())
{
WeightEntry e = i.next();
if(e.inRange(r))
{
return e.getObject();
}
}
}
return null;
} |
23d49524-d68d-41cd-93fd-2494d6bfbffd | 2 | public static void decodeToFile(String dataToDecode, String filename)
throws java.io.IOException {
Base64.OutputStream bos = null;
try {
bos = new Base64.OutputStream(
new java.io.FileOutputStream(filename), Base64.DECODE);
bos.write(dataToDecode.getBytes(PREFERRED_ENCODING));
} catch (java.io.IOException e) {
throw e;
} finally {
try {
bos.close();
} catch (Exception e) {
}
}
} |
61fd4987-da78-4ef4-abcd-76894ab8e422 | 0 | public String toCSV() {
return super.toCSV();
} |
3663e8f6-7c51-4475-bd0d-e4911e927120 | 3 | @Override
public void run() {
//timer
long lastTime;
lastTime = System.nanoTime();
long timer;
timer = System.currentTimeMillis();
final double ns;
ns = 1000000000.0 / 60.0;
double delta;
delta = 0;
//ups & fps counter
int frames;
frames = 0;
int updates;
updates = 0;
requestFocus(); //focus the canvas
while (running) {
long now;
now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
//update 60 times per second
while (delta >= 1) {
update();
updates++;
delta--;
}
render();
frames++;
if (System.currentTimeMillis() - timer >= 1000) {
timer += 1000;
// System.out.println(updates + " ups, " + frames + " fps");
frame.setTitle(TITLE + " | " + updates + " ups, " + frames + " fps");
updates = 0;
frames = 0;
}
}
stop();
} |
631f7bcf-5d8b-4e1c-8efc-0dde6d84038a | 1 | public static void main(String args[]) {
/* System.out.println(newLine + "Queue in Java" + newLine);
System.out.println("-----------------------" + newLine);
System.out.println("Adding items to the Queue" + newLine);
//Creating queue would require you to create instannce of LinkedList and assign
//it to Queue
//Object. You cannot create an instance of Queue as it is abstract
Queue queue = new LinkedList();
//you add elements to queue using add method
queue.add("Java");
queue.add(".NET");
queue.add("Javascript");
queue.add("HTML5");
queue.add("Hadoop");
System.out.println("Items in the queue..." + queue);
//You remove element from the queue using .remove method
//This would remove the first element added to the queue, here Java
System.out.println("remove element: " + queue.remove());
//.element() returns the current element in the queue, here when "java" is removed
//the next most top element is .NET, so .NET would be printed.
System.out.println("retrieve element: " + queue.element());
//.poll() method retrieves and removes the head of this queue
//or return null if this queue is empty. Here .NET would be printed and then would
//be removed
//from the queue
System.out.println("remove and retrieve element, null if empty: " + queue.poll());
//.peek() just returns the current element in the queue, null if empty
//Here it will print Javascript as .NET is removed above
System.out.println("retrieve element, null is empty " + queue.peek());*/
Scanner scr = new Scanner(System.in);
while (true) {
System.out.print("Write something : ");
String testss = scr.nextLine();
new Thread(new Test(testss)).start();
//listTest.add(testss);
}
} |
b490a424-199b-4e28-a443-159f9b999086 | 9 | public static void performTests(PrintWriter reporter) {
StudentMaster sm = new StudentMaster("Doug");
Student s = new Student("Doug");
for (int i = 0; i < 101; i++) {
s.addExamGrade(79.9);
sm.addExamGrade(79.9);
}
reporter.print(sm.equals(s));
sm = new StudentMaster("Doug");
s = new Student("Doug");
for (int i = 0; i < 101; i++) {
s.addExamGrade(80.1);
sm.addExamGrade(80.1);
}
sm = new StudentMaster("Doug");
s = new Student("Doug");
for (int i = 0; i < 101; i++) {
s.addExamGrade(80.9);
sm.addExamGrade(80.9);
}
reporter.print(sm.equals(s));
sm = new StudentMaster("Doug");
s = new Student("Doug");
for (int i = 0; i < 101; i++) {
s.addExamGrade(90.1);
sm.addExamGrade(90.1);
}
reporter.print(sm.equals(s));
sm = new StudentMaster("Doug");
s = new Student("Doug");
for (int i = 0; i < 101; i++) {
s.addExamGrade(70.1);
sm.addExamGrade(70.1);
}
reporter.print(sm.equals(s));
sm = new StudentMaster("Doug");
s = new Student("Doug");
for (int i = 0; i < 101; i++) {
s.addExamGrade(69.9);
sm.addExamGrade(69.9);
}
sm = new StudentMaster("Doug");
s = new Student("Doug");
for (int i = 0; i < 101; i++) {
s.addExamGrade(60.1);
sm.addExamGrade(60.1);
}
reporter.print(sm.equals(s));
sm = new StudentMaster("Doug");
s = new Student("Doug");
for (int i = 0; i < 101; i++) {
s.addExamGrade(59.9);
sm.addExamGrade(59.9);
}
reporter.print(sm.equals(s));
s.addExamGrade(-20.);
sm.addExamGrade(-20.);
reporter.print(sm.equals(s));
sm = new StudentMaster("Doug");
s = new Student("Doug");
for (int i = 0; i < 12345; i++) {
double num = Math.random() * 100;
s.addExamGrade(num);
sm.addExamGrade(num);
}
reporter.print(sm.equals(s));
s = new Student("Daniel", 15, 333.);
sm = new StudentMaster("Daniel", 15, 333.);
reporter.print(sm.equals(s));
s.addExamGrade(-20);
sm.addExamGrade(-20);
reporter.print(sm.equals(s));
reporter.println();
reporter.println();
} |
3412a3f4-33b8-4190-a302-31c1f1adf655 | 2 | public boolean hasWhitelistBypassPermission() {
return this.whitelistByPassPermission != null && !this.whitelistByPassPermission.equals("*") && !this.whitelistByPassPermission.equals("");
} |
50270189-6f38-46ea-a0e0-67a53e5a2978 | 8 | public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
if (root.left == null && root.right == null) return true;
if (root.left == null || root.right == null) return false;
if (root.left.val != root.right.val) return false;
TreeNode node = new TreeNode(0);
node.left = root.left.left;
node.right = root.right.right;
if (!isSymmetric(node)) return false;
node.left = root.left.right;
node.right = root.right.left;
if (!isSymmetric(node)) return false;
return true;
} |
bfde7637-3172-4613-b4be-7ab811d3a3d7 | 0 | void show(){
} |
9f2e2883-1df3-4ec8-ba47-178fc7e849b2 | 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(GUI_AdministrarSensores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUI_AdministrarSensores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUI_AdministrarSensores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUI_AdministrarSensores.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 GUI_AdministrarSensores().setVisible(true);
}
});
} |
2296fa70-2ee7-44d9-8a5f-a815f386da88 | 8 | protected LinkedHashMap<Pattern, String> load(File propertyFile) {
LinkedHashMap<Pattern, String> result = new LinkedHashMap<Pattern, String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream(propertyFile), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
if (line.length() == 0) {
continue;
}
char firstChar = line.charAt(0);
if (firstChar == '#' || firstChar == '!') {
continue;
}
int pos = line.indexOf('=');
if (pos < 0) {
continue;
}
String key = line.substring(0, pos);
String value = line.substring(pos + 1, line.length());
int pos2 = line.indexOf('@');
if (pos2 == 0) {
key = key.substring(1);
} else if (pos2 > 0) {
key = Pattern.quote(key.substring(0, pos2))
+ key.substring(pos2);
}
result.put(Pattern.compile(key), value);
}
} catch (IOException e) {
throw new GenException(Message.DOMAGEN9001, e, e);
} finally {
IOUtil.close(reader);
}
return result;
} |
9a9a1ca8-21ca-4184-9558-da79e3c9f2f2 | 9 | public void tfidfFromFile(String queryPath) throws FileNotFoundException{
Scanner sc = new Scanner(new BufferedReader(new FileReader(queryPath)));
String line = sc.nextLine();
// Get Name and Text of document
contents = line.toString().split("\\s+",2);
words = contents[1].split("\\s+");
// Process for document names and contents that are not empty (or just a space)
if (contents[0].length() > 1 && contents[1].length() > 1){
wordCounts = new HashMap<String, Double>();
double tf = 0;
double idf = 0;
maxWordCount = 0;
tfidf = new HashMap<String, Double>();
int count;
double documentCount = (double) docFrequency.getDocumentCount();
// Process each word to get totals
for (int i = 0; i < words.length; i++){
word = words[i];
if (wordCounts.containsKey(word)){
wordCounts.put(word, wordCounts.get(word) + 1.0);
} else {
wordCounts.put(word, 1.0);
}
}
// Get highest word count in the document
for (double value : wordCounts.values()){
maxWordCount = Math.max(maxWordCount, value);
}
// Process each unique word to get tfidf
for (int i = 0; i < words.length; i++){
word = words[i];
if (word.trim().length() > 1){
count = docFrequency.getCount(word);
if (count == 0){
count = 1;
}
idf = Math.log(documentCount / (double) count);
tf = 0.5 + (0.5 * wordCounts.get(word) / maxWordCount);
tfidf.put(word, tf * idf);
}
}
// Optional Steps:
// Sort tfidf
// Cut to top K (maybe)
// Get reducer key based on title
key = new IntWritable();
key.set(contents[0].toLowerCase().trim().charAt(0));
// Store Title
searchTitle = contents[0].toLowerCase().trim();
// Store Contents
searchContents = contents[1];
// Create tfidf string
sb = new StringBuilder(wordCounts.size());
sb.append(contents[0].toLowerCase().trim());
sb.append("|");
for (String key : tfidf.keySet()){
sb.append(key);
sb.append(":");
sb.append(tfidf.get(key));
sb.append(",");
}
tfidfString = sb.toString();
// Emit title + tfidf string
}
} |
92ccfc1a-85d6-4a70-9e70-307b0c95baa0 | 2 | @Override
public Properties getOutputProperties(){
Properties properties = new Properties();
properties.put(NAME,getName());
properties.put(DATE,Utils.toString(date));
properties.put(AMOUNT, amount.toString());
properties.put(COMMUNICATION, communication);
if(counterParty!=null){
properties.put(COUNTERPARTY,counterParty.getName());
}
properties.put(TRANSACTIONCODE,transactionCode);
properties.put(SIGN,isDebit()?"D":"C");
return properties;
} |
49d46458-5cb6-4ecc-971e-40ed0650c339 | 8 | public static /*@pure@*/ int[] stableSort(double[] array){
int[] index = new int[array.length];
int[] newIndex = new int[array.length];
int[] helpIndex;
int numEqual;
array = (double[])array.clone();
for (int i = 0; i < index.length; i++) {
index[i] = i;
if (Double.isNaN(array[i])) {
array[i] = Double.MAX_VALUE;
}
}
quickSort(array,index,0,array.length-1);
// Make sort stable
int i = 0;
while (i < index.length) {
numEqual = 1;
for (int j = i+1; ((j < index.length) && Utils.eq(array[index[i]],
array[index[j]])); j++)
numEqual++;
if (numEqual > 1) {
helpIndex = new int[numEqual];
for (int j = 0; j < numEqual; j++)
helpIndex[j] = i+j;
quickSort(index, helpIndex, 0, numEqual-1);
for (int j = 0; j < numEqual; j++)
newIndex[i+j] = index[helpIndex[j]];
i += numEqual;
} else {
newIndex[i] = index[i];
i++;
}
}
return newIndex;
} |
deba5bc1-5884-44e4-bf9c-7dd397a7e42e | 9 | @Override
public Integer value(final Matrix<TypeOfValue> matrix) {
int column = this._column;
int lowRow = this._lowerRowBound;
int highRow = this._upperRowBound;
Operator<TypeOfValue, TypeOfValue, Boolean> comparer = this._comparer;
if (highRow < lowRow)
throw new IllegalStateException("The bounds on the rows are incorrectly specified.");
else if (matrix == null)
throw new NullPointerException("Matrix not properly specified.");
else if (matrix.getLastColumn() < column ||
column < matrix.getFirstColumn())
throw new IllegalArgumentException("Matrix does not contain the specified column.");
else if (lowRow < matrix.getFirstRow() || matrix.getLastRow() < highRow)
throw new IllegalArgumentException("Matrix does not contain the specified rows.");
int index = lowRow - 1;
TypeOfValue value = null;
for (int row = lowRow; row <= highRow; row++)
{
TypeOfValue v = matrix.getValue(row, column);
if (value == null || comparer.value(value, v))
{
index = row;
value = v;
}
}
return index;
} |
d7af586f-66da-49ac-b5f8-8c8f839c22ae | 2 | @Override
public boolean isNotebookCorrect(Notebook memory) {
boolean isCorrect = true;
int numTestsSoFar = 0;
while (isCorrect && numTestsSoFar < numTests) {
final NotebookTester notebookTester = notebookTesterFactory.produceNotebookTester();
isCorrect &= notebookTester.isNotebookCorrect(memory);
messageFromTest = notebookTester.getMessageFromTest();
numTestsSoFar++;
}
return isCorrect;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.