text stringlengths 14 410k | label int32 0 9 |
|---|---|
@Override
public void reduce(Text key, Iterable<Text> values, Context context)
throws IOException
{
String[] arr;
float num1 = -1;
float num2 = -1;
float f;
synchronized (this)
{
if (null == AIDReducer.fs)
{
AIDReducer.fs = FileSystem.get(context.getConfiguration());
}
if (null == AIDReducer.format)
{
AIDReducer.initAIDPrediction(context.getConfiguration());
}
}
try
{
for (Text rs : values)
{
arr = rs.toString().split(DMSHandler.SEPCHAR);
if (arr.length != 2) return;
if (arr[0].charAt(0) == PredictionTrainDataFormat.GOODAID)
{
num1 = Float.valueOf(arr[1]);
}else
{
num2 = Float.valueOf(arr[1]);
}
}
if (-1 == num1 || -1 == num2) return;
f = (num1 - num2) / 100;
this.val.set(String.format("%.2f%%", f));
key.set(AIDReducer.format.toShowData(key.toString()));
context.write(key, this.val);
} catch (InterruptedException e)
{
e.printStackTrace();
}
} | 8 |
public String enkodeRC4(String result)
{
try
{
String text2Encrypt;
byte[] ciphertext1;
ab.system.libraries.security.ABSecurity.ControllEncRC4Engine s1 = new ab.system.libraries.security.ABSecurity.ControllEncRC4Engine();
text2Encrypt = result;
s1.init(true, new KeyParameter(ABSecurity.keyRC4().getBytes()));
ciphertext1 = new byte[text2Encrypt.length()];
s1.processBytes(text2Encrypt.getBytes(), 0, text2Encrypt.length(), ciphertext1, 0);
result = s1.bytesToHex(ciphertext1);
}
catch(Exception e)
{
e.printStackTrace();
}
return result;
} | 1 |
public boolean shipInBounds(Ship ship)
{
for(int x = ship.x; x < ship.x+ship.xSize; x++)
for(int y = ship.y; y < ship.y+ship.ySize; y++)
if(!isTile(x,y))
return false;
return true;
} | 3 |
private static void mergeSort(WoodInterface[] src, WoodInterface[] dest, int low,
int high, int off) {
int length = high - low;
// Insertion sort on smallest arrays
if (length < INSERTIONSORT_THRESHOLD) {
for (int i = low; i < high; i++)
for (int j = i; j > low
&& (dest[j - 1]).compareTo(dest[j].getC()) > 0; j--)
swap(dest, j, j - 1);
return;
}
// Recursively sort halves of dest into src
int destLow = low;
int destHigh = high;
low += off;
high += off;
int mid = (low + high) >>> 1;
mergeSort(dest, src, low, mid, -off);
mergeSort(dest, src, mid, high, -off);
// If list is already sorted, just copy from src to dest. This is an
// optimization that results in faster sorts for nearly ordered lists.
if (src[mid - 1].compareTo(src[mid].getC()) <= 0) {
System.arraycopy(src, low, dest, destLow, length);
return;
}
// Merge sorted halves (now in src) into dest
for (int i = destLow, p = low, q = mid; i < destHigh; i++) {
if (q >= high || p < mid
&& src[p].compareTo(src[q].getC()) <= 0)
dest[i] = src[p++];
else
dest[i] = src[q++];
}
} | 9 |
public String toString(Collection<State> states, String[] alphabet,
State starting) {
int maxCellLen = 0;
for (State state : states) {
if (state.name().length() > maxCellLen) {
maxCellLen = state.name().length();
}
List<String> eachStateMovesList = state.movesStringList();
for (String eachMove : eachStateMovesList) {
if (eachMove.length() > maxCellLen) {
maxCellLen = eachMove.length();
}
}
}
StringBuilder sb = new StringBuilder();
sb.append("Moves table:").append(System.getProperty("line.separator"));
sb.append("starting state: ").append(starting)
.append(System.getProperty("line.separator"));
appendCell(sb, maxCellLen + 1, "");
for (String ch : alphabet) {
appendCell(sb, maxCellLen + 1, ch);
}
sb.append(System.getProperty("line.separator"));
for (State state : states) {
appendCell(sb, maxCellLen, state.name());
for (String ch : alphabet) {
Move m = state.getMove(ch);
sb.append("|");
appendCell(sb, maxCellLen, m.toString());
}
sb.append(System.getProperty("line.separator"));
}
return sb.toString();
} | 7 |
public void completeAll() {
do {
completeStep();
} while (step != FINISHED);
} | 1 |
public Server(int port, String locationIP) {
ip = locationIP;
try {
serverS = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
} | 1 |
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder out = new StringBuilder();
int nCase = Integer.parseInt(in.readLine().trim());
for (int t = 0; t < nCase; t++) {
in.readLine();
if (t != 0)
out.append("\n");
String[] vars = in.readLine().trim().split(" ");
size = vars.length;
map = new int[100];
map2 = new char[size + 1];
ady = new ArrayList[size + 1];
parents = new int[size + 1];
int id = 1;
for (int i = 0; i < size; i++) {
char l = vars[i].charAt(0);
map[l] = id;
map2[id++] = l;
}
for (int i = 0; i <= size; i++)
ady[i] = new ArrayList<Integer>(30);
String[] ins = in.readLine().trim().split(" ");
for (int i = 0; i < ins.length; i++) {
int a = map[ins[i].charAt(0)];
int b = map[ins[i].charAt(2)];
ady[b].add(a);
parents[a]++;
}
for (int i = 1; i < parents.length; i++)
if (parents[i] == 0) {
parents[i]++;
ady[0].add(i);
}
ans = new ArrayList<String>();
DFS(0, 0, 0, "");
Collections.sort(ans);
for (String path : ans)
out.append(path + "\n");
if (ans.isEmpty())
out.append("NO\n");
}
System.out.print(out);
} | 9 |
public boolean jsFunction_waitEndProgress(int timeout) {
deprecated();
int curr = 0; if(timeout == 0) timeout = 10000;
while(JSBotUtils.hourGlass)
{
if(curr > timeout)
return false;
Sleep(25);
curr += 25;
}
return true;
} | 3 |
public void initCommands() {
LOGGER.debug("method initCommands starting...");
// 1. Initialize the standard commands
exitCommand = propertiesLoader.loadProperty(Constants.MAIN_EXIT_COMMAND);
helpCommand = propertiesLoader.loadProperty(Constants.MAIN_HELP_COMMAND);
commands = new HashMap<String, Command>();
// 2. Load available commands
ServiceLoader<Command> commandLoader = ServiceLoader.load(Command.class);
commandLoader.reload();
// 3. Map commands to its type.
Iterator<Command> commandsIterator = commandLoader.iterator();
while (commandsIterator.hasNext()) {
Command command = commandsIterator.next();
commands.put(command.getType(), command);
}
} | 1 |
private String getFileToOpen() {
JFileChooser projectFC = new JFileChooser();
int validPath = projectFC.showOpenDialog(myCP);
if (validPath == JFileChooser.ERROR_OPTION || validPath == JFileChooser.CANCEL_OPTION) {
return null;
} else {
return projectFC.getSelectedFile().toString();
}
} | 2 |
protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) {
return("Lexical error at line " +
errorLine + ", column " +
errorColumn + ". Encountered: " +
(EOFSeen ? "<EOF> " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") +
"after : \"" + addEscapes(errorAfter) + "\"");
} | 1 |
public void mousePressed(MouseEvent e) {
if(Global.isRunning) { return; } // block mouse input while simulating
if(e.getButton() == MouseEvent.BUTTON1) { // translate the view
shiftStartPoint = e.getPoint();
setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
} else if(e.getButton() == MouseEvent.BUTTON3) {
// rotate if 3D
if(pt instanceof Transformation3D) {
rotateStartPoint = e.getPoint();
}
}
} | 4 |
@Override
public int hashCode() {
int hash = 5;
hash = 97 * hash + (this.name != null ? this.name.hashCode() : 0);
hash = 97 * hash + (this.supportedTypes != null ? this.supportedTypes.hashCode() : 0);
hash = 97 * hash + (this.required ? 1 : 0);
hash = 97 * hash + (this.notNull ? 1 : 0);
hash = 97 * hash + (this.tail ? 1 : 0);
return hash;
} | 5 |
@Override
public String toString() {
// Alignment not performed
if (score == null) return "";
char matching[] = new char[alignmentA.length];
for (int i = 0; i < alignmentA.length; i++) {
if ((alignmentA[i] == ' ') || (alignmentB[i] == ' ') || (alignmentA[i] == '-') || (alignmentB[i] == '-')) matching[i] = ' ';
else if (alignmentA[i] == alignmentB[i]) matching[i] = '|';
else matching[i] = '*';
}
return "\t" + new String(alignmentA) + "\n\t" + new String(matching) + "\n\t" + new String(alignmentB);
} | 7 |
private static boolean isAllDataValid(TreeMap<Float, float[]> value) {
for (float[] f : value.values()) {
for (float f1 : f) {
if (f1 != f1) {
return false;
}
}
}
return true;
} | 3 |
public int size() { return N; } | 0 |
private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
int filaseleccionada = tablaRegistrar.getSelectedRow();
if(filaseleccionada>=0)
{
if(JOptionPane.showConfirmDialog(null, "Esa seguro de eliminar")==0){
lstPersonas.remove(filaseleccionada);
fichero.escribirFichero(lstPersonas);
cargarDatos();
}
}else{
JOptionPane.showMessageDialog(null, "seleccione la fila");
}
}//GEN-LAST:event_btnEliminarActionPerformed | 2 |
@Override
public String getJarName() {
return jarName;
} | 0 |
public Map<Integer, List<String>> getFolderContentsInfo(String folderName) {
Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
ArrayList<String> result = new ArrayList<String>();
//Folder root = session.getRootFolder();
Folder root = null;
if (!folderName.equalsIgnoreCase("Company Home")) {
try {
root = (Folder) session.getObjectByPath("/" + folderName);
} catch (Exception ex) {
}
} else {
root = (Folder) session.getObjectByPath("/" + "");
}
if (root != null) {
ItemIterable<CmisObject> children = root.getChildren();
int i = 0;
for (CmisObject o : children) {
List<String> valList = new ArrayList<String>();
valList.add(o.getName());
valList.add(o.getId());
valList.add(o.toString());
map.put(i, valList);
i++;
}
}
return map;
} | 4 |
public List<Integer> verifyVotes(List<Integer> u_votes, int user_id){
List<Integer> accepted=new LinkedList<Integer>();
Iterator<Integer> it=u_votes.listIterator();
while(it.hasNext()){
Integer i=it.next();
if(!tempCandidates.contains(new Candidate("","",i))){
continue;
}
if(votes.get(user_id).contains(i)){
continue;
}
try{
while(!write)
wait();
daLock.readLock().lock();;
votes.get(user_id).add(i);
accepted.add(i);
daLock.readLock().unlock();
synchronized(this){
notifyAll();
}
}
catch(InterruptedException e){
}
finally{
}
}
return accepted;
} | 5 |
@Override
public void componentMoved(ComponentEvent e) {
} | 0 |
@Override
public void removerUsuario(){
if ( this.num_usuarios == 0 ) System.out.println("\nNão existem "
+ "usuários.");
else{
System.out.println("\nQual dos usuários você gostaria de remover? "
+ "[ 1 - " + this.num_usuarios + " ]" );
int i = 1;
for ( Usuario x : this.usuarios ){
System.out.println( i + ")" + x);
i++;
}
System.out.print(" > ");
Scanner scan = new Scanner(System.in);
int op;
while(true){
if (scan.hasNextInt())
op = scan.nextInt();
else{
System.out.print("Erro. Insira um número.\n\n > ");
scan.next();
continue;
}
break;
}
op -= 1;
if( op < 0 || op > this.num_usuarios - 1 ){
System.out.println("Número inválido.");
}
else{
System.out.print("\nRemover o usuário "
+ usuarios.get(op).getUsername() + "? [ s / n ]"
+ "\n\n > " );
Scanner scan2 = new Scanner(System.in);
String resposta = scan2.nextLine();
if ( !"s".equals(resposta) && !"n".equals(resposta) ){
System.out.println("Resposta inválida.");
}
else{
if ( "s".equals(resposta) ){
this.usuarios.remove(op);
this.num_usuarios--;
System.out.println("\nUsuário removido com sucesso.");
}
else{
System.out.println("\nOk. Saindo...");
}
}
}
}
} | 9 |
@Override
public void execute(CommandSender sender, String worldName, List<String> args) {
this.sender = sender;
if (worldName == null) {
error("No world given.");
reply("Usage: /gworld setinventorygroup <worldname> <groupname>");
} else if (!hasWorld(worldName)) {
reply("World not found: " + worldName);
} else if (args.size() != 1) {
error("Wrong argument count.");
reply("Usage: /gworld setinventorygroup <worldname> <groupname>");
} else {
getWorld(worldName).setInventoryGroup(args.get(0));
reply("Inventory group for world " + worldName + " set to " + args.get(0));
}
} | 3 |
public ConnectionInfo getConnectionInfo() {
return connectionInfo;
} | 0 |
private String toMatrixString(int[][] counts, int[] clusterTotals,
Instances inst)
throws Exception {
StringBuffer ms = new StringBuffer();
int maxval = 0;
for (int i = 0; i < m_numClusters; i++) {
for (int j = 0; j < counts[i].length; j++) {
if (counts[i][j] > maxval) {
maxval = counts[i][j];
}
}
}
int Cwidth = 1 + Math.max((int) (Math.log(maxval) / Math.log(10)),
(int) (Math.log(m_numClusters) / Math.log(10)));
ms.append("\n");
for (int i = 0; i < m_numClusters; i++) {
if (clusterTotals[i] > 0) {
ms.append(" ").append(Utils.doubleToString((double) i, Cwidth, 0));
}
}
ms.append(" <-- assigned to cluster\n");
for (int i = 0; i < counts[0].length; i++) {
for (int j = 0; j < m_numClusters; j++) {
if (clusterTotals[j] > 0) {
ms.append(" ").append(Utils.doubleToString((double) counts[j][i],
Cwidth, 0));
}
}
ms.append(" | ").append(inst.classAttribute().value(i)).append("\n");
}
return ms.toString();
} | 8 |
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int N, i;
System.out.println("Enter value of N");
N = s.nextInt();
int array[] = new int[N];
System.out.println("Enter " + N + " Elements");
for (i = 0; i < N; i++)
array[i] = s.nextInt();
sorter(array);
System.out.println("\nElements after sorting ");
for (i = 0; i < N; i++)
System.out.print(array[i] + " ");
System.out.println();
} | 2 |
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof DefaultHighLowDataset)) {
return false;
}
DefaultHighLowDataset that = (DefaultHighLowDataset) obj;
if (!this.seriesKey.equals(that.seriesKey)) {
return false;
}
if (!Arrays.equals(this.date, that.date)) {
return false;
}
if (!Arrays.equals(this.open, that.open)) {
return false;
}
if (!Arrays.equals(this.high, that.high)) {
return false;
}
if (!Arrays.equals(this.low, that.low)) {
return false;
}
if (!Arrays.equals(this.close, that.close)) {
return false;
}
if (!Arrays.equals(this.volume, that.volume)) {
return false;
}
return true;
} | 9 |
private ConfigurationAreaChangeInformation[] parseConfigurationChanges() throws SAXException, InterruptedException {
final List<ConfigurationAreaChangeInformation> areaChangeInformations = new LinkedList<ConfigurationAreaChangeInformation>();
while(_xmlStream.matchStartElement("konfigurationsAenderung")) {
// Startelement
final AttributeMap attributes = _xmlStream.pullStartElement().getAttributes();
// Elemente auslesen, dies ist Text. Es wird solange alles eingelesen, bis das Endetag </konfigurationsAenderung> auftaucht
final StringBuilder textBuffer = new StringBuilder();
while(true) {
if(_xmlStream.matchStartElement()) {
StartElementEvent startElementEvent = _xmlStream.pullStartElement();
textBuffer.append("<" + startElementEvent.getLocalName());
final AttributeMap attributeMap = startElementEvent.getAttributes();
if(attributeMap.size() > 0) {
// Es gibt Attribute
String attributeNames[] = attributeMap.getNames();
for(int nr = 0; nr < attributeNames.length; nr++) {
textBuffer.append(" " + attributeNames[nr] + "=\"" + attributeMap.getValue(attributeNames[nr]) + "\"");
}
}
textBuffer.append(">");
}
else if(_xmlStream.matchCharacters()) {
String text = _xmlStream.pullCharacters().getText();
// text = Pattern.compile("\n").matcher(text).replaceAll("");
// text = Pattern.compile(" ").matcher(text).replaceAll("");
// System.out.println("geparster Text:" + text + ":Ende");
textBuffer.append(text);
}
else if(_xmlStream.matchEndElement()) {
if(_xmlStream.matchEndElement("konfigurationsAenderung")) {
break;
}
else {
// Ein anderes EndTag gelesen
textBuffer.append("</" + _xmlStream.pullEndElement().getLocalName() + ">");
}
}
}
// Ende konfigurationsAenderung
_xmlStream.pullEndElement();
// Es stehen alle Informationen zur Verfügung um ein Objekt zu erzeugen
areaChangeInformations.add(
new ConfigurationAreaChangeInformation(
attributes.getValue("stand"),
attributes.getValue("version"),
attributes.getValue("autor"),
attributes.getValue("grund"),
textBuffer.toString()
)
);
}// while
return areaChangeInformations.toArray(new ConfigurationAreaChangeInformation[areaChangeInformations.size()]);
} | 8 |
public int compareTo(Individual arg) {
// Compare by class name first:
String first = getClass().getSimpleName();
String argFirst = arg.getClass().getSimpleName();
int firstCompare = first.compareTo(argFirst);
if (firstCompare != 0)
return firstCompare;
if (name != null && arg.name != null) {
int secondCompare = name.compareTo(arg.name);
if (secondCompare != 0)
return secondCompare;
}
return (arg.id < id ? -1 : (arg.id == id ? 0 : 1));
} | 6 |
private void handleKeys(int delta) {
Player.p.setSpeed(speed);
if(rotateRight){
Player.p.rotate(delta* 0.1,0);
}
if(rotateLeft){
Player.p.rotate(delta* -0.1,0);
}
if (forward) {
Player.p.moveForward(delta, true);
}
if (backward) {
Player.p.moveForward(delta, false);
}
if (left) {
Player.p.moveSide(delta, false);
}
if (rigth) {
Player.p.moveSide(delta, true);
}
} | 6 |
@Override
public void valitseVuoroToimepide(){
if (r.nextInt(2) == 0){
valinta = Valinta.LUOLASTO;
int r3 = r.nextInt(3);
super.setValittuLuolasto(super.peli.getLuolastot().get(r3));
} else {
valinta = Valinta.KORTTI;
int r3 = r.nextInt(3)+1;
setValittuKorttiruutu(r3);
//ikävästi ui sidonnainen, ei voi oikein testata
try{
if(r3 == 1){
setValittuKortti(peli.getUi().getKauppaPanel().getK1panel().getKortti());
} else if (r3 == 2){
setValittuKortti(peli.getUi().getKauppaPanel().getK2panel().getKortti());
} else if (r3 == 3){
setValittuKortti(peli.getUi().getKauppaPanel().getK3panel().getKortti());
}
} catch (Exception e){}
}
if (valinta == Valinta.LUOLASTO){
Heittely heittely = new Heittely(valittuLuolasto, this, peli);
heittely.suoritaHeittely();
} else if (valinta == Valinta.KORTTI) {
if(!osta(valittuKortti)){
valitseVuoroToimepide();
}
}
} | 8 |
public boolean select(final int... ids) {
if (selected() && !selectedIsOnOf(ids)) {
deselect();
}
if (selectedIsOnOf(ids)) {
return true;
}
final Item item = ctx.inventory.select().id(ids).shuffle().poll();
if ((ctx.game.tab() == Game.Tab.INVENTORY || ctx.game.tab(Game.Tab.INVENTORY)) && item.click("Use")) {
return Condition.wait(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return selectedIsOnOf(ids);
}
}, 50, 20);
}
deselect();
return false;
} | 6 |
public XMLChecker(String args[]) {
// Get input from the console
String startingPath = ConsoleTools.getNonEmptyInput("Enter starting path: ");
String checkType = ConsoleTools.getNonEmptyInput("Enter check type (v) validate, (w) well-formed: ").toLowerCase();
while (!(checkType.equals(VALID) || checkType.equals(WELL_FORMED))) {
checkType = ConsoleTools.getNonEmptyInput("Enter check type (v) validate, (w) well-formed: ").toLowerCase();
}
String[] fileExtensions = ConsoleTools.getSeriesOfInputs("Enter file extension to match: ");
while (fileExtensions.length <= 0) {
fileExtensions = ConsoleTools.getSeriesOfInputs("Enter file extension to match: ");
}
System.out.println("");
// Setup the Crawler
DirectoryCrawler crawler = new DirectoryCrawler();
crawler.setFileHandler(new XMLCheckerFileContentsHandler(checkType, FileTools.LINE_ENDING_WIN));
crawler.setFileFilter(new FileExtensionFilter(fileExtensions));
crawler.setVerbose(false);
// Do the Crawl
System.out.println("STARTING...");
System.out.println("");
int status = crawler.crawl(startingPath);
System.out.println("DONE");
// java -classpath com.organic.maynard.jar;xerces.jar com.organic.maynard.XMLChecker
} | 3 |
public void RemoveChannel(String channel)
{
if(VoiceChannels.contains(channel)) VoiceChannels.remove(channel);
if(OpChannels.contains(channel)) OpChannels.remove(channel);
} | 2 |
public static void oldOutputANOVAs(GroupedChannels data,
List<String> groupNames, List<Integer> conditions, int numChunks,
int precision) {
// get all condition-group sequences:
ArrayList<GroupedChannels.TaggedDataSequence> allTDSs = data
.getAllSelectedTDSs(groupNames, conditions);
chunkData(allTDSs, numChunks); // COMMENT THIS LATER
// calculate required widths for printed names and condition numbers:
int nameWidth = longestLength(groupNames); // length of longest name
int conditionWidth = // number of digits in the largest condition number
String.valueOf(Collections.max(conditions)).length();
// make sure the fields will be wide enough to hold the ANOVA values,
// which will, in the widest case, consist of a 1 followed by a . and
// precision 0s: // AM I USING "PRECISION" RIGHT?
int idFieldWidth = nameWidth + conditionWidth + 2;
if (idFieldWidth < precision + 2) { // for the "1."
// if not, increase the condition width so the total field width is
// large enough:
idFieldWidth = precision + 2;
}
String idFieldFormat = "%-" + idFieldWidth + "s";
// output the first row, containing identifying information for each
// group-condition combination:
// first, output proper-width placeholder for the identifier column:
System.out.printf("%" + idFieldWidth + "s ", ""); // TOO HACKY??
// then, output all tds identifiers:
for (GroupedChannels.TaggedDataSequence tds : allTDSs) {
System.out.printf(idFieldFormat + " ", tds.getGroupName() + " c"
+ tds.getCondition());
}
System.out.println(); // print newline
// output ANOVA values line by line:
OneWayAnova myANOVA = new OneWayAnova();
for (GroupedChannels.TaggedDataSequence first : allTDSs) {
// output tds identifier in first column:
System.out.printf(idFieldFormat + " ", first.getGroupName() + " c"
+ first.getCondition());
// create Collection to send to the ANOVA object:
LinkedList<double[]> dataSets = new LinkedList<double[]>();
// convert first's data sequence to an array, then add it to
// dataSets
dataSets.add(toPrimitiveDoubleArray(first.getData()));
dataSets.add(null); // placeholder for second's data sequence
for (GroupedChannels.TaggedDataSequence second : allTDSs) {
// convert and add second's data sequence to position one in
// dataSets:
dataSets.set(1, toPrimitiveDoubleArray(second.getData()));
double result = -1; // not a valid ANOVA value so we know if
// something went wrong
try {
result = myANOVA.anovaPValue(dataSets);
} catch (Exception ex) {
System.out.println();
localError("unknown problem calculating ANOVA: "
+ ex.getMessage());
}
System.out.printf(
"%-" + idFieldWidth + "." + precision + "f ", result);
// dataSets.remove(1); // remove second's data from dataSets
}
System.out.println(); // print newline
}
} | 5 |
@SuppressWarnings("deprecation")
private void parseCommand(CommandSender sender, String... args)
throws EntityEffectError {
Player senderPlayer = (sender instanceof Player ? ((Player) sender)
: null);
Player player = null;
PlayableEntityEffect effect = null;
if (args.length > 0) {
try {
effect = PlayableEntityEffect.parse(args[0]);
} catch (NullPointerException e) {
throw new EntityEffectError("You must specify an effect.");
} catch (IllegalArgumentException e) {
throw new EntityEffectError("Unknown entity effect: " + args[0]);
}
}
if (args.length > 1) {
player = plugin.getServer().getPlayerExact(args[1]);
if (player == null) {
throw new EntityEffectError("Unknown player: " + args[1]);
}
}
playEffect(effect, senderPlayer, player);
} | 6 |
public int cdl3WhiteSoldiersLookback( )
{
return ((( ((( (this.candleSettings[CandleSettingType.ShadowVeryShort.ordinal()].avgPeriod) ) > ( (this.candleSettings[CandleSettingType.BodyShort.ordinal()].avgPeriod) )) ? ( (this.candleSettings[CandleSettingType.ShadowVeryShort.ordinal()].avgPeriod) ) : ( (this.candleSettings[CandleSettingType.BodyShort.ordinal()].avgPeriod) )) ) > ( ((( (this.candleSettings[CandleSettingType.Far.ordinal()].avgPeriod) ) > ( (this.candleSettings[CandleSettingType.Near.ordinal()].avgPeriod) )) ? ( (this.candleSettings[CandleSettingType.Far.ordinal()].avgPeriod) ) : ( (this.candleSettings[CandleSettingType.Near.ordinal()].avgPeriod) )) )) ? ( ((( (this.candleSettings[CandleSettingType.ShadowVeryShort.ordinal()].avgPeriod) ) > ( (this.candleSettings[CandleSettingType.BodyShort.ordinal()].avgPeriod) )) ? ( (this.candleSettings[CandleSettingType.ShadowVeryShort.ordinal()].avgPeriod) ) : ( (this.candleSettings[CandleSettingType.BodyShort.ordinal()].avgPeriod) )) ) : ( ((( (this.candleSettings[CandleSettingType.Far.ordinal()].avgPeriod) ) > ( (this.candleSettings[CandleSettingType.Near.ordinal()].avgPeriod) )) ? ( (this.candleSettings[CandleSettingType.Far.ordinal()].avgPeriod) ) : ( (this.candleSettings[CandleSettingType.Near.ordinal()].avgPeriod) )) )) +
2;
} | 5 |
public void run() {
Scanner in = new Scanner(System.in);
// get first line and get the number of cases to test.
int caseCount = Integer.parseInt(in.nextLine());
int loopCount = 0;
while (caseCount - loopCount > 0) {
String line = in.nextLine();
// extract numbers, this is the node count and edge count.
Scanner sc = new Scanner(line);
int vertexCount = sc.nextInt();
int edgeCount = sc.nextInt();
// Create the adjacency List.
adjacencyList = new ArrayList<ArrayList<edge>>();
adjacencyEdges = new ArrayList<HashSet<Integer>>();
for (int n = 0; n < vertexCount; n++) {
adjacencyList.add(new ArrayList<edge>());
adjacencyEdges.add(new HashSet<Integer>());
}
while (edgeCount-- > 0) {
// Get our next edge...
line = in.nextLine();
// extract numbers, this is the node count and edge count.
sc = new Scanner(line);
int source = sc.nextInt();
int dest = sc.nextInt();
edge edge1 = new edge(dest, 0);
edge edge2 = new edge(source, 0);
if (!adjacencyEdges.get(source).contains(edge1.hashCode())) {
adjacencyEdges.get(source).add(edge1.hashCode());
adjacencyList.get(source).add(edge1);
}
if (!adjacencyEdges.get(dest).contains(edge2.hashCode())) {
adjacencyEdges.get(dest).add(edge2.hashCode());
adjacencyList.get(dest).add(edge2);
}
}
System.out.printf("%d\n", ++loopCount);
// Print the resulting adjacency list.
for (int i = 0; i < vertexCount; i++) {
// Print the vertex number.
System.out.printf("%d: ", i);
ArrayList<edge> edges = adjacencyList.get(i);
// Sort the array list.
Collections.sort(edges);
// Print the contents of the array list.
for (int node = 0; node < edges.size(); node++) {
if (node + 1 == edges.size()) {
System.out.print(edges.get(node).vertex);
} else {
System.out.printf("%d, ", edges.get(node).vertex);
}
}
System.out.println();
}
}
} | 8 |
private byte[] getSound(String fileName) {
try {
URL url = Talker.class.getResource(fileName);
AudioInputStream stream = AudioSystem.getAudioInputStream(url);
AudioFormat format = stream.getFormat();
if ((format.getEncoding() == AudioFormat.Encoding.ULAW)
|| (format.getEncoding() == AudioFormat.Encoding.ALAW)) { // ��һ��ALAW/ULAW����ת����PCM�Ա�ط�
AudioFormat tmpFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
format.getSampleRate(),
format.getSampleSizeInBits() * 2, format.getChannels(),
format.getFrameSize() * 2, format.getFrameRate(), true);
stream = AudioSystem.getAudioInputStream(tmpFormat, stream);
format = tmpFormat;
}
DataLine.Info info = new DataLine.Info(Clip.class, format,
((int) stream.getFrameLength() * format.getFrameSize()));
if (line == null) {
DataLine.Info outInfo = new DataLine.Info(SourceDataLine.class,
format);// �����û��ʵ�� �Ƿ��ܹ��ҵ����ʵ���������ͣ�
if (!AudioSystem.isLineSupported(outInfo)) {
System.out.println("��֧��ƥ��" + outInfo + "�������");
throw new Exception("��֧��ƥ��" + outInfo + "�������");
}
line = (SourceDataLine) AudioSystem.getLine(outInfo); // �������
line.open(format, 50000);
line.start();
}
int frameSizeInBytes = format.getFrameSize();
int bufferLengthInFrames = line.getBufferSize() / 8;
int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes;
byte[] data = new byte[bufferLengthInBytes];
int numBytesRead = 0; // ��ȡ�ֽ���ݣ�������
if ((numBytesRead = stream.read(data)) != -1) {
int numBytesRmaining = numBytesRead;
}
byte[] newData = new byte[numBytesRead]; // ���ֽ�����и�ɺ��ʵĴ�С
for (int i = 0; i < newData.length; i++)
newData[i] = data[i];
return newData;
} catch (Exception e) {
return new byte[0];
}
} | 7 |
private void computePrimeFactors() {
long X = N;
long i;
for (i = 2; i != 1 && i * i < X; i++) {
if (X % i == 0) {
primes[primeCount++] = i;
do {
X /= i;
} while (X % i == 0);
}
}
if (X != 1) primes[primeCount++] = X;
for (long pri : primes) {
System.out.print(pri + "-");
}
System.out.println();
} | 6 |
public static void isiTabel(){
final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final String DB_URL = "jdbc:mysql://localhost/perpus";
// Database credentials
final String USER = "root";
final String PASS = "";
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT * FROM anggota where 1";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
int i=0;
while(rs.next()){
//Retrieve by column name
String nim = rs.getString("nim");
String nama = rs.getString("nama");
String jurusan = rs.getString("jurusan");
String alamat = rs.getString("alamat");
//Display values
jTable4.getModel().setValueAt(nim, i, 0);
jTable4.getModel().setValueAt(nama, i, 1);
jTable4.getModel().setValueAt(jurusan, i, 2);
jTable4.getModel().setValueAt(alamat, i, 3);
i++;
}
rs.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
} | 7 |
public void createNodes(OpdrachtCatalogus opdrachtCatalogus){
top.removeAllChildren();
try {
DefaultMutableTreeNode opdracht = null;
List<Opdracht> opdrachten = opdrachtCatalogus.getOpdrachten();
for(Opdracht o : opdrachten){
String nameOpdracht = o.toString();
opdracht = new DefaultMutableTreeNode(nameOpdracht);
top.add(opdracht);
}
DefaultMutableTreeNode currentNode = top.getNextNode();
do {
if (currentNode.getLevel()==1)
tree.expandPath(new TreePath(currentNode.getPath()));
currentNode = currentNode.getNextNode();
}
while (currentNode != null);
} catch (Exception e) {
System.out.println(e.getMessage());
}
} | 4 |
public static void setupConsoleLogging() {
Logger rootLogger = getRootLogger();
consoleHandler.setLevel(Level.ALL);
consoleHandler.setFormatter(new Formatter() {
private StringBuffer recordBuffer = new StringBuffer();
private DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z");
/**
* {@inheritDoc}
*/
@Override
public synchronized String format(LogRecord record) {
recordBuffer.setLength(0);
String linePrefix = dateFormatter.format(new Date(record.getMillis())) + " [" + record.getLevel() + "] [" + Thread.currentThread().getName() + "] [" + record.getSourceClassName() + "." + record.getSourceMethodName() + "] ";
recordBuffer.append(linePrefix).append(String.format(record.getMessage(), record.getParameters())).append('\n');
if (record.getThrown() != null) {
Throwable throwable = record.getThrown();
boolean causedBy = false;
while (throwable != null) {
recordBuffer.append(linePrefix);
if (causedBy) {
recordBuffer.append("caused by: ");
}
recordBuffer.append(throwable.getClass().getName());
if (throwable.getMessage() != null) {
recordBuffer.append(": ").append(throwable.getMessage());
}
recordBuffer.append("\n");
StackTraceElement[] stackTraceElements = throwable.getStackTrace();
for (StackTraceElement stackTraceElement : stackTraceElements) {
recordBuffer.append(linePrefix).append(" at ").append(stackTraceElement.getClassName()).append('.').append(stackTraceElement.getMethodName()).append("(").append(stackTraceElement.getFileName()).append(':').append(stackTraceElement.getLineNumber()).append(')').append("\n");
}
throwable = throwable.getCause();
causedBy = true;
}
}
return recordBuffer.toString();
}
});
rootLogger.addHandler(consoleHandler);
} | 5 |
public void sendKeyData() {
PlayerManager playerManager = registry.getPlayerManager();
if (playerManager != null) {
Player p = registry.getPlayerManager().getCurrentPlayer();
if (p != null) {
UDPKeys uk = new UDPKeys(
p.getId(),
gameController.getGamePanel().keySpacePressed,
gameController.getGamePanel().keyRightPressed,
gameController.getGamePanel().keyLeftPressed,
gameController.getGamePanel().keyGatherPressed,
gameController.getGamePanel().keyRobotPressed);
if(uk.hasChange(oldUK)) {
try {
sendPacket(uk);
oldUK = null;
oldUK = uk;
} catch (IOException e) {
e.printStackTrace();
//running = false;
}
}
}
}
} | 4 |
void notifyListeners(Object created, Page modified) {
for (TreeModelListener l : modelListeners) {
if (created != null) {
TreeModelEvent e = null;
if (created instanceof Name) {
e = new TreeModelEvent(this, ((Name)created).getPath());
} else if (created instanceof Page) {
e = new TreeModelEvent(this, ((Page)created).getPath());
} else {
throw new NotImplementedException();
}
l.treeNodesInserted(e);
//l.treeStructureChanged(new TreeModelEvent(this, new TreePath(root)));
}
}
} | 4 |
public void setData(int x, int y, int val) {
if (x < 0 || y < 0 || x >= w || y >= h) return;
data[x + y * w] = (byte) val;
} | 4 |
public JavaScriptObject getJsObject() {
JavaScriptObject jsObj = JsoHelper.createObject();
if (tag != null)
JsoHelper.setAttribute(jsObj, "tag", tag);
if (id != null)
JsoHelper.setAttribute(jsObj, "id", id);
if (cls != null)
JsoHelper.setAttribute(jsObj, "cls", cls);
if (style != null)
JsoHelper.setAttribute(jsObj, "style", style);
if (html != null)
JsoHelper.setAttribute(jsObj, "html", html);
for (@SuppressWarnings("rawtypes")
Iterator iterator = otherConfig.keySet().iterator(); iterator.hasNext();) {
String attribute = (String) iterator.next();
String value = (String) otherConfig.get(attribute);
JsoHelper.setAttribute(jsObj, attribute, value);
}
if (children != null) {
JavaScriptObject[] childrenJS = new JavaScriptObject[children
.size()];
int i = 0;
for (@SuppressWarnings("rawtypes")
Iterator it = children.iterator(); it.hasNext(); i++) {
DomConfig config = (DomConfig) it.next();
childrenJS[i] = config.getJsObject();
}
JsoHelper.setAttribute(jsObj, "children", childrenJS);
}
return jsObj;
} | 8 |
private NearbyPlace toNearbyPlace(RequestBean request, SearchLocation location)
throws CitysearchException {
NearbyPlace nearbyPlace = new NearbyPlace();
String addr = Utils.getLocationString(location.getCity(), location.getState());
nearbyPlace.setStreet(location.getStreet());
nearbyPlace.setCity(location.getCity());
nearbyPlace.setState(location.getState());
nearbyPlace.setPostalCode(location.getPostalCode());
nearbyPlace.setLocation(addr);
String adUnitIdentifier = request.getAdUnitIdentifier();
StringBuilder nameLengthProp = new StringBuilder(adUnitIdentifier);
nameLengthProp.append(".");
nameLengthProp.append(CommonConstants.NAME_LENGTH);
String name = location.getName();
name = Utils.getAbbreviatedString(name, nameLengthProp.toString());
nearbyPlace.setName(name);
String rating = location.getRating();
List<Integer> ratingList = Utils.getRatingsList(rating);
double ratings = Utils.getRatingValue(rating);
nearbyPlace.setRating(ratingList);
nearbyPlace.setRatings(ratings);
String reviewCount = location.getReviewCount();
int userReviewCount = Utils.toInteger(reviewCount);
nearbyPlace.setReviewCount(userReviewCount);
// Calculate distance only if lat&lon passed in request
if (!StringUtils.isBlank(request.getLatitude())
&& !StringUtils.isBlank(request.getLongitude())
&& !StringUtils.isBlank(location.getLatitude())
&& !StringUtils.isBlank(location.getLongitude())) {
BigDecimal sourceLat = new BigDecimal(request.getLatitude());
BigDecimal sourceLon = new BigDecimal(request.getLongitude());
BigDecimal destLat = new BigDecimal(location.getLatitude());
BigDecimal destLon = new BigDecimal(location.getLongitude());
double distance = Utils.getDistance(sourceLat, sourceLon, destLat, destLon);
Properties appProperties = PropertiesLoader.getApplicationProperties();
String propValue = appProperties.getProperty(CommonConstants.DISTANCE_DISPLAY_CUTOFF);
if (!StringUtils.isBlank(propValue) && StringUtils.isNumeric(propValue)) {
double nPropValue = Double.valueOf(propValue);
distance = (distance > nPropValue) ? -1 : distance;
}
nearbyPlace.setDistance(distance);
} else {
nearbyPlace.setDistance(-1);
}
nearbyPlace.setListingId(location.getListingId());
StringBuilder tagLengthProp = new StringBuilder(adUnitIdentifier);
tagLengthProp.append(".");
tagLengthProp.append(CommonConstants.TAGLINE_LENGTH);
String category = location.getCategory();
category = Utils.getAbbreviatedString(category, tagLengthProp.toString());
nearbyPlace.setCategory(category);
nearbyPlace.setAdDisplayURL(location.getAdDisplayUrl());
nearbyPlace.setAdImageURL(location.getImageUrl());
nearbyPlace.setPhone(location.getPhone());
nearbyPlace.setOffers(location.getOffers());
nearbyPlace.setCallBackFunction(request.getCallBackFunction());
nearbyPlace.setCallBackUrl(request.getCallBackUrl());
String adDisplayTrackingUrl = Utils.getTrackingUrl(nearbyPlace.getAdDisplayURL(), null,
request.getCallBackUrl(), request.getDartClickTrackUrl(),
nearbyPlace.getListingId(), nearbyPlace.getPhone(), request.getPublisher(),
request.getAdUnitName(), request.getAdUnitSize());
nearbyPlace.setAdDisplayTrackingURL(adDisplayTrackingUrl);
String callBackFn = Utils.getCallBackFunctionString(request.getCallBackFunction(),
nearbyPlace.getListingId(), nearbyPlace.getPhone());
nearbyPlace.setCallBackFunction(callBackFn);
return nearbyPlace;
} | 7 |
public static void main(String[] args) throws IOException {
StreamTokenizer st = new StreamTokenizer(new BufferedReader(
new InputStreamReader(System.in)));
while (st.nextToken() != StreamTokenizer.TT_EOF) {
int n = (int) st.nval;
if (n == 0)
System.out.println("NULL");
else {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
st.nextToken();
array[i] = (int) st.nval;
}
Main root = new Main(array[0]);
for (int i = 0; i < n; i++) {
Main m = Main.find(array[i], root);
st.nextToken();
String o = st.sval;
if (o.equals("d")) {
st.nextToken();
int p = (int) st.nval;
m.left = new Main(array[p - 1]);
st.nextToken();
p = (int) st.nval;
m.right = new Main(array[p - 1]);
} else if (o.equals("l")) {
st.nextToken();
int p = (int) st.nval;
m = Main.find(array[i], root);
m.left = new Main(array[p - 1]);
} else if (o.equals("r")) {
st.nextToken();
int p = (int) st.nval;
m = Main.find(array[i], root);
m.right = new Main(array[p - 1]);
}
}
Main.n = n;
Main.print(root);
}
}
} | 7 |
private void figthButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_figthButtonActionPerformed
//Set Rounds from textflield
rounds = 0;
try {
rounds = Integer.parseInt(throwsPerTextField.getText());
} catch (NumberFormatException e) {
extraTextField.setText("Throws per match must be an integer > 0");
return;
}
if (rounds > 0) {
info.setRounds(rounds);
} else {
extraTextField.setText("Throws per match must be an integer > 0");
return;
}
//Set difficulty from list
difficulty = difficultyList.getSelectedIndex() + 1;
if (difficulty < 1) {
extraTextField.setText("You must choose a difficulty before you can fight");
return;
}
disableLeftComponents(false);
enableComponents(true);
}//GEN-LAST:event_figthButtonActionPerformed | 3 |
public static Point[] generateControls(final int sx, final int sy, final int ex, final int ey, int ctrlSpacing, int ctrlVariance) {
final double dist = Math.sqrt((sx - ex) * (sx - ex) + (sy - ey) * (sy - ey));
final double angle = Math.atan2(ey - sy, ex - sx);
int ctrlPoints = (int) Math.floor(dist / ctrlSpacing);
ctrlPoints = ctrlPoints * ctrlSpacing == dist ? ctrlPoints - 1 : ctrlPoints;
if (ctrlPoints <= 1) {
ctrlPoints = 2;
ctrlSpacing = (int) dist / 3;
ctrlVariance = (int) dist / 2;
}
final Point[] result = new Point[ctrlPoints + 2];
result[0] = new Point(sx, sy);
for (int i = 1; i < ctrlPoints + 1; i++) {
final double radius = ctrlSpacing * i;
final Point cur = new Point((int) (sx + radius * Math.cos(angle)), (int) (sy + radius * Math.sin(angle)));
double percent = 1D - (double) (i - 1) / (double) ctrlPoints;
percent = percent > 0.5 ? percent - 0.5 : percent;
percent += 0.25;
final int curVariance = (int) (ctrlVariance * percent);
/**
* Hopefully {@link java.util.Random} is thread safe. (it is in Sun
* JVM 1.5+)
*/
cur.x = (int) (cur.x + curVariance * 2 * staticRandom.nextDouble() - curVariance);
cur.y = (int) (cur.y + curVariance * 2 * staticRandom.nextDouble() - curVariance);
result[i] = cur;
}
result[ctrlPoints + 1] = new Point(ex, ey);
return result;
} | 4 |
public void actionPerformed(ActionEvent ae){
if (ae.getSource() == addEmp){
for (int i = 0; i < 6; i++){
int n = 0;
int x = 0;
int y = 0;
if (i == 0){
n = 5;
x = 0;
y = 2;
newTextField = new JTextField(n);
g.anchor = GridBagConstraints.LINE_START;
g.gridx = x;
g.gridy = y;
empAssignP.add(newTextField, g);
} else if (i == 1){
n = 10;
x = 1;
y = 2;
newTextField = new JTextField(n);
g.anchor = GridBagConstraints.LINE_START;
g.gridx = x;
g.gridy = y;
empAssignP.add(newTextField, g);
} else if (i == 2){
n = 10;
x = 2;
y = 2;
newTextField = new JTextField(n);
g.anchor = GridBagConstraints.LINE_START;
g.gridx = x;
g.gridy = y;
empAssignP.add(newTextField, g);
} else if (i == 3){
n = 3;
x = 3;
y = 2;
newTextField = new JTextField(n);
g.anchor = GridBagConstraints.CENTER;
g.gridx = x;
g.gridy = y;
empAssignP.add(newTextField, g);
} else if (i == 4){
n = 3;
x = 4;
y = 2;
newTextField = new JTextField(n);
g.anchor = GridBagConstraints.CENTER;
g.gridx = x;
g.gridy = y;
empAssignP.add(newTextField, g);
} else if (i == 5){
n = 8;
x = 5;
y = 2;
newTextField = new JTextField(n);
g.anchor = GridBagConstraints.LINE_START;
g.gridx = x;
g.gridy = y;
empAssignP.add(newTextField, g);
addEmp2 = new JButton("+");
addEmp2.setBackground(Color.GREEN);
g.anchor = GridBagConstraints.LINE_START;
g.gridx = 6;
g.gridy = 2;
empAssignP.add(addEmp2, g);
delEmp = new JButton("-");
delEmp.setBackground(Color.RED);
g.anchor = GridBagConstraints.LINE_START;
g.gridx = 7;
g.gridy = 2;
empAssignP.add(delEmp, g);
}
empAssignP.revalidate();
}
}
} | 8 |
private void addAndRemoveButton(boolean justRemove)
{
boolean added = false;
for (Iterator<CButton> it = FileWalker.getInstance().getSetButtons().iterator(); it.hasNext();)
{
CButton cButton = it.next();
if (cButton == button)
{
it.remove();
if (justRemove)
return;
}
// Merge with other album with the same name
else if (!added && button.getText().equals(cButton.getText()))
{
added = true;
for (MediaElement mediaElement : button.getMedias())
cButton.getMedias().add(mediaElement);
}
}
// If not merge, simply add
if (!added)
FileWalker.getInstance().getSetButtons().add(button);
} | 7 |
@Override
public void drawSolutionk(Graphics drawingArea, int... arg) {
int diameter = arg[2];
int x = arg[0];
int y = arg[1];
int depth = arg[3];
int toDraw = DRAW_ALL;
if(arg.length == 5){
toDraw = arg[4];
}
if(depth == 0){return;}
drawingArea.drawOval(x - diameter/2, y - diameter/2, diameter, diameter);
if((toDraw & DRAW_UP) != 0){
drawSolutionk(drawingArea, x, y - 3*diameter/4, diameter/2, depth-1, DRAW_ULR);
}
if((toDraw & DRAW_DOWN) != 0){
drawSolutionk(drawingArea, x, y + 3*diameter/4, diameter/2, depth-1, DRAW_DLR);
}
if((toDraw & DRAW_LEFT) != 0){
drawSolutionk(drawingArea, x - 3*diameter/4, y, diameter/2, depth-1, DRAW_LUD);
}
if((toDraw & DRAW_RIGHT) != 0){
drawSolutionk(drawingArea, x + 3*diameter/4, y, diameter/2, depth-1, DRAW_RUD);
}
} | 6 |
public void welcome() {
while (!finished) {
str = "";
int selection = 0;
System.out
.println("------------------------------------------------------");
System.out
.println("Welcome to the new and improved Contact Manager Pro!");
System.out.println("What would you like to do?");
System.out.println("");
System.out.println("Enter 1 to add a new contact");
System.out.println("Enter 2 to add a new meeting");
System.out.println("Enter 3 to get contact information");
System.out.println("Enter 4 to get meeting information");
System.out.println("Enter 5 to edit meeting notes");
System.out.println("Enter EXIT to exit the program");
System.out.println("");
while (selection == 0) {
str = getInput();
if (str.equals("exit")) {
newContactManager.flush();
finished = true;
break;
}
try {
selection = Integer.parseInt(str);
} catch (NumberFormatException ex) {
System.out
.println("That was not an integer! Please try again.");
}
if (selection > 5 || selection < 1) {
System.out
.println("That was not an option, please try again.");
selection = 0;
System.out.println("Selection is zero");
}
}
mainMenu(selection);
}
} | 6 |
public static int wordLadder(String start, String end, Set<String> dict) {
if(start == null || end == null) {
return -1;
}
if(dict == null) {
return start.equals(end) ? 0 : -1;
}
LinkedList<String> queue = new LinkedList<>();
Map<String, String> parentMap = new HashMap<>();
dict.add(end);
queue.add(start);
parentMap.put(start, null);
while(!queue.isEmpty()) {
String s = queue.removeFirst();
if(s.equals(end)) {
String parent = parentMap.get(s);
int count = 1;
System.out.println(parent);
while(parent != null && !parent.equals(start)){
count ++;
parent = parentMap.get(parent);
System.out.println(parent);
}
return count;
}
for(String word : oneCharApart(s, dict, parentMap)) {
parentMap.put(word, s);
queue.add(word);
}
}
return -1;
} | 9 |
private String DNS_resolve()
{
@SuppressWarnings("unchecked")
LinkedList<Packet> buf = (LinkedList<Packet>) this.buffer.clone();
Iterator<Packet> itr = buf.iterator();
Pattern p = Pattern.compile("addr (\\d+\\.\\d+\\.\\d+\\.\\d+)");
//procura uma requisição DNS na lista de pacotes recebidos
while (itr.hasNext())
{
Packet packet = itr.next();
if (packet.getApplication() != null)
{
Matcher m = p.matcher(packet.getApplication().get_text());
this.buffer.remove(packet);
if (m.find())
return m.group(1);
}
}
//endereço não encontrado
return null;
} | 3 |
public void clearmemory(){
for(int i=0;i<65536;i++)
memnc[i]=0;
} | 1 |
public Pearson(UserPreferences user1, UserPreferences user2) {
userId1 = user1.getUserId();
userId2 = user2.getUserId();
intersection(user1, user2);
if (itemIds.length == user1.getItemIds().length && itemIds.length == user2.getItemIds().length) {
return;
}
pearson = calculatePearson();
calculateWeights();
} | 2 |
public void enqueue(E element) {
queue.insert(element);
} | 0 |
public void render() {
for (int c = 0; c < textElements.size(); c++) {
UITextElement text = textElements.get(c);
text.print();
}
for (int c = 0; c < boxElements.size(); c++) {
UIBoxElement element = boxElements.get(c);
element.draw();
}
//render look
if (look_actor != null) {
ActorType actorType = look_actor.type;
UITextElement name = new UITextElement(actorType.getName(), new Point(645, 500), 2, FontType.STD, Color.white);
UITextElement description = new UITextElement(actorType.getDescription(), new Point(645, 500 + name.getTotalHeight()),
1, FontType.STD, Color.white);
name.print();
description.print();
Image icon = portraits.getSprite(actorType.getPortaitID());
icon.draw(605, 500, 4);
}
//render hotkeys
Player player = game.player;
for (int c = 0; c < player.characterSheet.hotkeys.length; c++) {
float ppt = (DisplayConstant.width - 600) / 10f;
float scale = ppt / 10f;
AbilityType abilityType = player.characterSheet.hotkeys[c];
Image img = null;
if (abilityType == null) {
img = abilities.getSprite(AbilitySprite.blank);
} else {
img = abilities.getSprite(AbilityType.getAbilitySprite(abilityType));
}
//img.draw(DisplayConstant.width - ppt, c * ppt + 160, scale);
img.draw(c * ppt + 600, DisplayConstant.height - ppt, scale);
}
//Player info render
Image player_portrait = portraits.getSprite(PortraitSprite.player);
player_portrait.draw(605, 100, 6);
Image hp = health.getSprite(new SpriteID(0, 0));
Image nohp = nohealth.getSprite(new SpriteID(0, 0));
double maxhp = player.characterSheet.max_hp;
double curhp = player.characterSheet.hp;
float width_scale = (float) curhp / (float) maxhp;
nohp.draw(657, 120);
hp.draw(657, 120, width_scale * 100, 10f);
} | 5 |
public int getComboBox3 () {
if (jComboBox3.getSelectedIndex() == 0) return 10;
else if (jComboBox3.getSelectedIndex() == 1) return 50;
else if (jComboBox3.getSelectedIndex() == 2) return 100;
else if (jComboBox3.getSelectedIndex() == 3) return 250;
else if (jComboBox3.getSelectedIndex() == 4) return 500;
else if (jComboBox3.getSelectedIndex() == 5) return 1000;
return 5000;
} | 6 |
public String get(int searchID) {
if(searchID == 0) throw new IllegalArgumentException("Illegal Key: " + searchID);
try {
// Execute a query
this.stmt = this.conn.prepareStatement("SELECT v FROM api_results WHERE k=?");
this.stmt.setInt(1, searchID);
ResultSet rs = this.stmt.executeQuery();
String result = null;
// Extract data from result set
while (rs.next()) {
// Retrieve by column name
result = rs.getString("v");
}
// Clean-up environment
rs.close();
this.stmt.close();
if(result == null || result.equals(""))
{ throw new NoSuchEntryException(searchID + ""); }
return result;
} catch (SQLException se) {
throw new InternalErrorException("Query operation failed!");
} finally {
// finally block used to close resources
try {
if (this.stmt != null){
this.stmt.close();
}
} catch (SQLException se2)
{ throw new InternalErrorException("Statement cannot be closed!"); }// nothing we can do
}// end try
} | 7 |
public void update() {
if (this.parent1 != null) {
this.parent1.child = null;
}
if (this.parent2 != null) {
this.parent2.child = null;
}
if (this.node1 != null) {
this.parent1 = this.node1.getPotential();
}
if (this.node2 != null) {
this.parent2 = this.node2.getPotential();
}
if (this.parent1 == this) {
this.parent1 = null;
}
if (this.parent2 == this) {
this.parent2 = null;
}
if (this.parent1 != null) {
this.parent1.child = this;
}
if (this.parent2 != null) {
this.parent2.child = this;
}
Potential oldchild = this.child;
this.child = null;
this.setType();
this.setValue("NC", this.modifiedtime);
if (oldchild != null) {
oldchild.update();
}
} | 9 |
private void rb_insert_fixup(RBNode z) {
// makeDotFile();
// com.andreydev.rbtree.RBNode y;
RBNode y = nil;
while (z.getParrent().getColor() == Color.RED) {
if (z.getParrent() == z.getParrent().getParrent().getLeft()) {
y = z.getParrent().getParrent().getRight();
if (y.getColor() == Color.RED) {
z.getParrent().setColor(Color.BLACK);
y.setColor(Color.BLACK);
z.getParrent().getParrent().setColor(Color.RED);
} else if (z == z.getParrent().getRight()) {
z = z.getParrent();
left_rotate(z);
} else {
z.getParrent().setColor(Color.BLACK);
z.getParrent().getParrent().setColor(Color.RED);
right_rotate(z.getParrent().getParrent());
}
} else {
y = z.getParrent().getParrent().getLeft();
if (y.getColor() == Color.RED) {
z.getParrent().setColor(Color.BLACK);
y.setColor(Color.BLACK);
z.getParrent().getParrent().setColor(Color.RED);
z = z.getParrent().getParrent();
} else if (z == z.getParrent().getLeft()) {
z = z.getParrent();
right_rotate(z);
z.getParrent().setColor(Color.BLACK);
z.getParrent().getParrent().setColor(Color.RED);
left_rotate(z.getParrent().getParrent());
} else {
z.getParrent().setColor(Color.BLACK);
z.getParrent().getParrent().setColor(Color.RED);
left_rotate(z.getParrent().getParrent());
}
}
}
root.setColor(Color.BLACK);
// makeDotFile();
} | 6 |
public boolean initialiseWithLines(ArrayList<StringBuffer> lines, ProcessingOptions options) throws UnsupportedEncodingException {
//remove blank rows at the bottom
boolean done = false;
int i;
for(i = lines.size() - 1; !done; i--){
StringBuffer row = lines.get(i);
if(!StringUtils.isBlank(row.toString())) done = true;
}
rows = new ArrayList<StringBuffer>(lines.subList(0, i + 2));
if(options != null) fixTabs(options.getTabSize());
else fixTabs(options.DEFAULT_TAB_SIZE);
// make all lines of equal length
// add blank outline around the buffer to prevent fill glitch
// convert tabs to spaces (or remove them if setting is 0)
int blankBorderSize = 2;
int maxLength = 0;
int index = 0;
String encoding = null;
//if(options != null) encoding = options.getCharacterEncoding();
Iterator<StringBuffer> it = rows.iterator();
while(it.hasNext()){
String row = it.next().toString();
if(encoding != null){
byte[] bytes = row.getBytes();
row = new String(bytes, encoding);
}
if(row.length() > maxLength) maxLength = row.length();
rows.set(index, new StringBuffer(row));
index++;
}
it = rows.iterator();
ArrayList<StringBuffer> newRows = new ArrayList<StringBuffer>();
//TODO: make the following depend on blankBorderSize
StringBuffer topBottomRow =
new StringBuffer(StringUtils.repeatString(" ", maxLength + blankBorderSize * 2));
newRows.add(topBottomRow);
newRows.add(topBottomRow);
while(it.hasNext()){
StringBuffer row = it.next();
if(row.length() < maxLength) {
String borderString = StringUtils.repeatString(" ", blankBorderSize);
StringBuffer newRow = new StringBuffer();
newRow.append(borderString);
newRow.append(row);
newRow.append(StringUtils.repeatString(" ", maxLength - row.length()));
newRow.append(borderString);
newRows.add(newRow);
} else { //TODO: why is the following line like that?
newRows.add(new StringBuffer(" ").append(row).append(" "));
}
}
//TODO: make the following depend on blankBorderSize
newRows.add(topBottomRow);
newRows.add(topBottomRow);
rows = newRows;
replaceBullets();
replaceHumanColorCodes();
return true;
} | 8 |
public AnnotationVisitor visitAnnotation(final String desc,
final boolean visible) {
return new SAXAnnotationAdapter(getContentHandler(), "annotation",
visible ? 1 : -1, null, desc);
} | 1 |
protected OgexCameraNode toCameraNode( DataStructure ds, Map<BaseStructure, Object> index ) {
OgexCameraNode result = (OgexCameraNode)index.get(ds);
if( result != null ) {
return result;
}
result = new OgexCameraNode();
index.put(ds, result);
configureNode(result, ds, index, false);
OgexCameraObject camera = null;
for( BaseStructure child : ds ) {
String type = child.getType();
if( BASE_NODE_CHILDREN.contains(type) ) {
continue;
} else if( StructTypes.OBJECT_REF.equals(type) ) {
if( camera != null ) {
throw new RuntimeException("Too many ObjectRef structures found in CameraNode, from:" + child.location());
}
BaseStructure[] array = (BaseStructure[])child.getData();
if( array.length != 1 ) {
throw new RuntimeException("Too many references (" + array.length + ") found in CameraNode ObjectRef, from:" + child.location());
}
camera = toCamera((DataStructure)array[0], index);
} else {
log.warn("Unhandled structure type:" + child.getType() + ", from:" + child.location());
}
}
result.setCamera(camera);
return result;
} | 6 |
public static void main(String[] _args) {
final int NUMELEMENTS = 40;
double[] inArray = new double[NUMELEMENTS];
double[] outArray = new double[NUMELEMENTS];
// initialize inArray
for (int i=0; i<NUMELEMENTS; i++) {
inArray[i] = (double)i;
}
String sourceFileName = "SquaresDbl.hsail";
String squaresSource = null;
try {
squaresSource = new String(Files.readAllBytes(FileSystems.getDefault().getPath( sourceFileName)));
}
catch(IOException e) {
e.printStackTrace();
System.exit(-1);
}
OkraContext context = new OkraContext();
if (!context.isValid()) {System.out.println("...unable to create context"); System.exit(-1);}
OkraKernel kernel = new OkraKernel(context, squaresSource, "&run");
if (!kernel.isValid()) {System.out.println("...unable to create kernel"); System.exit(-1);}
kernel.setLaunchAttributes(NUMELEMENTS); // 1 dimension
for (int j=1; j<=3; j++) {
kernel.clearArgs();
kernel.pushDoubleArrayArg(outArray);
kernel.pushDoubleArrayArg(inArray);
double adjustment = j * 0.123;
kernel.pushDoubleArg(adjustment);
kernel.dispatchKernelWaitComplete();
boolean passed = true;
for (int i=0; i<NUMELEMENTS; i++) {
System.out.print(i + "->" + outArray[i] + ", ");
if (outArray[i] != i*i + adjustment) passed = false;
}
System.out.println((passed ? "\nPASSED": "\nFAILED") + "\n");
}
} | 8 |
public boolean canBuyDevCard(){
if(resources.getOre()>0&&resources.getSheep()>0&&resources.getWheat()>0){
return true;
}
return false;
} | 3 |
public void handleBattleMenuInput(){
boolean safeChoice = false;
String userChoice;
while(!safeChoice){
System.out.println("Command: ");
userChoice = input.nextLine();
if(userChoice.compareTo("Melee") == 0 || userChoice.compareTo("melee") == 0){
Battle battle = new Battle();
safeChoice = battle.meleeBattle(player, monster);
}
else if(userChoice.compareTo("Magic") == 0 || userChoice.compareTo("magic") == 0){
Battle battle = new Battle();
battle.magicBattleWarning();
int magicPower = input.nextInt();
safeChoice = battle.magicBattle(player, monster, magicPower);
}
}
} | 5 |
public static String intelligentCapitalize(String pText)
{
boolean lDoCap = false;
final StringTokenizer lST = new StringTokenizer(pText, ".- ", true);
final StringBuffer lSB = new StringBuffer(50);
while(lST.hasMoreTokens())
{
String lWord = lST.nextToken();
if(lWord.equals(".") || lWord.equals("-"))
{
lDoCap = true;
lSB.append(lWord);
continue;
}
if(lWord.equals(" "))
{
lDoCap = false;
lSB.append(lWord);
continue;
}
if(lDoCap || (lWord.length() > 3))
{
lSB.append(Character.toUpperCase(lWord.charAt(0)));
lSB.append(lWord.substring(1).toLowerCase());
} else
{
if(fsNoCap.contains(lWord.toLowerCase()))
{
lSB.append(lWord.toLowerCase());
} else
{
lSB.append(lWord.toUpperCase());
}
}
}
return lSB.toString();
} | 7 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (this.getClass() != obj.getClass() || obj == null)
return false;
Edge e = (Edge)obj;
return (n1 == e.n1) && (n2 == e.n2) ||
(n2 == e.n1) && (n1 == e.n2); // TODO should i support multigraphs? beacuse currently i exclude them with this code
} | 6 |
protected void cellDrawn(mxICanvas canvas, mxCellState state,
Object element, Object labelElement)
{
if (element instanceof Element)
{
String link = getLinkForCell(state.getCell());
if (link != null)
{
String title = getToolTipForCell(state.getCell());
Element elem = (Element) element;
if (elem.getNodeName().startsWith("v:"))
{
elem.setAttribute("href", link.toString());
if (title != null)
{
elem.setAttribute("title", title);
}
}
else if (elem.getOwnerDocument().getElementsByTagName("svg")
.getLength() > 0)
{
Element xlink = elem.getOwnerDocument().createElement("a");
xlink.setAttribute("xlink:href", link.toString());
elem.getParentNode().replaceChild(xlink, elem);
xlink.appendChild(elem);
if (title != null)
{
xlink.setAttribute("xlink:title", title);
}
elem = xlink;
}
else
{
Element a = elem.getOwnerDocument().createElement("a");
a.setAttribute("href", link.toString());
a.setAttribute("style", "text-decoration:none;");
elem.getParentNode().replaceChild(a, elem);
a.appendChild(elem);
if (title != null)
{
a.setAttribute("title", title);
}
elem = a;
}
String target = getTargetForCell(state.getCell());
if (target != null)
{
elem.setAttribute("target", target);
}
}
}
} | 8 |
public static void gcd2rgb(byte[] gcdPlane, int[] rgbPlane) {
for (int i = 0; i < gcdPlane.length; i++) {
switch (gcdPlane[i]) {
case cORANGE:
rgbPlane[i] = Color.ORANGE.getRGB();
break;
case cCYAN:
rgbPlane[i] = Color.CYAN.getRGB();
break;
case cBLUE:
rgbPlane[i] = Color.BLUE.getRGB();
break;
case cGREEN:
rgbPlane[i] = Color.GREEN.getRGB();
break;
case cRED:
rgbPlane[i] = Color.RED.getRGB();
break;
case cWHITE:
rgbPlane[i] = Color.WHITE.getRGB();
break;
case cYELLOW:
rgbPlane[i] = Color.YELLOW.getRGB();
break;
case cBLACK:
rgbPlane[i] = Color.BLACK.getRGB();
break;
default:
rgbPlane[i] = Color.GRAY.getRGB();
}
}
} | 9 |
public void end() {
if (position=='B') { position='U'; }
else if (position=='I') { position='E'; }
} | 2 |
public boolean contains(Tile loc) {
HashSet<Tile> tiles = cols.get(loc.getX());
if (tiles != null) {
for (Tile t : tiles) {
if (t.getY() > loc.getY() || t.getPlane() != loc.getPlane())
continue;
byte[] arr = data.get(t);
if (loc.getY() - t.getY() < arr.length) {
return true;
}
}
}
return false;
} | 5 |
public void setOrderNumber(String orderNumber) {
this.orderNumber = orderNumber;
} | 0 |
public static void setMaxAge(int newMAX_AGE)
{
MAX_AGE = newMAX_AGE;
} | 0 |
public void initializeId() {
String string = "";
for (HardwareSetAlternative hardwareSetAlternative : hardwareSetAlternatives)
string += hardwareSetAlternative.getId();
setId(Utils.getHash(string));
} | 1 |
private int valorMin( Partida partida, EstatPartida estat_partida, int alfa, int beta, EstatCasella estat_casella,
int profunditat, int profunditat_maxima, EstatCasella fitxa_jugador )
{
Tauler tauler = partida.getTauler();
if ( profunditat == profunditat_maxima || estat_partida == EstatPartida.GUANYA_JUGADOR_A ||
estat_partida == EstatPartida.GUANYA_JUGADOR_B || estat_partida == EstatPartida.EMPAT )
{
return funcioAvaluacio( tauler, estat_partida, profunditat, fitxa_jugador );
}
else
{
int mida = tauler.getMida();
for ( int fila = 0; fila < mida; ++fila )
{
for ( int columna = 0; columna < mida; ++columna )
{
try
{
tauler.mouFitxa( estat_casella, fila, columna );
}
catch ( IllegalArgumentException excepcio )
{
continue;
}
EstatPartida estat_partida_aux = partida.comprovaEstatPartida( fila, columna );
estat_casella = this.intercanviaEstatCasella( estat_casella );
beta = Math.min( beta,
this.valorMax( partida, estat_partida_aux, alfa, beta, estat_casella, ( profunditat + 1 ),
profunditat_maxima, fitxa_jugador ) );
tauler.treuFitxa( fila, columna );
if ( alfa >= beta )
{
return alfa;
}
estat_casella = this.intercanviaEstatCasella( estat_casella );
}
}
return beta;
}
} | 8 |
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof UnorderedPair)) return false;
final UnorderedPair pair = (UnorderedPair) o;
return (((first == null ? pair.first == null : first.equals(pair.first)) && (second == null ? pair.second == null : second.equals(pair.second))) || ((first == null ? pair.second == null : first.equals(pair.second)) && (second == null ? pair.first == null : second.equals(pair.first))));
} | 9 |
public static ListNode reverseKGroup(ListNode head, int k) {
ListNode h = null;
ListNode t = null;
ListNode lt = null;
ListNode p = head;
ListNode q = null;
ListNode hres = null;
int n = k;
while (null != p) {
t = p;
h = null;
while (null != p && n > 0) {
q = p;
p = p.next;
q.next = h;
h = q;
n--;
}
if (0 == n) {
if (null == hres) hres = h;
if (null != lt) lt.next = h;
lt = t;
t.next = p;
n = k;
} else {
p = h;
q = null;
h = null;
while (null != p) {
q = p.next;
p.next = h;
h = p;
p = q;
}
if (null != lt) lt.next = h;
if (null == hres) hres = h;
}
}
return hres;
} | 9 |
public String getIntegralByUID(Statement statement,String UID)//根据用户名获取积分
{
String result = null;
sql = "select integral from Users where UID = '" + UID +"'";
try
{
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
result = rs.getString("integral");
}
}
catch (SQLException e)
{
System.out.println("Error! (from src/Fetch/Users.getIntegralByUID())");
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
} | 2 |
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
if (txtMemberID.getText() != "") {
btnEdit.setEnabled(true);
try {
ResultSet rs = DB.myConnection().createStatement().executeQuery("select * from members where MemberID='" + Integer.parseInt(txtMemberID.getText()) + "'");
while (rs.next()) {
txtAddress.setText(rs.getString("MemberAddress"));
txtHome_telephone_Number.setText(rs.getString("MemberHomeTelephone"));
txtMember_Father_Name.setText(rs.getString("MemberFatherName"));
txtMember_First_Name.setText(rs.getString("MemberFirstName"));
txtMember_Middle_Name.setText(rs.getString("MemberMiddleName"));
txtMember_Mobile_Number.setText(rs.getString("MemberMobileNumber"));
txtMember_sur_Name1.setText(rs.getString("MemberSurname"));
txtMother_Name.setText(rs.getString("MemberMotherName"));
txtSchool_Admission_Number.setText(rs.getString("SchoolAdmissionNumber"));
lblRegisterLibrianName.setText(LoadLibrianData.LoadLibrianName(rs.getString("LibrianID")));
lblDate.setText(rs.getDate("RegisteredDate").toString());
}
} catch (SQLException e1) {
JOptionPane.showMessageDialog(this, "Sql Exception @ MemberDetails 433");
} catch (NumberFormatException e2) {
JOptionPane.showMessageDialog(this, "Please enter valid Member ID");
txtMemberID.grabFocus();
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Exception @ MemberDetails 440 please contact \ndeveloper team ");
e.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(this, "Please Enter valid Member ID");
txtMemberID.grabFocus();
}
}//GEN-LAST:event_jButton1ActionPerformed | 5 |
public void draw(Graphics2D g2){
if(getyOffset()>0){
g2.drawImage(Tile.dropDownBackground,0,getyOffset()-2*getWidth(),KarpfenGame.WIDTH, getWidth()*2,null);
for(int i=0;i<Skill.getNr();i++){
int addition=0;
if(i==enabledSkill){
g2.drawImage(Tile.dropDownSelected,i*KarpfenGame.WIDTH/(Skill.getNr())+getWidth()/2+5, getyOffset()-(int)(getWidth()*1.5+5), getWidth()+10, getWidth()+10,null);
addition=20;
}
if(i==0){
g2.drawImage(Tile.carp[0][0], i*KarpfenGame.WIDTH/(Skill.getNr())+getWidth()/2+20, getyOffset()-(int)(getWidth()*1.3)-addition/2, getWidth()-30+addition, getWidth()-30+addition, null);
}else if(i==1){
g2.drawImage(Tile.eel[0][2], i*KarpfenGame.WIDTH/(Skill.getNr())+getWidth()/2, getyOffset()-(int)(getWidth()*1.5)-addition/2,getWidth()+addition,getWidth()-10+addition, null);
}else if(i==3){
g2.drawImage(Tile.baloonFish2pic, i*KarpfenGame.WIDTH/(Skill.getNr())+getWidth()/2+15, getyOffset()-(int)(getWidth()*1.3)-addition/2,getWidth()+addition-30,getWidth()-30+addition, null);
}else if(i==4){
g2.drawImage(Tile.baloonFish, i*KarpfenGame.WIDTH/(Skill.getNr())+getWidth()/2+15, getyOffset()-(int)(getWidth()*1.3)-addition/2,getWidth()-30+addition,getWidth()-30+addition, null);
}
//g2.drawRect(i*KarpfenGame.WIDTH/(Skill.getNr())+getWidth()/2, getyOffset()-(int)(getWidth()*1.5), getWidth(), getWidth());
if(i==getEnabledSkill()){
g2.setColor(Color.BLUE);
}
}
}
} | 8 |
public Texture loadTexture(String path){
Texture tex = null;
try {
tex = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream(path));
} catch (IOException e) {
e.printStackTrace();
}
return tex;
} | 1 |
public void edit() throws Exception {
List<File> l = new ArrayList<File>();
for (Params p : model.getParams()) {
if (p.getFile() != null) {
l.add(new File(p.getFile()));
}
}
if (l.isEmpty()) {
throw new ComponentException("No parameter files to edit.");
}
// initial Parameter set generation
if (l.size() == 1) {
File f = l.get(0);
if (!f.exists()) {
// create the default parameter and fill it.
CSProperties p = DataIO.properties(ComponentAccess.createDefault(model.getComponent()));
DataIO.save(p, f, "Parameter");
}
}
//
nativeLF();
PEditor p = new PEditor(l);
// the frame
Image im = Toolkit.getDefaultToolkit().getImage(
getClass().getResource("/ngmf/ui/table.png"));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(p);
f.setIconImage(im);
f.setTitle("Parameter " + getName());
f.setSize(800, 600);
f.setLocation(500, 200);
f.setVisible(true);
f.toFront();
System.out.flush();
} | 5 |
static void drawTopLine(Graphics2D ctx, Game game, World world) {
if (topLine == null) {
topLine = new BufferedImage(1200, 66, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = topLine.createGraphics();
g2d.setPaint(textures.toTexture(15 * 12, 2));
g2d.fillRect(0, 0, 1200, 64);
g2d.setFont(doom.deriveFont(24f));
g2d.setColor(new Color(199, 52, 63));
String n1 = world.getPlayers()[0].getName() + ": " + world.getPlayers()[0].getGoalCount();
g2d.drawString(n1, 40, 50);
cacodemon.draw(g2d, new Rectangle(10, 25, 25, 25), 0);
String n2 = world.getPlayers()[1].getName() + ": " + world.getPlayers()[1].getGoalCount();
g2d.setColor(new Color(199, 74, 41));
g2d.drawString(n2, 1200 - 40 - g2d.getFontMetrics().stringWidth(n2), 50);
elemental.draw(g2d, new Rectangle(1200 - 10 - 25, 25, 25, 25), 0);
String txt = null;
boolean justGoal = world.getPlayers()[0].isJustMissedGoal() || world.getPlayers()[0].isJustScoredGoal();
if (justGoal) {
txt = "GoaL";
}
else if (world.getTick() - world.getTickCount() > 0 && world.getTick() - world.getTickCount() < 500 ) {
txt = "OvertimE";
}
if (txt != null) {
Map<TextAttribute, Object> attributes = new HashMap<TextAttribute, Object>();
attributes.put(TextAttribute.TRACKING, 0.15);
g2d.setFont(doom.deriveFont(48f).deriveFont(attributes));
g2d.setPaint(textures.toTexture(12*1+3));
g2d.drawString(txt, 600 - g2d.getFontMetrics().stringWidth(txt) / 2, 60);
}
g2d.dispose();
}
ctx.drawImage(topLine, 0, 0, null);
textures.draw(ctx, new Rectangle(450, 10, 46, 46), 15 * 12 + 1);
textures.draw(ctx, new Rectangle(684, 10, 46, 46), 15 * 12 + 1);
barrels.draw(ctx, new Rectangle(450, 20, barrels.wSize, barrels.hSize), (world.getTick() / 5) % 3 );
barrels.draw(ctx, new Rectangle(684, 20, barrels.wSize, barrels.hSize), (world.getTick() / 10) % 3 );
} | 6 |
public void selectAll() {
expandMenu();
for(int i = 0; i < methodTree.getRowCount(); i++) {
TreePath path = methodTree.getPathForRow(i);
if(path == null) return;
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) path.getLastPathComponent();
if(treeNode.getUserObject() instanceof TreeNodeObject) {
TreeNodeObject co = (TreeNodeObject) treeNode.getUserObject();
if(!co.isSelected() && co.isNoCategory()) {
co.setSelected(true);
handler.toggleDecodingMethod(co.getMethodID());
}
}
}
methodTree.repaint();
} | 5 |
protected void updatePowerUps() {
for (int i = 0; i < powerUpList.size(); i++) {
if (powerUpList.get(i).isExpired()) {
powerUpList.remove(i);
}
}
for (PowerUp p : powerUpList) {
p.move();
p.bounceOffWalls();
p.score(paddle1, player1);
if (!isEndless) {
p.score(paddle2, player2);
}
}
} | 4 |
public int getAlignedChar(int iMinusOne,boolean preferHigherIndices)
{
// internally to this package, strings are indexed 1...N, so
// we need to convert from the usual 0...N-1 Java convention
int i = iMinusOne+1;
int bestJ = -1;
double bestScore = -Double.MAX_VALUE;
for (int j=mat.getFirstStoredEntryInRow(i); j<=mat.getLastStoredEntryInRow(i); j++) {
if (mat.outOfRange(i,j)) log.error("out of range: "+i+","+j);
double score = mat.get(i,j);
if ((score>bestScore) || (score==bestScore && preferHigherIndices)) {
bestScore = score; bestJ = j;
}
}
// convert back to the usual 0...N-1 Java convention
return bestJ-1;
} | 5 |
private void buildPorts() {
int i=0, portIndex=0; // Compteur, numero des tuiles ports.
i = 0;
for (int j: portIndexes) { // Pour chaque tuile mer.
waterTile[i] = (WaterTile) grid[j]; // Ajouter la tuile mer au tableau des tuiles mers.
i++; // Incremente le compteur de tuiles mers.
}
for (i = 0 ; i < 9 ; i++) { // Pour les 9 ports de la carte.
do {
portIndex = randomInt(0, 17); // Choisit un nombre aleatoire parmi les 18 tuiles mers.
} while (!checkPort(portIndex)); // Tant que la verification du nombre n'a pas ete validee. La verification creee egalement les ports dans le modele.
}
i = 0;
for (WaterTile t: waterTile) { // Pour chaque tuile mer.
if (t.hasPorts()) { // Si la tuile est un port.
ports[i] = t; // Ajoute la tuile mer au tableau des tuiles mers etant des ports. Uniquement utile pour l'affichage des ports dans la console pour l'instant.
i++; // Incremente le compteur de tuiles ports.
}
}
for (i = 0 ; i < 5 ; i++) { // Pour les 5 ports specialises (<=> rapport d'echange 2:1 avec une ressource particuliere).
int j = 0;
do {
j = randomInt(0, 8); // Choisit un numero de port au hasard parmis les 9.
} while (ports[j].isSpecialized()); // Tant que le port de numero choisi est specialise.
ports[j].specialize(randomResource(i)); // Specialise le port avec la ressource en fonction de l'entier i qui symbolise ici egalement les 5 ressources.
}
for (WaterTile t: ports) { // Pour chaque port.
if (!t.isSpecialized()) t.specialize("all"); // S'il n'est pas specialise, le specialiser pour toutes les ressources (<=> rapport d'echange 3:1 avec toutes les ressources). La string ressource est alors "all".
fireSetPorts(t.getIndex(), t.getC1(), t.getC2(), t.getResource()); // Notifie les observateurs de la specialisation de la tuile mer en un port, en fonction de son numero, le 1er coin de l'hexagone etant un port, le deuxieme, et la ressource du port.
}
} | 9 |
public void printModel(Model pm,String sdfilename, boolean autostart, int line) throws InterruptedException {
if (state.connecting) {
cons.appendText("Still connecting. Please wait until connecting is established.");
return;
}
if (!state.connected) {
cons.appendText("Not connected");
return;
}
startline=0; //reset startline (resume)
if(sdfilename == null){
//Direct printing
cons.appendText("Add model to print queue");
printQueue.addModel(pm);
startline=line;
if (state.debug)
cons.appendText("Filling print queue, Printing:" + state.printing);
}else if (pm != null ){
//Stream to SD Card
printQueue.putAuto(GCodeFactory.getGCode("M21", -21));
printQueue.putAuto(GCodeFactory.getGCode("M28 "+sdfilename, -28));
state.streaming=true;
GCode finishstream = GCodeFactory.getGCode("M29 "+sdfilename, -29);
if(autostart){
GCode selectfile = GCodeFactory.getGCode("M23 "+sdfilename, -23);
GCode printfile = GCodeFactory.getGCode("M24", -24);
printQueue.addModel(pm,finishstream,selectfile,printfile);
state.sdprint=true;
}else{
printQueue.addModel(pm,finishstream);
}
if (state.debug)
cons.appendText("Filling queue to stream, streaming:" + state.printing);
}else{
//Print from SD Card
printQueue.putAuto(GCodeFactory.getGCode("M23 "+sdfilename, -23));
printQueue.putAuto(GCodeFactory.getGCode("M24", -24));
state.sdprint=true;
if (state.debug)
cons.appendText("SD print, Printing:" + state.printing);
}
setPrintMode(true,false);
} | 8 |
public boolean fetchAll(InputStream is) throws IOException {
//Decoder dec = new Decoder(sr,0,msglen);
while(true) {
int asrlen = objectLen();
if(DEBUG)System.out.println("Object size="+asrlen+"; Buffer size="+data.length+"; Current size="+length);
if((asrlen>0) && (asrlen>data.length)){
System.out.println("Object size="+asrlen+"; Buffer size="+data.length);
return false;
}
if ((asrlen<0) || (length < asrlen)) {
if(DEBUG)System.out.println("Object size="+asrlen+"; Current size="+length);
if(length == data.length) return false;
int inc = is.read(data, length, data.length-length);
if(inc == 0) return false;
length += inc;
//dec = new Decoder(data,0,length);
continue;
}
break;
}
return true;
} | 9 |
@Override
public Channel clone() {
Channel newChannel = new Channel(width, height);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
newChannel.setPixel(i, j, this.getPixel(i, j));
}
}
return newChannel;
} | 2 |
public static void printMat(Double[][] mat) throws IOException
{
String matrix = "{";
for (int i = 0; i < mat.length; i++)
{
matrix += "{";
for (int j = 0; j < mat[i].length; j++)
{
if (j != mat[i].length - 1)
matrix += mat[i][j] + ", ";
else
matrix += mat[i][j];
}
if (i != mat.length - 1)
matrix += "}, ";
else
matrix += "}";
}
matrix += "}";
bw.write(matrix + "\n");
} | 4 |
private static void sobelFile(String filename, int numIterations,
boolean rle) {
System.out.println("Reading image file " + filename);
PixImage image = ImageUtils.readTIFFPix(filename);
PixImage blurred = image;
if (numIterations > 0) {
System.out.println("Blurring image file.");
blurred = image.boxBlur(numIterations);
String blurname = "blur_" + filename;
System.out.println("Writing blurred image file " + blurname);
TIFFEncoder.writeTIFF(blurred, blurname);
}
System.out.println("Performing Sobel edge detection on image file.");
PixImage sobeled = blurred.sobelEdges();
String edgename = "edge_" + filename;
System.out.println("Writing grayscale-edge image file " + edgename);
TIFFEncoder.writeTIFF(sobeled, edgename);
if (rle) {
String rlename = "rle_" + filename;
System.out.println("Writing run-length encoded grayscale-edge " +
"image file " + rlename);
TIFFEncoder.writeTIFF(new RunLengthEncoding(sobeled), rlename);
}
if (numIterations > 0) {
System.out.println("Displaying input image, blurred image, and " +
"grayscale-edge image.");
System.out.println("Close the image to quit.");
ImageUtils.displayTIFFs(new PixImage[] { image, blurred, sobeled });
} else {
System.out.println("Displaying input image and grayscale-edge image.");
System.out.println("Close the image to quit.");
ImageUtils.displayTIFFs(new PixImage[] { image, sobeled });
}
} | 3 |
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerInteract(PlayerInteractEvent E)
{
if (E.getClickedBlock() == null || E.getPlayer().getItemInHand() == null)
return;
if (E.getClickedBlock().getType() == M.conf.PressBlock && E.getAction() == Action.LEFT_CLICK_BLOCK && E.getClickedBlock().getRelative(0, 2, 0).getType() == Material.PISTON_BASE)
{
if (!Utility.checkProtection(M, E)) return;
PistonBaseMaterial piston = new PistonBaseMaterial(Material.PISTON_BASE, E.getClickedBlock().getRelative(0, 2, 0).getData());
if (E.getPlayer().getItemInHand().getType() == Material.BOOK)
Utility.playerPrintBook(E.getPlayer(), E.getClickedBlock(), piston);
else if (E.getPlayer().getItemInHand().getType() == Material.WRITTEN_BOOK || E.getPlayer().getItemInHand().getType() == Material.ENCHANTED_BOOK)
Utility.playerClearBook(E.getPlayer(), E.getClickedBlock(), piston);
}
} | 9 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.