method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
5c4607dc-232a-4528-b480-e8da96cf6ece
| 6
|
private static void repl(Environment env, TurtleGraphics t) {
System.out.println(version);
System.out.println("type 'exit' to quit.");
System.out.println();
Scanner in = new Scanner(System.in);
while(true) {
System.out.print(">");
try {
String line = in.nextLine();
if ("exit".equals(line)) { break; }
while(Parser.complete(line).size() > 0) {
System.out.print(">>");
line += "\n" + in.nextLine();
}
runString(env, line, t);
}
catch(SyntaxError e) {
System.out.format("syntax error: %s%n", e.getMessage());
System.out.format("\t%s%n\t", e.line);
for(int z = 0; z < e.lineIndex; z++) {
System.out.print(e.line.charAt(z) == '\t' ? '\t' : ' ');
}
System.out.println("^");
env.reset();
}
}
System.exit(0);
}
|
d3736860-5232-4d67-808a-c783c527e4c9
| 2
|
public static String compress (String str) {
char pre = str.charAt( 0 );
int count = 1;
char cur = ' ';
StringBuffer sb = new StringBuffer();
for (int i = 1; i < str.length(); ++i ) {
cur = str.charAt(i) ;
if ( cur == pre ) {
++count;
}else {
sb.append( pre );
sb.append( Integer.toString(count) );
// sb.append( String.valueOf(count) );
pre = cur;
count = 1;
}
}
// deal with the last sequence of the same characters.
sb.append(cur);
sb.append( Integer.toString(count) );
return sb.toString();
}
|
aea4011b-14ec-4b77-bc0c-ce1d7d97ed57
| 1
|
public Guid readLegacyGuid()
throws IOException {
Guid guid = CycObjectFactory.makeGuid((String) readObject());
if (trace == API_TRACE_DETAILED) {
debugNote("readLegacyGuid: " + guid);
}
return guid;
}
|
69066250-aa2c-4b25-a797-d709a8a0c366
| 9
|
private void writeColorzz(int col, String dest) {
try {
OutputStream out = new BufferedOutputStream(new FileOutputStream(dest), 8096);
int i = 0;
int i2 = 0;
int step = 0;
int ii = 0;
while (i2 < biHeight) {
out.write(image.getVal(i, i2, col));
if (step == 0) { i2 ++; step = 1; }
else if (step == 1 || step == 3) { i ++; step = (step + 1) & 3; }
else { i2 --; step = 3; }
if (i2 >= biHeight && ii < biHeight) { i2 = (int)biHeight - 1; i ++; step = 0; }
if (i >= biWidth && ii < biHeight - 1) { ii += 2; i2 = ii; i = 0; step = 0; }
}
out.close();
} catch (Exception e) {e.printStackTrace();}
}
|
7840aec5-35da-463f-b23b-1ca2ea2827d8
| 6
|
public static Object getProperty(Object obj, String propertyName)
{
if (obj == null)
return null;
try
{
BeanInfo info = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
for (int i = 0; i < descriptors.length; i++)
{
if (descriptors[i].getName().equals(propertyName))
{
Method getter = descriptors[i].getReadMethod();
if (getter == null)
return null;
try {
return getter.invoke(obj);
} catch (Exception ex) {
System.out.println(descriptors[i].getName());
return null;
}
}
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
}
|
93b9117e-32b2-4ef8-bce0-ba365f5f749d
| 9
|
private boolean r_t_plural() {
int among_var;
int v_1;
int v_2;
int v_3;
int v_4;
int v_5;
int v_6;
// (, line 160
// setlimit, line 161
v_1 = limit - cursor;
// tomark, line 161
if (cursor < I_p1)
{
return false;
}
cursor = I_p1;
v_2 = limit_backward;
limit_backward = cursor;
cursor = limit - v_1;
// (, line 161
// [, line 162
ket = cursor;
// literal, line 162
if (!(eq_s_b(1, "t")))
{
limit_backward = v_2;
return false;
}
// ], line 162
bra = cursor;
// test, line 162
v_3 = limit - cursor;
if (!(in_grouping_b(g_V1, 97, 246)))
{
limit_backward = v_2;
return false;
}
cursor = limit - v_3;
// delete, line 163
slice_del();
limit_backward = v_2;
// setlimit, line 165
v_4 = limit - cursor;
// tomark, line 165
if (cursor < I_p2)
{
return false;
}
cursor = I_p2;
v_5 = limit_backward;
limit_backward = cursor;
cursor = limit - v_4;
// (, line 165
// [, line 165
ket = cursor;
// substring, line 165
among_var = find_among_b(a_9, 2);
if (among_var == 0)
{
limit_backward = v_5;
return false;
}
// ], line 165
bra = cursor;
limit_backward = v_5;
switch(among_var) {
case 0:
return false;
case 1:
// (, line 167
// not, line 167
{
v_6 = limit - cursor;
lab0: do {
// literal, line 167
if (!(eq_s_b(2, "po")))
{
break lab0;
}
return false;
} while (false);
cursor = limit - v_6;
}
break;
}
// delete, line 170
slice_del();
return true;
}
|
316925d8-db3f-44b0-becf-05cae704a731
| 4
|
public static void selectionSort (int[] array) {
for (int barrier = 0; barrier < array.length - 1; barrier++) {
int elem = array[barrier]; //обращению к элементу масива медленнее, чем к локальной перменной. не нужно делать проверок на границы массива
int aIndex = barrier+1;
int min = array[barrier+1]; //сначала считаем, что минимальный - первый. потом ищем какой на самом деле минимальный и узнаем его индекс
for (int index = barrier + 2; index < array.length; index++) {
if (array[index] < min ) {
min = array[index];
aIndex = index;
}
}
if (elem > array[aIndex]) { //хорошо придумал. шикарно
int tmp = array[aIndex];
array[aIndex] = array[barrier];
array[barrier] = tmp;
}
}
}
|
623331ca-498a-41bd-8ff1-1b4f81bf671b
| 8
|
@Override
public void run () {
byte buffer[] = new byte[4096];
String logBuffer = "";
int newLineIndex;
int nullIndex;
try {
while (is.read(buffer) > 0) {
logBuffer += new String(buffer).replace("\r\n", "\n");
nullIndex = logBuffer.indexOf(0);
if (nullIndex != -1) {
logBuffer = logBuffer.substring(0, nullIndex);
}
while ((newLineIndex = logBuffer.indexOf("\n")) != -1) {
if ( ignore != null) {
boolean skip = false;
for (String s: ignore) {
if (logBuffer.substring(0, newLineIndex).contains(s)) {
skip = true;
}
}
if(!skip) {
Logger.log(new LogEntry().copyInformation(logInfo).message(logBuffer.substring(0, newLineIndex)));
}
} else {
Logger.log(new LogEntry().copyInformation(logInfo).message(logBuffer.substring(0, newLineIndex)));
}
logBuffer = logBuffer.substring(newLineIndex + 1);
}
Arrays.fill(buffer, (byte) 0);
}
} catch (IOException e) {
Logger.logError("Error while reading log messages from external source(minecraft process)", e);
}
}
|
9bbe35e5-a018-4143-a1d5-76bacaf840bb
| 4
|
public UsuariHex carregaUsuari( String nom, String contrasenya, TipusJugadors tipus_jugador )
throws IllegalArgumentException, FileNotFoundException, IOException, ClassNotFoundException,
NullPointerException
{
if ( !UsuariHexGstr.getInstancia().existeixElement( getIdentificadorUnic( nom ) ) )
{
throw new IllegalArgumentException( "L'usuari no existeix." );
}
else
{
UsuariHex usuari = UsuariHexGstr.getInstancia().carregaElement( getIdentificadorUnic( nom ) );
if ( tipus_jugador == TipusJugadors.JUGADOR )
{
if ( UsuariHex.getNomsNoPermesos().contains( nom ) )
{
throw new IllegalArgumentException( "L'usuari demanat és intern del sistema." );
}
else if ( !usuari.getContrasenya().equals( contrasenya ) )
{
throw new IllegalArgumentException( "La contrasenya no és correcta." );
}
}
return usuari;
}
}
|
fec2d02b-ee9e-4973-b15d-7f96635122ef
| 8
|
private int closeSpecifications(List<SpecificationDocument> specificationDocuments, boolean checkForEdited)
{
int closedSpecifications = 0;
isClosingDocument = true;
boolean canceled = false;
Iterator<SpecificationDocument> iterator = specificationDocuments.iterator();
while (!canceled && iterator.hasNext())
{
SpecificationDocument specificationDocument = iterator.next();
if (checkForEdited && specificationDocument.isEdited())
{
// if checkForEdited and document is edited, ask to save it and then close
// if not saved, cancel the whole operation
// if use doesn't want to save it, close anyway
String editedMessage = MessageFormat.format(uiBundle.getString("fileWarning.closedEditedSpecification.message"),
specificationDocument.getFile().getName());
int closeState = JOptionPane.showConfirmDialog(this,
editedMessage,
uiBundle.getString("fileWarning.closedEditedSpecification.confirm"),
JOptionPane.YES_NO_CANCEL_OPTION);
switch (closeState)
{
case JOptionPane.YES_OPTION:
boolean saved = saveSpecification(specificationDocument);
if (saved)
{
closeSpecification(specificationDocument);
closedSpecifications++;
}
// if the file couldn't be save, fail and ignore
// the remaining specifications to be close
canceled = !saved;
break;
case JOptionPane.NO_OPTION:
closeSpecification(specificationDocument);
closedSpecifications++;
break;
case JOptionPane.CANCEL_OPTION:
canceled = true;
}
}
else
{
// blindly close the document because the user didn't want to save anything
closeSpecification(specificationDocument);
closedSpecifications++;
}
}
isClosingDocument = false;
return closedSpecifications;
}
|
1aa1f6c3-1542-436f-ac84-89be8acbb16a
| 2
|
int findNl(int next, int last) {
for (int i = next; i < last; i++) {
if (buffer[i] == '\n') return i;
}
return -1;
}
|
3fa73a92-06e9-4c06-adc2-ffb242ffa8ab
| 0
|
public EventsBean getEventbean() {
return eventbean;
}
|
4435bc7e-7b7d-4598-847c-b39fca0b6b0e
| 2
|
private Browser(Manufacturer manufacturer, Browser parent, int versionId, String name, String[] aliases, String[] exclude, BrowserType browserType, RenderingEngine renderingEngine, String versionRegexString) {
this.id = (short) ( ( manufacturer.getId() << 8) + (byte) versionId);
this.name = name;
this.parent = parent;
this.children = new ArrayList<Browser>();
this.aliases = aliases;
this.excludeList = exclude;
this.browserType = browserType;
this.manufacturer = manufacturer;
this.renderingEngine = renderingEngine;
if (versionRegexString != null)
this.versionRegEx = Pattern.compile(versionRegexString);
if (this.parent == null)
addTopLevelBrowser(this);
else
this.parent.children.add(this);
}
|
0cd38a4f-808a-4d08-a289-f66172944746
| 8
|
double[] MSDFromList(My3DData data3d, int l, boolean do3D)
{
double MSDs[] =new double[(int) Math.sqrt(NumMarkers(l)+1)];
double MSDNums[] =new double[(int) Math.sqrt(NumMarkers(l)+1)];
APoint point,point2;
double SumDist2;
int adT; // deltaTime but in unit steps
for (int i=0;i<NumMarkers(l);i++) {
for (int j=i+1;j<NumMarkers(l);j++) {
point=GetPoint(i,l);
point2=GetPoint(j,l);
int elem = (int) point.coord[3];
adT = (int) (point2.coord[data3d.TrackDirection]-point.coord[data3d.TrackDirection]);
if (do3D)
SumDist2 = point.SqrDistTo(point2,data3d.GetScale(elem,0),data3d.GetScale(elem,1),data3d.GetScale(elem,2));
else
SumDist2 = point.SqrXYDistTo(point2,data3d.GetScale(elem,0),data3d.GetScale(elem,1));
if (adT < 0) adT = -adT;
if (adT < MSDs.length+1)
{
if (adT > 0) {
MSDs[adT-1] += SumDist2;
MSDNums[adT-1]++;
}
}
else
j=NumMarkers(l); // break this for loop and go on
}
}
for (int i=0;i<MSDs.length;i++) {
if (MSDNums[i] > 0)
MSDs[i] /= MSDNums[i];
}
return MSDs;
}
|
dda65cac-377d-4c88-a0ff-ca532ab13f7c
| 6
|
@Override
public double read() {
time += 1.0 / 44100;
if (!running) {
amplitude = (amplitude>0 ?(amplitude - (level) / (release * 44100)) : 0);
} else if (time <= attack) {
amplitude += peek / (attack * 44100);
} else if (time > attack && time <= attack + decay) {
amplitude += (level - peek) / (decay * 44100);
} else if (time > attack + decay) {
amplitude = level;
}
return amplitude * sound.read();
}
|
bc594474-0e65-4619-afa2-522c03dc3eb3
| 5
|
public int argOfInterestOfZ(MessageContent z) {
// we look for the argmax
if (debug>=3) {
String dmethod = Thread.currentThread().getStackTrace()[2].getMethodName();
String dclass = Thread.currentThread().getStackTrace()[2].getClassName();
System.out.println("---------------------------------------");
System.out.println("[class: "+dclass+" method: " + dmethod+ "] " + "computing the Z index of"+z);
System.out.println("---------------------------------------");
}
int argmax = 0;
double maxvalue = z.getValue(0);
for (int index= 0; index < z.size()-1; index++) {
if (debug>=3) {
String dmethod = Thread.currentThread().getStackTrace()[2].getMethodName();
String dclass = Thread.currentThread().getStackTrace()[2].getClassName();
System.out.println("---------------------------------------");
System.out.println("[class: "+dclass+" method: " + dmethod+ "] " + "loop number "+index+" maxvalue="+maxvalue);
System.out.println("---------------------------------------");
}
if (maxvalue < z.getValue(index+1)) {
argmax = index+1;
maxvalue = z.getValue(index+1);
}
}
if (debug>=3) {
String dmethod = Thread.currentThread().getStackTrace()[2].getMethodName();
String dclass = Thread.currentThread().getStackTrace()[2].getClassName();
System.out.println("---------------------------------------");
System.out.println("[class: "+dclass+" method: " + dmethod+ "] " + "the argmax is "+argmax);
System.out.println("---------------------------------------");
}
return argmax;
}
|
f50ec239-8531-4208-b574-bd6a8552594b
| 0
|
public RegExMultiReplacementFileContentsHandler(String[] regexes, String lineEnding) {
super(lineEnding);
setRegExes(regexes);
}
|
c76747a0-0d28-4fbc-b9c3-7753d076e7ea
| 7
|
@SuppressWarnings("unchecked")
private int reloadRegisteredItems(){
int i = 0;
Validator validator = new Validator();
for (String itemName : registeredItems){
if (validator.verifyRegisteredItem(instance, items, recipes, itemName)){
CustomID customId = new CustomID(items.getString(Util.concatStrings(Constants.ITEMS, ".", itemName, ".", Constants.ITEM_ID)));
itemTypeMap.put(itemName, customId);
itemAbilitiesMap.put(itemName, (ArrayList<String>)items.getList(Util.concatStrings(Constants.ITEMS, ".", itemName, ".", Constants.ITEM_ABILITIES)));
itemUsePermissionMap.put(itemName, Boolean.valueOf(items.getBoolean(Util.concatStrings(Constants.ITEMS, ".", itemName, ".", Constants.ITEM_USE_PERMS))));
itemNameMap.put(itemName, items.getString(Util.concatStrings(Constants.ITEMS, ".", itemName, ".", Constants.ITEM_DISPLAY_NAME)));
itemRecipeMap.put(itemName, Boolean.valueOf(items.getBoolean(Util.concatStrings(Constants.ITEMS, ".", itemName, ".", Constants.ITEM_USE_RECIPE))));
String lorePath = Util.concatStrings(Constants.ITEMS, ".", itemName, ".", Constants.ITEM_LORE);
if (items.contains(lorePath)){
itemLoreMap.put(itemName, (ArrayList<String>)items.getList(lorePath));
}
else {
// default of lore of unknown, if left empty
ArrayList<String> emptyLore = new ArrayList<String>();
emptyLore.add("An unknown lore");
itemLoreMap.put(itemName, emptyLore);
}
String colorPath = Util.concatStrings(Constants.ITEMS, ".", itemName, ".", Constants.ITEM_COLOR);
if (items.contains(colorPath)){
itemColorMap.put(itemName, items.getString(colorPath));
}
else {
// default of
itemColorMap.put(itemName, "\247f");
}
String enchantmentPath = Util.concatStrings(Constants.ITEMS, ".", itemName, ".", Constants.ITEM_ENCHANTMENTS);
if (items.contains(enchantmentPath)){
List<String> yamlEnchants = (List<String>)items.getList(enchantmentPath);
if (yamlEnchants != null){
List<CustomEnchantment> enchantments = new ArrayList<CustomEnchantment>();
for (String enchantName : yamlEnchants){
int enchantLevel = items.getInt(Util.concatStrings(Constants.ITEMS, ".", itemName, ".", Constants.ITEM_ENCHANTMENTS_LEVEL, ".", enchantName));
CustomEnchantment newEnchant = new CustomEnchantment(Enchantment.getByName(enchantName), enchantLevel);
enchantments.add(newEnchant);
}
itemEnchantmentMap.put(itemName, enchantments);
}
}
i++;
}
else {
instance.getLog().warning(Util.editConsole((new StringBuilder(String.valueOf(itemName))).append(" item cannot be loaded!").toString()));
itemsToDelete.add(itemName);
}
}
return i;
}
|
a35dea56-0f19-4454-9eac-633211826955
| 1
|
private void drawRestOfJPanelDisplay(Graphics g) {
int numberLeftInPack = cardStack.size();
if (numberLeftInPack > 0) {
aFaceDownCard.drawCard(g, this);
drawNumberInsideCardArea(g, aFaceDownCard);
}
drawGameInformation(g);
}
|
403a402b-b271-4ce7-bb61-8f797d59275c
| 0
|
@Override
public void setIdleTimeout(long idleTimeout) {
this.idleTimeout = idleTimeout;
}
|
79bce53c-0170-419c-a5c8-212eb2fb56ed
| 7
|
@Override
public void act(Table table) {
StringBuffer message = new StringBuffer();
message.append(table.tableRepresentation());
message.append("\n\nWhat would you like to do? Please input \"h\" for Hit or \"s\" for Stand...");
// get input from user
String input;
do {
input = (String) BlackjackGame.getUi().getInput(message.toString());
} while ((!input.startsWith("S")) && (!input.startsWith("s"))
&& (!input.startsWith("H")) && (!input.startsWith("h")));
if (input.startsWith("H") || input.startsWith("h")) {
try {
BlackjackGame.getUi().showOutput("You hit!");
this.hit(table);
} catch (Exception e) {
System.err.println(e.getMessage());
System.exit(1);
}
} else {
this.stand(table);
BlackjackGame.getUi().showOutput("You stood!");
}
}
|
98b92d01-c2ef-4f1d-8e42-a9e4df1a1033
| 3
|
@Override
public boolean
equals(Object o) {
if (o == this) {
return true;
} else if (o instanceof SQLQuery) {
SQLQuery oo = (SQLQuery)o;
return oo.builder.equals(this.builder)
&& oo.parameters.equals(this.parameters);
} else {
return false;
}
}
|
c979ef07-c417-4abe-8c57-a38a52615ed2
| 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(ViewMainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ViewMainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ViewMainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ViewMainFrame.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 ViewMainFrame().setVisible(true);
}
});
}
|
20d0c541-f085-4929-838c-25f475081b86
| 8
|
public List<Integer> addCycle(int leftX, int leftY, int rightX, int rightY,
int[][] matrix) {
List<Integer> result = new LinkedList<Integer>();
if (leftX == rightX && leftY == rightY) {
result.add(matrix[leftX][leftY]);
return result;
}
for (int i = leftY; i <= rightY; i++) {
result.add(matrix[leftX][i]);
}
for (int i = leftX + 1; i <= rightX; i++) {
result.add(matrix[i][rightY]);
}
if (leftX != rightX) {
for (int i = rightY - 1; i >= leftY; i--) {
result.add(matrix[rightX][i]);
}
}
if (leftY != rightY) {
for (int i = rightX - 1; i > leftX; i--) {
result.add(matrix[i][leftY]);
}
}
return result;
}
|
b48e4cfd-4d10-4241-a207-444f08f98371
| 3
|
public Tilbakemelding opprettBruker(PreparedStatement setning, ResultSet res, Connection forbindelse, String brukernavn, String passord) {
Tilbakemelding returverdi = Tilbakemelding.nyBrukerIkkeOk;
try {
getBrukerData();
setning = forbindelse.prepareStatement("select brukernavn from bruker where brukernavn = ?");
setning.setString(1, brukernavn);
res = setning.executeQuery();
if(!res.next() && sjekkPassordKriterier(passord)){
setning = forbindelse.prepareStatement("insert into rolle (brukernavn,rolle) values(?,?)");
setning.setString(1, brukernavn);
setning.setString(2, "bruker");
setning.executeUpdate();
Opprydder.lukkSetning(setning);
setning = forbindelse.prepareStatement("insert into bruker(brukernavn,passord) values(?,?)");
setning.setString(1, brukernavn);
setning.setString(2, passord);
setning.executeUpdate();
returverdi = Tilbakemelding.nyBrukerOk;
}else{
returverdi = Tilbakemelding.nyBrukerIkkeOk;
}
} catch (SQLException e) {
Opprydder.skrivMelding(e, "opprettbruker()");
} finally {
Opprydder.lukkResSet(res);
Opprydder.lukkSetning(setning);
Opprydder.lukkForbindelse(forbindelse);
}
return returverdi;
}
|
dbb0dbac-cf1d-48f7-9f2b-1850bd4e0c83
| 1
|
public void setBtn_Std_Fontsize(int fontsize) {
if (fontsize <= 0) {
this.buttonStdFontSize = UIFontInits.STDBUTTON.getSize();
} else {
this.buttonStdFontSize = fontsize;
}
somethingChanged();
}
|
c2b50658-5477-4085-b3a8-2bafc13e53c7
| 5
|
public void keepOnlyDuplexes() {
for (int i = 0; i < parent.tracks.size(); i++) {
for (int j = 0; j < parent.tracks.get(i).matches.length; j++) {
if (parent.tracks.get(i).matches[j] != 0) {
Track target = getTrackById(j);
if (target == null) {
parent.tracks.get(i).setMatch(j, 0);
} else if (target.matches[parent.tracks.get(i).getId()] == 0) {
parent.tracks.get(i).setMatch(j, 0);
}
}
}
}
}
|
fed3602f-f9e1-401d-84e6-84aecaf3b79e
| 7
|
private void add(Automaton newOne, Automaton other) {
AutomatonDrawer d1 = new AutomatonDrawer(newOne), d2 = new AutomatonDrawer(
other);
Rectangle2D bounds1 = d1.getBounds(), bounds2 = d2.getBounds();
if (bounds1 == null)
bounds1 = new Rectangle2D.Float();
if (bounds2 == null)
bounds2 = new Rectangle2D.Float();
double d = bounds1.getY() + bounds1.getHeight() - bounds2.getY() + 20.0;
State[] otherStates = other.getStates();
Map otherToNew = new HashMap();
for (int i = 0; i < otherStates.length; i++) {
State s = otherStates[i];
Point p = new Point(s.getPoint().x, s.getPoint().y + (int) d);
State s2 = newOne.createState(p);
if (other.isFinalState(s))
newOne.addFinalState(s2);
s2.setLabel(s.getLabel());
/*
* To maintain Moore machine state output.
*/
if(newOne instanceof MooreMachine && other instanceof MooreMachine)
{
MooreMachine m = (MooreMachine) newOne;
MooreMachine n = (MooreMachine) other;
m.setOutput(s2, n.getOutput(s));
}
otherToNew.put(s, s2);
}
Transition[] otherTransitions = other.getTransitions();
for (int i = 0; i < otherTransitions.length; i++) {
Transition t = otherTransitions[i];
State from = (State) otherToNew.get(t.getFromState()), to = (State) otherToNew
.get(t.getToState());
newOne.addTransition(t.copy(from, to));
}
}
|
ee53a1cd-d137-436f-a1e2-2eb521eb08c4
| 3
|
private void fill() {
switch (difficulty) {
case "E":
readBoards(1);
break;
case "M":
readBoards(2);
break;
case "H":
readBoards(3);
break;
// case "A":
// buildBoard();
// break;
default:
break;
}
}
|
a68908c1-f75d-4a09-8d41-b28d2d581323
| 2
|
public CompoundGenerator(QuestionGenerator... generators) {
if (generators == null || generators.length == 0) {
throw new IllegalArgumentException("No generators.");
}
Collections.addAll(this.generators, generators);
}
|
1d4fa42c-b62c-4090-9c20-e2848e905a16
| 3
|
protected void populate(Annotation[] annotations, String className)
{
if (annotations == null) return;
Set<String> classAnnotations = classIndex.get(className);
for (Annotation ann : annotations)
{
Set<String> classes = annotationIndex.get(ann.getTypeName());
if (classes == null)
{
classes = new HashSet<String>();
annotationIndex.put(ann.getTypeName(), classes);
}
classes.add(className);
classAnnotations.add(ann.getTypeName());
}
}
|
24a28b99-10d6-4927-908a-bf7d1dec746e
| 1
|
private void carregaFormasPagamento(){
FormasPagamentoDAO dao = new FormasPagamentoDAO();
listaFromasPagamento = dao.ListarTodos();
cbxTipoPagamento.removeAllItems();
for(FormasPagamento f : listaFromasPagamento){
cbxTipoPagamento.addItem(f);
}
}
|
df61888b-4568-4771-8fa5-28f2c97e9434
| 8
|
public String getRecommendListForAdamicAdar() {
String recommend = "";
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/NETWORK_TEST?"
+ "user=root&password=root");
connect.setAutoCommit(false);
statement = connect.createStatement();
for (String node : this.nodeList) {
String sql = "select rd.recommend, (rd.CNF/(d1.degree + d2.degree)) as score "
+ "from (select g1.START_NODE as node, g2.START_NODE as recommend, "
+ "count(*) as CNF from network_test." + this.table
+ " as g1, network_test." + this.table
+ " as g2 where g1.END_NODE = g2.END_NODE and g1.START_NODE <> g2.START_NODE "
+ "and (g1.START_NODE, g2.START_NODE) not in (select * from network_test." + this.table + ") "
+ "and g1.START_NODE = '" + node + "'"
+ " group by g2.START_NODE order by CNF desc) as rd,"
+ "(select START_NODE as node, count(*) as degree from network_test." + this.table
+ " where START_NODE = '" + node + "'"
+ ") as d1, (select START_NODE as node, count(*) as degree from network_test." + table
+ " group by START_NODE) as d2 where rd.recommend = d2.node "
+ "order by score desc limit 10";
resultSet = statement.executeQuery(sql);
recommend += node + ":";
while (resultSet.next()) {
String recommendNode = resultSet.getString("Recommend");
recommend += recommendNode + ",";
}
recommend += "\n";
}
connect.commit();
statement.close();
connect.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
try {
if(statement!=null)
statement.close();
} catch(SQLException se2) {
}// nothing we can do
try{
if(connect!=null)
connect.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
return recommend;
}
|
fcca3883-5a81-4ddb-933a-c51c438e5210
| 6
|
public static void printGist(int[] arr) {
int[][] res = toPrintable(arr);
int maxDigits = maxDigits(arr);
for (int i = 0; i < res.length; i++) {
for (int j = 0; j < res[i].length; j++)
switch (res[i][j]) {
case WALL:
wall(); break;
case BLOCK:
block(); break;
case BLANK:
blank(); break;
case WATER:
water(); break;
default:
printHeight(res[i][j], maxDigits, j == 0);
}
line();
}
}
|
1f2f8e94-c7b4-4587-b21f-cf974c7b335f
| 0
|
protected Farm() {}
|
3dbfdb3b-f902-4a9a-9001-7191d2ad654a
| 8
|
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet reSet = null;
/* 开源数据连接池 */
// BasicDataSource dataSource = new BasicDataSource();
// dataSource.setDriverClassName("com.mysql.jdbc.Driver");
// dataSource.setUrl("jdbc:mysql://localhost/test");
// dataSource.setUsername("root");
// dataSource.setPassword("root");
try {
/* 通过配置文件方式来设置DBCP,注意配置文件的key写法要与上面的setXXXX相对应,首字母改为小写 */
Properties prop = new Properties();
prop.load(new FileReader(DBCPDemo01.class.getClassLoader().getResource("dbcp.properties").getPath()));
BasicDataSourceFactory factory = new BasicDataSourceFactory();
BasicDataSource dataSource = (BasicDataSource)factory.createDataSource(prop);
/* 得到数据连接。 */
conn = dataSource.getConnection();
ps = conn.prepareStatement("SELECT * FROM users");
reSet = ps.executeQuery();
while(reSet.next()){
System.out.println(reSet.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
} finally{
if(reSet!=null){
try {
reSet.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
/* 手动将其引用指向null,java的内存清理机制最终会对其清除 */
reSet = null;
}
}
if(ps!=null){
try {
ps.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
/* 手动将其引用指向null,java的内存清理机制最终会对其清除 */
ps = null;
}
}
if(conn!=null){
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
/* 手动将其引用指向null,java的内存清理机制最终会对其清除 */
conn = null;
}
}
}
}
|
f7b4896d-4444-4707-892f-bbcfac36b56b
| 5
|
public static String get(String propertyName)
{
if (prop == null || prop.getProperty(propertyName) == null)
{
try
{
loadProperties(propertyFilePath);
}
catch (IOException e)
{
try
{
propertyFilePath = ".." + File.separator + propertyFilePath;
loadProperties(propertyFilePath);
}
catch (FileNotFoundException ex)
{
System.err.println("Property file not found");
e.printStackTrace();
System.exit(0);
}
catch (IOException ex)
{
System.err.println("Error while reading property file");
e.printStackTrace();
System.exit(0);
}
}
}
return prop.getProperty(propertyName);
}
|
8b9d02dc-11b9-4568-86cd-32f1eba8495f
| 9
|
@Override
public void run() {
boolean shutdown = false;
try (Socket socket = this.socket) {
Request request = getRequest();
WebResponse response = new WebResponse();
if (request == null) {
WebLogger.log("request = null");
response.setError(Response.STATUS_BAD_REQUEST, "request == null");
} else {
WebLogger.log("request = " + request.getMethod() + " " + request.getPath());
Servlet servlet = server.findServlet(request);
if (servlet == null) {
WebLogger.log("servlet = null");
response.setError(Response.STATUS_NOT_FOUND, "servlet not found");
} else {
WebLogger.log("servlet = " + servlet.getName());
try {
servlet.service(request, response);
} catch (Exception e) {
response.setError(Response.STATUS_ERROR, e);
}
}
}
WebLogger.log("response = " + response.getStatus());
if (response.getStatus() == null) {
response.setError(Response.STATUS_ERROR, "response status == null");
} else if (response.getStatus().equals(WebResponse.STATUS_SHUTDOWN)) {
shutdown = true;
response.setStatus(Response.STATUS_OK);
}
PrintStream stream = new PrintStream(socket.getOutputStream(), false, "UTF-8");
if (request != null && request.getMethod().equals(Request.METHOD_HEAD)) {
response.writeTo(stream, true);
} else {
response.writeTo(stream, false);
}
} catch (IOException e) {
e.printStackTrace();
}
if (shutdown) {
System.exit(0);
}
}
|
7647b32d-9852-42dc-aa05-27c629fd83fd
| 8
|
public void displayPoint(GeoPoint gp) throws IOException {
double marginBuffer = 0.2;
double sx = (Math.abs(gp.longitude - params.longMin) / (1 + marginBuffer) *
windowFactor + pWidth * marginBuffer / 2);
double sy = pHeight - (Math.abs(gp.latitude - params.latMin) / (1 + marginBuffer) *
windowFactor + pHeight * marginBuffer / 2);
int x = (int) (sx);
int y = (int) (sy);
double iconSize = gp.size;
/* Recolor the actual image that paints to the panel. We take whatever color is
* selected by the user, and apply it subtractively to the icon color. So if the
* user chooses green, and the icon image file is white, it shows as green. However,
* if the icon file is red, and the user chooses green, it shows as black. This is
* as close as I could come in a quick hack to mimicking the behaviour of Google
* Earth with custom icons; it's a reasonable approximation of what you'll see in
* GE. Slightly messy algorism, but there you go. Might have problems with some
* icon files (I don't know what happens if you try to load something with no Alpha
* channel... */
// TODO this takes too long. Would be way better with OpenGL...
if(icon != null){
int w = icon.getWidth();
int h = icon.getHeight();
BufferedImage iconToDraw = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
int[] rgbArray = new int[w * h];
icon.getRGB(0, 0, w, h, rgbArray, 0, w);
for(int i = 0; i < rgbArray.length; i++){
Color col = new Color(rgbArray[i], true);
int oldR = col.getRed();
int oldG = col.getGreen();
int oldB = col.getBlue();
int oldA = col.getAlpha();
int newR = (oldR > gp.color.getRed()) ? gp.color.getRed() : oldR;
int newG = (oldG > gp.color.getGreen()) ? gp.color.getGreen() : oldG;
int newB = (oldB > gp.color.getBlue()) ? gp.color.getBlue() : oldB;
int newA = (oldA > gp.color.getAlpha()) ? gp.color.getAlpha() : oldA;
col = new Color(newR, newG, newB, newA);
rgbArray[i] = col.getRGB();
}
mapGraphics.setColor(gp.color);
iconToDraw.setRGB(0, 0, w, h, rgbArray, 0, w);
/* Custom icons (pictures) in Google Earth seem show up about 45 pixels wide
* onscreen when the icon size value is 1. Let's use 10 pixels as our default
* value, since the Joekit preview window is maybe 1/4 the screen */
int iconHalfWidth = (int)(iconSize * 5);
int iconHalfHeight = (int)(iconSize * 5 * h / w);
int iconWidth = (iconHalfWidth < 1) ? 1 : iconHalfWidth * 2;
int iconHeight = (iconHalfHeight < 1) ? 1 : iconHalfHeight * 2;
mapGraphics.drawImage(iconToDraw, x - iconHalfWidth, y - iconHalfHeight,
iconWidth, iconHeight, null);
}else{
mapGraphics.setColor(gp.color);
int iconScreenSize = (int)(iconSize * 8);
mapGraphics.fillOval(x, y, iconScreenSize, iconScreenSize);
// TODO display an error to the user concerning their unworkable image file
}
}
|
734ed7a5-8753-4bd9-b696-45ebafc61912
| 0
|
@Test
public void test_removePawn(){
assertNotNull(board);
board.removeAllPawns();
numberOfPawns=0;
assertEquals(numberOfPawns, board.numberOfPawns());
Pawn pawn1 = new Pawn('l', 3,4, board);
Pawn pawn2 = new Pawn('m', 2,3, board);
board.addPawn(pawn1);
assertEquals(numberOfPawns + 1, board.numberOfPawns());
board.addPawn(pawn2);
assertEquals(numberOfPawns +2, board.numberOfPawns());
board.removePawn(pawn2);
assertEquals(numberOfPawns+2-1, board.numberOfPawns());
}
|
a11ec67d-8c26-4230-825a-d545ea46da71
| 2
|
@Override
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
if (event.getItemSelectable().equals(supplierComboBox)) {
fillUpProductComboBox();
refreshTab(productComboBox.getSelectedIndex());
}
}
}
|
a238ba6d-4b01-4eae-b0da-c0053d2b1a37
| 4
|
public void addBlockDestroyEffects(int var1, int var2, int var3, int var4, int var5) {
if(var4 != 0) {
Block var6 = Block.blocksList[var4];
byte var7 = 4;
for(int var8 = 0; var8 < var7; ++var8) {
for(int var9 = 0; var9 < var7; ++var9) {
for(int var10 = 0; var10 < var7; ++var10) {
double var11 = (double)var1 + ((double)var8 + 0.5D) / (double)var7;
double var13 = (double)var2 + ((double)var9 + 0.5D) / (double)var7;
double var15 = (double)var3 + ((double)var10 + 0.5D) / (double)var7;
int var17 = this.rand.nextInt(6);
this.addEffect((new EntityDiggingFX(this.worldObj, var11, var13, var15, var11 - (double)var1 - 0.5D, var13 - (double)var2 - 0.5D, var15 - (double)var3 - 0.5D, var6, var17, var5)).func_4041_a(var1, var2, var3));
}
}
}
}
}
|
c12beffb-8973-4654-a863-de7872ade594
| 5
|
public static void insertAdress(Adress a){
try {
if(conn == null || conn.isClosed()){
conn = DatabaseConnection.getConnection();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
conn.setAutoCommit(false);
PreparedStatement stmt = conn.prepareStatement("INSERT INTO Addresses(address_id, street, number, bus, postal_code, city) "
+ "VALUES(null,?,?,?,?,?)",PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, a.getStreet());
stmt.setString(2, a.getHouseNr());
stmt.setString(3, a.getBus());
stmt.setInt(4, a.getZipcode());
stmt.setString(5, a.getCity());
stmt.execute();
ResultSet keyResultSet = stmt.getGeneratedKeys();
int newAdressId = 0;
if (keyResultSet.next()) {
newAdressId = (int) keyResultSet.getInt(1);
a.setAdressID(newAdressId);
}
conn.commit();
conn.setAutoCommit(true);
}catch(SQLException e){
System.out.println("insert fail!! - " + e);
}
}
|
62237305-848e-4de7-b336-484ad74331dd
| 4
|
public PluginUpdate getUpdate(String userKey) {
PluginUpdate update = null;
try {
userKey = userKey == null ? "" : userKey;
String url = this.urlManager.getUpdate(Constants.APP_KEY, userKey, Utils.getPluginVersion().toString(true));
JSONObject jo = getJson(Methods.POST, url, null);
if (jo.getInt("response_code") == 200) {
update = new PluginUpdate(new PluginVersion(jo.getInt("version_major"),
jo.getInt("version_minor"),
jo.getString("version_build")),
jo.getString("download_url"),
jo.getString("changes"),
jo.getString("more_info_url"));
}
} catch (JSONException e) {
BmLog.error("status getting status", e);
} catch (Throwable e) {
BmLog.error("status getting status", e);
}
return update;
}
|
98e51aea-6be3-488c-b6b8-0d15dea66622
| 4
|
public static void main( String [ ] args )
{
int numElements = 128;
int numInSameSet = 16;
DisjointSetsSlow ds = new DisjointSetsSlow( numElements );
int set1, set2;
for( int k = 1; k < numInSameSet; k *= 2 )
{
for( int j = 0; j + k < numElements; j += 2 * k )
{
set1 = ds.find( j );
set2 = ds.find( j + k );
ds.union( set1, set2 );
}
}
for( int i = 0; i < numElements; i++ )
{
System.out.print( ds.find( i )+ "*" );
if( i % numInSameSet == numInSameSet - 1 )
System.out.println( );
}
System.out.println( );
}
|
7982cd80-2c28-4585-948e-9bc28ef74f3e
| 6
|
public boolean getBoolean(String key) throws JSONException {
Object object = this.get(key);
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("JSONObject[" + quote(key)
+ "] is not a Boolean.");
}
|
c152924c-3cc5-45b1-911c-ff2dfc83f4dc
| 6
|
@EventHandler(priority = EventPriority.HIGHEST)
public void onSignChange(SignChangeEvent event)
{
Block block = event.getBlock();
if(block.getState() instanceof Sign)
{
int line = CustomFunction.findKey(event.getLines());
if(line == -1) return;
if(event.getLine(line).equalsIgnoreCase("["+ Config.SIGN_TEXT + "]")) event.setLine(line, "["+ Config.SIGN_TEXT_COLOR + Config.SIGN_TEXT + ChatColor.BLACK + "]");
if(CustomFunction.hasPermission(event.getPlayer(), "signurls.place")) {}
else
{
event.getPlayer().sendMessage(SignURLs.PREFIX + "You can not place [SignURLs] signs!");
block.breakNaturally();
return;
}
if(line == 3)
{
event.getPlayer().sendMessage(SignURLs.PREFIX + "You can not place [SignURLs] on the buttom line!");
block.breakNaturally();
return;
}
else
{
line++;
String lineText = event.getLine(line);
if(!CustomFunction.linkExists(lineText))
{
event.getPlayer().sendMessage(SignURLs.PREFIX + "The link " + ChatColor.YELLOW
+ lineText + ChatColor.WHITE + " could not be found in the DB!");
block.breakNaturally();
}
}
}
}
|
cf942312-eb8c-4657-8e36-1b8e8ad80f21
| 2
|
public int getPortalAt(final Location check){
if(check.getBlock().equals(one.getBlock())) return 1;
else if(check.getBlock().equals(one.getBlock())) return 2;
return 0;
}
|
f050e24a-f475-4462-ae63-527b0cfeb498
| 0
|
private OthelloBoardBinary(){}
|
43392687-e5ea-4804-a172-fdcaba5e4980
| 0
|
public String getTitle() {
return title;
}
|
b3a3c3ae-b279-48fa-9125-4cbf4876ced8
| 9
|
private void defineMonitor ()
{
GraphicsDevice GDev = InfoLauncher.instance().getLocation().getGDev()[ InfoLauncher.instance().getLocation().getGDevice() ];
System.out.println( InfoLauncher.instance().getLocation().getGDevice() );
Dimension screenEnd = new Dimension( GDev.getDisplayMode().getWidth() + GDev.getDefaultConfiguration().getBounds().x, GDev.getDisplayMode().getHeight() + GDev.getDefaultConfiguration().getBounds().y );
Dimension screenStart = new Dimension( GDev.getDefaultConfiguration().getBounds().x, GDev.getDefaultConfiguration().getBounds().y );
if ( this.getLocationOnScreen().x > screenEnd.width || this.getLocationOnScreen().y > screenEnd.height ||
this.getLocationOnScreen().x < screenStart.width ||
this.getLocationOnScreen().y < screenStart.height )
{
logger.debug( "Entered new monitor." );
for ( int i = 0; i < InfoLauncher.instance().getLocation().getGDev().length; i++ )
{
if ( this.getLocationOnScreen().x < InfoLauncher.instance().getLocation().getGDev()[ i ].getDisplayMode().getWidth() + InfoLauncher.instance().getLocation().getGDev()[ i ].getDefaultConfiguration().getBounds().x &&
this.getLocationOnScreen().y < InfoLauncher.instance().getLocation().getGDev()[ i ].getDisplayMode().getHeight() + InfoLauncher.instance().getLocation().getGDev()[ i ].getDefaultConfiguration().getBounds().y &&
this.getLocationOnScreen().x > InfoLauncher.instance().getLocation().getGDev()[ i ].getDefaultConfiguration().getBounds().x &&
this.getLocationOnScreen().x > InfoLauncher.instance().getLocation().getGDev()[ i ].getDefaultConfiguration().getBounds().x )
{
InfoLauncher.instance().getLocation().setGDevice( i );
InfoLauncher.instance().getLocation().setScreen();
logger.debug( "Monitor changed: <br> New screen is device" + i );
}
}
}
}
|
7518e58e-fae9-4a00-9d73-3d0507e02ca7
| 9
|
@Override
public void run() throws IOException {
int in = 0;
draw();
m_IO.flush();
do {
// get next key
in = m_IO.read();
switch (in) {
case BasicTerminalIO.LEFT:
case BasicTerminalIO.UP:
if (!selectPrevious()) {
m_IO.bell();
}
break;
case BasicTerminalIO.RIGHT:
case BasicTerminalIO.DOWN:
if (!selectNext()) {
m_IO.bell();
}
break;
case BasicTerminalIO.TABULATOR:
case BasicTerminalIO.ENTER:
in = -1;
break;
default:
m_IO.bell();
}
m_IO.flush();
} while (in != -1);
}// run
|
e6124ea1-f39c-4606-8c76-29cb3e4ab38e
| 8
|
public static void pprintLiteralWrapper(LiteralWrapper self, org.powerloom.PrintableStringWriter stream) {
{ Surrogate testValue000 = Stella_Object.safePrimaryType(self);
if (Surrogate.subtypeOfBooleanP(testValue000)) {
{ BooleanWrapper self000 = ((BooleanWrapper)(self));
stream.print(self000.wrapperValue);
}
}
else if (Surrogate.subtypeOfIntegerP(testValue000)) {
{ IntegerWrapper self000 = ((IntegerWrapper)(self));
stream.print(self000.wrapperValue);
}
}
else if (Surrogate.subtypeOfFloatP(testValue000)) {
{ FloatWrapper self000 = ((FloatWrapper)(self));
stream.print(self000.wrapperValue);
}
}
else if (Surrogate.subtypeOfCharacterP(testValue000)) {
{ CharacterWrapper self000 = ((CharacterWrapper)(self));
stream.print(self000.wrapperValue);
}
}
else if (Surrogate.subtypeOfStringP(testValue000)) {
{ StringWrapper self000 = ((StringWrapper)(self));
if (((Boolean)(Stella.$PRINTREADABLYp$.get())).booleanValue()) {
stream.print("\"" + self000.wrapperValue + "\"");
}
else {
stream.print(self000.wrapperValue);
}
}
}
else if (Surrogate.subtypeOfP(testValue000, OntosaurusUtil.SGT_STELLA_MUTABLE_STRING_WRAPPER)) {
{ MutableStringWrapper self000 = ((MutableStringWrapper)(self));
if (((Boolean)(Stella.$PRINTREADABLYp$.get())).booleanValue()) {
stream.print("\"" + self000.wrapperValue + "\"");
}
else {
stream.print(self000.wrapperValue);
}
}
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("`" + testValue000 + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
}
}
|
029c3f53-455e-44ab-a6b0-8cbcdf869e5c
| 8
|
private void configurePath() {
// Configurar carpeta de usuario
USER_HOME = System.getProperty("user.home"); //$NON-NLS-1$
// Configurar carpeta de aplicacion
File appDir = new File(USER_HOME + "\\TH Solution\\"); //$NON-NLS-1$
if (!appDir.exists() || !appDir.isDirectory()) {
boolean result = appDir.mkdir();
if(result) {
System.out.println("DIRECTORIO creado"); //$NON-NLS-1$
}
}
APP_HOME = appDir.getAbsolutePath() + "\\"; //$NON-NLS-1$
// Configurar carpeta de instalacion
String value;
try {
value = WinRegistry.readString (
WinRegistry.HKEY_LOCAL_MACHINE, //HKEY
"SOFTWARE\\THSolution", //Key (32 bits) //$NON-NLS-1$
"InstallPath"); //ValueName //$NON-NLS-1$
if (value == null){
value = WinRegistry.readString (
WinRegistry.HKEY_LOCAL_MACHINE, //HKEY
"SOFTWARE\\Wow6432Node\\THSolution", //Key (64 bits) //$NON-NLS-1$
"InstallPath"); //ValueName //$NON-NLS-1$
}
if(value == null){
return;
}
INSTALL_PATH = value + "\\"; //$NON-NLS-1$
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
|
3304c59a-0d83-492e-b0b7-ca2ae362b803
| 3
|
public CtConstructor getConstructor(String desc)
throws NotFoundException
{
CtMember.Cache memCache = getMembers();
CtMember cons = memCache.consHead();
CtMember consTail = memCache.lastCons();
while (cons != consTail) {
cons = cons.next();
CtConstructor cc = (CtConstructor)cons;
if (cc.getMethodInfo2().getDescriptor().equals(desc)
&& cc.isConstructor())
return cc;
}
return super.getConstructor(desc);
}
|
b7b5eb94-dce8-4e61-9f92-fdddd1c003e3
| 9
|
public String guardar (){
if("".equals(nombre) || "".equals(carrera) || "".equals(edad) || "".equals(correo) || "".equals(contraseña) ||
"".equals(carnet) || "".equals(año) || "".equals(telefono) || "".equals(direccion)){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Información necesaria faltante"));
}
else{
Texto archivo = new Texto();
Persona persona = new Persona (nombre, carrera, edad, correo, contraseña, carnet, año, telefono, direccion, foto);
Nodo nuevo = new Nodo (persona);
this.lista.agregar(nuevo);
archivo.guardar(nombre, nombre+nl+ carrera+nl+ edad+nl+ correo+nl+ contraseña+nl+ carnet+nl+ año+nl+ telefono+nl+ direccion+nl+ foto+nl+nuevo);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Se registro correctamente "+nombre+" "+contraseña+" "+carnet));
return "faces/inicio.xhtml";
}
return null;
}
|
735de8db-ebb7-48ad-bfe3-ef4ffae5b29f
| 3
|
public static HashMap<Integer, HashMap<Character, Integer>> initLanguagesMap(
String[] frequencies) {
HashMap<Integer, HashMap<Character, Integer>> mapOfLanguageFreq = new HashMap<Integer, HashMap<Character, Integer>>();
// Build correct amount of maps
for (int i = 0; i < frequencies.length; i++) {
mapOfLanguageFreq.put(i, new HashMap<Character, Integer>());
}
// While there are more elements
for (int i = 0; i < frequencies.length; i++) {
int charCount = 0;
String freqChart = frequencies[i];
HashMap<Character, Integer> languageMap = mapOfLanguageFreq.get(i);
// Go through string and build a language map out of the string
// under examination
while (charCount < freqChart.length()) {
char c = freqChart.charAt(charCount);
int value = Integer.parseInt(freqChart.substring(charCount + 1,
charCount + 3));
languageMap.put(c, value);
charCount += 3;
}
}
return mapOfLanguageFreq;
}
|
dc696631-e229-4676-b804-3388868a1e7c
| 6
|
private void set_agent(String agent, String type)
{
AgentEnum a = AgentEnum.valueOf(type);
switch(a)
{
case DNSServer:
DNSServer dnss = new DNSServer(agent, this.dns_table);
this.agents.put(agent, dnss);
break;
case FTPClient:
FTPClient ftpc = new FTPClient(agent);
this.agents.put(agent, ftpc);
break;
case FTPServer:
FTPServer ftps = new FTPServer(agent);
this.agents.put(agent, ftps);
break;
case HTTPClient:
HTTPClient httpc = new HTTPClient(agent);
this.agents.put(agent, httpc);
break;
case HTTPServer:
HTTPServer https = new HTTPServer(agent);
this.agents.put(agent, https);
break;
case Sniffer:
Sniffer sniffer = new Sniffer(agent, this.clock);
this.agents.put(agent, sniffer);
break;
default: break;
}
}
|
bea53ab6-567b-458d-b7e3-297dac85bdb0
| 0
|
public double getTotal() {
return total;
}
|
ea443589-d496-43fa-a3b9-d672423a9129
| 8
|
public static boolean delete (Object bean) {
String sql;
PreparedStatement stmt=null;
try{
if(bean instanceof Patient){
sql = "DELETE FROM patients WHERE pid = ?";
stmt = conn.prepareStatement(sql);
return deletePatient((Patient)bean, stmt);
}
if(bean instanceof Employee){
sql = "DELETE FROM employees WHERE username = ?";
stmt = conn.prepareStatement(sql);
return deleteEmployee((Employee)bean, stmt);
}
if(bean instanceof Drug){
sql = "DELETE FROM Drugs WHERE drugid = ?";
stmt = conn.prepareStatement(sql);
return deleteDrug((Drug)bean, stmt);
}
if(bean instanceof Prescription){
sql = "DELETE FROM Prescriptions WHERE presc_id = ?";
stmt = conn.prepareStatement(sql);
return deletePrescription((Prescription) bean, stmt);
}
if(bean instanceof Schedule){
sql = "DELETE FROM schedu1es WHERE work_day = ? and username = ?";
stmt = conn.prepareStatement(sql);
return deleteSchedule((Schedule)bean, stmt);
}
}catch(SQLException e){
System.out.println("SQLException within delete()");
System.out.println(e);
}finally{
if(stmt != null)
try {
stmt.close();
} catch (SQLException e) {
System.out.println("unable to close stmt within delete()");
e.printStackTrace();
}
}
return false;
}
|
dc1fc2f6-2352-456c-a29c-ff230b519b68
| 1
|
public void transform() {
changed = true;
while (changed) {
changed = false;
propagate();
}
}
|
e4e46d48-e579-489b-8b1f-3c2cf9661b09
| 2
|
private boolean hasNetherPerms(Player playerToCheck)
{
boolean hasPermission = false;
try
{
if(playerToCheck.hasPermission("modgod.nether"))
{
hasPermission = true;
}
}
catch(Exception ex)
{
// player is probably no longer online
}
return (hasPermission);
}
|
2f6eb928-66e3-4af7-88ac-163cba6ebb62
| 0
|
public ItemSetChooser(Grammar grammar, Component parent) {
this.grammar = grammar;
this.parent = parent;
chooseTable = new GrammarTable(new ImmutableGrammarTableModel(grammar));
chooseTable.addMouseListener(GTListener);
choiceTable = new GrammarTable(new ImmutableGrammarTableModel());
JScrollPane p = new JScrollPane(chooseTable);
p.setPreferredSize(new Dimension(200, 200));
panel.add(p, BorderLayout.WEST);
p = new JScrollPane(choiceTable);
p.setPreferredSize(new Dimension(200, 200));
panel.add(p, BorderLayout.EAST);
// Set up the tool bar.
JToolBar bar = new JToolBar();
bar.add(new AbstractAction("Closure") {
public void actionPerformed(ActionEvent e) {
closure();
}
});
bar.add(new AbstractAction("Finish") {
public void actionPerformed(ActionEvent e) {
finish();
}
});
panel.add(bar, BorderLayout.NORTH);
}
|
18e5ad7a-05b8-4d25-b163-6d538cb6a3f2
| 6
|
public static void loadData(File file) throws FileNotFoundException{
if(!file.exists())
throw new FileNotFoundException("Could not find file.");
YAMLFile data = new YAMLFile(true);
data.Load(file);
VirtualAudioCableManager.getManager().frame.getExField().setText(
data.getString("exeFolder"));
VirtualAudioCableManager.getManager().cables.clear();
for(String key : data.keySet()){
if(key.startsWith("cable") && key.endsWith("WindowName")){ //we found a new cable!
String name = key.split("\\.")[1];
VirtualAudioCable cable = new VirtualAudioCable(name);
for(Argument arg : Argument.values()){
if(data.getString("cable." + name + "." + arg.getTitle()) != null){
cable.setArgument(arg, data.getString("cable." + name + "." + arg.getTitle()));
}
}
VirtualAudioCableManager.getManager().cables.add(cable);
}
}
VirtualAudioCableManager.getManager().frame.updateList();
}
|
b02d4f79-1dcb-4588-82c0-64e9176947db
| 3
|
public String getQuantity() {
if (quantity==0) {
return "";
}
else if(quantity%1==0 || quantity == 1){
return ""+(int)quantity;
}
return String.valueOf(quantity);
}
|
7cb397c2-7464-4751-825f-07419ff02556
| 6
|
private boolean isPlaceable(int col, int row) {
if (row < 0 || row >= size)
throw new IllegalArgumentException(
"isPlaceable : row "
+ row + "parameter out of bounds, must be between 0 and "
+ size);
if (col < 0 || col >= size)
throw new IllegalArgumentException(
"isPlaceable : col "
+ col + "parameter out of bounds, must be between 0 and "
+ size);
if (grid[col][row] == PositionStatus.UNSAFE
|| grid[col][row] == PositionStatus.OCCUPIED)
return false;
else
return true;
}
|
9ed7f555-f181-462c-bfa2-4ef794eacfda
| 9
|
public List<Task> sort(final int colIndex, final boolean sortDown)
{
getTasks();
if(colIndex >= 0 && colIndex <= 6)
{
Collections.sort(tasks, new Comparator<Task>()
{
@Override
public int compare(Task arg0, Task arg1)
{
int result = 0;
if (colIndex == 1 || colIndex == 2 || colIndex == 3
|| colIndex == 5 || colIndex == 6)
{
StringComparer stringComparator = new StringComparer(
sortDown);
result = comparer(stringComparator, arg0, arg1, colIndex);
}
else if (colIndex == 0)
{
IntegerComparer intComparator = new IntegerComparer(
sortDown);
result = comparer(intComparator, arg0, arg1, colIndex);
}
else if (colIndex == 4)
{
DateComparer dateComparator = new DateComparer(sortDown);
result = comparer(dateComparator, arg0, arg1, colIndex);
}
return result;
}
});
}
else
{
throw new IllegalArgumentException("Invalid Column index.");
}
return tasks;
}
|
2dc3e44f-f1a2-43da-99ef-4cef9822b387
| 6
|
public static void main(String[]args){
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int m = in.nextInt();
int c = in.nextInt();
TreeMap<Integer,TreeSet<Integer>> h = new TreeMap<>();
for (int i = 1 ; i <= c ;i++){
int x = in.nextInt();
int y = in.nextInt();
h.putIfAbsent(y, new TreeSet<>());
TreeSet<Integer>t=h.get(y);
t.add(x);
h.put(y, t);
}
List<TreeMap<Integer,Integer>> l = new ArrayList<>(); // blank list of all possible paths
h.keySet().stream().forEach((i) -> {
// y coordinate of existed diagonals
TreeSet<Integer> t = h.get(i); // set of x coordinates of existed diagonals
t.stream().forEach((u) -> {
// every x of existed diagonals
boolean used = false; // if existed entry was used in list of paths
int k = 0;
while (k<l.size()){
//for (TreeMap<Integer,Integer> o:l){ // look through every path of possible maps
TreeMap<Integer,Integer> o = l.get(k);
if ((o.lastKey()<u)){ //
TreeMap<Integer,Integer> p = new TreeMap<>();
p.putAll(o);
p.put(u, i);
l.add(p);
used=true;
}
k++;
}
if (!used) {
TreeMap<Integer,Integer> s = new TreeMap<>();
s.put(u, i);
l.add(s);
}
});
});
int maxD = 0;
for (TreeMap<Integer,Integer> j:l){
maxD = (j.size()>maxD)?j.size():maxD;
}
out.println(Math.round(100*(n-maxD)+100*(m-maxD)+Math.sqrt(maxD*maxD*20000)));
out.flush();
}
|
5326c52c-4452-4811-93d3-e249a333c709
| 1
|
private void render() {
if (texture != null) {
texture.bind();
}
data.bind();
data.draw(GL11.GL_TRIANGLES, 0, idx);
data.unbind();
renderCalls++;
}
|
8a3e9f00-3bb6-4680-a01f-ca7c19990348
| 1
|
public void updateRangeListener(String resource, int rangeToAdd) {
GameActor actor = actors.get(resource);
if(actor == null) {
createPrototype(resource);
actor = actors.get(resource);
}
WeaponsComponent wc = (WeaponsComponent)actor.getComponent("WeaponsComponent");
wc.setRange(wc.getRange() + rangeToAdd);
}
|
f5bb5cc5-bec5-4031-a0bf-0cbffb9c8aa0
| 4
|
public static Elements decoder(char s) throws PusherException {
switch (s)
{
case 'x' : return WALL;
case '*' : return BOX;
case '&' : return GOAL;
case '.' : return EMPTY;
}
throw new PusherException("no such element " + s);
}
|
1938076b-2d5c-4a50-8f31-402ce093064d
| 0
|
private HibernateSessionFactory() {
}
|
c20ee78e-8857-4843-82dd-4d1059954b8a
| 0
|
public edit()
{
this.requireLogin = true;
this.addParamConstraint("id", ParamCons.INTEGER);
this.addParamConstraint("name", true);
this.addParamConstraint("capacity", ParamCons.INTEGER, true);
this.addRtnCode(405, "permission denied");
this.addRtnCode(406, "venue not found");
this.addRtnCode(201, "already exists");
}
|
bd1b6400-6b98-49cf-a3bf-b5a4b1ed9084
| 8
|
@Override
public String toString() {
String ret = null;
switch(suit){
case CLUBS:
ret = "C";
break;
case DIAMONDS:
ret = "D";
break;
case HEARTS:
ret = "H";
break;
case SPADES:
ret = "S";
break;
default:
//Do nothing.
}
switch(value){
case 14:
ret += "A";
break;
case 13:
ret += "K";
break;
case 12:
ret += "Q";
break;
case 11:
ret += "J";
break;
default:
ret += value;
}
return ret;
}
|
3565d03f-a95f-42ff-b1b6-0553053369a1
| 7
|
private static void loadData(Library library) throws FileNotFoundException, IOException {
BufferedReader in = new BufferedReader(new FileReader("data.csv"));
while (in.ready()) {
String line = in.readLine();
if (line.startsWith("#")) continue;
StringTokenizer csvReader = new StringTokenizer(line, ",");
Item item = null;
String type = csvReader.nextToken();
try {
if (type.equalsIgnoreCase("book")) {
item = new Book(csvReader.nextToken(),
csvReader.nextToken(),
Integer.parseInt(csvReader.nextToken()),
Rating.valueOf(csvReader.nextToken()),
csvReader.nextToken());
} else if (type.equalsIgnoreCase("comic")) {
item = new Comic(csvReader.nextToken(),
csvReader.nextToken(),
Integer.parseInt(csvReader.nextToken()),
Rating.valueOf(csvReader.nextToken()),
csvReader.nextToken(),
Integer.parseInt(csvReader.nextToken()),
csvReader.nextToken());
} else if (type.equalsIgnoreCase("magazine")) {
item = new Magazine(csvReader.nextToken(),
csvReader.nextToken(),
Integer.parseInt(csvReader.nextToken()),
Rating.valueOf(csvReader.nextToken()),
csvReader.nextToken(),
Integer.parseInt(csvReader.nextToken()),
csvReader.nextToken(),
csvReader.nextToken());
} else {
System.err.println("Unrecognized type : \"" + type + "\".");
continue;
}
} catch (IllegalArgumentException iae) {
printException(iae);
}
try {
library.addItem(item);
} catch (DuplicateException | NullPointerException ex) {
printException(ex);
}
}
}
|
fca61d8a-79d7-45d2-a292-06fd69a69de6
| 6
|
public boolean comprobarEstado() {
int numVivas = 0; // numero de vecinas vivas
nuevoEstado = estado;
for (int i = 0; i < numVecinas; i++) {
if (vecina[i].estado) numVivas++;
}
if (estado) {
if (numVivas < 2) // muerte por soledad
nuevoEstado = false;
if (numVivas > 3) // muerte por superpoblacion
nuevoEstado = false;
} else {
if (numVivas == 3) // nace nueva celula
nuevoEstado = true;
}
return nuevoEstado;
}
|
e8ed818f-0520-4d30-a33b-2c484e59c35e
| 1
|
public void Initialize() {
try {
Class.forName(this.dbDriver);
}
catch (ClassNotFoundException ex) {
System.out.println("Impossible d'initialiser le driver.\n" + ex.getMessage());
}
}
|
0a1e6723-cb73-4ab1-ab6b-96e4142dafe8
| 1
|
public Button(JButton button) {
this.button = button;
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
if (clickHandler != null)
clickHandler.run();
}
});
}
|
e7dd31be-0233-4fc0-b68c-1bbdcd15baad
| 3
|
public void findAndRandomizeSpawnpoints(Tile topTile){
Tile currentJTile = topTile;
for(int j = 0; j < dimension; j++){
Tile currentKTile = currentJTile;
for(int k = 0; k < dimension; k++){
if(currentKTile.tileType == TileType.SPAWN){
freeSpawnpoints.add(currentKTile);
}
currentKTile = currentKTile.rightDown;
}
currentJTile = currentJTile.leftDown;
}
Debug.debug("Found " + freeSpawnpoints.size() + " spawnpoints. Randomizing...");
Collections.shuffle(freeSpawnpoints);
}
|
efaa453d-91f7-4374-b2a7-ab15539ffe08
| 6
|
public long add(long millis, long value) {
int year = iChronology.year().get(millis);
int newYear = year + (int)TestGJChronology.div(value, 12);
if (year < 0) {
if (newYear >= 0) {
newYear++;
}
} else {
if (newYear <= 0) {
newYear--;
}
}
int newMonth = get(millis) + (int)TestGJChronology.mod(value, 12);
if (newMonth > 12) {
if (newYear == -1) {
newYear = 1;
} else {
newYear++;
}
newMonth -= 12;
}
int newDay = iChronology.dayOfMonth().get(millis);
millis = iChronology.getTimeOnlyMillis(millis)
+ iChronology.millisFromGJ(newYear, newMonth, newDay);
while (get(millis) != newMonth) {
millis = iChronology.dayOfYear().add(millis, -1);
}
return millis;
}
|
94a1489d-1db5-44d6-a6e8-d2247371185b
| 0
|
@RequestMapping(value = "/employee/skillset/{employeeId}", method = RequestMethod.GET)
@ResponseBody
public String getEmployeeSkillSet(@PathVariable String employeeId)
throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode objectNode = objectMapper.createObjectNode();
UserSkillSet userSkillSet = employeeDao.employeeSkillSet(employeeId);
String data = objectMapper.writeValueAsString(userSkillSet.getSkills());
objectNode.put("skillset", data);
return objectNode.toString();
}
|
18721448-57d0-46e2-b206-1e39c3154dcc
| 2
|
public Metrics(final Plugin plugin) throws IOException {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
}
this.plugin = plugin;
// load the config
configurationFile = getConfigFile();
configuration = YamlConfiguration.loadConfiguration(configurationFile);
// add some defaults
configuration.addDefault("opt-out", false);
configuration.addDefault("guid", UUID.randomUUID().toString());
configuration.addDefault("debug", false);
// Do we need to create the file?
if (configuration.get("guid", null) == null) {
configuration.options().header("http://mcstats.org").copyDefaults(true);
configuration.save(configurationFile);
}
// Load the guid then
guid = configuration.getString("guid");
debug = configuration.getBoolean("debug", false);
}
|
dc737f08-b5da-4e52-a3e2-3cb2af4129aa
| 5
|
public static void process(Configuration config) {
String dirName = config.getInputdir();
MappingTable mt = new MappingTable(config.getMapfile(), config);
logger.info("Processing files in " + dirName + ".");
// Actually process all the files.
Path path = Paths.get(dirName);
FileProcessor fp = new FileProcessor(mt, config.getOutputs());
try {
Files.walkFileTree(path, fp);
} catch (IOException e) {
logger.error("Error processing file " + path, e);
}
logger.info("" + mt.getNumUses() + " records mapped; " + mt.getErrors()+ " records caused error(s).");
// Processing completed; save statistics, if required.
String stat = config.getSavestats();
if (stat != null) {
PrintStream out;
boolean close;
if (stat.isEmpty()) {
close = false;
out = System.out;
} else {
close = true;
try {
out = new PrintStream(stat);
} catch (FileNotFoundException e) {
logger.error(e.getMessage(), e);
return;
}
}
mt.printStatistics(out);
if (close) out.close();
}
}
|
6926ed1a-7114-42b0-8343-6ac107af92db
| 7
|
protected Area getParentArea()
{
if((parentArea!=null)&&(parentArea.get()!=null))
return parentArea.get();
final int x=Name().indexOf('_');
if(x<0)
return null;
if(!CMath.isNumber(Name().substring(0,x)))
return null;
final Area parentA = CMLib.map().getArea(Name().substring(x+1));
if((parentA==null)
||(!CMath.bset(parentA.flags(),Area.FLAG_INSTANCE_PARENT))
||(CMath.bset(parentA.flags(),Area.FLAG_INSTANCE_CHILD)))
return null;
parentArea=new WeakReference<Area>(parentA);
return parentA;
}
|
f1960f99-5db1-45c2-be1f-4d5f25041c50
| 0
|
public Exponential(int mean, Random rnd)
{
this.mean = mean;
this.rnd = rnd;
}
|
c89d2e7f-8d0d-41ca-897d-f658bea96096
| 8
|
public void testCheckMinIdleKeyedObjectPoolKeys() throws Exception {
try {
@SuppressWarnings("unchecked")
final KeyedObjectPool<String, Object> pool = createProxy(KeyedObjectPool.class, (List<String>)null);
PoolUtils.checkMinIdle(pool, (Collection<String>)null, 1, 1);
fail("PoolUtils.checkMinIdle(KeyedObjectPool,Collection,int,long) must not accept null keys.");
} catch (IllegalArgumentException iae) {
// expected
}
// Because this isn't determinist and you can get false failures, try more than once.
AssertionFailedError afe = null;
int triesLeft = 3;
do {
afe = null;
try {
final List<String> calledMethods = new ArrayList<String>();
@SuppressWarnings("unchecked")
final KeyedObjectPool<String, ?> pool = createProxy(KeyedObjectPool.class, calledMethods);
final Collection<String> keys = new ArrayList<String>(2);
keys.add("one");
keys.add("two");
final Map<String, TimerTask> tasks = PoolUtils.checkMinIdle(pool, keys, 1, CHECK_PERIOD); // checks minIdle immediately
Thread.sleep(CHECK_SLEEP_PERIOD); // will check CHECK_COUNT more times.
final Iterator<TimerTask> iter = tasks.values().iterator();
while (iter.hasNext()) {
final TimerTask task = iter.next();
task.cancel();
}
final List<String> expectedMethods = new ArrayList<String>();
for (int i=0; i < CHECK_COUNT * keys.size(); i++) {
expectedMethods.add("getNumIdle");
expectedMethods.add("addObject");
}
assertEquals(expectedMethods, calledMethods); // may fail because of the thread scheduler
} catch (AssertionFailedError e) {
afe = e;
}
} while (--triesLeft > 0 && afe != null);
if (afe != null) {
throw afe;
}
}
|
9a71ae18-1c4c-49a5-ae8a-c0150918ebe9
| 0
|
private String getNameTypeObj(String objName) {
return objName.substring(nameGameWorld.length());
}
|
e1f44b27-104f-4958-a162-8eb4d30f36d9
| 8
|
public static Proposition findEquatingProposition(Stella_Object directobject, LogicObject indirectobject) {
{ Stella_Object indirectobjectvalue = Logic.valueOf(indirectobject);
Stella_Object backlinkedindirectobject = indirectobjectvalue;
if (!Stella_Object.isaP(backlinkedindirectobject, Logic.SGT_LOGIC_LOGIC_OBJECT)) {
backlinkedindirectobject = indirectobject;
}
{ Proposition value000 = null;
{ Proposition prop = null;
Iterator iter000 = ((Iterator)((Logic.descriptionModeP() ? Logic.unfilteredDependentPropositions(backlinkedindirectobject, Logic.SGT_PL_KERNEL_KB_EQUIVALENT).allocateIterator() : Logic.allTrueDependentPropositions(backlinkedindirectobject, Logic.SGT_PL_KERNEL_KB_EQUIVALENT, false))));
loop000 : while (iter000.nextP()) {
prop = ((Proposition)(iter000.value));
if ((prop.operator == Logic.SGT_PL_KERNEL_KB_EQUIVALENT) &&
((Stella_Object.eqlP((prop.arguments.theArray)[0], directobject) &&
Stella_Object.eqlP(Logic.valueOf((prop.arguments.theArray)[1]), indirectobjectvalue)) ||
(Stella_Object.eqlP((prop.arguments.theArray)[1], directobject) &&
Stella_Object.eqlP(Logic.valueOf((prop.arguments.theArray)[0]), indirectobjectvalue)))) {
value000 = prop;
break loop000;
}
}
}
{ Proposition value001 = value000;
return (value001);
}
}
}
}
|
f3ebff86-af4c-48de-b606-797c3332bda0
| 0
|
public void initGame(World w, int matchNum, int total) {
world = w;
match = matchNum;
totalMatches = total;
setXYasVertex(false); //RECOMMENDED: leave this as FALSE.
setHeight(HEXSIZE); //Either setHeight or setSize must be run to initialize the hex
}
|
193a3aee-c250-4a31-9449-924c2e0b472c
| 1
|
public void testNullValuesToGetInstanceThrowsException() {
try {
UnsupportedDateTimeField.getInstance(null, null);
assertTrue(false);
} catch (IllegalArgumentException e) {
assertTrue(true);
}
}
|
21ed4341-f29d-4c99-b004-bd520f58f584
| 6
|
public void run() {
if(url != null)
{
// Obtain the results of the project's file feed
if(readFeed())
{
if(versionCheck(versionTitle))
{
String fileLink = getFile(versionLink);
if(fileLink != null && type != UpdateType.NO_DOWNLOAD)
{
String name = file.getName();
// If it's a zip file, it shouldn't be downloaded as the plugin's name
if(fileLink.endsWith(".zip"))
{
String [] split = fileLink.split("/");
name = split[split.length-1];
}
saveFile(new File("plugins/" + updateFolder), name, fileLink);
}
else
{
result = UpdateResult.UPDATE_AVAILABLE;
}
}
}
}
}
|
95ea8d15-81c8-40d5-8d05-2c7c714e1da0
| 7
|
public static double Levenshtein(String s, String t) {
if (s.length() == 0)
return t.length();
if (t.length() == 0)
return s.length();
int matrix[][] = new int[s.length() + 1][t.length() + 1];
for (int i = 0; i <= s.length(); i++)
matrix[i][0] = i;
for (int i = 0; i <= t.length(); i++)
matrix[0][i] = i;
int cost = 0;
for (int i = 1; i <= s.length(); i++) {
for (int j = 1; j <= t.length(); j++) {
cost = ((s.charAt(i - 1) == t.charAt(j - 1)) ? 0 : 1);
matrix[i][j] = Math.min(
matrix[i - 1][j] + 1,
Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j - 1]
+ cost));
}
}
return ((double) (matrix[s.length()][t.length()] / Math.max(s.length(), t.length())));
}
|
b677bd75-a039-4be1-85c7-f1b974088e9a
| 9
|
public static void main(String[] args) {
System.out.printf("Veuillez entrez votre année de naissance : ");
Scanner myScan = new Scanner(System.in);
int anneeNaissance = myScan.nextInt();
int anneeCourante = Calendar.getInstance().get(Calendar.YEAR);
int age = anneeCourante - anneeNaissance;
if (anneeNaissance != 1987) {
System.out.println("Vous n'êtes pas né(e) en 1987");
}
if (age < 18 && anneeNaissance % 4 == 0) {
System.out.println("Gagner cadeau surprise (age < 18 et né dans une année bissextile");
} else {
System.out.println("Pas de cadeau");
}
if (anneeNaissance % 2 == 0) {
System.out.println("L'année que vous avez entrée est pair");
} else {
System.out.println("L'année que vous avez entrée est impair");
}
// Année bissextile: http://fr.wikipedia.org/wiki/Ann%C3%A9e_bissextile
// Condition1: divisible par 4 _ET_ NON divisible par 100
// OU
// Condition2: divisible par 400
boolean cond1Bissextile = (anneeNaissance % 4 == 0 && anneeNaissance % 100 != 0);
boolean cond2Bissextile = (anneeNaissance % 400 == 0);
// Test Equivalent (sans utiliser variables):
// if ( (anneeNaissance % 4 == 0 && anneeNaissance % 100 != 0) || anneeNaissance % 400 )
if (cond1Bissextile || cond2Bissextile) // equiv:
{
System.out.println("L'année est bissextile");
} else {
System.out.println("L'année n'est pas bissextile");
}
if (age <= 10 || age >= 60) {
System.out.printf("Vous pouvez prendre le bus gratuitement (age = %d)\n", age);
} else {
System.out.printf("Vous devez payez votre ticket de bus (age = %d)\n", age);
}
}
|
5893f1b2-b631-4eef-977c-5898f03ec73a
| 5
|
public final void tick() {
step += 1;
if (--timeUntilAddRandomGrass < 0) {
timeUntilAddRandomGrass = 10;
for (int i = 0; i < Parameter.REGROWTH_RATE.getValue(); ++i) {
addRandomGrass();
}
}
for (final Entity e : entities) {
e.step(this);
if (e.getHealth() <= 0) {
entities.remove(e);
} else if (e.getHealth() > Parameter.REPRODUCTION_HP.getValue()) {
entities.add(e.replicate(this));
}
}
setChanged();
notifyObservers();
}
|
f7d6f37b-b420-4b83-ac07-bc04244faf2b
| 0
|
public void leaving(final String name, final Object o) {
info(StringUtils.shortName(o.getClass()) + "-" + o.hashCode() + " leaving " + name + "()");
}
|
70cfa342-8325-4437-9464-b7d5ffc8bc2e
| 9
|
@Override
public ClassMap readClassMap(SymbolSet ss, int fixed, boolean readNames) throws IOException {
ClassMap ret = new ClassMap();
// load the names if necessary
if(readNames) {
String r = reader.readLine();
int numNames = Integer.parseInt(r);
while(numNames-- != 0)
ret.addClass(reader.readLine());
}
// if there are fixed values, write them
int size = ss.getSize();
for(int i = 0; i < Math.min(size,fixed); i++) {
int c = ret.addClass(ss.getSymbol(i));
if(c != i)
throw new IllegalArgumentException("Fatal error in loadClassMap");
ret.addEntry(i, i, 0);
}
// read the rest of the entries
while(reader.ready()) {
String line = reader.readLine();
if(line.length() == 0)
break;
StringTokenizer st = new StringTokenizer(line," ");
int c = ret.addClass(st.nextToken());
int v = ss.addSymbol(st.nextToken());
float prob = 0;
if(st.hasMoreTokens())
prob = (float) Float.parseFloat(st.nextToken());
if(v == 0 && c == 1) v = 1; // handle end-of-sentence
ret.addEntry(v, c, prob);
}
return ret;
}
|
4ce91d14-51b7-4f12-9357-a6212cc7c1d5
| 2
|
@Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_F1)
{
System.out.println("F1 Key Released! Toggling Debug Grid!");
if(DRAW_DEBUG_GRID == false)
{
this.showDebugGrid(true);
}
else
{
this.showDebugGrid(false);
}
}
}
|
1c83972c-f2a2-4d96-a255-f16f162ba929
| 6
|
public static void main(String[] args) {
System.out.print("Zadej cislo: ");
int sirka = VstupInt.ctiInt();
System.out.print("Zadej cislo: ");
int delka = VstupInt.ctiInt();
for (int i = 0; i < delka; i++) {
for (int j = 0; j < sirka; j++) {
if ((i == 0) || (i == (delka -1)))
System.out.print("*");
else {
if ((j == 0) || (j == (sirka - 1)))
System.out.print("*");
else
System.out.print(" ");
}
}
System.out.println();
}
}
|
2959e6b9-7b7c-4d28-90eb-a78e9bad7039
| 9
|
public void populateUserList(ArrayList<User> users) {
userListPanel.removeAll();
for (final User u : users) {
ImageIcon avatar = new ImageIcon(ImageManager.getInstance().getImage("graphics/avatars/" + u.getAvatarFilename()).getImage().getScaledInstance(35, 35, Image.SCALE_DEFAULT));
final JLabel userLabel = new JLabel(u.getUsername(), avatar, SwingConstants.HORIZONTAL);
JPanel userHolder = new JPanel();
userHolder.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
userHolder.setOpaque(true);
userHolder.setPreferredSize(new Dimension(150, 42));
userHolder.setSize(new Dimension(150, 42));
userHolder.setMaximumSize(new Dimension(150, 42));
if (u.getFaction().equals(StaticData.federation)) {
userHolder.setBackground(new Color(10, 10, 150, 40));
} else if (u.getFaction().equals(StaticData.klingon)) {
userHolder.setBackground(new Color(150, 10, 10, 40));
} else if (u.getFaction().equals(StaticData.romulan)) {
userHolder.setBackground(new Color(10, 150, 10, 40));
} else if (u.getFaction().equals(StaticData.cardassian)) {
userHolder.setBackground(new Color(150, 150, 10, 40));
} else if (u.getFaction().equals(StaticData.dominion)) {
userHolder.setBackground(new Color(115, 0, 150, 40));
} else {
userHolder.setBackground(new Color(60, 255, 0, 100));
}
userHolder.add(userLabel);
userLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
JPopupMenu menu = new JPopupMenu(u.getUsername());
JMenuItem usernameItem = new JMenuItem(u.getUsername());
JMenuItem chatItem = new JMenuItem(Client.getLanguage().get("chat_menu_chat"));
JMenuItem mailItem = new JMenuItem(Client.getLanguage().get("chat_menu_send_mail"));
JMenuItem ignoreItem = new JMenuItem(Client.getLanguage().get("chat_menu_ignore"));
chatItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean openTab = true;
for (int i = 0; i < chatTabbedPane.getTabCount(); i++) {
if (chatTabbedPane.getTitleAt(i).equalsIgnoreCase(u.getUsername())) {
ChatPanel comp = (ChatPanel) chatTabbedPane.getComponentAt(i);
openTab = false;
chatTabbedPane.setSelectedIndex(i);
break;
}
}
if (openTab) {
ChatPanel cp = new ChatPanel();
chatTabbedPane.addTab(u.getUsername(), cp);
}
}
});
menu.add(usernameItem);
menu.addSeparator();
menu.add(chatItem);
menu.add(mailItem);
menu.add(ignoreItem);
menu.show(userLabel, e.getX(), e.getY());
}
@Override
public void mousePressed(MouseEvent e) {
}
});
userListPanel.add(userHolder);
}
repaint();
validate();
}
|
e3d7f6b7-0162-41b0-9423-b0a547681b1a
| 1
|
protected void fireReceiveMessage(final ISocketServerConnection ssc,
IRemoteCallObjectMetaData meta, IRemoteCallObjectData data,
final long connectionId) throws Exception {
if (!meta.getExecCommand().equalsIgnoreCase(ISession.KEEPALIVE_MESSAGE)) {
ssc.setLastAccessTime(new Date().getTime());
ConnectionInfo info = new ConnectionInfo(
connectionId,
ssc.getCreationTime(),
ssc.getIdleTimeout(),
ssc.getLastAccessTime(),
ssc.getLastReceiptTime(),
ssc.getRemoteIP(),
ssc.getRemotePort());
fireReceiveMessageEvent(new ReceiveMessageEvent(this,
info,
meta.getExecCommand(),
data.getData()));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.