text stringlengths 14 410k | label int32 0 9 |
|---|---|
public static String insert(String s, String insert, int offset) {
if (s == null) {
return null;
}
if (insert == null) {
return s;
}
if (offset > s.length()) {
offset = s.length();
}
StringBuilder sb = new StringBuilder(s);
sb.insert(offset, insert);
return sb.toString();
} | 3 |
@Override
public void run() {
try(DatagramSocket workerSocket = new DatagramSocket()) {
Sender statusSender = new Sender(workerSocket, remotePort, remoteAddress);
if(!isValid()) {
statusSender.sendObject(new ERR(ERR.FILE_ALREADY_EXISTS, "The requested file" + request.fileName + " aleardy exists on the server."));
return;
}
else {
statusSender.sendObject(new ACK(0));
}
Logger.log("Starting file receive");
try {
byte[] result = FileReceiver.receiveFile(workerSocket, remoteAddress);
Logger.log("Got file on server: " + new String(result));
}
catch(IOException e) {
Logger.fatalError("Failed file tranfer: " + e.getMessage(), e);
}
} catch (SocketException e) {
Logger.fatalError("Failed to create server worker: ", e);
}
} | 3 |
public static void outputResults(LinkedList largest_formable_words, int formable_word_amount){
WordNode next_node;
System.out.print("\nLongest Word");
if(largest_formable_words.getSize() > 1)
System.out.print("s");
System.out.print(":");
if(largest_formable_words.getSize() > 0){
next_node = largest_formable_words.getHead();
for(int i = 0; i < largest_formable_words.getSize(); ++i){
if((i % 5) == 0)
System.out.print("\n\t");
System.out.print(next_node.getWord());
// Adding Commas
if(((i+1) % (largest_formable_words.getSize())) != 0)
System.out.print(", ");
next_node = next_node.getNext();
}
System.out.print("\n\nBesides the longest word, " + (formable_word_amount-largest_formable_words.getSize()) + " words can be formed from other words within the list.");
}else{
System.out.println("\nNo words could be formed by permutations of other smaller words.\n");
}
System.out.println('\n');
} | 5 |
@Override
public String toString() {
if (isDisposed()) {
return "VCNTreeItem [Disposed; isWrap=" + isWrap + ", id=" + id
+ ", foregroundColor=" + foregroundColor + ", isBold="
+ isBold + "]";
}
return "VCNTreeItem [name = " + getText() + ", isWrap=" + isWrap + ", id=" + id +
", foregroundColor=" + foregroundColor + ", isBold="
+ isBold + "]";
} | 1 |
public void removeZone(String zoneName)
{
//Intermediate zone variable for use when iterating
Zone currentZone;
//The index of the zone to be removed. Initialised at 999 so that if
//no zone match is found, there is no risk of inadvertently removing
//an unintended zone (as would be the case if initialised to a low
//number)
int zoneToRemove = 999;
//Iterate through zones vector, comparing the given zoneName with the
//current zone name. When a match is found, the loop is broken and the
//index of the zone to be removed is defined
for(int i=0; i<zones.size();i++)
{
currentZone = zones.get(i);
if(currentZone.name == zoneName)
{
zoneToRemove = i;
break;
}
}
//If a matching zone was found, remove the zone.
if(zoneToRemove != 999)
{
zones.remove(zoneToRemove);
zones.trimToSize();
}
else{
if(Debug.localMouse)
System.out.println("Zone of name '"+zoneName+"' could not be " +
"removed - name not found");
}
} | 4 |
private static String formatLabel(String label) {
return (label == null ) ? "" : label;
} | 1 |
private void check(int i,int j){
if(i<1|| i<1 || i>gridSize|| j>gridSize){
throw new IllegalArgumentException();
}
} | 4 |
public Iterator iterateHashCode(final int hash) {
// /#ifdef JDK12
cleanUp();
// /#endif
return new Iterator() {
private int known = modCount;
private Bucket nextBucket = buckets[Math.abs(hash % buckets.length)];
private Object nextVal;
{
internalNext();
}
private void internalNext() {
while (nextBucket != null) {
if (nextBucket.hash == hash) {
nextVal = nextBucket.get();
if (nextVal != null)
return;
}
nextBucket = nextBucket.next;
}
}
public boolean hasNext() {
return nextBucket != null;
}
public Object next() {
if (known != modCount)
throw new ConcurrentModificationException();
if (nextBucket == null)
throw new NoSuchElementException();
Object result = nextVal;
nextBucket = nextBucket.next;
internalNext();
return result;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
} | 5 |
public void Profile(){
int opt;
System.out.println("Email: "+email+", Nombre: "+name+", Fecha de ingreso: "+fecha);
do{
System.out.println("\t1.Cambiar mi email");
System.out.println("\t2.Cambiar mi password");
System.out.println("\t3.Cambiar mi nombre");
System.out.println("\t4.Regresar al menu de Reportes");
System.out.print("Escoja su opcion: ");
opt = scan.nextInt();
if(opt==4){
break;
}
else if(opt<1 || opt > 4){
System.out.println("Opcion Invalida");
}
else{
System.out.println("Ingrese su password");
if(pass(scan.next())){
switch(opt){
case 1: System.out.print("Ingresa el nuevo email: ");
setEmail(scan.next());
break;
case 2: System.out.print("Ingrese el nuevo password");
setPassword(scan.next());
break;
case 3: System.out.print("Ingrese el nuevo nombre");
setName(scan.next());
break;
}
}
else{
System.out.println("Password Incorrecto");
}
}
}while(opt!=4);
} | 8 |
public Object[] getReaders() {
Object[] readers = null;
try {
readers = PCSCManager.getTerminalsList().toArray();
} catch (CardException e) {
JOptionPane.showMessageDialog(null, "Nenhuma leitora instalada",
"Erro", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
return readers;
} | 1 |
private static void studyDatasetBaseLyon() throws IOException, Exception {
//study network
// for mac
neatANN.readInputDataFromExcel(AppProperties.fileName(), AppProperties.answerColNumber());
// for pc
//neatANN.readInputDataFromExcel("c:/Users/Administrateur/Desktop/these_softPartie/database/PCR4_PCPA_test_20.xls", 24);
//neatANN.normalization();
neatANN.standartisation();
neatANN.makeThreeSamplesRandomized();
neatANN.buildPopulation();
//NeatClass.p_GA_max_iterations = 30;
List< GraphDate> dataToPrint = neatANN.NEATalgorithm();
for (GraphDate graphDate : dataToPrint) {
// create images
XYSeries series1 = new XYSeries("Training error");
XYSeries series2 = new XYSeries("Testing error");
XYSeries series3 = new XYSeries("Validation error");
XYSeriesCollection dataset = new XYSeriesCollection();
dataset.addSeries(series1);
dataset.addSeries(series2);
dataset.addSeries(series3);
for (int i = 0; i < graphDate.getNiterations(); i++) { //number of iterations
series1.add(i + 1, graphDate.getData(0, i));
series2.add(i + 1, graphDate.getData(1, i));
series3.add(i + 1, graphDate.getData(2, i));
}
final JFreeChart chart = createSimpleChart(dataset);
/*final Marker iteration = new ValueMarker(175.0);
iteration.setPaint(Color.darkGray);
iteration.setLabel(String.valueOf(graphDate.getNiterations()));
iteration.setLabelTextAnchor(TextAnchor.TOP_CENTER);*/
ChartUtilities.saveChartAsJPEG(new File("generation_No_" + graphDate.getGenerationNumber() + ".jpeg"), chart, 800, 600);
}
// resultats og best organism
writeBestOrganism();
} | 2 |
public void send()
{
try
{
Socket client = new Socket(SHOST, SPORT);
ObjectOutputStream os =
new ObjectOutputStream(client.getOutputStream());
Message m = new Message(this, "Client", "hello");
os.writeObject(m);
os.flush();
ObjectInputStream is =
new ObjectInputStream(client.getInputStream());
Object o = is.readObject();
if (o instanceof Message)
{
m = (Message) o;
System.out.println(
"Client received: " + m.geContent() + " from " + m.geName());
}
client.close();
}
catch (IOException | ClassNotFoundException e)
{
e.printStackTrace();
}
} | 2 |
@Override
public Class<?> getColumnClass(int i) {
return Icon.class;
} | 1 |
public void removeRoster (Roster roster) {
if (roster == null)
return;
if (rosters.contains(roster.getRosterID())) {
rosters.remove ((Object)roster.getRosterID());
}
} | 2 |
public void emulate()
{
ran = false; // tracks if the whole program ran
boolean good = true; // tracks if each step was successful
// Set the next piece of code to be executed.
String code = (String) view.getMemoryTable().getValueAt(programCounter, 0);
// Start executing the program.
int runTracker = 0;
while (!ran) {
if (runTracker > 10000) {
int n = JOptionPane.showConfirmDialog(
null,
"Program appears to be taking a while to execute (or it may be"
+ "\nstuck in an infinite loop). Would you like to terminate?",
"Infinite Loop detected",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
terminated = true;
return;
}
runTracker = 0;
}
// If we reach "0000", then it's a HLT statement, end execution.
if (code.equalsIgnoreCase("0000")) {
ran = true;
currentCode = code;
highlightCode();
return;
}
// While the program hasn't reached the end (just a safety measure, not really needed)
// Do this.. programCounter != programEnd
good = executeNextStep(code); // Execute the code
setRegisters(); // Set the status registers accordingly
counter++; // Increment counter
if (code.startsWith("1")) {
if (findNegative(code.substring(0, 4))) {
view.setNegBit(true);
}
}
// Add an error if something went wrong and return.
if (!good) {
EmulatorControl.addError(new EmulatorError(">>ERROR<< AN ERROR OCCURED WHEN EMULATING", 0));
return;
}
// Set the next piece of code.
code = (String) view.getMemoryTable().getValueAt(programCounter, 0);
// Used when there's an ORG statement in the middle of the program.
if (code.equals("") && !code.equals("0000")) {
getBearing();
code = (String) view.getMemoryTable().getValueAt(programCounter, 0);
}
runTracker++;
}
} | 9 |
static private final boolean cons(int i)
{ switch (b[i])
{ case 'a': case 'e': case 'i': case 'o': case 'u': return false;
case 'y': return (i==0) ? true : !cons(i-1);
default: return true;
}
} | 7 |
private void acao137() throws SemanticError {
if (idAtual instanceof IdentificadorMetodo) {
if (((IdentificadorMetodo) idAtual).getTipo() != null)
throw new SemanticError("Método sem tipo esperado");
} else {
throw new SemanticError("Identificador de método esperado");
}
idMetodoChamado = (IdentificadorMetodo) idAtual;
parametroAtualPodeSerReferencia = true;
} | 2 |
private void createBoardImage() {
Graphics2D g = (Graphics2D) gameBoard.getGraphics();
g.setColor(new Color(0x999999));
g.fillRoundRect(0, 0, BOARD_WIDTH, BOARD_HEIGHT, Tile.ARC_WIDTH,
Tile.ARC_HEIGHT);
g.setColor(new Color(0x999999));
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
int x = SPACING + SPACING * col + Tile.WIDTH * col;
int y = SPACING + SPACING * row + Tile.HEIGHT * row;
g.fillRoundRect(x, y, Tile.WIDTH, Tile.HEIGHT, Tile.ARC_WIDTH,
Tile.ARC_HEIGHT);
}
}
} | 2 |
public CycSymbol readKeyword()
throws IOException {
String keywordString = (String) readObject();
if (!(keywordString.startsWith(":"))) {
keywordString = ":" + keywordString;
}
return CycObjectFactory.makeCycSymbol(keywordString);
} | 1 |
public void setPlayer(int player)
{
if(player == 2 || player == 1)
{
this.player = player;
}
} | 2 |
private void doSubLWorkerTerminated(SubLWorkerEvent event) {
Object[] curListeners = getInferenceListeners();
List<Exception> errors = new ArrayList<Exception>();
for (int i = curListeners.length - 1; i >= 0; i -= 1) {
try {
((InferenceWorkerListener) curListeners[i]).notifyInferenceTerminated(this, event.getException());
} catch (Exception e) {
errors.add(e);
}
}
if (errors.size() > 0) {
throw new RuntimeException(errors.get(0)); // @hack
}
} | 3 |
private User authenticate(Request request) {
// Extract authentication credentials
String authentication = ((ContainerRequest) request).getHeaderString(HttpHeaders.AUTHORIZATION);
if (authentication == null) {
throw new AuthenticationException("Authentication credentials are required", REALM);
}
if (!authentication.startsWith("Basic ")) {
return null;
// additional checks should be done here
// "Only HTTP Basic authentication is supported"
}
authentication = authentication.substring("Basic ".length());
String[] values = Base64.decodeAsString(authentication).split(":");
if (values.length < 2) {
throw new WebApplicationException(400);
// "Invalid syntax for username and password"
}
String username = values[0];
String password = values[1];
if ((username == null) || (password == null)) {
throw new WebApplicationException(400);
// "Missing username or password"
}
// Validate the extracted credentials
User user;
String cfgUser = "admin";
String cfgPass = "admin";
if (username.equals(cfgUser) && password.equals(cfgPass)) {
user = new User("user", "user");
System.out.println("USER AUTHENTICATED");
// } else if (username.equals("admin") && password.equals("adminadmin")) {
// user = new User("admin", "admin");
// System.out.println("ADMIN AUTHENTICATED");
} else {
System.out.println("USER NOT AUTHENTICATED");
throw new AuthenticationException("Invalid username or password\r\n", REALM);
}
return user;
} | 7 |
public void deletePerson(Person person, ArrayList<Person> list) {
int answer = JOptionPane.showConfirmDialog(null, "Do you really want to delete "
+ person.getName() + "?", " CONFIRMATION ", JOptionPane.YES_NO_OPTION);// displaying
// JOptionPane.YES_NO_OPTION
// Confirmdialog
// box
if (answer == JOptionPane.YES_OPTION) {
driver.getPersonDB().deletePersonFromList(person);
}
if (list.size() > 0) {
setTextField(0, list);
}
else {
setTextField(list.size() - 1, list);
clearTextFields(list);
deletePersonButton.setEnabled(false);
editPersonButton.setEnabled(false);
submitButton.setVisible(false);
}
revalidate();
repaint();
} | 2 |
public void doDead() {
if (!isShell) {
switch (ai.getDirection()) {
case LEFT:
setAnimation(new String[]{"koopaDeadLeft"});
break;
case RIGHT:
setAnimation(new String[]{"koopaDeadRight"});
break;
}
}
setDead(true);
if (doPoints) {
stage.getScoreBalk().killEnemy();
doPoints = false;
}
} | 4 |
public Set<Map.Entry<K,Double>> entrySet() {
return new AbstractSet<Map.Entry<K,Double>>() {
public int size() {
return _map.size();
}
public boolean isEmpty() {
return TObjectDoubleMapDecorator.this.isEmpty();
}
public boolean contains( Object o ) {
if ( o instanceof Map.Entry ) {
Object k = ( ( Map.Entry ) o ).getKey();
Object v = ( ( Map.Entry ) o ).getValue();
return TObjectDoubleMapDecorator.this.containsKey( k ) &&
TObjectDoubleMapDecorator.this.get( k ).equals( v );
} else {
return false;
}
}
public Iterator<Map.Entry<K,Double>> iterator() {
return new Iterator<Map.Entry<K,Double>>() {
private final TObjectDoubleIterator<K> it = _map.iterator();
public Map.Entry<K,Double> next() {
it.advance();
final K key = it.key();
final Double v = wrapValue( it.value() );
return new Map.Entry<K,Double>() {
private Double val = v;
public boolean equals( Object o ) {
return o instanceof Map.Entry &&
( ( Map.Entry ) o ).getKey().equals( key ) &&
( ( Map.Entry ) o ).getValue().equals( val );
}
public K getKey() {
return key;
}
public Double getValue() {
return val;
}
public int hashCode() {
return key.hashCode() + val.hashCode();
}
public Double setValue( Double value ) {
val = value;
return put( key, value );
}
};
}
public boolean hasNext() {
return it.hasNext();
}
public void remove() {
it.remove();
}
};
}
public boolean add( Map.Entry<K,Double> o ) {
throw new UnsupportedOperationException();
}
public boolean remove( Object o ) {
boolean modified = false;
if ( contains( o ) ) {
//noinspection unchecked
K key = ( ( Map.Entry<K,Double> ) o ).getKey();
_map.remove( key );
modified = true;
}
return modified;
}
public boolean addAll(Collection<? extends Map.Entry<K,Double>> c) {
throw new UnsupportedOperationException();
}
public void clear() {
TObjectDoubleMapDecorator.this.clear();
}
};
} | 6 |
@Override
public GameState use(Game game) {
List <Npc> npcs;
npcs = game.getCurrentRoom().getNpcs();
Kill killablenpc = null;
for(Npc creature : npcs){
if(creature instanceof Killable1){
killablenpc = (Kill) creature;
}
}
if(killablenpc != null){
if (!History.getHistory().isLoaded()){
nbLivesRemain = killablenpc.getNbLives();
if(nbLivesRemain > 0 ){
removeNbLives = rdm.nextDouble()*(100/nbLivesRemain) + 13;
killablenpc.setNbLives(nbLivesRemain - removeNbLives.intValue());
System.out.println(killablenpc.getStatement());
if(killablenpc.getStatement().length() > removeNbLives)
killablenpc.setStatement(killablenpc.getStatement().substring(killablenpc.getStatement().length()- removeNbLives.intValue(), killablenpc.getStatement().length()));
System.out.println("The "+killablenpc.getName()+" has "+killablenpc.getNbLives() +" lives \n "
+ "You removed "+removeNbLives.intValue() + " lives");
if(killablenpc.getNbLives() <= 0){
System.out.println("FINISH THE "+killablenpc.getName().toUpperCase() +"!!");
}
}
else {
System.out.println("You overcame "+killablenpc.getName());
for(Item reward : killablenpc.getItems()){
game.getCurrentRoom().addItem(reward);
System.out.println("The "+killablenpc.getName()+ " dropped something look around");
}
game.getCurrentRoom().removeNpcs(killablenpc);
}
}
else {
System.out.println("You overcame "+killablenpc.getName());
for(Item reward : killablenpc.getItems()){
game.getCurrentRoom().addItem(reward);
System.out.println("The "+killablenpc.getName()+ " dropped something look around");
}
game.getCurrentRoom().removeNpcs(killablenpc);
}
return game.getGameState();
}else{
System.out.println("You can't use this object here");
return game.getGameState();
}
} | 9 |
public float[] decodeFloats() {
float[] res = new float[decodeInt()];
for (int i = 0; i < res.length; i++) {
res[i] = decodeFloat();
}
return res;
} | 1 |
public ChatServer(ServerInfo serverInfo, int verbose) {
this.serverInfo = serverInfo;
this.clients = new HashMap<String, Socket>();
this.clientHandlerThread = new Thread[(int) serverInfo.getMaxClients()];
this.verbose = verbose;
} | 0 |
public boolean equals( Object o ) {
Tuple<T, E> tuple = ( Tuple<T, E> ) o;
return tuple.getFirstElement().equals( firstElement ) &&
tuple.getSecondElement().equals( secondElement );
} | 1 |
private boolean zzRefill() throws java.io.IOException {
/* first: make room (if you can) */
if (zzStartRead > 0) {
System.arraycopy(zzBuffer, zzStartRead,
zzBuffer, 0,
zzEndRead-zzStartRead);
/* translate stored positions */
zzEndRead-= zzStartRead;
zzCurrentPos-= zzStartRead;
zzMarkedPos-= zzStartRead;
zzPushbackPos-= zzStartRead;
zzStartRead = 0;
}
/* is the buffer big enough? */
if (zzCurrentPos >= zzBuffer.length) {
/* if not: blow it up */
char newBuffer[] = new char[zzCurrentPos*2];
System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length);
zzBuffer = newBuffer;
}
/* finally: fill the buffer with new input */
int numRead = zzReader.read(zzBuffer, zzEndRead,
zzBuffer.length-zzEndRead);
if (numRead < 0) {
return true;
}
else {
zzEndRead+= numRead;
return false;
}
} | 3 |
public InputElement makeInput(WebNode node) {
//TODO how to keep consistent with isInput method? Use reflection?
if (SubmitButton.isSubmit(node))
return new SubmitButton(node);
if (Button.isButton(node))
return new Button(node);
if (Textarea.isTextarea(node))
return new Textarea(node);
if (Text.isText(node))
return new Text(node);
if (Checkbox.isCheckbox(node))
return new Checkbox(node);
if (Radio.isRadio(node))
return new Radio(node);
if (Password.isPassword(node))
return new Password(node);
if (Select.isSelect(node))
return new Select(node);
//TODO postprocessing of radio buttons?
if (isInput(node))
throw new InconsistencyException("InputElementFactory.makeInput", "InputElementFactory.isInput", node.toString());
else
throw new NotSupportedException("InputEleemntFactory.makeInput", node.toString());
} | 9 |
public void searchSolicitacoes() {
facesContext = FacesContext.getCurrentInstance();
ArrayList<String> caminhos = new ArrayList<>();
ArrayList<String> colunas = new ArrayList<>();
ArrayList<String> propertyName = new ArrayList<>();
ArrayList<Object> listObjetos = new ArrayList<>();
caminhos.add("solicitacoes.solicitacao");
colunas.add("solicitacao");
try {
if (!(solicitacoes.getSolExa_Pedido().equals(0))) {
listaSolicitacoesExames = genericDAO.searchObject(SolicitacoesExames.class, "solicitacoes",
null, null,
new String[]{"solExa_Pedido"}, new Object[]{solicitacoes.getSolExa_Pedido()});
} else {
if (!(nomeProfissional.getCli_nome().isEmpty())) {
caminhos.add("solicitacao.profissionalPedido");
colunas.add("profissionalPedido");
caminhos.add("profissionalPedido.cliente");
colunas.add("cliente");
propertyName.add("cliente.cli_nome");
listObjetos.add(nomeProfissional.getCli_nome());
}
if (!(procedimentos.getDes_codigoProcedimento().isEmpty())) {
caminhos.add("solicitacoes.descricaoExames");
colunas.add("descricaoExames");
propertyName.add("descricaoExames.des_codigoProcedimento");
listObjetos.add(procedimentos.getDes_codigoProcedimento());
}
if (!(cliente.getCli_CNS().isEmpty())) {
caminhos.add("solicitacao.cliente");
colunas.add("cliente");
propertyName.add("cliente.cli_CNS");
listObjetos.add(cliente.getCli_CNS());
}
String[] arrayCaminhos = caminhos.toArray(new String[caminhos.size()]);
String[] arrayColunas = colunas.toArray(new String[colunas.size()]);
String[] arrayPropertyName = propertyName.toArray(new String[propertyName.size()]);
Object[] arrayObjects = listObjetos.toArray(new Object[listObjetos.size()]);
listaSolicitacoesExames = genericDAO.searchObject(SolicitacoesExames.class, "solicitacoes",
arrayCaminhos, arrayColunas, arrayPropertyName, arrayObjects);
}
} catch (Exception ex) {
Logger.getLogger(BuscarSolicitacaoMB.class.getName()).log(Level.SEVERE, null, ex);
}
} | 5 |
public BorderPane bottom() {
BorderPane bottom = new BorderPane();
AnchorPane slider = new AnchorPane();
Rectangle rectangle = new Rectangle();
rectangle.autosize();
rectangle.setWidth(490);
rectangle.setHeight(60);
rectangle.setFill(Paint.valueOf(Color.WHITE.toString()));
rectangle.setStroke(Paint.valueOf(Color.GRAY.toString()));
rectangle.setStrokeWidth(1.0);
rectangle.setStrokeType(StrokeType.INSIDE);
Label label = new Label("Farbtiefe wählen:");
label.setLabelFor(rectangle);
label.getStylesheets().add("labelstyle.css");
final Slider depthSlider = new Slider();
depthSlider.setMin(3.0);
depthSlider.setMax(24.0);
depthSlider.setValue(3.0);
depthSlider.setBlockIncrement(3.0);
depthSlider.setMajorTickUnit(3.0);
depthSlider.setShowTickMarks(true);
depthSlider.setShowTickLabels(true);
depthSlider.setBlockIncrement(3.0);
depthSlider.setMinorTickCount(0);
depthSlider.setSnapToTicks(true);
depthSlider.setValue(targetDepth);
depthSlider.valueProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observableValue, Number number, Number number2) {
targetDepth = number2.doubleValue();
if (sourcePath != null) {
SimpleColorReduction reduct = new SimpleColorReduction();
reduct.setDestBitDepth((int) targetDepth);
InputStream is;
try {
BufferedImage src = ImageIO.read(new File(sourcePath));
if (src.getWidth() >= 150 || src.getHeight() >= 150) {
BufferedImage prevIMG = new BufferedImage(150, 150, src.getType());
for (int i = 0; i < 150; i++) {
for (int j = 0; j < 150; j++) {
prevIMG.setRGB(i, j, src.getRGB(i, j));
}
}
src = prevIMG;
}
reduct.setSourceImage(src);
reduct.generateImage();
BufferedImage temp = reduct.getReducedImage();
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(temp, "png", os);
is = new ByteArrayInputStream(os.toByteArray());
Image targetPreview = new Image(is);
targetView.setImage(targetPreview);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
//slider.setPadding(new Insets(5, 0, 0, 0));
slider.setLeftAnchor(label, 10.0);
slider.setTopAnchor(rectangle, 9.0);
slider.setTopAnchor(depthSlider, 22.0);
slider.setLeftAnchor(depthSlider, 7.0);
slider.setRightAnchor(depthSlider, 7.0);
slider.getChildren().addAll(rectangle, label, depthSlider);
bottom.setTop(slider);
BorderPane startButton = new BorderPane();
Button startGen = new Button();
startGen.setText("Starte Reduzierung");
startGen.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
if (sourcePath == null) {
showWarning("Bitte ein Quellbild bestimmen!");
return;
}
if (targetPath == null) {
showWarning("Bitte einen Speicherort bestimmen!");
return;
}
Main.genStrings(sourcePath, targetPath, (int) depthSlider.getValue());
showWarning("Bild erfolgreich generiert!");
}
});
startButton.setPadding(new Insets(12, 7, 7, 7));
startButton.setCenter(startGen);
bottom.setBottom(startButton);
return bottom;
} | 9 |
public void generateTerrain(int par1, int par2, byte[] par3ArrayOfByte)
{
byte var4 = 4;
byte var5 = 16;
byte var6 = 63;
int var7 = var4 + 1;
byte var8 = 17;
int var9 = var4 + 1;
this.biomesForGeneration = this.worldObj.getWorldChunkManager().getBiomesForGeneration(this.biomesForGeneration, par1 * 4 - 2, par2 * 4 - 2, var7 + 5, var9 + 5);
this.noiseArray = this.initializeNoiseField(this.noiseArray, par1 * var4, 0, par2 * var4, var7, var8, var9);
for (int var10 = 0; var10 < var4; ++var10)
{
for (int var11 = 0; var11 < var4; ++var11)
{
for (int var12 = 0; var12 < var5; ++var12)
{
double var13 = 0.125D;
double var15 = this.noiseArray[((var10 + 0) * var9 + var11 + 0) * var8 + var12 + 0];
double var17 = this.noiseArray[((var10 + 0) * var9 + var11 + 1) * var8 + var12 + 0];
double var19 = this.noiseArray[((var10 + 1) * var9 + var11 + 0) * var8 + var12 + 0];
double var21 = this.noiseArray[((var10 + 1) * var9 + var11 + 1) * var8 + var12 + 0];
double var23 = (this.noiseArray[((var10 + 0) * var9 + var11 + 0) * var8 + var12 + 1] - var15) * var13;
double var25 = (this.noiseArray[((var10 + 0) * var9 + var11 + 1) * var8 + var12 + 1] - var17) * var13;
double var27 = (this.noiseArray[((var10 + 1) * var9 + var11 + 0) * var8 + var12 + 1] - var19) * var13;
double var29 = (this.noiseArray[((var10 + 1) * var9 + var11 + 1) * var8 + var12 + 1] - var21) * var13;
for (int var31 = 0; var31 < 8; ++var31)
{
double var32 = 0.25D;
double var34 = var15;
double var36 = var17;
double var38 = (var19 - var15) * var32;
double var40 = (var21 - var17) * var32;
for (int var42 = 0; var42 < 4; ++var42)
{
int var43 = var42 + var10 * 4 << 11 | 0 + var11 * 4 << 7 | var12 * 8 + var31;
short var44 = 128;
var43 -= var44;
double var45 = 0.25D;
double var49 = (var36 - var34) * var45;
double var47 = var34 - var49;
for (int var51 = 0; var51 < 4; ++var51)
{
if ((var47 += var49) > 0.0D)
{
par3ArrayOfByte[var43 += var44] = (byte)Block.stone.blockID;
}
else if (var12 * 8 + var31 < var6)
{
par3ArrayOfByte[var43 += var44] = (byte)Block.waterStill.blockID;
}
else
{
par3ArrayOfByte[var43 += var44] = 0;
}
}
var34 += var38;
var36 += var40;
}
var15 += var23;
var17 += var25;
var19 += var27;
var21 += var29;
}
}
}
}
} | 8 |
public String listItem(User user) {
String result = "";
result += "Music: " + super.getName() + " - " + getArtist() + "\n";
if (super.getNumberOfCopies() <= 0 && !super.isElectronicallyAvailable()) {
result += "Currently unavailable.\n";
} else {
result += "Available as: \n";
if (super.getNumberOfCopies() > 0) {
result += "CD for " + super.getPhysicalPrice() + " ("
+ (super.getNumberOfCopies())
+ (super.getNumberOfCopies() > 1 ? " copies left)" : " copy left)")
+ "\n";
}
if (super.isElectronicallyAvailable()) {
result += "eMusic for " + super.getElectronicPrice() + "\n";
}
}
if (user instanceof Administrator) {
result += "\nPurchase statistics:\n";
result += "CD (" + super.getPurchaseCount()
+ (super.getPurchaseCount() == 1 ? " purchase" : " purchases") + ")\n";
if (super.isElectronicallyAvailable()) {
result += "eMusic (" + super.getePurchaseCount()
+ (super.getPurchaseCount() == 1 ? " purchase" : " purchases") + ")\n";
}
}
return result;
} | 9 |
public void notifyListeners() {
if (!boardListener.isEmpty()) {
for (int i = 0; i < boardListener.size(); i++) {
boardListener.get(i).boardChanged();
}
}
} | 2 |
@Test
public void testBogusStream() throws IOException {
final String filename = "test.wav";
final File file = File.createTempFile("testBogusFile", filename);
FileOutputStream out = new FileOutputStream(file);
final Random random = new Random();
for (int i=0; i<8*1024; i++) {
out.write(random.nextInt());
}
out.close();
FFStreamInputStream in = null;
try {
in = new FFStreamInputStream(new BufferedInputStream(new FileInputStream(file)));
in.read(new byte[1024]);
fail("Expected UnsupportedAudioFileException");
} catch (UnsupportedAudioFileException e) {
// expected this
e.printStackTrace();
assertTrue(e.toString().endsWith("(Operation not permitted)")
|| e.toString().endsWith("(Invalid data found when processing input)")
|| e.toString().endsWith("(End of file)")
|| e.toString().endsWith("(Invalid data found when processing input)")
|| e.toString().contains("Probe score too low")
);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
file.delete();
}
} | 8 |
private int readEscapeChar() {
int c = getc();
if (c == 'n')
c = '\n';
else if (c == 't')
c = '\t';
else if (c == 'r')
c = '\r';
else if (c == 'f')
c = '\f';
else if (c == '\n')
++lineNumber;
return c;
} | 5 |
public static void main(String args[]) {
/*
float line[] = staggeredLine(17, 2.0f) ;
I.say("Line is: ") ;
for (float f : line) I.add(((int) (f * 10))+", ") ;
//*/
//*
final int SIZE = 16 ;
List <Coord[]> regions = genRegionsFor(SIZE, 3) ;
I.say(regions.size()+" regions generated!") ;
int ID = 0 ;
int map[][] = new int[SIZE][SIZE] ;
for (Coord c : Visit.grid(0, 0, SIZE, SIZE, 1)) map[c.x][c.y] = -1 ;
for (Coord[] region : regions) {
for (Coord c : region) map[c.x][c.y] = ID ;
ID++ ;
}
for (int y = 0 ; y < SIZE ; y++) {
I.say("\n") ;
for (int x = 0 ; x < SIZE ; x++) {
I.add(((char) ('A' + map[x][y]))+", ") ;
}
}
//*/
} | 5 |
public static void checkOutputPath(File targetPath)
{
if(targetPath != null && targetPath.exists()) {
// shows a window which asks you if the old content of the output directory should be deleted
// int confirmation = JOptionPane.showConfirmDialog(null, "Output directory not empty. Delete all contents of '" + targetPath + "' and continue?", "Confirmation", JOptionPane.YES_NO_OPTION);
// if (confirmation == JOptionPane.NO_OPTION)
// return;
try {
FileUtils.deleteDirectory(targetPath);
} catch (IOException e1) {
throw new RuntimeException("Unable to clean output directory: " + e1.getMessage(), e1);
}
targetPath.mkdirs();
}
if(!targetPath.exists())
targetPath.mkdir();
} | 4 |
private void parseClassDeclaration() throws SyntaxError {
accept(Token.CLASS);
parseIdentifier();
accept(Token.LCURLY);
while(isStarterDeclarators(currentToken.kind)) {
parseDeclarators();
parseIdentifier();
switch(currentToken.kind) {
case Token.SEMICOLON:
acceptIt();
break;
case Token.LPAREN:
acceptIt();
if(isStarterParameterList(currentToken.kind))
parseParameterList();
accept(Token.RPAREN);
accept(Token.LCURLY);
while(isStarterStatement(currentToken.kind))
parseStatement();
if(currentToken.kind == Token.RETURN) {
acceptIt();
parseExpression();
accept(Token.SEMICOLON);
}
accept(Token.RCURLY);
break;
default:
syntacticError("\";\" or \"(\" expected here, instead of " +
"\"%\"", currentToken.spelling);
break;
}
}
accept(Token.RCURLY);
} | 6 |
public JMenuItem createSaveItem() {
save = new JMenuItem("Save");
save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
save.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
if (!(w == null)) {
FileOutputStream output;
File f;
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FileNameExtensionFilter("Wallet file", "wallet"));
chooser.setAcceptAllFileFilterUsed(false);
int op = chooser.showSaveDialog(null);
if (op == JFileChooser.APPROVE_OPTION) {
f = new File(chooser.getSelectedFile() + ".wallet");
try {
output = new FileOutputStream(f);
ObjectOutputStream out = new ObjectOutputStream(output);
out.writeObject(w);
close = true;
out.close();
output.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (op == JFileChooser.CANCEL_OPTION) {
close = false;
}
} else {
JOptionPane.showMessageDialog(null, "Wallet not created !");
}
}
});
save.setEnabled(false);
return save;
} | 5 |
private void emitTableConstants() throws IOException
{
for ( Table table : mModel.getTables() )
{
writer.emitSingleLineComment( "Table " + table.name + " constants " );
writer.emitField( "String", SqlUtil.IDENTIFIER( table ), EnumSet.of( Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL ), "\"" + table.name + "\"" );
int index = 0;
// default _ID field
Field defaultrow = Table.getDefaultAndroidIdField();
writer.emitField( "String", SqlUtil.ROW_COLUMN( table, defaultrow ), EnumSet.of( Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL ), "\"" + defaultrow.name + "\"" );
writer.emitField( "int", SqlUtil.ROW_COLUMN_POSITION( table, defaultrow ), EnumSet.of( Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL ), "" + index );
index++;
for ( Field row : table.fields )
{
writer.emitField( "String", SqlUtil.ROW_COLUMN( table, row ), EnumSet.of( Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL ), "\"" + row.name + "\"" );
writer.emitField( "int", SqlUtil.ROW_COLUMN_POSITION( table, row ), EnumSet.of( Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL ), "" + index );
index++;
}
writer.emitEmptyLine();
}
for ( View view : mModel.getViews() )
{
writer.emitSingleLineComment( "View " + view.name + " constants " );
int index = 0;
for ( Pair<String, String> select : view.fields )
{
writer.emitField( "String", SqlUtil.ROW_COLUMN( view, (select.snd == null) ? select.fst : select.snd ), EnumSet.of( Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL ), "\"" + Util.sanitize( select.snd, false ) + "\"" );
writer.emitField( "int", SqlUtil.ROW_COLUMN_POSITION( view, (select.snd == null) ? select.fst : select.snd ), EnumSet.of( Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL ), "" + index );
index++;
}
writer.emitEmptyLine();
}
} | 6 |
public boolean exists(String value) {
if (!isEmpty()) {
ListElement current = head;
while (current != tail.next()) {
if (current.getValue().equals(value)) {
return true;
}
current = current.next();
}
}
return false;
} | 3 |
public boolean create(Class<?> layout) {
Field[] publicFields = layout.getFields();
if (publicFields.length == 0) {
Utilities.outputError("The given table layout '" + layout.getName() + "' for the table '" + m_name + "' has no public fields.");
return false;
}
String createTable = "CREATE TABLE `" + m_name + "` (";
for (Field field : publicFields) {
final String fieldName = field.getName();
final String fieldType = convertType(field.getType());
if (fieldType == null) {
Utilities.outputError("The given table layout '" + layout.getName() + "' for the table '" + m_name + "' has unknown type '" + field.getType().getSimpleName() + "'.");
return false;
}
createTable += fieldName + " " + fieldType + ",";
}
createTable = createTable.substring(0, createTable.length() - 1);
createTable += ")";
m_database.query(createTable, true);
Utilities.outputDebug("Created table `" + m_name + "` for plugin " + m_database.getOwnerName());
return true;
} | 4 |
private void bowlToHtml(StringBuffer buf) {
buf.append("<div>");
// Text information about bowl id
buf.append("<div style=\"width: 200px; height: 40px; text-align: center;font-size: 25px; font-weight: bold; font-family: 'Comic Sans MS', cursive, sans-serif\">" + "Bowl #" + round + "," + bowlId + "</div>\n");
// empty up left square
buf.append(" <div style=\"width: 34px; height: 80px; float:left;\"></div>\n");
for (int c = 0; c < FRUIT_NAMES.length; c++) {
String color = FRUIT_COLORS[c];
String cname = Character.toString((char)(65+c));
buf.append("<div style=\"width: 34px; height: 40px; font-size:20px; font-weight:bold;font-family:'Comic Sans MS', cursive, sans-serif;text-align:center;float:left; border: 1px solid black; background-color: " + color + "\">" + cname + "</div>\n");
}
// initial distribution
buf.append(" <div style=\"width: 432px; height: 40px; float: left; border: 1px solid black;\">\n");
for (int r = 0 ; r != FRUIT_NAMES.length ; ++r) {
String s = "-";
if (currentBowl != null)
s = Integer.toString(currentBowl[r]);
buf.append(" <div style=\"width: 36px; height: 40px; float:left; text-align: center; font-size: 20px;\n");
buf.append(" font-weight: bold; font-family: 'Comic Sans MS', cursive, sans-serif\">" + s + "</div>\n");
}
buf.append(" </div>\n");
int score = 0;
if (currentPlayer != -1) {
for (int c = 0; c < 12; c++) {
score += preference[currentPlayer][c] * currentBowl[c];
}
}
buf.append(" <div style=\"width: 36px; height: 40px; float:left; border: 1px solid black; text-align: center;\n");
buf.append(" font-size: 20px; font-weight: bold; font-family: 'Comic Sans MS', cursive, sans-serif\">" + score + "</div>\n");
buf.append(" <div style=\"clear:both;\"></div>\n");
// Print player action
if (action != null)
buf.append("<div style=\"width: 400px; height: 40px; text-align: center;font-size: 25px; font-weight: bold; font-family: 'Comic Sans MS', cursive, sans-serif\">" + action + "</div>\n");
buf.append("</div>");
} | 6 |
public static void RegDespesaUI(){
RegDespesaUI nome;
} | 0 |
public static Object[] subtract(Object[] A, Object[] B) {
// Short-circuit for empty sets (A-{} = A and {}-B = {} = A)
if (A == null || A.length == 0 || B == null || B.length == 0)
return A;
// Clones A, so as to leave it unaffected
Object[] Ac = A.clone();
/* Iterates through all the current names, moving new ones to the front of the array,
* such that, Ac[0..i) are the new names
*/
int i = 0;
for (int j = 0; j < Ac.length; j++) {
boolean isNew = true;
for (Object b : B)
if (b.equals(Ac[j])) {
isNew = false;
break;
}
if (isNew)
Ac[i++] = Ac[j];
}
// diff = Ac[0..i) = A - B
Object[] diff = new Object[i];
System.arraycopy(Ac, 0, diff, 0, i);
return diff;
} | 8 |
public Disciplina pesquisaDisciplina(String codigo)
throws DisciplinaInexistenteException {
Disciplina listaDisc = null;
for (Disciplina e : disciplina) {
if (e.getCodigo().equals(codigo)) {
listaDisc = e;
break;
}
}
if (listaDisc == null) {
throw new DisciplinaInexistenteException("Pesquisa Disciplina");
} else {
return listaDisc;
}
} | 3 |
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if (method.equals(Connection.class.getMethod("commit"))) {
throw new SQLException();
} else if (method.equals(Connection.class.getMethod("rollback"))) {
throw new SQLException();
} else if (method.equals(Connection.class.getMethod("close"))) {
throw new SQLException();
}
if (method.equals(Object.class.getMethod("toString"))) {
return "Transactional(" + con + ")";
} else if (method.equals(Object.class.getMethod("hashCode"))) {
return con.hashCode();
} else if (method.equals(Object.class.getMethod("equals",
Object.class))) {
Object other = args[0];
if (other != null && Proxy.isProxyClass(other.getClass())) {
InvocationHandler handler = Proxy
.getInvocationHandler(other);
if (ConnectionHandler.class.isAssignableFrom(handler
.getClass())) {
return con
.equals(ConnectionHandler.class.cast(handler).con);
}
}
return false;
}
return method.invoke(con, args);
} | 9 |
public double[] rawItemStandardDeviations(){
if(!this.dataPreprocessed)this.preprocessData();
if(!this.variancesCalculated)this.meansAndVariances();
return this.rawItemStandardDeviations;
} | 2 |
public boolean onTyhja() {
return suoritustasot.get(0).onTyhja() && seuraavaArvollinen == null;
} | 1 |
public MonopolyResult buy (int playerID, int eventID, boolean buy)
{
try
{
if(!_gameManager.isGameExists() || !_gameManager.isGameActive())
{
return new MonopolyResult("no active game");
}
Event last = _gameManager.getLastGameEvent();
if(last.getEventID() != eventID)
{
return new MonopolyResult("illegal event id");
}
HumanPlayer player = _gameManager.getGamePlayerById(playerID);
// invalid player id
if(player == null)
{
return new MonopolyResult("illegal player id");
}
// last event player and requasting player are not the same
if(_gameManager.getPlayerByName(last.getPlayerName()) != player)
{
return new MonopolyResult("illegal player id");
}
if(!player.isInGame())
{
return new MonopolyResult("player not in game, can't buy");
}
player.setDesicion(buy);
_gameManager.stopGameTimer();
return new MonopolyResult();
}
catch(Exception e)
{
Logger.getLogger(MonopolyGame.class.getName()).log(Level.SEVERE, "error in buy", e);
return new MonopolyResult("unknown error");
}
} | 7 |
public void remove()
{
throw new UnsupportedOperationException();
} | 0 |
public void indexDocument(Document doc, int docID) {
HashSet<String> seenWords = new HashSet<String>();
for (int i=0 ; i<doc.terms.size() ; i++) {
String term = doc.terms.get(i);
// XXX: this is too simplistic. we must count multiple iterations
// of the same term in a doc.
if (!invIndex.containsKey(term)) {
// Postingslist must know position too
invIndex.put(term, new PostingsList(term));
}
invIndex.get(term).add(docID, i);
// Only count each term once per document for frequencies.
if (!seenWords.contains(term)) {
if (!frequencies.containsKey(term)) {
frequencies.put(term, 1);
} else {
frequencies.put(term, frequencies.get(term) + 1);
}
seenWords.add(term);
}
}
} | 4 |
private void saveShieldStorage() {
if (shieldStorageConfig == null || shieldStorageConfig == null) {
// Don't save if there is nothing to save
return;
}
// Make a backup of the old storage file just in case
File backupFile = new File(directory, "shields.yml.old");
try {
// Create backup file if it doesn't exist (may throw IOException)
backupFile.createNewFile();
// Open files for reading/writing (may throw FileNotFoundException)
FileInputStream in = new FileInputStream(shieldStorageFile);
FileOutputStream out = new FileOutputStream(backupFile);
// Set up buffer
byte[] data = new byte[4096];
int bytes = 0;
// Copy data into backup file (may throw IOException)
while((bytes = in.read(data)) >= 0) {
out.write(data, 0, bytes);
}
// Close files (may throw IOException)
out.close();
in.close();
} catch(java.io.FileNotFoundException ex) {
log.warning("[FactionShield] FactionShield: Failed to back up shields.yml: File not found");
} catch (IOException e) {
log.warning("[FactionShield] FactionShield: Failed to back up shields.yml: Read or write error");
}
try {
// Attempt to write changed config to disk
shieldStorageConfig.save(shieldStorageFile);
} catch (IOException ex) {
log.info("Could not persist storage to " + shieldStorageFile + ex);
}
} | 6 |
private static void run() {
long ct;
ArrayList<MovingComponent> mcal = new ArrayList<MovingComponent>(10);
mcal.add(ba);
mcal.add(pd);
while(true){
// for(int i = 0; i < breakout.sizeOf(); i++){
// breakout.returnComponent(i);
// }
for (int i = 0; i < mcal.size(); i ++){
mcal.get(i).updatePosition();
bcal.add(5, (BreakoutComponent) mcal.get(i));
}
// breakout.addMouseMotionListener( new MouseMotionListener() {
//
// @Override
// public void mouseDragged(MouseEvent e) {
// // TODO Auto-generated method stub
//
// }
//
// @Override
// public void mouseMoved(MouseEvent e) {
// pd.mouseX = e.getX() - 40;
// }
//
// });
// System.out.println(mcal.get(0));
System.out.println(bcal.get(5));
//// breakout.addComponent(ba);
// Brick brick = new Brick(100, 20, 40, 10);
// bcal.add(5, brick);
for (int i = 0; i < mcal.size(); i ++){
mcal.get(i).collisionCheck(bcal);
}
breakout.repaint();
ct = System.currentTimeMillis();
while(System.currentTimeMillis() < ct + 20){
}
}
} | 4 |
public static int setMax_period(int new_max_period) {
if (new_max_period > 0 && new_max_period >= min_period) {
max_period = new_max_period;
return max_period;
} else {
return -1;
}
} | 2 |
public boolean isSet(String key) {
if (key == null) throw new IllegalArgumentException(CLASS + ": key may not be null");
if (!keys.containsKey(key)) throw new IllegalArgumentException(CLASS + ": unknown key: " + key);
return keys.get(key).getResultCount() > 0 ? true : false;
} | 3 |
protected AutomatonEnvironment getEnvironment() {
return environment;
} | 0 |
public boolean isDebugging() {
return debugging || (parent != null && parent.isDebugging());
} | 2 |
@Override
public boolean okMessage(Environmental oking, CMMsg msg)
{
if((oking==null)||(!(oking instanceof MOB)))
return super.okMessage(oking,msg);
final MOB mob=(MOB)oking;
if(msg.amITarget(mob)
&&(msg.targetMinor()==CMMsg.TYP_GIVE)
&&(msg.tool() instanceof Coins))
{
final String currency=CMLib.beanCounter().getCurrency(mob);
final double[] owe=totalMoneyOwed(mob,msg.source());
final double coins=((Coins)msg.tool()).getTotalValue();
if((paid!=null)&&(paid.contains(msg.source())))
owe[OWE_TOTAL]-=owe[OWE_CITIZENTAX];
final String owed=CMLib.beanCounter().nameCurrencyShort(currency,owe[OWE_TOTAL]);
if((!((Coins)msg.tool()).getCurrency().equals(CMLib.beanCounter().getCurrency(mob))))
{
msg.source().tell(L("@x1 refuses your money.",mob.name(msg.source())));
CMLib.commands().postSay(mob,msg.source(),L("I don't accept that kind of currency."),false,false);
return false;
}
if(coins<owe[OWE_TOTAL])
{
msg.source().tell(L("@x1 refuses your money.",mob.name(msg.source())));
CMLib.commands().postSay(mob,msg.source(),L("That's not enough. You owe @x1. Try again.",owed),false,false);
return false;
}
}
return true;
} | 9 |
public boolean isPrefixOf(ArgPosition otherArgPosition) {
if (otherArgPosition == null || otherArgPosition.depth() < depth()) {
return false;
} else {
return path.equals(otherArgPosition.getPath().subList(0, path.size()));
}
} | 2 |
private void move(int i, int j) {
if(i == 0 && j == 1) facingDirection = FORWARD;
if(i == 1 && j == 0) facingDirection = RIGHT;
if(i == 0 && j == -1) facingDirection = BACKWARD;
if(i == -1 && j == 0) facingDirection = LEFT;
moveAmountX += getSpeed() * i;
moveAmountY += getSpeed() * j;
} | 8 |
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for (Entry<? extends K, ? extends V> entry : m.entrySet()) {
put(entry.getKey(), entry.getValue());
}
} | 5 |
@Override
public void bsp(
BSPPeer<NullWritable, NullWritable, NullWritable, NullWritable, NullWritable> peer)
throws IOException, SyncException, InterruptedException {
int nbRowsBlocks = nbRowsA / blockSize;
int nbColsBlocks = nbColsB / blockSize;
int nbBlocks = nbRowsBlocks * nbColsBlocks;
int blocksPerPeer = nbBlocks / peer.getNumPeers();
int p = peer.getPeerIndex();
int lastBlock = (p+1)*blocksPerPeer;
if (p==peer.getNumPeers()-1) {
lastBlock = nbBlocks;
}
ArrayList<Block> aBlocks = new ArrayList<Block>();
ArrayList<Block> bBlocks = new ArrayList<Block>();
for (int block = p*blocksPerPeer; block<lastBlock; block++){
int i = block/nbColsBlocks;
int j = block%nbColsBlocks;
for (int k = 0; k < nbRowsBlocks; k++) {
Block aBlock = new Block(i, k, blockSize);
aBlocks.add(aBlock);
Block bBlock = new Block(k,j,blockSize);
bBlocks.add(bBlock);
}
}
int aILast = ((lastBlock-1)/nbColsBlocks)*blockSize+blockSize;
int bILast = nbRowsBlocks*blockSize;
HamaConfiguration conf = peer.getConfiguration();
int rows = conf.getInt(inputMatrixARows, 4);
int cols = conf.getInt(inputMatrixACols, 4);
String[] parts = conf.get(inputMatrixAPathString).split("/");
String aName = parts[parts.length-1];
Utils.readMatrixBlocks(conf.get(inputMatrixAPathString)+"/"+aName, peer.getConfiguration(), rows, cols, blockSize, aILast, aBlocks);
rows = conf.getInt(inputMatrixBRows, 4);
cols = conf.getInt(inputMatrixBCols, 4);
parts = conf.get(inputMatrixBPathString).split("/");
String bName = parts[parts.length-1];
Utils.readMatrixBlocks(conf.get(inputMatrixBPathString)+"/"+bName, peer.getConfiguration(), rows, cols, blockSize, bILast, bBlocks);
HashMap<String, Matrix> resBlocks = new HashMap<String, Matrix>();
for (int b = 0; b<aBlocks.size(); b++){
Block aBlock = aBlocks.get(b);
Block bBlock = bBlocks.get(b);
String ind = aBlock.getI() + "," + bBlock.getJ();
Matrix resBlock = resBlocks.get(ind);
if (resBlock==null){
resBlock = new Matrix(blockSize,blockSize);
resBlock.zeroes();
}
resBlock = resBlock.sum(aBlock.getBlock().strassen(bBlock.getBlock()));
resBlocks.put(ind, resBlock);
}
parts = conf.get(inputMatrixCPathString).split("/");
String cName = parts[parts.length-1];
for (String ind : resBlocks.keySet()){
Matrix block = resBlocks.get(ind);
Path path = new Path(conf.get(inputMatrixCPathString)+"/"+cName+ind.split(",")[0]+"_"+ind.split(",")[1]+".mat");
Utils.writeMatrix(block.getValues(), path, conf);
}
} | 6 |
private Component getHeader() {
JButton jbAdd = new JButton("add");
jbAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Vector<String> newRow = new Vector<String>();
newRow.add("AaValue" + delete_me++);
newRow.add("BbValue");
jtableModel.addRow(newRow);
}
});
JButton jbEdit = new JButton("edit");
jbEdit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
}
});
JButton jbDelete = new JButton("delete");
jbDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int rowIndex = jtable.getSelectedRow();
if (rowIndex >= 0) {
Vector modelRows = jtableModel.getDataVector();
System.out.println(modelRows.get(rowIndex));
modelRows.remove(rowIndex);
jtableModel.setDataVector(modelRows, head_jtable);
}
}
});
JButton jbX = new JButton("close");
jbX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
frame.setVisible(false);
}
});
JPanel jpnlHeader = new JPanel(new GridLayout(1, 4));
jpnlHeader.add(jbX);
jpnlHeader.add(jbAdd);
jpnlHeader.add(jbEdit);
jpnlHeader.add(jbDelete);
jpnlHeader.setPreferredSize(new Dimension(250, 24));
return jpnlHeader;
} | 1 |
public void setLeft(PExp node)
{
if(this._left_ != null)
{
this._left_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._left_ = node;
} | 3 |
public static void main(String[] args) {
PorterStemmer s = new PorterStemmer();
for (int i = 0; i < args.length; i++) {
try {
InputStream in = new FileInputStream(args[i]);
byte[] buffer = new byte[1024];
int bufferLen, offset, ch;
bufferLen = in.read(buffer);
offset = 0;
s.reset();
while(true) {
if (offset < bufferLen)
ch = buffer[offset++];
else {
bufferLen = in.read(buffer);
offset = 0;
if (bufferLen < 0)
ch = -1;
else
ch = buffer[offset++];
}
if (Character.isLetter((char) ch)) {
s.add(Character.toLowerCase((char) ch));
}
else {
s.stem();
System.out.print(s.toString());
s.reset();
if (ch < 0)
break;
else {
System.out.print((char) ch);
}
}
}
in.close();
}
catch (IOException e) {
System.out.println("error reading " + args[i]);
}
}
} | 7 |
private Object number() {
int length = 0;
boolean isFloatingPoint = false;
buf.setLength(0);
if (c == '-') {
add();
}
length += addDigits();
if (c == '.') {
add();
length += addDigits();
isFloatingPoint = true;
}
if (c == 'e' || c == 'E') {
add();
if (c == '+' || c == '-') {
add();
}
addDigits();
isFloatingPoint = true;
}
String s = buf.toString();
return isFloatingPoint
? (length < 17) ? (Object)Double.valueOf(s) : new BigDecimal(s)
: (length < 19) ? (Object)Long.valueOf(s) : new BigInteger(s);
} | 9 |
@Override
protected void run() {
int cycles = 20;
EDA eda = (EDA) algorithms.get("EDA");
eda.setConfiguration(this);
ClonAlg clonAlg = (ClonAlg) algorithms.get("ClonAlg");
clonAlg.setConfiguration(this);
// Calculate max iterations
for (int cycle = 0; cycle < cycles; cycle++) {
maxIterations += eda.getGenerations();
if ( cycle % 10 == 0) {
maxIterations += clonAlg.getIterations();
maxIterations += eda.getGenerations();
}
}
setMaxIterations(maxIterations);
for (int cycle = 0; cycle < cycles; cycle++) {
System.out.println(((double) cycle/999.0 * 100) + "%");
eda.setInitialIndividual(eda.getBestIndividual());
eda.run();
if ( cycle % 10 == 0) {
clonAlg.setInitialIndividual(eda.getBestIndividual());
clonAlg.run();
eda.setInitialIndividual(clonAlg.getBestIndividual());
eda.run();
}
}
runBestIndividual = eda.getBestIndividual();
} | 4 |
private void doDeleteAll() {
System.out.print("\n[Performing DELETE ALL] ... ");
try {
Statement st = conn.createStatement();
st.executeUpdate("TRUNCATE TABLE COFFEES");
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
} | 1 |
private Document createDocument(String data) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setCoalescing(true);
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(true);
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
StringReader reader = new StringReader(data);
InputSource inputSource = new InputSource(reader);
Document doc = builder.parse(inputSource);
return doc;
} | 0 |
public void felvisz(int i, int j, int k){
if(k==0){
sajat[i][j]=1;
sajat[a][b]=9;
a=i;
b=j;
}
else{
sajat[i][j]=2;
sajat[c][d]=9;
c=i;
d=j;
}
} | 1 |
public void removeProp(Entity entity) {
if(props.contains(entity)) {
props.remove(entity);
if(!noChildren()) {
for(int x = 0; x<propChildren.length; x++) {
propChildren[x].removeProp(entity);
}
}
}
} | 3 |
public JobSchedulerBuilder withJobName( String jobName )
{
this.jobName = jobName;
return this;
} | 0 |
private Node findBestNode(){
Node best = open.get (0);
for (int i = 0; i < open.size(); i++){
Node temp = open.get (i);
if (best.getFinalCost() > temp.getFinalCost()){
best = temp;
}
}
return best;
} | 2 |
private static Dimension getScaledDimension(Dimension imgSize, Dimension boundary) {
int original_width = imgSize.width;
int original_height = imgSize.height;
int bound_width = boundary.width;
int bound_height = boundary.height;
int new_width = original_width;
int new_height = original_height;
// first check if we need to scale width
if (original_width > bound_width) {
//scale width to fit
new_width = bound_width;
//scale height to maintain aspect ratio
new_height = (new_width * original_height) / original_width;
}
// then check if we need to scale even with the new height
if (new_height > bound_height) {
//scale height to fit instead
new_height = bound_height;
//scale width to maintain aspect ratio
new_width = (new_height * original_width) / original_height;
}
return new Dimension(new_width, new_height);
} | 2 |
public void calculate() throws IOException {
OggStreamAudioData data;
// Calculate the headers sizing
OggAudioInfoHeader info = headers.getInfo();
handleHeader(info);
handleHeader(headers.getTags());
handleHeader(headers.getSetup());
// Have each audio packet handled, tracking at least granules
while ((data = audio.getNextAudioPacket()) != null) {
handleAudioData(data);
}
// Calculate the duration from the granules, if found
if (lastGranule > 0) {
long samples = lastGranule - info.getPreSkip();
double sampleRate = info.getSampleRate();
if (info instanceof OpusInfo) {
// Opus is a special case - granule *always* runs at 48kHz
sampleRate = OpusAudioData.OPUS_GRANULE_RATE;
}
durationSeconds = samples / sampleRate;
}
} | 3 |
public static double getDouble() {
double x = 0.0;
while (true) {
String str = readRealString();
if (str == null) {
errorMessage("Floating point number not found.",
"Real number in the range " + (-Double.MAX_VALUE) + " to " + Double.MAX_VALUE);
}
else {
try {
x = Double.parseDouble(str);
}
catch (NumberFormatException e) {
errorMessage("Illegal floating point input, " + str + ".",
"Real number in the range " + (-Double.MAX_VALUE) + " to " + Double.MAX_VALUE);
continue;
}
if (Double.isInfinite(x)) {
errorMessage("Floating point input outside of legal range, " + str + ".",
"Real number in the range " + (-Double.MAX_VALUE) + " to " + Double.MAX_VALUE);
continue;
}
break;
}
}
inputErrorCount = 0;
return x;
} | 4 |
@Override
public T get(int index) {
if (index <= size()) {
MyList<T> node = first;
for(int i = 1; i < index; i++) {
node = node.right;
}
return node.value;
}
return null;
} | 2 |
private static void calcParam() {
if(!fullScreen) {
height = defHeight;
width = defWidth;
}
} | 1 |
public int[] importsCount(String[] requires){
n = requires.length;
graph = new boolean[n][n];
visited = new boolean[n];
graph = new boolean[n][n];
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
if(requires[i].charAt(j)=='Y') graph[i][j] = true;
}
}
for(int i=0; i<n; i++){
Arrays.fill(visited,false);
dfs(i, i);
}
int[] result = new int[n];
for(int i=0; i<n; i++){
int count = 0;
for(int j=0; j<n; j++){
if(graph[i][j]) count++;
}
result[i] = count;
}
return result;
} | 7 |
public int[] getPixels() {
return pixels;
} | 0 |
public Send(){
super();
} | 0 |
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
} | 0 |
private int read() throws IOException {
if (reader != null)
return reader.read();
else if (input != null)
return input.read();
else
throw new IllegalStateException();
} | 2 |
public String getCode() {
return code;
} | 0 |
private void RangeCheck(int index) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
} | 2 |
public static Matrix frustum(float left, float right, float bottom,
float top, float zNear, float zFar) {
if (zNear <= 0.0f || zFar < 0.0f) {
throw new RuntimeException(
"Frustum: zNear and zFar must be positive, and zNear>0");
}
if (left == right || top == bottom) {
throw new RuntimeException(
"Frustum: top,bottom and left,right must not be equal");
}
// Frustum matrix:
// 2*zNear/dx 0 A 0
// 0 2*zNear/dy B 0
// 0 0 C D
// 0 0 −1 0
float zNear2 = 2.0f * zNear;
float dx = right - left;
float dy = top - bottom;
float dz = zFar - zNear;
float A = (right + left) / dx;
float B = (top + bottom) / dy;
float C = -1.0f * (zFar + zNear) / dz;
float D = -2.0f * (zFar * zNear) / dz;
return new Matrix(zNear2 / dx, 0, 0, 0, 0, zNear2 / dy, 0, 0, A, B, C, -1,
0, 0, D, 0);
} | 4 |
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
Debug.print("Action performed on: " + o);
if(o == okButton) {
// create a new Ferm object
Hop i = new Hop();
i.setName(txtName.getText());
i.setAlpha(Double.parseDouble(txtAlpha.getText()));
i.setCost(txtCost.getText());
i.setStock(Double.parseDouble(txtStock.getText()));
i.setUnits(cUnits.getSelectedItem().toString());
i.setDescription(txtDescr.getText());
i.setStorage(Double.parseDouble(txtStorage.getText()));
i.setDate(txtDate.getText());
i.setModified(bModified.isSelected());
int result = 1;
int found = db.find(i);
Debug.print("Searched for Hop, returned: "+found);
// check to see if we have this hop already in the db
if(found >= 0){
// This already exists, do we want to overwrite?
result = JOptionPane.showConfirmDialog((Component) null,
"This ingredient exists, overwrite original?","alert", JOptionPane.YES_NO_CANCEL_OPTION);
switch(result) {
case JOptionPane.NO_OPTION:
setVisible(false);
dispose();
return;
case JOptionPane.YES_OPTION:
db.hopsDB.remove(found);
break;
case JOptionPane.CANCEL_OPTION:
return;
default:
break;
}
}
db.hopsDB.add(i);
db.writeHops();
setVisible(false);
dispose();
} else if(o == cancelButton) {
dispose();
}
} | 6 |
private void jComboBoxCommandeClientInterlocuteurItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxCommandeClientInterlocuteurItemStateChanged
// si changement ou choix interlocuteur
if (evt.getStateChange() == ItemEvent.SELECTED) {
Interlocuteur interlocuteur = (Interlocuteur) jComboBoxCommandeClientInterlocuteur.getSelectedItem();
id_interlocuteur =interlocuteur.getIdinterlocuteur();
//System.out.println(interlocuteur.getNom());
try {
Service service = RequetesService.SelectServiceById(interlocuteur.getIdservice());
// System.out.println(service.toString());
Entreprise entreprise = RequetesEntreprise.SelectEntrepriseById(service.getIdentreprise());
//System.out.println(entreprise.toString());
this.jComboBoxCommandeClientEntreprise.removeAllItems();
this.jComboBoxCommandeClientEntreprise.addItem(entreprise);
} catch (SQLException ex) {
Logger.getLogger(VueCommandeClientDebut.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_jComboBoxCommandeClientInterlocuteurItemStateChanged | 2 |
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if (!validateFecha(fechaOferta)) {
errors.add("fechaOferta", new ActionMessage("error.fecha.invalida"));
}
if (!validateTelefono(telefono)) {
errors.add("telefono", new ActionMessage("error.telefono.invalido"));
}
if (!validateCorreo(correo)) {
errors.add("correo", new ActionMessage("error.correo.invalido"));
}
if (nomEmpresa.matches("\\w") || nomEmpresa.equals("")) {
errors.add("nomEmpresa", new ActionMessage("error.campo.vacio"));
}
if (direccion.matches("\\w") || direccion.equals("")) {
errors.add("direccion", new ActionMessage("error.campo.vacio"));
}
if (contacto.matches("\\w") || contacto.equals("")) {
errors.add("contacto", new ActionMessage("error.campo.vacio"));
}
return errors;
} | 9 |
private void setResourceURL(URL url) {
resource_url = url;
} | 0 |
private ctrlDisco() {
//Facs = new File("./Data/facturas");
//Clientes = new File("./Data/clientes");
//Coches = new File(":/Data/coches");
if (!Clientes.exists()) {
Clientes.mkdirs();
}
if (!Coches.exists()) {
Coches.mkdirs();
}
if (!Facs.exists()) {
Facs.mkdirs();
}
crearArchivo("clientes/clientes");
crearArchivo("coches/coches");
} | 3 |
public ParseException generateParseException() {
jj_expentries.removeAllElements();
boolean[] la1tokens = new boolean[29];
for (int i = 0; i < 29; i++) {
la1tokens[i] = false;
}
if (jj_kind >= 0) {
la1tokens[jj_kind] = true;
jj_kind = -1;
}
for (int i = 0; i < 6; i++) {
if (jj_la1[i] == jj_gen) {
for (int j = 0; j < 32; j++) {
if ((jj_la1_0[i] & (1<<j)) != 0) {
la1tokens[j] = true;
}
}
}
}
for (int i = 0; i < 29; i++) {
if (la1tokens[i]) {
jj_expentry = new int[1];
jj_expentry[0] = i;
jj_expentries.addElement(jj_expentry);
}
}
int[][] exptokseq = new int[jj_expentries.size()][];
for (int i = 0; i < jj_expentries.size(); i++) {
exptokseq[i] = (int[])jj_expentries.elementAt(i);
}
return new ParseException(token, exptokseq, tokenImage);
} | 9 |
public String getName() {
return Name;
} | 0 |
public void loadProperties() {
try {
FileInputStream fis = new FileInputStream(new File(Main.USER_PROPS));
props.load(fis);
} catch (IOException e) {
initProperties();
}
if (!validProperties())
initProperties();
this.setBounds(new Integer(props.getProperty("X")).intValue(),
new Integer(props.getProperty("Y")).intValue(), new Integer(
props.getProperty("width")).intValue(), new Integer(
props.getProperty("height")).intValue());
toolbar.setTreeSelected(new Boolean(props.getProperty("tree"))
.booleanValue());
this.showHideNavigator();
} | 2 |
public void testSaveStranogGosta() {
Osoba o = new Osoba();
o.setImePrezime("Alen Kopic");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
o.setDatumRodjenja(sdf.parse("1992-10-21"));
} catch (java.text.ParseException p) {
System.out.println(p.toString());
}
o.setAdresa("Vitkovac 166");
Gost g = new Gost();
g.setMjestoRodjenja("Beograd");
g.setOsoba(o);
DBManager.saveOsobu(o);
DBManager.saveGosta(g);
StraniGost sg = new StraniGost();
sg.setBrojPutneIsprave("A000000");
sg.setBrojVize("A000000");
try {
sg.setDatumDozvoleBoravka(sdf.parse("2014-06-10"));
} catch (java.text.ParseException p) {
System.out.println(p.toString());
}
try {
sg.setDatumUlaskaUBih(sdf.parse("2014-06-10"));
} catch (java.text.ParseException p) {
System.out.println(p.toString());
}
sg.setDrzavljanstvo("BIH");
sg.setGost(g);
sg.setVrstaPutneIsprave("Neka");
sg.setVrstaVize("Neka");
DBManager.saveStranogGosta(sg);
List<StraniGost> stranigosti = DBManager.dajStraneGoste();
Boolean tacno=false;
for (StraniGost i : stranigosti) {
if(i.getBrojPutneIsprave()!=null)
if( i.getBrojPutneIsprave().equals(sg.getBrojPutneIsprave()))
tacno=true;
}
Assert.assertTrue(tacno);
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t1 = session.beginTransaction();
session.delete(o);
session.delete(g);
session.delete(sg);
t1.commit();
session.close();
} | 6 |
public static String[] generateInitialData(final int accountsNumber, final int transferNumber) {
List<Future<String>> futures = new ArrayList<>();
ExecutorService threadPool = Executors.newFixedThreadPool(2);
futures.add(threadPool.submit(new Callable<String>() {
@Override
public String call() throws Exception {
StringBuilder builder = new StringBuilder(1_000_000);
ThreadLocalRandom random = ThreadLocalRandom.current();
builder.append(accountsNumber);
for (int i = 0; i < accountsNumber; i++) {
builder.append(' ').append(random.nextInt(0, DEFAULT_BALANCE_BOUND));
}
return builder.toString();
}
}));
futures.add(threadPool.submit(new Callable<String>() {
@Override
public String call() throws Exception {
StringBuilder builder = new StringBuilder(10_000_000);
ThreadLocalRandom random = ThreadLocalRandom.current();
builder.append(transferNumber);
for (int i = 0; i < transferNumber; i++) {
builder.append(' ').append( random.nextInt(0, accountsNumber) ).
append(' ').append( random.nextInt(0, accountsNumber) ).
append(' ').append( random.nextInt(0, TRANSFER_AMOUNT_BOUND) );
}
return builder.toString();
}
}));
threadPool.shutdownNow();
final String[] result = new String[futures.size()];
for (int i = 0; i < futures.size(); i++){
try {
result[i] = futures.get(i).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
return result;
} | 4 |
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.