method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
0569fa3e-4688-4ce7-bbda-406473225f6e | 8 | protected void processStyleBlocks(List<String> styleBlocks) {
if(generateStatistics) {
for(String block : styleBlocks) {
statistics.getOriginalMetrics().setInlineStyleSize(statistics.getOriginalMetrics().getInlineStyleSize() + block.length());
}
}
if(compressCss) {
for(int i = 0; i < styleBlocks.size(); i++) {
styleBlocks.set(i, compressCssStyles(styleBlocks.get(i)));
}
} else if(generateStatistics) {
for(String block : styleBlocks) {
statistics.setPreservedSize(statistics.getPreservedSize() + block.length());
}
}
if(generateStatistics) {
for(String block : styleBlocks) {
statistics.getCompressedMetrics().setInlineStyleSize(statistics.getCompressedMetrics().getInlineStyleSize() + block.length());
}
}
} |
0d9789e3-e02f-402a-a590-e441a7f2bd9d | 4 | public static boolean endsWithIgnoreCase(String str, String suffix) {
if (str == null || suffix == null) {
return false;
}
if (str.endsWith(suffix)) {
return true;
}
if (str.length() < suffix.length()) {
return false;
}
String lcStr = str.substring(str.length() - suffix.length()).toLowerCase();
String lcSuffix = suffix.toLowerCase();
return lcStr.equals(lcSuffix);
} |
9c1a8a90-787a-41ab-bc7c-360f0fea5475 | 7 | private void parseMaskAndAdjustmentData(PsdInputStream stream) throws IOException {
int size = stream.readInt();
assert size == 0 || size == 20 || size == 36;
if (size > 0) {
Mask mask = new Mask();
mask.top = stream.readInt();
mask.left = stream.readInt();
mask.bottom = stream.readInt();
mask.right = stream.readInt();
mask.defaultColor = stream.readByte() & 0xff;
assert mask.defaultColor == 0 || mask.defaultColor == 255;
byte flags = stream.readByte();
mask.relative = (flags & 0x01) != 0;
mask.disabled = ((flags >> 1) & 0x01) != 0;
mask.invert = ((flags >> 2) & 0x01) != 0;
if (size == 20) {
stream.skipBytes(2);
} else {
byte realFlags = stream.readByte();
mask.relative = (realFlags & 0x01) != 0;
mask.disabled = ((realFlags >> 1) & 0x01) != 0;
mask.invert = ((realFlags >> 2) & 0x01) != 0;
mask.defaultColor = stream.readByte() & 0xff;
assert mask.defaultColor == 0 || mask.defaultColor == 255;
mask.top = stream.readInt();
mask.left = stream.readInt();
mask.bottom = stream.readInt();
mask.right = stream.readInt();
}
if (handler != null) {
handler.maskLoaded(mask);
}
}
} |
6c824c97-0eec-4615-ac7c-a48323020e72 | 2 | @SuppressWarnings("unchecked")
private void sendEndGameMove(){
check(isMyTurn() && currentMove == VERIFY);
String winnerId = coderId;
List<String> feedbackHistory = (List<String>) state.get(FEEDBACKHISTORY);
String lastFeedback = feedbackHistory.get(feedbackHistory.size()-1);
if (lastFeedback.equals("4b0w")) {
winnerId = guesserId;
}
this.sendEndGameOperation(coderId, guesserId, winnerId);
} |
05383b11-e90e-41bc-9808-fd044d255862 | 0 | public int getGraphZ() {
return graphZ;
} |
a22dabbc-4b3e-4a91-bcf0-1908d201bfe0 | 6 | * @param itemSlot The itemSlot
* @param newItemId The new item After Drinking
* @param healType The type of poison it heals
*/
public void potionPoisonHeal(int itemId, int itemSlot, int newItemId, int healType) {
c.attackTimer = c.getCombat().getAttackDelay(c.getItems().getItemName(c.playerEquipment[c.playerWeapon]).toLowerCase());
if(c.duelRule[5]) {
c.sendMessage("Potions has been disabled in this duel!");
return;
}
if(!c.isDead && System.currentTimeMillis() - c.foodDelay > 2000) {
if(c.getItems().playerHasItem(itemId, 1, itemSlot)) {
c.sendMessage("You drink the "+c.getItems().getItemName(itemId).toLowerCase()+".");
c.foodDelay = System.currentTimeMillis();
// Actions
if(healType == 1) {
//Cures The Poison
} else if(healType == 2) {
//Cures The Poison + protects from getting poison again
}
c.startAnimation(0x33D);
c.getItems().deleteItem(itemId, itemSlot, 1);
c.getItems().addItem(newItemId, 1);
requestUpdates();
}
}
} |
f5b4727e-d7a7-4be5-9063-5856b9083fd8 | 7 | static private String stripControlCharacters(String s) {
StringBuffer sb = new StringBuffer(s.length() + 1);
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch > 256 || ch == '\n' || ch == '\t' || ch == '\r' || ch == 226) {
sb.append(' ');
continue;
}
//System.out.println(" ch: " + ch + " (int)ch: " + (int)ch + " Character.isISOControl(ch): " + Character.isISOControl(ch));
if ((int) ch < 129)
sb.append(ch);
else
sb.append(' ');
}
return sb.toString();
} |
81e2b6b4-be5b-489a-8c00-e1244e37a37f | 7 | static final int method1760(int i, int j, int k) {
if (k == -2) {
return 0xbc614e;
}
if (k == -1) {
if (i >= 2) {
if (i > 126) {
i = 126;
}
} else {
i = 2;
}
return i;
}
i = i * (0x7f & k) >> 7;
if (i < 2) {
i = 2;
} else if (i > 126) {
i = 126;
}
if (j != 7) {
method1764(-120);
}
return i + (0xff80 & k);
} |
f3144655-db92-49a9-825a-6ef4af5f5676 | 0 | protected void end() {} |
ab08353a-caad-474b-a29d-ad92aa6e22c0 | 3 | public void trimData( int maxLength )
{
if( audioData == null || maxLength == 0 )
audioData = null;
else if( audioData.length > maxLength )
{
byte[] trimmedArray = new byte[maxLength];
System.arraycopy( audioData, 0, trimmedArray, 0,
maxLength );
audioData = trimmedArray;
}
} |
ee4eca6e-74cc-45ea-a237-fabaf60a06cd | 2 | public String getCode(){
String str = "";
String itemCode = item.getCode();
if(itemCode != ""){
String nextTemp = Tree.getNextTemp();
str = item.getCode() +
this.printLineNumber(true) +
nextTemp + " := " + item.place + "\n" +
this.printLineNumber(true) + "push := " + nextTemp + "\n";
}
else{
str = this.printLineNumber(true) +
"push := " + item.place + "\n";
}
ArgumentListExpression itemsList = this.items;
if(itemsList != null)
str = str + itemsList.getCode();
return str;
} |
ad0200bc-5814-490e-9125-7fa51b1547e2 | 6 | private synchronized void resize(int newSizeColumns, int newSizeRows)
{
TerminalCharacter [][]newCharacterMap = new TerminalCharacter[newSizeRows][newSizeColumns];
for(int y = 0; y < newSizeRows; y++)
for(int x = 0; x < newSizeColumns; x++)
newCharacterMap[y][x] = new TerminalCharacter(
' ',
convertColorToAWT(Color.WHITE, false),
convertColorToAWT(Color.BLACK, false),
false,
false,
false);
synchronized(resizeMutex) {
for(int y = 0; y < size().getRows() && y < newSizeRows; y++) {
for(int x = 0; x < size().getColumns() && x < newSizeColumns; x++) {
newCharacterMap[y][x] = this.characterMap[y][x];
}
}
this.characterMap = newCharacterMap;
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
terminalFrame.pack();
}
});
onResized(newSizeColumns, newSizeRows);
}
} |
49a8b890-1c27-4cd3-a271-610cc7a5691f | 8 | @Override
public Map<String, String> validateForCreate(Map<String, Object> properties) throws Exception {
Connection conn = ConnectionManager.getInstance().getConnection();
Map<String, String> erros = new HashMap<String, String>();
if (properties != null) {
Long viagemFk = (Long) properties.get("viagem_fk");
if (viagemFk == null) {
erros.put("viagem_fk", "Campo obrigatório!");
}
Long categoriaFk = (Long) properties.get("categoria_fk");
if (viagemFk == null) {
erros.put("categoria_fk", "Campo obrigatório!");
}
byte[] comprovate = (byte[]) properties.get("comprovate");
if (comprovate == null) {
erros.put("comprovate", "Campo obrigatório!");
}
int valor = (int) properties.get("valor");
if (valor == 0) {
erros.put("valor", "Campo obrigatório!");
}
Date dataCompra = (Date) properties.get("data_compra");
if (dataCompra == null) {
erros.put("data_compra", "Campo obrigatório!");
}
Time horaCompra = (Time) properties.get("hora_compra");
if (horaCompra == null) {
erros.put("hora_compra", "Campo obrigatório!");
}
int valorRealAutorizado = (int) properties.get("valor_autorizado");
if (valorRealAutorizado == 0) {
erros.put("valor_autorizado", "Campo obrigatório!");
}
}
return erros;
} |
1fef9d5f-ee75-418e-a932-22c0f3dd333c | 1 | public void cleanup() {
Collection windows = configurationToTraceWindow.values();
Iterator it = windows.iterator();
while (it.hasNext())
((TraceWindow) it.next()).dispose();
configurationToTraceWindow.clear();
} |
b92ea0e9-064e-42ae-9ee3-3154b7682ecb | 1 | public void setMaxSpeed(double maxSpeed) {
if(_negated) {
_minSpeed = maxSpeed;
} else {
_maxSpeed = maxSpeed;
}
} |
ebb5548f-c6e9-4f21-a52d-c825f0d90b0c | 8 | @Override
public synchronized int compare(Integer i1, Integer i2) {
Queue<PutTask> putQueue1 = putMap.get(i1);
Queue<GetTask> getQueue1 = getMap.get(i1);
Queue<PutTask> putQueue2 = putMap.get(i2);
Queue<GetTask> getQueue2 = getMap.get(i2);
Long time1 = timerMap.get(i1);
Long time2 = timerMap.get(i2);
long currentTime = System.currentTimeMillis();
long term1 = (putQueue1 != null ? putQueue1.size() : 0) + (getQueue1 != null ? getQueue1.size() : 0) + (time1 != null ? (currentTime - time1) : 0);
long term2 = (putQueue2 != null ? putQueue2.size() : 0) + (getQueue2 != null ? getQueue2.size() : 0) + (time2 != null ? (currentTime - time2) : 0);
return (term1 - term2) > 0 ? 1 : (term1 - term2) < 0 ? -1 : 0;
} |
0f663cde-b15c-4bff-a376-960225638fa3 | 6 | public void LItemClothesAll(String folder) throws Exception {
SPProgressBarPlug.setStatus("Adding clothes to pool");
NumberFormat formatter = new DecimalFormat("000");
LVLI LItemClothesAll = (LVLI) SkyProcStarter.merger.getLeveledItems().get(new FormID("106662Skyrim.esm"));
OTFT FarmClothesRandom = (OTFT) SkyProcStarter.merger.getOutfits().get(new FormID("09D4B5Skyrim.esm"));
for (int bodies = 1; bodies < RBS_Main.amountBodyTypes; bodies++) {
String s = formatter.format(bodies);
LVLI targetllist = (LVLI) SkyProcStarter.patch.makeCopy(LItemClothesAll, LItemClothesAll.getEDID() + "RBS_F" + s);
List<LeveledEntry> listEntries = targetllist.getFlattenedEntries();
targetllist.clearEntries();
for (ARMO patchedArmor : SkyProcStarter.patch.getArmors()) {
if (patchedArmor.getEDID().contains("Clothes") && patchedArmor.getEDID().contains(s)) {
targetllist.addEntry(patchedArmor.getForm(), 1, 1);
}
}
targetllist.set(LeveledRecord.LVLFlag.UseAll, false);
// SkyProcStarter.patch.addRecord(targetllist);
OTFT targetOutfit2 = (OTFT) SkyProcStarter.patch.makeCopy(FarmClothesRandom, "ClothesAllRBS_F" + s);
targetOutfit2.clearInventoryItems();
targetOutfit2.addInventoryItem(targetllist.getForm());
for (LVLI llist2 : SkyProcStarter.patch.getLeveledItems()) {
if (llist2.getEDID().equals("LItemBootsAllRBS" + s)) {
targetOutfit2.addInventoryItem(llist2.getForm());
}
}
}
} |
1d46ee01-6cb8-4a57-91ac-002a755e069b | 2 | public static void main(String[] args)
{
int[][] data = new int[2][2];
int[][] data2 = new int[2][2];
data[0][0] = 1;
data[0][1] = 3;
data[1][0] = 2;
data[1][1] = 4;
data2[0][0] = 0;
data2[0][1] = 1;
data2[1][0] = 5;
data2[1][1] = 6;
int[][] res = new int[2][2];
res = mul(data,data2);
for (int i = 0; i < res.length; i++)
{
for (int j = 0; j < res.length; j++) {
System.out.print(res[i][j] + " ");
}
System.out.println();
}
} |
c7ecc146-f625-46bc-832c-be61cc6452fb | 7 | public void ascend(){
eraseCenter();
for(int col = 0; col < board.getWidth(); col++){
int[] values = new int[board.getLength()];
for(int i = 0; i < values.length; i++){
values[i] = -2;
}
for(int row = 0; row < board.getLength();row++){
if(board.getValue(row, col) != -2){
if(board.isValid(row-2, col)){
values[row-2] = board.getValue(row, col);
}
else if(board.isValid(row-1,col)){
values[values.length-1] = board.getValue(row, col);
}
else{
values[values.length -2] = board.getValue(row,col);
}
}
}
for(int i = 0; i < values.length; i++){
board.setValue(i, col, values[i]);
}
}
markCenter();
} |
a847a2f2-6708-48dc-aab6-beda02d00d25 | 9 | public void update(float deltaTimeElapsedMs) {
// Moves character or scrolls background accordingly
if (speedX < 0) {
centerX += Util.factorByElapsedTimeMs(speedX, deltaTimeElapsedMs);
}
if (speedX == 0 || speedX < 0) {
bg1.setSpeedX(0);
bg2.setSpeedX(0);
}
if (centerX <= 200 && speedX > 0) {
centerX += speedX;
}
if (speedX > 0 && centerX > 200) {
bg1.setSpeedX(-MOVESPEED / 5);
bg2.setSpeedX(-MOVESPEED / 5);
}
// Updates Y Position
centerY += Util.factorByElapsedTimeMs(speedY, deltaTimeElapsedMs);
// Handles Jumping
speedY += 1;
if (speedY > 3) {
jumped = true;
}
// prevents going beyond coordinate of 0
if (centerX + speedX <= 20) {
centerX = 21;
}
Rectangle entirePlayerRect = boundaries.get(0);
entirePlayerRect.setRect(centerX - 20, centerY - 20, 40, 40);
Rectangle leftSidePlayerRect = boundaries.get(1);
leftSidePlayerRect.setRect(centerX - 20, centerY - 20, 20, 40);
Rectangle rightSidePlayerRect = boundaries.get(2);
rightSidePlayerRect.setRect(centerX, centerY - 20, 20, 40);
perimeter.setRect(centerX - 110, centerY - 110, 180, 180);
// footLeft.setRect(centerX - 50, centerY + 20, 50, 15);
// footRight.setRect(centerX, centerY + 20, 50, 15);
currentSprite.getAnimation().update(50);
} |
4333a6a5-0526-4a69-a6f7-c51524b4bfd1 | 7 | Class286_Sub4(OpenGlToolkit var_ha_Sub2, Class83 class83) {
super(var_ha_Sub2);
aBoolean6233 = false;
do {
try {
aClass83_6242 = class83;
if (((Class83) aClass83_6242).aClass258_Sub1_1443 == null
|| !(((OpenGlToolkit) ((Class286) this).aHa_Sub2_3684)
.aBoolean7791)
|| !(((OpenGlToolkit) ((Class286) this).aHa_Sub2_3684)
.aBoolean7783))
break;
Class242 class242
= (WidgetVariable.method3249
(35633, -21, ((Class286) this).aHa_Sub2_3684,
"uniform float time;\nuniform float scale;\nvarying vec3 wvVertex;\nvarying float waterDepth;\nvoid main() {\nwaterDepth = gl_MultiTexCoord0.z;\nvec4 ecVertex = gl_ModelViewMatrix*gl_Vertex;\nwvVertex.x = dot(gl_NormalMatrix[0], ecVertex.xyz);\nwvVertex.y = dot(gl_NormalMatrix[1], ecVertex.xyz);\nwvVertex.z = dot(gl_NormalMatrix[2], ecVertex.xyz);\ngl_TexCoord[0].x = dot(gl_TextureMatrix[0][0], gl_MultiTexCoord0)*scale;\ngl_TexCoord[0].y = dot(gl_TextureMatrix[0][1], gl_MultiTexCoord0)*scale;\ngl_TexCoord[0].z = time;\ngl_TexCoord[0].w = 1.0;\ngl_FogFragCoord = 1.0-clamp((gl_Fog.end+ecVertex.z)*gl_Fog.scale, 0.0, 1.0);\ngl_Position = ftransform();\n}\n"));
Class242 class242_6_
= (WidgetVariable.method3249
(35632, -53, ((Class286) this).aHa_Sub2_3684,
"varying vec3 wvVertex;\nvarying float waterDepth;\nuniform vec3 sunDir;\nuniform vec4 sunColour;\nuniform float sunExponent;\nuniform vec2 waveIntensity;\nuniform float waveExponent;\nuniform float breakWaterDepth;\nuniform float breakWaterOffset;\nuniform sampler3D normalSampler;\nuniform samplerCube envMapSampler;\nvoid main() {\nvec4 wnNormal = texture3D(normalSampler, gl_TexCoord[0].xyz).rbga;\nwnNormal.xyz = 2.0*wnNormal.xyz-1.0;\nvec3 wnVector = normalize(wvVertex);\nvec3 wnReflection = reflect(wnVector, wnNormal.xyz);\nvec3 envColour = textureCube(envMapSampler, wnReflection).rgb;\nvec4 specularColour = sunColour*pow(clamp(-dot(sunDir, wnReflection), 0.0, 1.0), sunExponent);\nfloat shoreFactor = clamp(waterDepth/breakWaterDepth-breakWaterOffset*wnNormal.w, 0.0, 1.0);\nfloat waveFactor = pow(1.0-shoreFactor, waveExponent)-0.5;\nwaveFactor = -4.0*waveFactor*waveFactor+1.0;\nfloat ndote = dot(wnVector, wnNormal.xyz);\nfloat fresnel = pow(1.0-abs(ndote), 1.0);\nvec4 surfaceColour = mix(vec4(envColour, fresnel*shoreFactor), (waveIntensity.x*wnNormal.wwww)+waveIntensity.y, waveFactor)+specularColour*shoreFactor;\ngl_FragColor = vec4(mix(surfaceColour.rgb, gl_Fog.color.rgb, gl_FogFragCoord), surfaceColour.a);\n}\n"));
aClass337_6234
= Class318_Sub1_Sub5_Sub2.method2493((((Class286) this)
.aHa_Sub2_3684),
-1,
(new Class242[]
{ class242,
class242_6_ }));
aBoolean6237 = aClass337_6234 != null;
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
("er.<init>("
+ (var_ha_Sub2 != null
? "{...}" : "null")
+ ','
+ (class83 != null ? "{...}"
: "null")
+ ')'));
}
break;
} while (false);
} |
5a62c3a6-c22f-4097-9229-15c50e5d47d7 | 4 | public BufferedImage crop(int x, int y, int height, int width) {
//Outside of image
if (x > img.getWidth() || y > img.getHeight())
return null;
if (height + y > img.getHeight())
height = img.getHeight() - y;
if (width + x > img.getWidth())
width = img.getWidth() - x;
return img.getSubimage(x, y, width, height);
} |
dfba209d-78af-4337-b13f-4d17278e7910 | 6 | static public void release() {
if (!injected) return;
try {
// Define
boolean fa;
boolean ff;
Field flagsList;
Field flagsListMod;
// Get: fields required for reflection
flagsList = DefaultFlag.class.getDeclaredField("flagsList");
flagsListMod = Field.class.getDeclaredField("modifiers");
// Check: field access
fa = flagsList.isAccessible();
ff = Modifier.isFinal(flagsList.getModifiers());
// Access: set accessible
if (fa) {
flagsList.setAccessible(true);
}
// Access: set non-final
if (ff) {
flagsListMod.setAccessible(true);
flagsListMod.setInt(flagsList, flagsList.getModifiers() & ~Modifier.FINAL);
}
// Set: field
flagsList.set(null, getOriginalFlags());
// Reset access changes
if (ff) {
flagsListMod.setInt(flagsList, flagsList.getModifiers() | Modifier.FINAL);
flagsListMod.setAccessible(false);
}
if (fa) {
flagsList.setAccessible(false);
}
// Done!
injected = false;
WorldRegionsPlugin.getInstanceLogger().info("Released flags!");
} catch (Throwable ex) {
WorldRegionsPlugin.getInstanceLogger().log(Level.SEVERE, "Unable to release flags!", ex);
}
} |
477ba30c-5441-4512-9001-1e37500c1a9b | 8 | public Object readMap(AbstractHessianInput in)
throws IOException
{
String name = null;
String type = null;
String description = null;
boolean isRead = false;
boolean isWrite = false;
boolean isIs = false;
while (! in.isEnd()) {
String key = in.readString();
if ("name".equals(key))
name = in.readString();
else if ("attributeType".equals(key))
type = in.readString();
else if ("description".equals(key))
description = in.readString();
else if ("isRead".equals(key))
isRead = in.readBoolean();
else if ("isWrite".equals(key))
isWrite = in.readBoolean();
else if ("is".equals(key))
isIs = in.readBoolean();
else {
in.readObject();
}
}
in.readMapEnd();
try {
MBeanAttributeInfo info;
info = new MBeanAttributeInfo(name, type, description,
isRead, isWrite, isIs);
return info;
} catch (Exception e) {
throw new IOException(String.valueOf(e));
}
} |
6e6a89ff-1109-42df-86b4-634918721d5b | 4 | public static boolean isBlank(String str){
if(str==null){
return true;
}
if(str.trim().length()<1){
return true;
}
if(str.trim().equals("")){
return true;
}
if(str.trim().toLowerCase().equals("null")){
return true;
}
return false;
} |
305f9e5c-0917-4222-ad22-4f0d88c98904 | 9 | @Override
public final boolean incrementToken() throws java.io.IOException {
if (!input.incrementToken()) {
return false;
}
char[] buffer = termAtt.termBuffer();
final int bufferLength = termAtt.termLength();
final String type = typeAtt.type();
if (type == APOSTROPHE_TYPE && // remove 's
bufferLength >= 2 &&
buffer[bufferLength-2] == '\'' &&
(buffer[bufferLength-1] == 's' || buffer[bufferLength-1] == 'S')) {
// Strip last 2 characters off
termAtt.setTermLength(bufferLength - 2);
} else if (type == ACRONYM_TYPE) { // remove dots
int upto = 0;
for(int i=0;i<bufferLength;i++) {
char c = buffer[i];
if (c != '.')
buffer[upto++] = c;
}
termAtt.setTermLength(upto);
}
return true;
} |
df9a9309-5d0e-4f38-a3ee-8f3db962d3b2 | 3 | private void deleteClienteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteClienteButtonActionPerformed
if(tablaClientes.getSelectedRow() >= 0){
askWind a = new askWind(new javax.swing.JFrame(),true,"Seguro que desea eliminar este cliente?");
a.setLocationRelativeTo(null);
a.show();
if(a.getValue() == true){
try{
taller.eliminarCliente(clientes.get(tablaClientes.getSelectedRow()).getNombre());
initTablasClientes();
initTablasCoches();
}
catch(Exception e){
excepWind w = new excepWind(new javax.swing.JFrame(),true,e.getMessage());
w.show();
}
}
a.dispose();
}
}//GEN-LAST:event_deleteClienteButtonActionPerformed |
5a422b93-9dc5-4106-bb6e-9bd4bd30fda3 | 6 | public double classifierData(List<Feat> classifiers) throws IOException{
Features f = new Features(0, 0);
f.integralImages(f.FACES, f.numbFaces, f.integralFaces);
System.out.println(new Date() + "--- Integralfaces. Done");
f.integralImages(f.NONFACES, f.numbNonFaces, f.integralNonFaces);
System.out.println(new Date() + "--- Integralnonfaces. Done");
for(Feat cl : classifiers){
//Point endPoint = new Point(cl.position.getFirst() , cl.size.getFirst());
//get Rectangle data
switch(cl.shape){
case HOR2:
break;
case HOR3:
break;
case VERT2:
break;
case VERT3:
break;
case QUAD:
break;
}
}
return 0.0;
} |
6df2573c-b66d-48c0-ae26-df1d8b4a256a | 3 | public char nextClean() throws JSONException {
for (;;) {
char c = this.next();
if (c == 0 || c > ' ') {
return c;
}
}
} |
75109ff1-d28a-49ce-9830-fbafa2d3b4af | 4 | private static String validateSong(String artist, String title) {
HashMap<String, String> songList = DataManager.getSongMap().get(artist);
for(String songFromMap : songList.keySet()) {
int levDist = StringUtils.getLevenshteinDistance(songFromMap.toUpperCase(), title.toUpperCase());
double ratio = (songFromMap.length() - levDist + 0.0) / (songFromMap.length() + 0.0);
if(ratio == 1.0) {
Logger.LogToStatusBar(songFromMap + " exactly matches");
return songFromMap;
}
else if(ratio >= 0.5) {
ArrayList<String> matches = DataManager.getSongMatches().get(artist + " " + title);
if(matches == null) {
matches = new ArrayList<String>();
matches.add(songFromMap);
DataManager.getSongMatches().put(artist + " " + title, matches);
}
else {
matches.add(songFromMap);
DataManager.getSongMatches().remove(artist + " " + title);
DataManager.getSongMatches().put(artist + " " + title, matches);
}
}
}
return "";
} |
cf53d5c6-9d70-4642-9b50-692bc695bf53 | 6 | public DayTimeDurationAttribute(boolean negative, long days, long hours,
long minutes, long seconds,
int nanoseconds)
throws IllegalArgumentException {
super(identifierURI);
this.negative = negative;
this.days = days;
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
this.nanoseconds = nanoseconds;
// Convert all the components except nanoseconds to milliseconds
// If any of the components is big (too big to be an int),
// use the BigInteger class to do the math so we can detect
// overflow.
if ((days > Integer.MAX_VALUE) || (hours > Integer.MAX_VALUE) ||
(minutes > Integer.MAX_VALUE) || (seconds > Integer.MAX_VALUE)) {
if (big24 == null) {
big24 = BigInteger.valueOf(24);
big60 = BigInteger.valueOf(60);
big1000 = BigInteger.valueOf(1000);
bigMaxLong = BigInteger.valueOf(Long.MAX_VALUE);
}
BigInteger bigDays = BigInteger.valueOf(days);
BigInteger bigHours = BigInteger.valueOf(hours);
BigInteger bigMinutes = BigInteger.valueOf(minutes);
BigInteger bigSeconds = BigInteger.valueOf(seconds);
BigInteger bigTotal = bigDays.multiply(big24).add(bigHours)
.multiply(big60).add(bigMinutes).multiply(big60)
.add(bigSeconds).multiply(big1000);
// If the result is bigger than Long.MAX_VALUE, we have an
// overflow. Indicate an error (should be a processing error,
// since it can be argued that we should handle gigantic
// values for this).
if (bigTotal.compareTo(bigMaxLong) == 1)
throw new IllegalArgumentException("total number of " +
"milliseconds " +
"exceeds Long.MAX_VALUE");
// If no overflow, convert to a long.
totalMillis = bigTotal.longValue();
} else {
// The numbers are small, so do it the fast way.
totalMillis = ((((((days * 24) + hours) * 60) + minutes) * 60) +
seconds) * 1000;
}
} |
4c83c4c3-9168-431c-963f-c05aad9b681f | 1 | public static void asm_iorwf(Integer befehl, Prozessor cpu) {
Integer w = cpu.getW();
Integer f = getOpcodeFromToBit(befehl, 0, 6);
Integer erg = w | cpu.getSpeicherzellenWert(f);
if(getOpcodeFromToBit(befehl, 7, 7) == 1) {
cpu.setSpeicherzellenWert(f, erg, true);
}
else {
cpu.setW(erg, true);
}
cpu.incPC();
} |
a6c0adf7-8a54-48c8-bdd5-c3cdcaad66ed | 0 | public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
} |
632d602c-2c12-4041-8b37-57a7731055c4 | 2 | public void sendMail(String mailServer, String from, String[] to, String subject, String messageBody, String attachmentPath, String attachmentName) throws MessagingException, AddressException
{
boolean debug = false;
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.EnableSSL.enable","true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", mailServer);
props.put("mail.debug", "true");
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(debug);
try
{
Transport bus = session.getTransport("smtp");
bus.connect();
Message message = new MimeMessage(session);
//X-Priority values are generally numbers like 1 (for highest priority), 3 (normal) and 5 (lowest).
message.addHeader("X-Priority", "1");
message.setFrom(new InternetAddress(from));
InternetAddress[] addressTo = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++)
addressTo[i] = new InternetAddress(to[i]);
message.setRecipients(Message.RecipientType .TO, addressTo);
message.setSubject(subject);
BodyPart body = new MimeBodyPart();
// body.setText(messageBody);
body.setContent(messageBody,"text/html");
BodyPart attachment = new MimeBodyPart();
DataSource source = new FileDataSource(attachmentPath);
attachment.setDataHandler(new DataHandler(source));
attachment.setFileName(attachmentName);
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
multipart.addBodyPart(attachment);
message.setContent(multipart);
Transport.send(message);
System.out.println("Sucessfully Sent mail to All Users");
bus.close();
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
} |
f4cd90a9-0e1a-4d8f-8f92-b606be6d3903 | 6 | public double getWinningOdds(int a, int d) {
attackers = a;
defenders = d;
outcome = new double[attackers + 1][defenders + 1];
for (int i = 0; i < attackers + 1; i++)
for (int j = 0; j < defenders + 1; j++)
outcome[i][j] = -1.0;
outcome[attackers][defenders] = 1.0;
double winOdds = 0.0;
double likelyOutcome = -1.0;
for (int i = attackers; i >= 2; i--)
{
winOdds += getOdds(i, 0);
if (outcome[i][0] > likelyOutcome)
likelyOutcome = outcome[i][0];
}
for (int i = 1; i <= defenders; i++)
{
if (outcome[1][i] > likelyOutcome)
likelyOutcome = outcome[1][i];
}
return winOdds;
} |
2d14357f-89d5-460a-815f-18fdbcc880b8 | 0 | @Override
public void actionPerformed(ActionEvent e) {
quit();
} |
5dfe2800-8ae1-4d9d-b00a-87b4610e1140 | 5 | public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
String name = "";
String host = "";
int port = 0;
int i = 0;
int money;
try//name, host, and then port -- lines 43-73 checks the args[] for info
{
name = args[i];
i++;
}
catch(ArrayIndexOutOfBoundsException e)
{
//name = DEFAULT_TEST_NAME;//tester
System.err.println("Please enter a name when attempting to join a poker table.");
System.err.println("ERROR - No player name specified.");
System.exit(0);//cannot have no name
}
try
{
host = args[i];
i++;
}
catch(ArrayIndexOutOfBoundsException e)
{
host = DEFAULT_HOST;
}
try
{
port = Integer.parseInt(args[i]);
}
catch(ArrayIndexOutOfBoundsException e)
{
port = DEFAULT_PORT;
}
if(port > 65535 || port < 0)
port = DEFAULT_PORT;//port must be within limits
money = DEFAULT_MONEY;//TODO tester
Player newPlayer = new Player(host, port, name, money);//create new player
newPlayer.accept();
} |
d8fbfaf2-84bf-4567-90d3-b748c226b211 | 6 | public boolean hit(PlayerState param,Mario mario){
// TODO :: IMPLEMENT PROJECTILE INFO FOR THE KOOPA
mario.rebound();
if(flying){
flying=false;
if(getDy()<0)
setDy(0);
return false;
}else if(!shell){
shell=true;
if(getDy()<0)
setDy(0);
setDx(0);
return false;
}else{
// hit when shell
if(getDx()==0.0){
if(facingRight)
setDx(shellSpeed);
else
setDx(-shellSpeed);
}else
setDx(0.0);
return false;
}
} |
f3916ded-4d91-4c74-8660-061ead12a5ea | 9 | public void keyPressed(KeyEvent e) {
switch(e.getExtendedKeyCode()) {
case KeyEvent.VK_LEFT:
//System.out.println("lewo");
action = "right";
Pang.game.ihLudzik.currentFrame=4;
if (x_ > 0) v_x_ =-speed_; break;
case KeyEvent.VK_UP:
//System.out.println("gora");
if (y_ > 0) /*v_y_ =-speed_;*/ break;
case KeyEvent.VK_RIGHT:
//System.out.println("prawo");
action = "right";
Pang.game.ihLudzik.currentFrame=4;
if (x_ < Config.DEF_WIDTH-Size.valueOf(size_)*res) v_x_ =speed_; break;
case KeyEvent.VK_DOWN:
//System.out.println("dol");
if (y_ < Config.DEF_HEIGHT) /*v_y_ =speed_;*/ break;
case KeyEvent.VK_SPACE:
//System.out.println("strzal");
shoot(); break;
}
} |
5dc3ae59-59e8-4f86-93e3-9e4f1fb64207 | 6 | private void playBoard()
{
do
{
playGame();
this.tryAgain = false;
while(this.tryAgain == false)
{
System.out.print("\n Play again (Y/N): ");
this.theUsersInput = this.someInput.next();
System.out.print("\n ") ;
// we get a String in, we only want the first character
// a String is like an array, the first position starts at 0
// theLetterIn is of type char
this.theLetterIn = this.theUsersInput.charAt(0);
//now comparing two characters
if( (this.theLetterIn == 'Y') || ( this.theLetterIn == 'y') )
{
this.tryAgain = true;
}
else if((this.theLetterIn == 'N') || ( this.theLetterIn == 'n'))
{
System.exit(0);
}else
{
System.out.print("\n Invalid Entry");
System.out.println(" \n Press enter to continue");
this.someInput.nextLine();
}
}
}
while(this.tryAgain);
}//EOM-playBoard() |
5f3222f4-239f-4022-85a4-bb8c237178a9 | 3 | private boolean playerStartPositionsHasNoTeleporter(Grid grid) {
List<Teleporter> teleporters = getTeleportersOfGrid(grid);
for (Player p : grid.getAllPlayersOnGrid())
for (Teleporter teleport : teleporters)
if (grid.getElementPosition(teleport).equals(p.getBeginPosition()))
return false;
return true;
} |
171ca4ae-21f7-4399-b697-4d138e85ad8c | 7 | private void dumpMemory(int address, int size) {
String tmp = "";
String tmp2 = "";
String t;
System.out.println("Dumping memory: " + address);
for (int i = 0; i < size; i++) {
t = Integer.toString(memory[i + address] & 0xff, 16);
if (t.length() < 2)
t = "0" + t;
tmp = tmp + t + " ";
if (i % 4 == 3) tmp += " ";
if (memory[i + address] > 32 && memory[i + address] < 99)
tmp2 += (char) memory[i + address];
else
tmp2 += ".";
if (i % 16 == 15) {
String adr = Integer.toString(address + i - 15, 16);
while (adr.length() < 4)
adr = "0" + adr;
System.out.println(adr + " " + tmp + " " + tmp2);
tmp = "";
tmp2 = "";
}
}
} |
6f7482a0-f46f-40bc-a130-325053ca3433 | 9 | private boolean verifierChamps(){
String erreurMsg = "";
boolean result = true;
if (nomTF.getText().length() < 3)
{
erreurMsg += "Le nom doit au moins avoir trois caracteres.\n";
result = false;
}
if (prenomTF.getText().length() < 3)
{
erreurMsg += "Le prenom doit au moins avoir trois caracteres.\n";
result = false;
}
if (!utils.Validators.NumeroTelValidator(telephoneTF.getText()) )
{
erreurMsg += "Le numéro de téléphone n'est pas valide.\n";
result = false;
}
else if (!utils.Validators.TailleNumTelValidator(telephoneTF.getText()) )
{
erreurMsg += "Le numéro de téléphone est supérieur a 8 chiffre .\n";
result = false;
}
else if (!utils.Validators.NomPrenomValidator(nomTF.getText()) )
{
erreurMsg += "Le Nom est invalide.\n";
result = false;
}
else if (!utils.Validators.NomPrenomValidator(prenomTF.getText()) )
{
erreurMsg += "Le Prennom est invalide.\n";
result = false;
}
else if (!utils.Validators.DateValidator(dateNaissanceTF.getText()) )
{
erreurMsg += "Le Format de la date est incorecte .\n";
result = false;
}
else if (!utils.Validators.ConfirmerMotDePasseValidator(passwordTF.getText(),confirmationPasswordTF.getText()))
{
erreurMsg += "la confirmation du mot de passe est inccorecte \n";
result = false;
}
if (!result)
JOptionPane.showMessageDialog(null, erreurMsg);
return result;
} |
93aa445d-e7d1-4f58-8077-f7bf34ab63b1 | 2 | private void ouvrirLecture(){
if(tamponSocket == null) {
try{ tamponSocket = new BufferedReader(new InputStreamReader(socket.getInputStream())); }
catch(IOException io){ io.printStackTrace(); }
}
} |
7b6749a1-038f-48f5-ab41-195053e92cdd | 4 | protected void createBuffers( SSLSession session ) {
int appBufferMax = session.getApplicationBufferSize();
int netBufferMax = session.getPacketBufferSize();
if( inData == null ) {
inData = ByteBuffer.allocate( appBufferMax );
outCrypt = ByteBuffer.allocate( netBufferMax );
inCrypt = ByteBuffer.allocate( netBufferMax );
} else {
if( inData.capacity() != appBufferMax )
inData = ByteBuffer.allocate( appBufferMax );
if( outCrypt.capacity() != netBufferMax )
outCrypt = ByteBuffer.allocate( netBufferMax );
if( inCrypt.capacity() != netBufferMax )
inCrypt = ByteBuffer.allocate( netBufferMax );
}
inData.rewind();
inData.flip();
inCrypt.rewind();
inCrypt.flip();
outCrypt.rewind();
outCrypt.flip();
} |
98378344-45d9-46b5-be0d-eb07ee0a90c8 | 8 | public void getCommitter()
{
networkController.SendMessage("getPromotion#" + clientId + "," + clientType + "," + userCommitter + "," + userName);
clientType = userCommitter;
committer = true;
cleanLabels();
if(observer)
getObserver.setVisible(true);
if(contributor)
getContributor.setVisible(true);
if(reporter)
getReporter.setVisible(true);
if(tester)
getTester.setVisible(true);
if(leader)
getLeader.setVisible(true);
actualRole = ActualRole.Committer;
actualRoleLabel.setLocation(540, 20);
actualRoleLabel.setText("Current Role: " + actualRole);
actualRoleLabel.setVisible(true);
if (numVotedSatisfactory >= gameSettings[numCommittedSettings] && !leader) {
getPromotedLeader.setVisible(true);
}
gameInfoRow1Label.setText("Vote " + gameSettings[numCommittedSettings] + " times correctly");
gameInfoRow1Label.setSize(150, 20);
gameInfoRow1Label.setLocation(550, 90);
gameInfoRow1Label.setVisible(true);
gameInfoRow2Label.setText("to get promoted as a Project Leader.");
gameInfoRow2Label.setLocation(510, 110);
gameInfoRow2Label.setSize(225, 20);
gameInfoRow2Label.setVisible(true);
gameInfoRow3Label.setText("You are now a Committer. When there is a");
gameInfoRow3Label.setLocation(495, 160);
gameInfoRow3Label.setSize(240, 20);
gameInfoRow3Label.setVisible(true);
gameInfoRow4Label.setText("voting you can vote for committing values.");
gameInfoRow4Label.setLocation(500, 180);
gameInfoRow4Label.setSize(240, 20);
gameInfoRow4Label.setVisible(true);
if (conflictExists) {
gameInfoRow5Label.setText("Voting at the Position [" + conflictX + "][" + conflictY + "] for the value " + cells[conflictX][conflictY].current);
gameInfoRow5Label.setLocation(495, 205);
gameInfoRow5Label.setSize(250, 20);
gameInfoRow5Label.setVisible(true);
voteCommiting.setVisible(true);
voteRemove.setVisible(true);
} else {
gameInfoRow5Label.setText("There is not a voting at the moment.");
gameInfoRow5Label.setLocation(510, 205);
gameInfoRow5Label.setSize(225, 20);
gameInfoRow5Label.setVisible(true);
}
gameInfoRow6Label.setText("Number of votes corrects: " + numVotedSatisfactory);
gameInfoRow6Label.setLocation(530, 280);
gameInfoRow6Label.setSize(200, 20);
gameInfoRow6Label.setVisible(true);
repaint();
} |
d18200ad-5619-432b-ba27-640c27aa688e | 6 | protected Account ReadAccount(String accountFile, String id) throws ClassNotFoundException{
ArrayList<Account> accs = new ArrayList<Account>();
Account acc = null;
Object temp = null;
try {
obji = new ObjectInputStream(new FileInputStream(accountFile));
try {
temp = obji.readObject();
} catch (IOException e) {
System.err.println("File Read Failed! @ DataFileHandler in ReadAccount");
}
if (temp instanceof AccountList) {
accs = ((AccountList) temp).getAccs();
}
for(int i = 0; i < accs.size(); i++){
acc = accs.get(i);
if(acc.getUsername() == id){
break;
}
}
obji.close();
return acc;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
obji.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return null;
}
} |
424fd820-432f-46be-8b03-9bccbdc37597 | 6 | @Override
public String getColumnName(int column){
String name = "??";
switch (column){
case 0:
name ="produktId";
break;
case 1:
name ="produktNavn";
break;
case 2:
name ="fareNiveau";
break;
case 3:
name ="salgsPris";
break;
case 4:
name ="kostPris";
break;
case 5:
name ="avance";
break;
}
return name;
} |
8fb8c14d-5129-406c-b21f-7405607e15ba | 8 | private void setSizes(Container parent) {
int count = parent.getComponentCount();
Insets insets = parent.getInsets();
if (parent instanceof JPanel) {
insets = new Insets(0, 0, 0, 0);
}
int insetWidth = 0;
int insetHeight = 0;
if (insets != null) {
insetWidth = insets.left + insets.right;
insetHeight = insets.top + insets.bottom;
}
Dimension dimension = null;
preferredWidth = 0;
preferredHeight = 0;
minWidth = 0;
minHeight = 0;
for (int index = 0; index < count; index++) {
Component component = parent.getComponent(index);
if (component != null && component.isVisible()) {
dimension = component.getPreferredSize();
if (dimension == null) {
dimension = component.getMinimumSize();
}
if (preferredWidth < component.getX() + dimension.width + hgap) {
preferredWidth = component.getX() + dimension.width + hgap;
}
if (preferredHeight < component.getY() + dimension.height + vgap) {
preferredHeight = component.getY() + dimension.height + vgap;
}
}
}
preferredWidth += hgap;
preferredWidth += insetWidth;
preferredHeight += vgap;
preferredHeight += insetHeight;
minHeight = preferredHeight;
minWidth = preferredWidth;
} |
f7667e1b-fd81-4e94-b7cb-c0a76aecb244 | 0 | public String getItemName() {
return this.itemName;
} |
9a2a00c5-efa9-4f82-8386-edf4b15bb59d | 6 | private RandomGenerator createRandomGenerator(long seed, Class<? extends RandomGenerator> randGenClass, RandomGenerator... params) {
try {
Constructor<? extends RandomGenerator> constructor ;
if ( params == null || params.length == 0 ) {
constructor = null ;
}
else {
constructor = randGenClass.getConstructor( RandomGenerator[].class ) ;
}
RandomGenerator randGen = constructor != null ? constructor.newInstance( (Object)params ) : randGenClass.newInstance() ;
randGen.initialize(seed);
return randGen ;
}
catch (Exception e) {
throw new IllegalStateException(e) ;
}
} |
7e6db21d-0435-43ad-99c7-6ef7e9f71220 | 6 | public int lengthOfLastWord(String s) {
if (s == null) return 0;
int j = s.length() -1;
while (j>=0 && s.charAt(j) == ' ') j --;
if (j == -1) return 0;
int i = j;
while (i >= 0 && s.charAt(i) != ' ') i --;
return j -i;
} |
bc738a05-a1b2-4e32-a44e-3c75022c36b9 | 6 | public MergeIterators(Comparator<E> comp, Iterator<E>[] itList,
E[] nextContainer) {
if (itList == null)
throw new IllegalArgumentException("Null array of iterators");
if (comp == null)
throw new IllegalArgumentException("Null comparator");
if (nextContainer == null)
throw new IllegalArgumentException("Null next container");
if (itList.length != nextContainer.length)
throw new IllegalArgumentException(
"Iterator array and next container must have the same size");
this.comp = comp;
this.itList = itList;
this.nextList = nextContainer;
for (int i = 0; i < itList.length; i++) {
Iterator<E> it = itList[i];
if (it.hasNext()) {
nextList[i] = it.next();
} else {
nextList[i] = null;
}
}
advance();
} |
687a7fbc-bb08-4197-a62e-889f6cba95ce | 3 | public static void notEmpty(Collection<?> collection, String message) {
if (collection == null || collection.isEmpty()) {
throw new IllegalArgumentException(message);
}
} |
864dfc57-ca6d-432d-b049-35b49ca7d418 | 6 | public static boolean check(Serializable object) {
// TODO Auto-generated method stub
if (object instanceof Grammar)
{
Grammar g=(Grammar) object;
Production[] p=g.getProductions();
//check first 3 productions to make sure this grammar is from conversion
int count=0;
if (p.length < 3)
return false;
for (int i=0; i<3; i++)
{
String lhs=p[i].getLHS();
String rhs=p[i].getRHS();
if (lhs.equals(LHS_DEFAULT[i]) && rhs.equals(RHS_DEFAULT[i]))
{
count++;
}
}
if (count==3)
return true;
else
return false;
}
return false;
} |
2468e695-755f-4b65-ba42-7d0455fc80ce | 5 | final FEMValue _compileArrayAsValue_() throws IllegalArgumentException {
if (!this._arrayEnabled_) throw this._illegal_(null, " Wertlisten sind nicht zulässig.");
final List<FEMValue> result = new ArrayList<>();
this.skip();
if (this._compileType_() == ']') {
this.skip();
return FEMArray.EMPTY;
}
while (true) {
final FEMValue value = this._compileParamAsValue_();
result.add(value);
switch (this._compileType_()) {
case ';': {
this.skip();
this._compileType_();
break;
}
case ']': {
this.skip();
return FEMArray.from(result);
}
default: {
throw this._illegal_(null, " Zeichen «;» oder «]» erwartet.");
}
}
}
} |
2cb52919-e09a-4ba6-a525-9a72ba0992f2 | 5 | @Override
public void actionPerformed(ActionEvent e) {
if( e.getSource() == boton_alta_turno ){
Controlador.getInstance().accion(EventoNegocio.GUI_ALTA_TURNO,GUIPrincipal_Turno.this);
}
else if( e.getSource() == boton_baja_turno){
Controlador.getInstance().accion(EventoNegocio.GUI_BAJA_TURNO, GUIPrincipal_Turno.this);
}
else if( e.getSource() == boton_modificar_turno){
Controlador.getInstance().accion(EventoNegocio.GUI_MODIFICAR_TURNO, GUIPrincipal_Turno.this);
}
else if (e.getSource() == boton_mostrar_turno) {
Controlador.getInstance().accion(EventoNegocio.GUI_MOSTRAR_TURNO, GUIPrincipal_Turno.this);
}else if (e.getSource() == boton_mostrar_lista_turnos) {
Controlador.getInstance().accion(EventoNegocio.GUI_MOSTRAR_LISTA_TURNOS, GUIPrincipal_Turno.this);
}
} |
56e133ca-d4d9-4d86-95e3-d3de024097db | 4 | static private void validateDirectory (File aDirectory) throws FileNotFoundException {
if (aDirectory == null) {
throw new IllegalArgumentException("Directory should not be null.");
}
if (!aDirectory.exists()) {
throw new FileNotFoundException("Directory does not exist: " + aDirectory);
}
if (!aDirectory.isDirectory()) {
throw new IllegalArgumentException("Is not a directory: " + aDirectory);
}
if (!aDirectory.canRead()) {
throw new IllegalArgumentException("Directory cannot be read: " + aDirectory);
}
} |
e208b866-3a5c-4881-b911-d390ae5e0581 | 4 | public Trajectory<TobiiFrame> getClosestTrajectoryTo(long timestamp) {
Trajectory<TobiiFrame> bestTraj = null;
long bestDelta = Long.MAX_VALUE;
for(Trajectory<TobiiFrame> traj : trajectories.values()) {
Map.Entry<Long, TobiiFrame> startFrame = traj.getFrameEqualHigher(0L);
if(null == startFrame) {
// Somebody was wildly jamming the spacebar, no frames recorded between one Space and the next
continue;
}
long trajStart = startFrame.getKey();
long currDelta = Math.abs( trajStart - timestamp );
if( currDelta < bestDelta ) {
bestDelta = currDelta;
bestTraj = traj;
}
}
if(bestDelta == Long.MAX_VALUE) {
System.err.println("Could not find a matching Tobii timestamp; skipping.");
return null;
} else {
System.err.println("For Track-It timestamp " + timestamp + ", found match at Tobii timestamp " + bestDelta + " away.");
return bestTraj;
}
} |
d54f3325-450e-441b-b840-cfc52b3e7a4b | 5 | private boolean supressImport(JClass clazz, JClass c) {
if (clazz instanceof JNarrowedClass) {
clazz = clazz.erasure();
}
if (clazz instanceof JAnonymousClass) {
clazz = clazz._extends();
}
if(clazz._package().isUnnamed())
return true;
final String packageName = clazz._package().name();
if(packageName.equals("java.lang"))
return true; // no need to explicitly import java.lang classes
if (clazz._package() == c._package()) {
// inner classes require an import stmt.
// All other pkg local classes do not need an
// import stmt for ref.
// no need to explicitly import a class into itself
return isNestedInSelf(clazz, c);
}
return false;
} |
23b9ed23-a19c-4ad3-8e30-8edb170e0e88 | 9 | public static String getPath(int startX, int startY, int endX, int endY, TileGrid grid) {
String out = "";
openList = new ArrayList<Node>();
closedList = new ArrayList<Node>();
openList.add(new Node(grid.getTile(startX, startY),null));
Pathfinder.endX = endX;
Pathfinder.endY = endY;
Node goalNode = new Node(grid.getTile(endX, endY),null);
Node currentNode;
System.out.println("Start: " + startX + " " + startY + " End: " + endX + " " + endY);
while(true) {
currentNode = getBestNode(openList);
if (currentNode == null) System.out.println("Pathfinder: current node is NULL");
if (currentNode.equals(goalNode)) {
break;
}
openList.remove(currentNode);
closedList.add(currentNode);
//N
if (grid.getTile(currentNode.tile.x,currentNode.tile.y-1) != null) {
Node newNode = new Node(grid.getTile(currentNode.tile.x,currentNode.tile.y-1),currentNode);
checkNode(newNode);
}
//E
if (grid.getTile(currentNode.tile.x+1,currentNode.tile.y) != null) {
Node newNode = new Node(grid.getTile(currentNode.tile.x+1,currentNode.tile.y),currentNode);
checkNode(newNode);
}
//S
if (grid.getTile(currentNode.tile.x,currentNode.tile.y+1) != null) {
Node newNode = new Node(grid.getTile(currentNode.tile.x,currentNode.tile.y+1),currentNode);
checkNode(newNode);
}
//W
if (grid.getTile(currentNode.tile.x-1,currentNode.tile.y) != null) {
Node newNode = new Node(grid.getTile(currentNode.tile.x-1,currentNode.tile.y),currentNode);
checkNode(newNode);
}
}
while(currentNode.parent != null) {
out += currentNode.parentDirection();
currentNode = currentNode.parent;
}
String reversedOut = "";
for (int i = out.length() - 1; i >= 0; i--) {
reversedOut += out.charAt(i);
}
System.out.println("Path: " + reversedOut);
return(reversedOut);
} |
e041a81a-d7c7-49da-91cc-7c35e7ce0744 | 2 | private void miAddDiscActionPerformed(ActionEvent e) {
if (Manager.getInstance().getCurrentProfile() == null) {
JOptionPane.showMessageDialog(null, "No profile has been selected.");
return;
}
Object[] discNames = Manager.getInstance().getDiscNames().toArray();
String selectedDisc = (String) JOptionPane.showInputDialog(this,
"Select the disc.",
"Add Disc to Profile",
JOptionPane.QUESTION_MESSAGE,
null,
discNames,
discNames[0]);
if (selectedDisc == null) { return; }
Disc disc = Manager.getInstance().getDiscs().getDisc(selectedDisc);
Manager.getInstance().getCurrentProfile().addDiscToBag(disc);
updateProfile();
} |
14141407-7163-4f94-a5e4-8b3eeb14e276 | 6 | private static boolean loadIntoSubSystem() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(bos);
} catch (Exception e) {
return false;
}
try {
oos.writeObject(m_tmp);
} catch (Exception e) {
return false;
}
try {
oos.flush();
} catch (Exception e) {
return false;
}
try {
oos.close();
} catch (Exception e) {
return false;
}
try {
bos.close();
} catch (IOException e) {
return false;
}
byte [] byteData = bos.toByteArray();
Mod m = null;
ByteArrayInputStream bais = new ByteArrayInputStream(byteData);
try {
m = (Mod) new ObjectInputStream(bais).readObject();
} catch (Exception e) {
return false;
}
mods.add(m);
return true;
} |
96be73a3-8dde-48db-b86b-d91fe37a9ad2 | 4 | public void nextStep(){
MyHex current = nexts.pollLast();
current.visit();
ArrayList<MyHex> k = m.getNeighbors(current).getAllTrimmed();
for(MyHex h : k)
if(!h.hasBeenVisited() && !nexts.contains(h))
nexts.push(h);
//canvas.paintOne(geo, m, current.x(), current.y());
canvas.paintAll(geo, m);
if(nexts.isEmpty()){
this.stop();
return;
}
} |
2d685c2c-2d43-43ac-887c-e6dffe1e3580 | 1 | private void addSprite(TileMap map,
Sprite hostSprite, int tileX, int tileY)
{
if (hostSprite != null) {
// clone the sprite from the "host"
Sprite sprite = (Sprite)hostSprite.clone();
// center the sprite
sprite.setX(
TileMapRenderer.tilesToPixels(tileX) +
(TileMapRenderer.tilesToPixels(1) -
sprite.getWidth()) / 2);
// bottom-justify the sprite
sprite.setY(
TileMapRenderer.tilesToPixels(tileY + 1) -
sprite.getHeight());
// add it to the map
map.addSprite(sprite);
}
} |
fae13e40-74a7-42cd-9e0f-e1984a7f35d6 | 0 | public void setState(State state) {
this.state = state;
} |
b68aecf0-c202-463d-9686-b5445696a56f | 3 | public void run() {
// Get config data
ConfigManager cm = new ConfigManager();
// Connect to server through RMI port 1099.
Rmi rmi = null;
try {
Registry registry = LocateRegistry.getRegistry(
cm.getServerIp(), 1099);
rmi = (Rmi) registry.lookup("pcs");
} catch (RemoteException | NotBoundException e) {
JOptionPane.showMessageDialog(null,
"Cannot connect to server. Please restart system.");
e.printStackTrace();
System.exit(0);
}
// Keep fetching new data every half a minute from the server.
while (true) {
try {
RmiData socketData = rmi.getData(username, password);
socketData.saveToFile();
clientView.updateViews(); // it will automatically take the
// data from the saved file
Thread.sleep(30000); // check every 30 seconds
} catch (InterruptedException | RemoteException e) {
// If there was an error getting data from server
JOptionPane
.showMessageDialog(null,
"Lost connection with server. Please restart system.");
e.printStackTrace();
System.exit(0);
}
}
} |
d2aa75e7-9056-4277-878a-98a777159000 | 2 | @Override
public OutputStream getOutputStream() throws IOException {
switch (failValue) {
case 0:
return new OutputStream() {
@Override
public void write(int b) throws IOException {
}
};
case 1:
return null;
default:
throw new IOException();
}
} |
a935b37a-7d2d-4de4-ae37-20637a6af2dd | 4 | public static void addTile(Tile t) {
if(allTiles != null) {
for(int i=0;i<allTiles.length;i++) {
if(allTiles[i]==null) {
allTiles[i] = t;
return;
} else {
if(allTiles[i].getTileId().equalsIgnoreCase(t.getTileId())) {
return;
}
}
}
}
} |
02809aee-f6e3-4ded-b6ca-6a8d0f484dd1 | 9 | public double computeDynamicCutoff() {
{ IncrementalPartialMatch self = this;
{ IncrementalPartialMatch parent = ((IncrementalPartialMatch)(self.parent));
double cutoff = 0.0;
if (parent != null) {
if (parent.kind == Logic.KWD_AND) {
{ double pcutoff = parent.dynamicCutoff;
double totweight = parent.totalWeight;
double propweight = self.propositionWeight(self.controlFrame.proposition);
double weight = ((propweight == Stella.NULL_FLOAT) ? 1.0 : (((propweight < 0.1) ? 0.1 : propweight)));
double maxother = (totweight - parent.accumulatedWeight) - weight;
double unscaledcutoff = ((pcutoff * totweight) - parent.accumulatedScore) - maxother;
cutoff = unscaledcutoff / weight;
}
}
else {
cutoff = parent.dynamicCutoff;
}
if ((cutoff < 0.0) &&
(!self.controlFrame.reversePolarityP)) {
cutoff = 0.0;
}
else if ((cutoff > 0.0) &&
self.controlFrame.reversePolarityP) {
cutoff = 0.0;
}
else if (!(self.controlFrame.reversePolarityP == parent.controlFrame.reversePolarityP)) {
cutoff = 0 - cutoff;
}
}
return (cutoff);
}
}
} |
e622ed71-fe52-4093-8f68-0e6cdd469fa6 | 6 | private void putResize (K key, int value) {
// Check for empty buckets.
int hashCode = key.hashCode();
int index1 = hashCode & mask;
K key1 = keyTable[index1];
if (key1 == null) {
keyTable[index1] = key;
valueTable[index1] = value;
if (size++ >= threshold) resize(capacity << 1);
return;
}
int index2 = hash2(hashCode);
K key2 = keyTable[index2];
if (key2 == null) {
keyTable[index2] = key;
valueTable[index2] = value;
if (size++ >= threshold) resize(capacity << 1);
return;
}
int index3 = hash3(hashCode);
K key3 = keyTable[index3];
if (key3 == null) {
keyTable[index3] = key;
valueTable[index3] = value;
if (size++ >= threshold) resize(capacity << 1);
return;
}
push(key, value, index1, key1, index2, key2, index3, key3);
} |
546e31fd-f0de-46c4-8042-0926e2762ac5 | 3 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StorySkeleton other = (StorySkeleton) obj;
return ID == other.ID;
} |
805a8e7d-c1b4-4bcf-aab6-942c31a2792c | 8 | HideToSystemTray(){
super("SystemTray test");
System.out.println("creating instance");
try{
System.out.println("setting look and feel");
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exception e){
System.out.println("Unable to set LookAndFeel");
}
if(SystemTray.isSupported()){
System.out.println("system tray supported");
tray=SystemTray.getSystemTray();
Image image = Toolkit.getDefaultToolkit().getImage("/Users/administrator/Desktop/Screen shot 2012-01-21 at 7.12.05 PM.png");
ActionListener exitListener=new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Exiting....");
System.exit(0);
}
};
PopupMenu popup=new PopupMenu();
MenuItem defaultItem=new MenuItem("Exit");
defaultItem.addActionListener(exitListener);
popup.add(defaultItem);
defaultItem=new MenuItem("Open");
defaultItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//tray.remove(trayIcon);
setVisible(true);
repaint();
setVisible(true);
System.out.println("Open");
}
});
popup.add(defaultItem);
trayIcon=new TrayIcon(image, "SystemTray Demo", popup);
trayIcon.setImageAutoSize(true);
}else{
System.out.println("system tray not supported");
}
addWindowStateListener(new WindowStateListener() {
public void windowStateChanged(WindowEvent e) {
System.out.println("-----:"+e.getNewState());
if(e.getNewState()==ICONIFIED){
try {
tray.add(trayIcon);
setVisible(false);
System.out.println("added to SystemTray");
} catch (AWTException ex) {
System.out.println("unable to add to tray");
}
}
if(e.getNewState()==7){
try{
tray.add(trayIcon);
setVisible(false);
System.out.println("added to SystemTray");
}catch(AWTException ex){
System.out.println("unable to add to system tray");
}
}
if(e.getNewState()==MAXIMIZED_BOTH){
tray.remove(trayIcon);
setVisible(true);
System.out.println("Max both");
System.out.println("Tray icon removed");
}
if(e.getNewState()==NORMAL){
tray.remove(trayIcon);
setVisible(true);
System.out.println("Max NORMAL");
System.out.println("Tray icon removed");
}
}
});
setIconImage(Toolkit.getDefaultToolkit().getImage("Duke256.png"));
setVisible(true);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} |
b1d96d26-fc36-4e95-af12-a4411abf92bd | 9 | public void logic(){
//̹ƶ
if( clientTank.getType()==Tank.BLACK_TANK ){
clientTank.active(selectKey, tankSpeed+BLACK_BUFF,SCREEN_WIDTH,SCREEN_HEIGHT);
}
else{
clientTank.active(selectKey, tankSpeed,SCREEN_WIDTH,SCREEN_HEIGHT);
}
//
if( fire==true ){
clientTank.fire();
fire = false;
}
//ӵƶ
if( clientTank.getType()==Tank.BLACK_TANK ){
for(Bullet b:clientTank.getBullets()){
b.active(bulletSpeed+BLACK_BUFF);
}
}
else{
for(Bullet b:clientTank.getBullets()){
b.active(bulletSpeed);
}
}
//ɾԽӵ
for(int i=0; i<clientTank.getBullets().size(); i++){
if( !clientTank.getBullets().get(i).inRange(SCREEN_WIDTH, SCREEN_HEIGHT) ){
clientTank.getBullets().remove(i);
break;
}
}
//ҪϢ
clientTank.setClientMessage(message);
//Լ̹ݸӷõҵ̹
sendAndGet();
//Լޱӵ
for(Tank tank:tanks){
clientTank.hit(tank.getBullets(),bulletDamage);
}
//Լӵ
for(Bullet b:clientTank.getBullets()){
b.hit(tanks);
}
} |
4d01e434-8c84-4271-b24b-e79a4b48d38b | 1 | private String getPassword()
{
JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel(AutoAppro.messages.getString("bar2auto_passwd_content"));
JPasswordField pass = new JPasswordField();
panel.add(label, BorderLayout.PAGE_START);
panel.add(pass, BorderLayout.CENTER);
int valid = JOptionPane.showConfirmDialog(null, panel, AutoAppro.messages.getString("bar2auto_passwd_title"),
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (valid != JOptionPane.OK_OPTION)
return null;
return new String(pass.getPassword());
} |
d47a1ec1-61ee-49a3-8360-71e59c53c2a4 | 7 | @Override
public void actionPerformed(ActionEvent e) {
enableApply.setEnabled(false);
disableApply.setEnabled(false);
button.setEnabled(false);
if(e.getSource().equals(enableApply)) {
new Thread(new Runnable() {
@Override
public void run() {
try {
AdminClient.client.enableGPS();
JOptionPane.showMessageDialog(SetupGPS.this, "The GPS has been successfully enabled.");
} catch(IllegalAccessError e) {
JOptionPane.showMessageDialog(SetupGPS.this, "Selected GPS is already enabled.", "Error", JOptionPane.ERROR_MESSAGE);
} catch (SocketTimeoutException e) {
JOptionPane.showMessageDialog(SetupGPS.this, "The connection is down.", "Error", JOptionPane.ERROR_MESSAGE);
Authentication authentication = new Authentication(parent);
authentication.setLocation(SetupGPS.this.getX() - SetupGPS.this.getWidth(), SetupGPS.this.getY());
parent.getContentPane().add(authentication, 0);
Utilities.transitionEffect(SetupGPS.this, authentication, parent, true);
SwitchServerWindow s = new SwitchServerWindow();
s.requestFocus();
}
enableApply.setEnabled(true);
disableApply.setEnabled(true);
button.setEnabled(true);
}
}).start();
}else if(e.getSource().equals(disableApply)) {
new Thread(new Runnable() {
@Override
public void run() {
try {
AdminClient.client.disableGPS();
JOptionPane.showMessageDialog(SetupGPS.this, "The GPS has been successfully disabled.");
} catch(IllegalAccessError e) {
JOptionPane.showMessageDialog(SetupGPS.this, "Selected GPS is already disabled.", "Error", JOptionPane.ERROR_MESSAGE);
} catch (SocketTimeoutException e) {
JOptionPane.showMessageDialog(SetupGPS.this, "The connection is down.", "Error", JOptionPane.ERROR_MESSAGE);
Authentication authentication = new Authentication(parent);
authentication.setLocation(SetupGPS.this.getX() - SetupGPS.this.getWidth(), SetupGPS.this.getY());
parent.getContentPane().add(authentication, 0);
Utilities.transitionEffect(SetupGPS.this, authentication, parent, true);
SwitchServerWindow s = new SwitchServerWindow();
s.requestFocus();
}
enableApply.setEnabled(true);
disableApply.setEnabled(true);
button.setEnabled(true);
}
}).start();
} else if(e.getSource().equals(button)) {
Menu m = new Menu(parent, "resources/Menu.png");
m.setLocation(SetupGPS.this.getX() - SetupGPS.this.getWidth(), SetupGPS.this.getY());
parent.getContentPane().add(m, 0);
Utilities.transitionEffect(SetupGPS.this, m, parent, true);
}
} |
27fc2240-9372-4d64-9519-18e0474fa100 | 5 | public static double[] MethodNewton(double y[]) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
double[] x = new double[func.length];
x = Arrays.copyOf(y, y.length);
//Количество итераций
int k = 10;
//Точность
// System.out.println("Точность итераций: ");
double e1 = 1e-6;
double e2 = 1e-6;
for (int i = 0; i < k; i++) {
double[] F = discrepancy(x, func);
double[][] J = Jacobian(x, dfunc);
double[] cloneOfX = MethodOfGauss.copyMatrix(x);
MethodOfGauss.Gauss(J, F);
double[] dx = MethodOfGauss.reverseGauss(J, F);
for (int j = 0; j < x.length; j++) {
x[j] -= dx[j];
}
double d1 = MethodOfGauss.rate(discrepancy(x, func));
double d2 = rate(x,cloneOfX);
// System.out.print("k= " + i);
// System.out.println("| d1=" + d1 + ", d2= " + d2);
if (d1 < e1 && d2 < e2) {
k = i;
break;
}
}
for (int i = 0 ; i < x.length; i++) {
// System.out.print(x[i] + " ");
}
// System.out.println("\n" + "k = " + k);
return x;
} |
f3aee664-9968-402f-8971-ac4f61978fc6 | 2 | public void placeUnits(Player player, Dimension minimumRange, Dimension maximumRange) {
for (Unit unit : player.getUnits()) {
int x, y;
do {
x = MathUtil.randomInteger(minimumRange.width, maximumRange.width);
y = MathUtil.randomInteger(minimumRange.height, maximumRange.height);
} while(!grid[x][y].isEmpty());
//TODO: Place units nonrandomly, somehow.
//In the meantime, don't test this code with too many units.
grid[x][y].setUnit(unit);
}
} |
bfc3200a-f4aa-4a73-b301-9b921854c03a | 0 | public FileItem createItem(String fieldName, String contentType, boolean isFormField, String fileName)
{
return new MonitoredDiskFileItem(fieldName, contentType, isFormField, fileName, getSizeThreshold(), getRepository(), listener);
} |
60dca688-fdfe-4308-9dbd-29440fdc97f9 | 4 | private void endCircle(String to) {
if (to.equals("slide"))
slide.addEntity(circle);
else if (to.equals("quizslide"))
quizSlide.addEntity(image);
else if (to.equals("scrollpane"))
scrollPane.addEntity(image);
else if (to.equals("feedback"))
quizSlide.addFeedback(image);
} |
29b1369d-2ff7-4540-9542-a1c4f036fa9a | 5 | final public CycList andForm(boolean requireEOF) throws ParseException, java.io.IOException, UnsupportedVocabularyException {
CycList sentences = null;
CycList val = new CycList();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case AND_CONSTANT:
jj_consume_token(AND_CONSTANT);
break;
case AND_GUID_CONSTANT:
jj_consume_token(AND_GUID_CONSTANT);
break;
default:
jj_la1[5] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
val.add(getCycAccess().and);
sentences = sentenceList(false);
if (sentences != null) { val.addAll(sentences); }
eof(requireEOF);
{if (true) return val;}
throw new Error("Missing return statement in function");
} |
3791a486-6d93-4089-bed8-2dfce78ab1b0 | 9 | @Override
public String List_file_url3(String id) {
String texto_html = "";
try {
this.conn = FactoryConnectionDB.open(FactoryConnectionDB.ORACLE);
String sql = "SELECT NO_ARCHIVO,NO_ARCHIVO_ORIGINAL FROM RHTV_CONTRATO_ADJUNTO where ID_CONTRATO='" + id.trim() + "'";
ResultSet rs = this.conn.query(sql);
while (rs.next()) {
String tipo = rs.getString("NO_ARCHIVO").substring(rs.getString("NO_ARCHIVO").length() - 3, rs.getString("NO_ARCHIVO").length());
if (tipo.trim().equals("PDF") || tipo.equals("OCX") || tipo.equals("DOC")) {
if (tipo.equals("OCX") || tipo.equals("DOC")) {
texto_html = texto_html + "<a class='mustang-gallery' title='" + rs.getString("NO_ARCHIVO_ORIGINAL") + "' href='" + Url_Archivo + "Contratos_Adjuntos/" + rs.getString("NO_ARCHIVO") + "'><img src='" + Url_Archivo + "Contratos_Adjuntos/' style='width:100px;height:100px;' class='borde'><br>" + rs.getString("NO_ARCHIVO_ORIGINAL") + "</a>";
} else {
texto_html = texto_html + "<a class='mustang-gallery' title='" + rs.getString("NO_ARCHIVO_ORIGINAL") + "' href='" + Url_Archivo + "Contratos_Adjuntos/" + rs.getString("NO_ARCHIVO") + "'><img src='" + Url_Archivo + "Contratos_Adjuntos/' style='width:100px;height:100px;' class='borde'><br>" + rs.getString("NO_ARCHIVO_ORIGINAL") + "</a>";
}
} else {
texto_html = texto_html + "<a class='mustang-gallery' title='" + rs.getString("NO_ARCHIVO_ORIGINAL") + "' href='" + Url_Archivo + "Contratos_Adjuntos/" + rs.getString("NO_ARCHIVO") + "'><img src='" + Url_Archivo + "Contratos_Adjuntos/" + rs.getString("NO_ARCHIVO") + "' style='width:100px;height:100px;' class='borde'></a>";
}
}
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
} catch (Exception e) {
throw new RuntimeException("ERROR : " + e.getMessage());
} finally {
try {
this.conn.close();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
return texto_html;
} |
20265824-deb2-4157-9ab4-87acb3a78b36 | 2 | public void setMass(double m)
{
if(getMass() == Log.MASS && m != Log.MASS)
{System.out.println("ERROR: Attempted to change mass of log " + getName() + ".");}
super.setMass(Log.MASS);
} |
779af648-108a-4ad4-9c9d-66053254a6b2 | 6 | private void actionPanel(JPanel panel) {
actionsPanel = new JPanel();
actionsPanel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
actionsPanel.setBounds(520, 279, 320, 103);
panel.add(actionsPanel);
actionsPanel.setLayout(null);
actionsPanel.setVisible(false);
final JLabel x1Label = new JLabel("X1");
x1Label.setHorizontalAlignment(SwingConstants.RIGHT);
x1Label.setBounds(6, 37, 25, 14);
actionsPanel.add(x1Label);
x1Label.setRequestFocusEnabled(false);
x1Label.setForeground(Color.BLACK);
x1Label.setFont(new Font("Tahoma", Font.BOLD, 12));
x1Field = new JTextField();
x1Field.setHorizontalAlignment(SwingConstants.CENTER);
x1Field.setEditable(false);
x1Field.setBounds(41, 35, 25, 20);
actionsPanel.add(x1Field);
x1Field.setColumns(10);
y1Field = new JTextField();
y1Field.setEditable(false);
y1Field.setHorizontalAlignment(SwingConstants.CENTER);
y1Field.setBounds(41, 66, 25, 20);
actionsPanel.add(y1Field);
y1Field.setColumns(10);
final JLabel y1Label = new JLabel("Y1");
y1Label.setHorizontalAlignment(SwingConstants.RIGHT);
y1Label.setBounds(6, 68, 25, 14);
actionsPanel.add(y1Label);
y1Label.setRequestFocusEnabled(false);
y1Label.setForeground(Color.BLACK);
y1Label.setFont(new Font("Tahoma", Font.BOLD, 12));
final JLabel x2Label = new JLabel("X2");
x2Label.setBounds(76, 37, 16, 14);
actionsPanel.add(x2Label);
x2Label.setFont(new Font("Tahoma", Font.BOLD, 12));
x2Label.setForeground(Color.BLACK);
x2Field = new JTextField();
x2Field.setHorizontalAlignment(SwingConstants.CENTER);
x2Field.setEditable(false);
x2Field.setBounds(102, 35, 25, 20);
actionsPanel.add(x2Field);
x2Field.setColumns(10);
final JLabel y2Label = new JLabel("Y2");
y2Label.setBounds(76, 68, 16, 14);
actionsPanel.add(y2Label);
y2Label.setFont(new Font("Tahoma", Font.BOLD, 12));
y2Label.setForeground(Color.BLACK);
y2Field = new JTextField();
y2Field.setEditable(false);
y2Field.setHorizontalAlignment(SwingConstants.CENTER);
y2Field.setBounds(102, 66, 25, 20);
actionsPanel.add(y2Field);
y2Field.setColumns(10);
final JLabel bidLabel = new JLabel("$");
bidLabel.setHorizontalAlignment(SwingConstants.RIGHT);
bidLabel.setFont(new Font("Tahoma", Font.BOLD, 12));
bidLabel.setBounds(76, 53, 16, 14);
actionsPanel.add(bidLabel);
bidButton = new JButton("Bid");
bidButton.setBounds(177, 50, 80, 23);
actionsPanel.add(bidButton);
bidButton.setRequestFocusEnabled(false);
bidField = new IntTextField();
bidField.setBounds(99, 51, 68, 20);
actionsPanel.add(bidField);
bidField.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null,
null, null));
bidField.setBackground(SystemColor.window);
bidField.setColumns(10);
seismicCostField = new JTextField();
seismicCostField.setBounds(137, 35, 120, 20);
actionsPanel.add(seismicCostField);
seismicCostField.setEditable(false);
seismicCostField.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
seismicCostField.setColumns(10);
drillButton = new JButton("Drill");
drillButton.setBounds(102, 32, 80, 55);
actionsPanel.add(drillButton);
requestButton = new JButton("Seismic Request");
requestButton.setBounds(137, 65, 120, 23);
actionsPanel.add(requestButton);
/*crossButton = new JToggleButton("Slice View");
crossButton.setBounds(18, 34, 100, 55);
actionsPanel.add(crossButton);*/
JPanel radioPanel = new JPanel();
radioPanel.setBounds(1, 5, 304, 26);
actionsPanel.add(radioPanel);
radioPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 0));
SLButton = new JRadioButton("Seismic Line");
radioPanel.add(SLButton);
SLButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//map.colorSeismicKnowledge(null);
map.repaint(); //calls paintColorsMode();
map.sMode = 1;
x2Label.setVisible(true);
x2Field.setVisible(true);
y2Label.setVisible(true);
y2Field.setVisible(true);
requestButton.setVisible(true);
seismicCostField.setVisible(true);
requestButton.setVisible(true);
seismicCostField.setVisible(true);
//crossButton.setVisible(true);
x1Label.setVisible(false);
x1Field.setVisible(false);
y1Label.setVisible(false);
y1Field.setVisible(false);
x2Label.setVisible(false);
x2Field.setVisible(false);
y2Label.setVisible(false);
y2Field.setVisible(false);
bidButton.setVisible(false);
bidField.setVisible(false);
bidLabel.setVisible(false);
drillButton.setVisible(false); map.curBGColor =new Color(82, 61, 0);
}
});
//SLButton.setSelected(true);
SLButton.setActionCommand("S");
buttonGroup.add(SLButton);
SLButton.setBackground(UIManager.getColor("Button.background"));
JRadioButton bidButton1 = new JRadioButton("Bid");
radioPanel.add(bidButton1);
bidButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//map.colorBiddableLand(null);
map.repaint(); //calls paintColorsMode();
map.curBGColor =new Color(184,138,0);
bidButton.setVisible(true);
bidField.setVisible(true);
bidLabel.setVisible(true);
x2Label.setVisible(false);
x2Field.setVisible(false);
y2Label.setVisible(false);
y2Field.setVisible(false);
drillButton.setVisible(false);
requestButton.setVisible(false);
seismicCostField.setVisible(false);
//crossButton.setVisible(false);
}
});
bidButton1.setActionCommand("B");
buttonGroup.add(bidButton1);
bidButton1.setBackground(UIManager.getColor("Button.background"));
JRadioButton drillButton1 = new JRadioButton("Drill");
radioPanel.add(drillButton1);
drillButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//map.colorDrillableLand(null);
map.repaint(); //calls paintColorsMode();
map.curBGColor =new Color(240,240,240);
bidButton.setVisible(false);
bidField.setVisible(false);
bidLabel.setVisible(false);
x2Label.setVisible(false);
x2Field.setVisible(false);
y2Label.setVisible(false);
y2Field.setVisible(false);
drillButton.setVisible(true);
requestButton.setVisible(false);
seismicCostField.setVisible(false);
//crossButton.setVisible(false);
}
});
drillButton1.setActionCommand("D");
buttonGroup.add(drillButton1);
drillButton1.setBackground(UIManager.getColor("Button.background"));
requestButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
int x1Value = Integer.parseInt(x1Field.getText());
int y1Value = Integer.parseInt(y1Field.getText());
int x2Value = Integer.parseInt(x2Field.getText());
int y2Value = Integer.parseInt(y2Field.getText());
if (operator.makeNewSeismicRequest(x1Value, y1Value, x2Value, y2Value)) {
addMessage("Valid. Seismic Data Request Made.");
seismicCostField.setText("");
} else {
addMessage("Problem with request. Verify valid coordinates and enough funds.");
}
x1Field.setText("");
y1Field.setText("");
x2Field.setText("");
y2Field.setText("");
} catch (NumberFormatException nfe) {
addMessage("Problem with request. Please select a cell.");
}
}
});
/*crossButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
int x1Value = Integer.parseInt(x1Field.getText());
int y1Value = Integer.parseInt(y1Field.getText());
int x2Value = Integer.parseInt(x2Field.getText());
int y2Value = Integer.parseInt(y2Field.getText());
if (operator.makeNewSeismicRequest(x1Value, y1Value, x2Value, y2Value)) {
addMessage("Valid. Seismic Data Request Made.");
seismicCostField.setText("");
} else {
addMessage("Problem with request. Verify valid coordinates and enough funds.");
}
x1Field.setText("");
y1Field.setText("");
x2Field.setText("");
y2Field.setText("");
} catch (NumberFormatException nfe) {
addMessage("Problem with request. Please select a cell.");
}
}
});*/
drillButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
int xValue = Integer.parseInt(x1Field.getText());
int yValue = Integer.parseInt(y1Field.getText());
if (operator.makeNewDrill(xValue,yValue)) {
addMessage("Valid. Drill Request Made.");
} else {
addMessage("Problem with drill. Make sure the land is owned and there are enough funds.");
}
} catch (NumberFormatException nfe) {
addMessage("Problem with drill. Please select a cell.");
}
}
});
bidButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
int xValue = Integer.parseInt(x1Field.getText());
int yValue = Integer.parseInt(y1Field.getText());
int bidValue = Integer.parseInt(bidField.getText());
if (operator.makeNewBid(xValue,yValue,bidValue)) {
addMessage("Valid. Bid Request Placed.");
x1Field.setText("");
y1Field.setText("");
bidField.setText("");
} else {
addMessage("Invalid Bid. Make sure there are enough funds, or that the minimum bid is met.");
}
} catch (NumberFormatException nfe) {
addMessage("Invalid Bid. Please enter an integer amount in the bid field, or select a cell.");
}
}
});
} |
e2cacc2b-2634-4c19-9ead-f0fde37877e6 | 0 | public TMBruteParsePane(GrammarEnvironment environment, Grammar orig, Grammar trim, HashMap<String, String> map, InputTableModel model) {
super(environment, orig);
this.treePanel = new UnrestrictedTreePanel(this, map);
initView();
myTrimmedGrammar=trim;
myTrimmedGrammar.setStartVariable("S");
myModel = model;
} |
61e9028c-4e23-4635-b845-45ad32f60e01 | 4 | protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
@SuppressWarnings("unchecked")
HttpParams params = new HttpParams(request.getParameterMap());
String output = "";
// Determine method
String method = (params.containsKey("method") ? params.getFirst("method") : "overview");
if (method.equalsIgnoreCase("overview")) {
response.setContentType("application/json");
OverviewRequest overviewRequest = new OverviewRequest();
overviewRequest.setSwLat(56);
overviewRequest.setSwLon(-70);
overviewRequest.setNeLat(90);
overviewRequest.setNeLon(-5);
List<String> excludeRegions = new ArrayList<String>();
excludeRegions.add("808");
overviewRequest.getExcludeMap().put("sourceRegion", excludeRegions);
OverviewResponse overviewResponse = aisService.getOverview(overviewRequest);
output = gson.toJson(overviewResponse);
}
else if (method.equalsIgnoreCase("details")) {
response.setContentType("application/json");
Integer id = Integer.parseInt(params.getFirst("id"));
DetailedAisTarget detailedAisTarget = aisService.getTargetDetails(id, params.containsKey("past_track"));
output = gson.toJson(detailedAisTarget);
}
else if (method.equalsIgnoreCase("table")) {
response.setContentType("text/plain");
OverviewRequest overviewRequest = new OverviewRequest(params);
String table = aisService.getOverviewTable(overviewRequest);
output = table;
}
out.print(output);
} |
de709164-fda2-482b-be98-45fbdc4a70d1 | 0 | public RegExFindFileContentsHandler(String regex, String lineEnding) {
super(lineEnding);
setRegEx(regex);
} |
4d7fff2d-cd8e-4969-b47c-2143c25dda4e | 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(frmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(frmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(frmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(frmMain.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 frmMain().setVisible(true);
}
});
} |
da44476f-9038-4190-ab99-710bf558cf93 | 5 | private static ClassType parseClassType2(String sig, Cursor c, ClassType parent)
throws BadBytecode
{
int start = ++c.position;
char t;
do {
t = sig.charAt(c.position++);
} while (t != '$' && t != '<' && t != ';');
int end = c.position - 1;
TypeArgument[] targs;
if (t == '<') {
targs = parseTypeArgs(sig, c);
t = sig.charAt(c.position++);
}
else
targs = null;
ClassType thisClass = ClassType.make(sig, start, end, targs, parent);
if (t == '$') {
c.position--;
return parseClassType2(sig, c, thisClass);
}
else
return thisClass;
} |
54653267-6055-42a2-b212-edad0c1d438c | 9 | public static
java.util.Calendar[] toArrayOfCalendar(Collection collection)
{
if(collection == null || collection.size() == 0) return new java.util.Calendar[0];
java.util.Calendar[] aResult = new java.util.Calendar[collection.size()];
int i = 0;
Iterator iterator = collection.iterator();
while(iterator.hasNext()) {
Object oValue = iterator.next();
if(oValue instanceof java.util.Calendar) {
aResult[i++] = (java.util.Calendar) oValue;
continue;
}
Calendar cal = Calendar.getInstance();
if(oValue instanceof java.sql.Date) {
cal.setTimeInMillis(((java.sql.Date) oValue).getTime());
aResult[i++] = cal;
}
else
if(oValue instanceof java.sql.Timestamp) {
cal.setTimeInMillis(((java.sql.Timestamp) oValue).getTime());
aResult[i++] = cal;
}
else
if(oValue instanceof java.util.Date) {
cal.setTimeInMillis(((java.util.Date) oValue).getTime());
aResult[i++] = cal;
}
else
if(oValue instanceof String) {
String sDate = WUtil.normalizeStringDate((String) oValue);
if(sDate == null) return null;
cal.setTimeInMillis(WUtil.stringToLongDate(sDate));
aResult[i++] = cal;
}
else {
return null;
}
}
return aResult;
} |
8967c321-3e7b-424e-b975-71f330c08f83 | 5 | public void setResource( boolean _shape, boolean _color, boolean _size,
boolean _weight, boolean _healthy ){
int ONES_MASK = (0xFFFFFFFF);
int color = _color?ONES_MASK:~(1<<6);
int shape = _shape?ONES_MASK:~(1<<7);
int size = _size?ONES_MASK:~(1<<8);
int weight = _weight?ONES_MASK:~(1<<9);
int healthy = _healthy?ONES_MASK:~(1<<10);
resource = color & shape & size & weight & healthy;
} |
ed2b4c1c-7e11-44aa-a8f7-1271410dd3aa | 0 | private boolean annotationMatches(Annotation antFromMethod, String antFromUser) {
String justAnnotationNameFromUserInput = extractAnnotationNameFromUserInput(antFromUser);
String justAnnotationNameFromMethod = extractAnnotationNameFromMethod(antFromMethod);
return justAnnotationNameFromMethod.equalsIgnoreCase(justAnnotationNameFromUserInput);
} |
1bdc3822-4f72-4c2c-9fe7-b33d499162a9 | 5 | public boolean isPassed() {
Calendar cal = Calendar.getInstance();
int currY = cal.get(Calendar.YEAR);
int currMo = cal.get(Calendar.MONTH) + 1;
int currD = cal.get(Calendar.DAY_OF_MONTH);
int currH = cal.get(Calendar.HOUR_OF_DAY);
int currMi = cal.get(Calendar.MINUTE);
int y = (this.year == -1) ? currY : this.year;
int mo = (this.month == -1) ? currMo : this.month;
int d = (this.day == -1) ? currD : this.day;
int h = (this.hour == -1) ? currH : this.hour;
int mi = (this.minute == -1) ? currMi : this.minute;
/*
* Values: minute 1
* hour 60
* day 1440
* month 44640
* year 535680
*/
int reached = (currY - y) * 535680 + (currMo - mo) * 44640 + (currD - d) * 1440 + (currH - h) * 60 + (currMi - mi);
return reached >= 0;
} |
831d9c70-1dcc-4e14-97c9-d226d7912dda | 2 | public SessionKey unserializeSessionKey(String keyFilename) {
SessionKey sessionKey = null;
try {
File f = new File(keyFilename);
f.createNewFile();
InputStream file = new FileInputStream(keyFilename);
InputStream buffer = new BufferedInputStream(file);
ObjectInput input = new ObjectInputStream(buffer);
try {
sessionKey = (SessionKey) input.readObject();
} finally {
input.close();
f.delete();
}
} catch (Throwable e) {
if (DEBUG) {
System.out.println("An error has ocurred unserializing key to memory: " + e.getMessage());
e.printStackTrace();
}
}
return sessionKey;
} |
3c1934f6-2284-4879-b614-a80771ea91b2 | 0 | public void setMimeType(String mimeType) {
this.mimeType = mimeType;
} |
fc1b583b-97f1-45ca-af49-29518fca017e | 4 | private void createProjectControlPanel() {
Vector<JButton> cb = createCustomButtons();
if(cb.size() == 0) {
return; // no buttons to be displayed
}
projectControlContent.removeAll();
JButton minimizeButton;
if(appConfig.guiControlPanelShowProjectControl) {
minimizeButton = createFrameworkIconButton("minimizeProjectControl", "minimize.gif", "Minimize");
} else {
minimizeButton = createFrameworkIconButton("maximizeProjectControl", "maximize.gif", "Maximize");
}
minimizeButton.setPreferredSize(new Dimension(21, 11));
projectControlContent.add(minimizeButton, JLayeredPane.PALETTE_LAYER);
minimizeButton.setBounds(controlPanelWidth - 26, 3, 21, 11);
addToDisabledButtonList(minimizeButton); // disable while simulating
JPanel customButtons = new JPanel();
customButtons.setBorder(BorderFactory.createTitledBorder("Project Control"));
if(appConfig.guiControlPanelShowProjectControl) {
customButtons.setPreferredSize(new Dimension(controlPanelWidth, 3000));
customButtons.setLayout(new MultiLineFlowLayout(controlPanelWidth, 0, 0));
for(JButton b : cb) {
customButtons.add(b);
addToDisabledButtonList(b);
}
customButtons.doLayout();
// adjust the size of the
Dimension d = customButtons.getLayout().preferredLayoutSize(customButtons);
d.width = controlPanelWidth; // enforce the width
customButtons.setPreferredSize(d);
} else {
customButtons.setLayout(new BoxLayout(customButtons, BoxLayout.Y_AXIS));
}
projectControlContent.add(customButtons);
// Finally set the size of the viewPanel
Dimension dim = customButtons.getPreferredSize();
customButtons.setBounds(0, 0, controlPanelWidth, dim.height);
projectControlContent.setPreferredSize(dim);
projectControlContent.invalidate();
} |
2f78973f-92fd-44d5-9e07-86030ae2ab10 | 7 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical target, boolean auto, int asLevel)
{
if(target==null)
{
final PresenceReaction A=(PresenceReaction)mob.fetchEffect(ID());
if(A!=null)
A.shutdownPresence(mob);
if(affected==mob)
shutdownPresence(mob);
return A!=null;
}
if(!(target instanceof MOB))
return false;
reactToM=(MOB)target;
for(final Object O : commands)
addAffectOrBehavior((String)O);
if(auto)
{
synchronized(mob)
{
if(mob.fetchEffect(ID())==null)
{
mob.addNonUninvokableEffect(this);
initializeManagedObjects(mob);
}
return true;
}
}
else
{
makeLongLasting();
makeNonUninvokable();
setAffectedOne(mob);
initializeManagedObjects(mob);
return true;
}
} |
1798e5cd-b9f5-42f3-9f6b-b72fbad0f61e | 1 | private void showLog_settingsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showLog_settingsButtonActionPerformed
if (debug)
logger.log(Level.DEBUG, "Setting preference \"showLog\" from " + settings.showLog() + " to " + showLog_settingsButton.isSelected());
settings.setShowLog(showLog_settingsButton.isSelected());
}//GEN-LAST:event_showLog_settingsButtonActionPerformed |
febf2137-f214-454d-b962-d87693e07a7d | 0 | private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
modificar.setVisible(false);
}//GEN-LAST:event_jButton2ActionPerformed |
902b1982-524b-42a2-948c-bfab79ab727b | 8 | public int AddInstanceToBestCluster(Instance inst) {
double delta;
double deltamax;
int clustermax = -1;
if (clusters.size() > 0) {
int tempS = 0;
int tempW = 0;
if (inst instanceof SparseInstance) {
for (int i = 0; i < inst.numValues(); i++) {
tempS++;
tempW++;
}
} else {
for (int i = 0; i < inst.numAttributes(); i++) {
if (!inst.isMissing(i)) {
tempS++;
tempW++;
}
}
}
deltamax = tempS / Math.pow(tempW, m_Repulsion);
for (int i = 0; i < clusters.size(); i++) {
CLOPECluster tempcluster = clusters.get(i);
delta = tempcluster.DeltaAdd(inst, m_Repulsion);
// System.out.println("delta " + delta);
if (delta > deltamax) {
deltamax = delta;
clustermax = i;
}
}
} else {
CLOPECluster newcluster = new CLOPECluster();
clusters.add(newcluster);
newcluster.AddInstance(inst);
return clusters.size() - 1;
}
if (clustermax == -1) {
CLOPECluster newcluster = new CLOPECluster();
clusters.add(newcluster);
newcluster.AddInstance(inst);
return clusters.size() - 1;
}
clusters.get(clustermax).AddInstance(inst);
return clustermax;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.