method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
f3416b17-65ef-43f3-9a78-3ac380ff24c6 | 5 | public void normalizeSquared(int col) {
double sqr = 0.0f;
for(int j=0; j < nrows; j++) {
double x = (double) getValue(j, col);
sqr += x * x;
}
System.out.println("Normalize-squared: " + col + " sqr: " + sqr);
float div = (float) Math.sqrt(sqr);
System.out.println("Div : " + div);
if (Float.isInfinite(div) || Float.isNaN(div)) throw new RuntimeException("Illegal normalizer: " + div);
if (sqr == 0.0f) throw new IllegalArgumentException("Column was all-zeros!");
for(int j=0; j < nrows; j++) {
float x = getValue(j, col);
setValue(j, col, x / div);
}
} |
c6b8ef77-f81d-42e4-947a-f0b233a24c70 | 3 | @Override
public void actionPerformed(ActionEvent e) {
OutlinerDocument doc = (OutlinerDocument) Outliner.documents.getMostRecentDocumentTouched();
OutlinerCellRendererImpl textArea = doc.panel.layout.getUIComponent(doc.tree.getEditingNode());
if (textArea == null) {
return;
}
Node node = textArea.node;
JoeTree tree = node.getTree();
OutlineLayoutManager layout = tree.getDocument().panel.layout;
if (doc.tree.getComponentFocus() == OutlineLayoutManager.TEXT) {
CopyAction.copyText(textArea, tree, layout);
} else if (doc.tree.getComponentFocus() == OutlineLayoutManager.ICON) {
CopyAction.copy(tree, layout);
}
} |
6b3fd0af-0684-4c29-896d-0eb5165ca6e9 | 0 | public String getId() {
return id;
} |
f40de6f3-ba42-4795-8f5b-28d1dd4abc3d | 9 | @SuppressWarnings({ "unused", "unchecked" })
private HashMap<String, ActionPattern> buildActionPatterns(Agent agent,
HashMap<String, Competence> competences2,
HashMap<String, ActionPattern> actionPatterns2) {
//HashMap<String, ActionPattern> returnActionPatterns = new HashMap<String, ActionPattern>();
HashMap<String, ActionPattern> returnActionPatterns = actionPatterns2;
Object[] actionPatternArray = this.actionPatterns.keySet().toArray();
for (int i = 0 ; i < actionPatternArray.length; i++) {
String actionPattern = (String) actionPatternArray[i];
ArrayList<CopiableElement> elementList = new ArrayList<CopiableElement>();
Object[] elementNames = this.actionPatterns.get(actionPattern).Third.toArray();
for (int j = 0; j <elementNames.length -1; j++ ) {
//deal with all but the last element
if (elementNames[j].getClass().equals(String.class) && false) {
//senseacts not implemented
//unreachable see if conditions
log.error("Unsupported request for sense-act, will ignore");
} else if (elementNames[j].getClass().equals(TupleThree.class)) {
//sense
elementList.add(buildSense(agent,(TupleThree<String,String,String>)elementNames[j]));
} else {
//action
elementList.add(getTriggerable(agent, (String)elementNames[j]));
}
}
//last element can also be a competence
if (elementNames[elementNames.length-1].getClass().equals(String.class) && false) {
//senseacts not yet implemented
//unreachable see if conditions
log.error("Unsupported request for sense-act, will ignore");
} else if (elementNames[elementNames.length-1].getClass().equals(TupleThree.class)) {
//sense
elementList.add(buildSense(agent,(TupleThree<String,String,String>)elementNames[elementNames.length-1]));
} else {
//action
elementList.add(getTriggerable(agent, (String)elementNames[elementNames.length-1],competences2));
}
//elementList toArray
CopiableElement[] elementArray = new CopiableElement[elementList.size()];
for (int j = 0; j < elementArray.length; j++) {
elementArray[j] = elementList.get(j);
}
ActionPattern newAP = actionPatterns2.get(actionPattern);
newAP.setElements(elementArray);
returnActionPatterns.put(actionPattern, newAP);
}
return returnActionPatterns;
} |
a7fc131e-fd42-4c43-899c-d0fe5865a3cc | 9 | double[] recPositions(int chrom) {
//get all recPositions of the first haplotype:
double[] recpos = new double[0];
for (int p=0; p<getPloidy(); p++) {
ArrayList<Double> hrecs = haplostruct[chrom][p].getRecombPos();
int rp=0; //index to recpos
for (int hp=0; hp<hrecs.size(); hp++) {
//first: skip all smaller recpos items:
while (rp<recpos.length && recpos[rp]<hrecs.get(hp)) {
rp++;
}
//if hrecs value not in recpos: insert
if (rp>=recpos.length || recpos[rp]!=hrecs.get(hp)) {
double[] tmp = new double[recpos.length+1];
for (int i=0; i<rp; i++) {
tmp[i] = recpos[i];
}
tmp[rp] = hrecs.get(hp);
for (int i=rp; i<recpos.length; i++ ) {
tmp[i+1] = recpos[i];
}
recpos = tmp;
}
//else hrec already in recpos, do nothing
//rc (still) points to recpos value identical to hrecs value
}
}
assert recpos[0]==popdata.getChrom(chrom).getHeadPos();
//delete the first (headPos) position:
double[] result = new double[recpos.length-1];
for (int i=0; i<result.length; i++) {
result[i] = recpos[i+1];
}
return result;
} |
a559dd18-0750-4b26-8464-b628ae775d4c | 9 | public void writeVariant(Variant var) throws IOException {
if (var.isStringType()) {
writeString(var.getString());
} else if (var.isObjectType()) {
out.append('{');
writeln();
boolean first = true;
for (Map.Entry<String, Variant> e : var.varObject().entrySet()) {
if (first) {
first = false;
} else {
out.append(',');
writeln();
}
writeString(e.getKey());
out.append(':');
writeVariant(e.getValue());
}
out.append('}');
} else if (var.isArrayType()) {
out.append('[');
boolean first = true;
for (Variant item : var.varList()) {
if (first) {
first = false;
} else {
out.append(',');
writeln();
}
writeVariant(item);
}
out.append(']');
} else if (var.isPrimaryType()) {
out.append(var.toString());
} else if (var.isNull()) {
out.append("null");
} else {
throw new RuntimeException("Ignoring unsupported var: " + var.getDebugInfo());
}
} |
0751eb4c-ed9f-4093-9a94-7b6e76e72a2a | 5 | public static void update(GameContainer container, int delta) throws SlickException {
if (isInputPressed(Controls.DEBUG)) {
setDebug(!isDebug());
}
if (transition != null) {
transition.update(game, container, delta);
if (transition.isComplete()) {
if (transition instanceof TiledMapTransition) {
((TiledMapTransition) transition).executeAfterCompletion();
}
transition = null;
}
}
camera.update(delta);
container.setShowFPS(isDebug());
for (int i = 0; i < entities.size(); i++) {
AbstractEntity entity = (AbstractEntity) entities.get(i);
entity.update(delta);
}
} |
04d65ad6-4362-4e85-9628-556a20d2865c | 4 | @Raw
public World(double width, double height, boolean[][] passableMap,
Random random) throws IllegalArgumentException {
if (!isValidDimension(width, height))
throw new IllegalArgumentException("The dimension provided isn't a valid dimension for a World");
if(random == null)
throw new IllegalArgumentException("The random parameter was a null reference, which isn't allowed.");
if(passableMap == null)
throw new IllegalArgumentException("The passableMap musn't be a null reference.");
if(!isRectangleDimension(passableMap))
throw new IllegalArgumentException("The passableMap must be a rectangle shaped dimension.");
this.width = width;
this.height = height;
//Cloned because we don't want anyone to modify our world while we're playing.
this.passableMap = getInvertedMap(Util.deepClone(passableMap));
this.random = random;
gameObjList = new ArrayList<GameObject>();
teamList = new ArrayList<Team>();
} |
3e794cb6-e131-40aa-b1d3-79b8170a7974 | 2 | private String getTripText (Integer trip) {
String s = "Gruppe: " + tripsOfDay.get(trip).getGroupNumber().toString();
s += " Fluss: " + tripsOfDay.get(trip).getRiver().getRiverName();
s += " WW" + tripsOfDay.get(trip).getRiver().getWwLevel() + "\n";
s += "Start: " + tripsOfDay.get(trip).getRiver().getTripFrom();
s += " / Ziel: " + tripsOfDay.get(trip).getRiver().getTripTo();
s += " (" + tripsOfDay.get(trip).getRiver().getTripLength() + "km)\n";
if (tripsOfDay.get(trip).getIsEducation())
s += "Schulungsfahrt\n";
else
s += "F\u00fchrungsdsfahrt\n";
s += "Abfahrt: " + new SimpleDateFormat("hh.mm").format(tripsOfDay.get(trip).getTripStartTime());
s += " Gruppenst\u00e4rke: " + tripsOfDay.get(trip).getTotalGroupSize().toString() + "\n";
s+= "Fahrtenleiter:\n";
for (int r = 0; r < tripsOfDay.get(trip).getRosterCount(); r++) {
s += " " + tripsOfDay.get(trip).getRosterName(r) + " (" + tripsOfDay.get(trip).getRosterPhoneNumber (r) + ")\n";
}
s+= "Bemerkung: " + tripsOfDay.get(trip).getComment();
return s;
} |
7736262a-1f82-4947-b214-25161b960dcc | 1 | private boolean jj_2_21(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_21(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(20, xla); }
} |
4b28e552-5192-4e94-969c-f500a24f5342 | 5 | public void printTable() {
Setup.println(" DISTANCE TABLE");
Setup.println("----------------------------------------------------------");
for (String n : dv.keySet()) {
Setup.print("\t" + n);
}
Setup.println();
// print mine
Setup.print(id);
for (String n : dv.keySet()) {
Setup.print("\t" + dv.get(n));
}
Setup.println();
// print neighbors'
for (NbrCostPair ncp : nbrList) {
HashMap<String, Integer> ndv = ncp.getNbr().getDv();
Setup.print(ncp.getNbr().getId());
for (String n : dv.keySet()) {
Integer distance = ndv.get(n);
Setup.print("\t" + ((distance == null) ? "INF" : distance));
}
Setup.println();
}
Setup.println();
} |
ae55588f-a161-4e99-a0e3-ce53d0fc50ca | 9 | protected void backfitHoldOutInstance(Instance inst, double weight,
Tree parent) throws Exception {
// Insert instance into hold-out class distribution
if (inst.classAttribute().isNominal()) {
// Nominal case
if (m_ClassProbs == null) {
m_ClassProbs = new double[inst.numClasses()];
}
System.arraycopy(m_Distribution, 0, m_ClassProbs, 0, inst.numClasses());
m_ClassProbs[(int)inst.classValue()] += weight;
Utils.normalize(m_ClassProbs);
} else {
// Numeric case
if (m_ClassProbs == null) {
m_ClassProbs = new double[1];
}
m_ClassProbs[0] *= m_Distribution[1];
m_ClassProbs[0] += weight * inst.classValue();
m_ClassProbs[0] /= (m_Distribution[1] + weight);
}
// The process is recursive
if (m_Attribute != -1) {
// If node is not a leaf
if (inst.isMissing(m_Attribute)) {
// Distribute instance
for (int i = 0; i < m_Successors.length; i++) {
if (m_Prop[i] > 0) {
m_Successors[i].backfitHoldOutInstance(inst, weight *
m_Prop[i], this);
}
}
} else {
if (m_Info.attribute(m_Attribute).isNominal()) {
// Treat nominal attributes
m_Successors[(int)inst.value(m_Attribute)].
backfitHoldOutInstance(inst, weight, this);
} else {
// Treat numeric attributes
if (inst.value(m_Attribute) < m_SplitPoint) {
m_Successors[0].backfitHoldOutInstance(inst, weight, this);
} else {
m_Successors[1].backfitHoldOutInstance(inst, weight, this);
}
}
}
}
} |
fb47c8a7-df31-4419-a744-3ed974f6425d | 8 | public int getSearchArticleCount(String search,String val, int area) throws Exception{
Connection conn = null;
PreparedStatement pstmt = null;
Statement stmt = null;
ResultSet rs = null;
int x = 0;
try{
conn = getConnection();
val = new String(val.getBytes("iso_8859-1"),"utf-8");
String sql = "select count(*) from food where "+search+" like '%"+val+"%' and area="+area;
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
if(rs.next()){
x = rs.getInt(1);
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
if(rs != null){
try{rs.close();}
catch(SQLException e){e.printStackTrace();}
}
if(pstmt != null){
try{pstmt.close();}
catch(SQLException e){e.printStackTrace();}
}
if(conn != null){
try{conn.close();}
catch(SQLException e){e.printStackTrace();}
}
}
return x;
} |
30f9cc13-61a1-4f04-a905-272aa0518ea8 | 5 | @SuppressWarnings("unchecked")
@PUT
@Produces( { "application/json", "application/xml" })
@Path("/mood/title/{title}/{username}/{valence}/{arousal}")
public void putMoodByName(@PathParam("title") String title,
@PathParam("username") String username,
@PathParam("valence") double valence, @PathParam("arousal") double arousal) {
if(valence>=0 && valence <=1 && arousal>=0 && arousal<=1){
PersistenceManager pm = PMF.get().getPersistenceManager();
User user = getUser(username);
Query q = pm.newQuery("select from " + Experience.class.getName()
+ " where title=='" + title + "'");
List<Experience> experiences = (List) q.execute();
Experience experience = experiences.get(0);
Event newMoodEvent = new Event();
newMoodEvent.setId(UUID.randomUUID().toString());
newMoodEvent.setExperienceid(experience.getId());
newMoodEvent.setClassName("MoodEvent");
newMoodEvent.setCreator(user.getUsername());
newMoodEvent.setDatetimemillis(new Date().getTime());
newMoodEvent.setShared(false);
newMoodEvent.setLatitude("0");
newMoodEvent.setLongitude("0");
newMoodEvent.setValence(valence);
newMoodEvent.setArousal(arousal);
try {
try {
experience.getEvents().add(newMoodEvent);
pm.makePersistent(experience);
} catch (Exception e) {
// TODO: handle exception
}
} finally {
pm.close();
}
}else{
//Do not insert
}
} |
36c08e12-67f1-4f8a-9b5a-efa4045cb8b9 | 6 | @Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(jbEscolha)) {
String strMsg = validaFormulario();
if (!strMsg.equals("")) {
JOptionPane.showMessageDialog(rootPane, strMsg);
} else {
if (jrbDocAnalise.isSelected()) {
VControle.listaEventos.add(new EventoManutencaoPreventiva(VControle.manutencaoAtiva, VControle.funcionarioAtivo, EnumTiposManuPreventiva.PREVENTIVA_DOC_ANALISE));
}
else if (jrbDocProjeto.isSelected()) {
VControle.listaEventos.add(new EventoManutencaoPreventiva(VControle.manutencaoAtiva, VControle.funcionarioAtivo, EnumTiposManuPreventiva.PREVENTIVA_DOC_PROJETO));
}
else if (jrbTestes.isSelected()) {
VControle.listaEventos.add(new EventoManutencaoPreventiva(VControle.manutencaoAtiva, VControle.funcionarioAtivo, EnumTiposManuPreventiva.PREVENTIVA_TESTES));
}
else if (jrbCodigo.isSelected()) {
VControle.listaEventos.add(new EventoManutencaoPreventiva(VControle.manutencaoAtiva, VControle.funcionarioAtivo, EnumTiposManuPreventiva.PREVENTIVA_CODIGO));
}
dispose();
}
}
} |
404600f9-749d-44b6-8651-6523b7d41bae | 9 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
MOB target=mob;
if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB))
target=(MOB)givenTarget;
if(target.fetchEffect(this.ID())!=null)
{
mob.tell(target,null,null,L("<S-NAME> <S-IS-ARE> already berzerk."));
return false;
}
if((!auto)&&(!mob.isInCombat()))
{
mob.tell(L("You aren't in combat!"));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MSG_QUIETMOVEMENT,L("<T-NAME> get(s) a wild look in <T-HIS-HER> eyes!"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
hpAdjustment=(int)Math.round(CMath.div(target.maxState().getHitPoints(),5.0));
beneficialAffect(mob,target,asLevel,0);
target.curState().setHitPoints(target.curState().getHitPoints()+hpAdjustment);
target.recoverMaxState();
}
}
else
beneficialVisualFizzle(mob,null,L("<S-NAME> huff(s) and grunt(s), but can't get angry."));
return success;
} |
a25eb782-6230-42cc-ade9-fc93e733356f | 7 | public boolean existII(char[][] board, String word) {
if (board == null || board.length == 0 || word.length() > board.length * board[0].length)
return false;
char c = word.charAt(0);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (c == board[i][j]) {
boolean[][] visited = new boolean[board.length][board[0].length];
if (exist(board, word, 0, visited, i, j))
return true;
}
}
}
return false;
} |
046f3ae3-9e14-4c58-8711-fb9741f8b2c8 | 6 | @EventHandler
public void SilverfishNausea(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getSilverfishConfig().getDouble("Silverfish.Nausea.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getSilverfishConfig().getBoolean("Silverfish.Nausea.Enabled", true) && damager instanceof Silverfish && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, plugin.getSilverfishConfig().getInt("Silverfish.Nausea.Time"), plugin.getSilverfishConfig().getInt("Silverfish.Nausea.Power")));
}
} |
eada5247-2b41-4708-9d68-74c138146cb9 | 7 | public boolean doHashCheck (DownloadInfo asset, final List<String> remoteHash) throws IOException {
String hash = DownloadUtils.fileHash(asset.local, asset.hashType).toLowerCase();
List<String> assetHash = asset.hash;
boolean good = false;
if (asset.hash == null) {
if (remoteHash != null) {
assetHash = remoteHash;
} else if (asset.getBackupDLType() == DLType.FTBBackup && DownloadUtils.backupIsValid(asset.local, asset.url.getPath().replace("/FTB2", ""))) {
good = true;
}
}
if (good || assetHash != null && assetHash.contains(hash))
return true;
Logger.logWarn("Asset hash checking failed: " + asset.name + " " + asset.hashType + " " + hash);//unhashed DL's are not allowed!!!
asset.local.delete();
return false;
} |
258d0975-4be4-4aed-a7fa-c6f2bb81ed25 | 8 | public static void main (String[] args) throws FileNotFoundException {
Scanner key = new Scanner(System.in);
// System.out.println("enter title name");
// String input = key.nextLine();
File htmlDir = new File("G:/Code/htmls/");
File[] htmls = htmlDir.listFiles();
ArrayList<String> inputs = new ArrayList<String>();
for (File htmlFile: htmls) {
if (htmlFile.toString().endsWith(".html")) {
inputs.add(htmlFile.getName().replaceAll(".html", ""));
}
}
for (String input: inputs) {
File inputFile = new File("G:/Code/htmls/" + input + ".html");
String imagedir = "G:/Code/Database/" + input + "+/";
File imageDirFile = new File(imagedir);
imageDirFile.mkdir();
Scanner reader = new Scanner(new FileReader(inputFile));
ArrayList<String> urls = new ArrayList<String>();
while (reader.hasNext()) {
input = reader.nextLine();
if (input.contains("card.php?card_id")) {
urls.add(input);
}
}
for (int i = 0; i < urls.size(); i++) {
String thisUrl = urls.get(i).replaceAll("\t", "").replaceAll("<li>", "").replaceAll("</ul><ul>", "").replaceAll(" ", "");
thisUrl = thisUrl.substring(66, 71);
urls.set(i, thisUrl);
}
int fileIndex = 0;
try {
for (String cardnum: urls) {
URL url = new URL("http://images.littleakiba.com/tcg/weiss-schwarz/card-large.php?card_id=" + cardnum);
URLConnection conn = url.openConnection();
conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
InputStream in = conn.getInputStream();
BufferedImage image = ImageIO.read(in);
ImageIO.write(image, "jpg", new File(imagedir + fileIndex + ".jpg"));
fileIndex++;
}
}
catch (IOException e)
{
e.printStackTrace();
}
reader.close();
}
// DirectoryStream<Path> ds;
// try
// {
// ds = Files.newDirectoryStream(FileSystems.getDefault().getPath(imagedir));
//
// ArrayList<Path> dirPaths = new ArrayList<Path>();
// for (Path p: ds) {
// if (new File(p.toString()).isDirectory()) {
// dirPaths.add(p);
// }
// }
// ds.close();
// for (Path p: dirPaths) {
// File dirFile = new File(p.toString());
// File[] directoryListing = dirFile.listFiles();
// if (directoryListing != null) {
// int i = 0;
// for (String cardString: urls) {
// for (File imageFile: directoryListing) {
// if (imageFile.toString().contains(cardString)) {
// imageFile.renameTo(new File(imageFile.toString().replaceAll(cardString, Integer.toString(i))));
// break;
// }
// }
// i++;
// }
// ds.close();
// }
// }
// }
// catch (IOException e)
// {
// e.printStackTrace();
// }
//
} |
44c6f5b1-c21e-475c-9707-8a4ea9643b77 | 5 | public void run(){
while(true){
try {
try { Thread.sleep(1000); } catch (InterruptedException ex) {}
System.err.println("Deamon");
Transporte tr = new Transporte(100);
DatagramPacket p = tr.receberDatagramPacket(receiveSocket);
if(p!=null){
System.err.print("Deamon: ");
System.err.println(p.getAddress() + "," + p.getPort());
tr = tr.receberDeDatagramPacket(p);
System.err.print("Deamon: ");
System.err.println(tr.toString()); //teste
if(tr.eqFlag("SYN")){
Thread t = new Thread(new AplicacaoServidor(p,this.root));
t.start();
//t.join();
}
}
//} catch (InterruptedException ex) {
} catch (IOException ex) {}
}
} |
7b1b138b-ebbe-4315-96b9-d88dfa6324e6 | 5 | public boolean isReady(){
return ( !resultReady && !isPlaceHolder(addr_comp[0]) &&
!isPlaceHolder(addr_comp[1]) &&
( !is_store || (is_store && !isPlaceHolder(addr_comp[2])) ) ); // force store to wait for register value
} |
2c20f763-d38a-4dd7-a8f4-d856efb255a0 | 9 | private static void diffDefaultValues(final PrintWriter writer,
final PgView oldView, final PgView newView,
final SearchPathHelper searchPathHelper) {
final List<PgView.DefaultValue> oldValues =
oldView.getDefaultValues();
final List<PgView.DefaultValue> newValues =
newView.getDefaultValues();
// modify defaults that are in old view
for (final PgView.DefaultValue oldValue : oldValues) {
boolean found = false;
for (final PgView.DefaultValue newValue : newValues) {
if (oldValue.getColumnName().equals(newValue.getColumnName())) {
found = true;
if (!oldValue.getDefaultValue().equals(
newValue.getDefaultValue())) {
searchPathHelper.outputSearchPath(writer);
writer.println();
writer.print("ALTER TABLE ");
writer.print(
PgDiffUtils.getQuotedName(newView.getName()));
writer.print(" ALTER COLUMN ");
writer.print(PgDiffUtils.getQuotedName(
newValue.getColumnName()));
writer.print(" SET DEFAULT ");
writer.print(newValue.getDefaultValue());
writer.println(';');
}
break;
}
}
if (!found) {
searchPathHelper.outputSearchPath(writer);
writer.println();
writer.print("ALTER TABLE ");
writer.print(PgDiffUtils.getQuotedName(newView.getName()));
writer.print(" ALTER COLUMN ");
writer.print(PgDiffUtils.getQuotedName(
oldValue.getColumnName()));
writer.println(" DROP DEFAULT;");
}
}
// add new defaults
for (final PgView.DefaultValue newValue : newValues) {
boolean found = false;
for (final PgView.DefaultValue oldValue : oldValues) {
if (newValue.getColumnName().equals(oldValue.getColumnName())) {
found = true;
break;
}
}
if (found) {
continue;
}
searchPathHelper.outputSearchPath(writer);
writer.println();
writer.print("ALTER TABLE ");
writer.print(PgDiffUtils.getQuotedName(newView.getName()));
writer.print(" ALTER COLUMN ");
writer.print(PgDiffUtils.getQuotedName(newValue.getColumnName()));
writer.print(" SET DEFAULT ");
writer.print(newValue.getDefaultValue());
writer.println(';');
}
} |
4cc53ed1-e0f8-4a2a-8262-759b6e91fcc1 | 7 | public static void M(Topic root) {
ArrayList<SparseMatrix> edges = root.Get_edgeset();
float[][] eijk = root.clone2df(root.Get_edgeweight());
int ii = eijk.length; // number of edges
int jj = eijk[0].length; // number of topics
//float[] rho_z_M = root.clone1df(root.Get_rho_z());
float[] rho_z_M = new float[eijk[0].length];
Arrays.fill(rho_z_M, 0);
for(int j = 0; j< jj; j++){
for(int i = 0; i< ii; i ++){
rho_z_M[j] = rho_z_M[j] + eijk[i][j];
}
}
root.Set_rho_zM(rho_z_M);
/**
* Setting the thetai values for each word across topics
*/
float[][] sumthetai = new float[root.Get_thetai().length][root.Get_thetai()[0].length];
for(int i = 0; i< sumthetai[0].length; i++){
Arrays.fill(sumthetai[i], 0);
}
Iterator<SparseMatrix> it = edges.iterator();
int ew = 0;
while (it.hasNext()) {
SparseMatrix current = it.next();
for (int t = 0; t < sumthetai[0].length; t++) {
sumthetai[current.getwordid1() - 1][t] = sumthetai[current.getwordid1() - 1][t] + eijk[ew][t];
sumthetai[current.getwordid2() - 1][t] = sumthetai[current.getwordid2() - 1][t] + eijk[ew][t];
}
ew++;
}
float[][] thetai = new float[sumthetai.length][sumthetai[0].length];
for (int i = 0; i < sumthetai.length; i++) {
for (int j = 0; j < sumthetai[0].length; j++) {
thetai[i][j] = sumthetai[i][j] / rho_z_M[j];
}
}
} |
add1772f-00fd-474f-ac3a-326c4fbedf0c | 7 | public void testThreadSafety() throws Exception {
rnd = newRandom();
final int numThreads = 5;
final int numDocs = 50;
final ByteArrayPool pool = new ByteArrayPool(numThreads, 5);
Directory dir = new RAMDirectory();
final IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.LIMITED);
final String field = "test";
Thread[] ingesters = new Thread[numThreads];
for (int i = 0; i < numThreads; i++) {
ingesters[i] = new Thread() {
@Override
public void run() {
try {
for (int j = 0; j < numDocs; j++) {
Document d = new Document();
d.add(new Field(field, new PoolingPayloadTokenStream(pool)));
writer.addDocument(d);
}
} catch (Exception e) {
e.printStackTrace();
fail(e.toString());
}
}
};
ingesters[i].start();
}
for (int i = 0; i < numThreads; i++) {
ingesters[i].join();
}
writer.close();
IndexReader reader = IndexReader.open(dir, true);
TermEnum terms = reader.terms();
while (terms.next()) {
TermPositions tp = reader.termPositions(terms.term());
while(tp.next()) {
int freq = tp.freq();
for (int i = 0; i < freq; i++) {
tp.nextPosition();
assertEquals(pool.bytesToString(tp.getPayload(new byte[5], 0)), terms.term().text);
}
}
tp.close();
}
terms.close();
reader.close();
assertEquals(pool.size(), numThreads);
} |
c2d5d947-0cd1-456f-af54-48fb63e062fe | 2 | public void close()
{
if(socket != null)
{
try{
socket.close();
ServerHelper.log(LogType.NETWORK, "ServerSocket geschlossen");
}
catch(IOException e)
{
ServerHelper.log(LogType.ERROR, "Fehler beim Schließen des Serversockets");
}
}
} |
8409b190-0e71-46f2-bf56-28d633d638ec | 9 | @Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
throws IOException {
if (dir.toString().equalsIgnoreCase(ROOTDIR))
return CONTINUE;
String name = "" + dir;
String[] comps = name.split("/");
String tmp = comps[comps.length - 1].toLowerCase();
if (related.length == 0) {
p.addColumn(tmp, Printer.Type.BOTH);
} else {
p.addColumn(StringUtils.join(related, " "), Printer.Type.BOTH);
}
if (this.docs.documents.size() > 5000 ) {
System.out.println("Too many files, skipping");
p.addColumn(docs.documents.size(), Printer.Type.BOTH);
p.addColumn(docs.numSentences(), Printer.Type.BOTH);
p.addColumn("0", Printer.Type.BOTH);
p.addColumn("0", Printer.Type.TIMING);
p.addColumn("Too Large", Printer.Type.TEXT);
p.endRow();
return CONTINUE;
}
File file = new File("LexRankFiles/Input");
String[] myFiles = file.list();
for (int i=0; i<myFiles.length; i++) {
File myFile = new File(file, myFiles[i]);
myFile.delete();
}
System.out.println(file.list().length);
file = new File("Results/LexRank.INPU");
if (file.exists()) {
file.delete();
} else {
System.out.println("Missing file");
}
int i = 0;
for (Document d: this.docs.documents) {
// Write Vocab
file = new File("LexRankFiles/Input", ""+i);
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write("<DOC>\n");
bw.write("<DOCNO>\n");
bw.write(i + "\n");
bw.write("</DOCNO>\n");
bw.write("<DOCTYPE>NEWS</DOCTYPE>\n");
bw.write("<TXTTYPE>NEWSWIRE</TXTTYPE>\n");
bw.write("<TEXT>" + d.text + "</TEXT>\n");
bw.write("</DOC>");
bw.close();
i++;
}
String[] cmd = { "java", "dragon.config.SummarizationEvaAppConfig", "/home/graveendran/workspace/StanfordNLPTest/sumcfg2005.xml", "1" };
Process proc;
proc = new ProcessBuilder(cmd).redirectError(Redirect.INHERIT).redirectOutput(Redirect.INHERIT).start();
//proc = new ProcessBuilder(cmd).start();
try {
proc.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Done Execution");
File f = new File("Results/LexRank.INPU");
List<String> summary = new ArrayList<String>();
if (f.exists()) {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
summary.add(line);
}
br.close();
} else {
summary.add("Missing summary");
System.out.println("Failed");
}
p.addColumn(docs.documents.size(), Printer.Type.BOTH);
p.addColumn(docs.numSentences(), Printer.Type.BOTH);
long totalWords = 0;
long executionTime = System.currentTimeMillis() - dirStart;
p.addColumn(totalWords, Printer.Type.BOTH);
p.addColumn(executionTime, Printer.Type.TIMING);
p.addColumn(StringUtils.join(summary, " ").trim(), Printer.Type.TEXT);
p.endRow();
return CONTINUE;
} |
36394461-62ea-4a1c-b7fd-a882e84190d9 | 5 | public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder out = new StringBuilder();
String line = "";
while ((line = in.readLine()) != null && line.length() != 0) {
double xm = Double.parseDouble(line.trim());
double ym = Double.parseDouble(in.readLine().trim());
Point m = new Point(xm, ym);
int n = Integer.parseInt(in.readLine().trim());
Point[] s = new Point[n + 1];
for (int i = 0; i < n + 1; i++) {
double x = Double.parseDouble(in.readLine().trim());
double y = Double.parseDouble(in.readLine().trim());
s[i] = new Point(x, y);
}
double dis = Double.MAX_VALUE, d;
Point ans = new Point(0, 0);
for (int i = 1; i < n + 1; i++) {
Point per = minPointSeg(s[i - 1], s[i], m);
d = dis(per, m);
if (d < dis) {
dis = d;
ans = per;
}
}
out.append(f(ans.x) + "\n" + f(ans.y) + "\n");
}
System.out.print(out);
} |
034494ab-cebb-4496-a49f-a1316bf5c8a4 | 7 | public static final int getDropRate(byte village) {
switch (village) {
case 0:
return 20;
case 1:
return 10;
case 2:
return 10;
case 3:
return 30;
case 4:
return 10;
case 5:
return 20;
case 6:
return 30;
default:
return 10;
}
} |
f4b4584a-3f56-423e-9ca2-02028b64fc12 | 1 | public void removeEdge(final GraphNode v, final GraphNode w) {
final Block src = (Block) v;
final Block dst = (Block) w;
if (FlowGraph.DEBUG) {
System.out.println(" REMOVING EDGE " + src + " -> " + dst);
}
super.removeEdge(src, dst);
cleanupEdge(src, dst);
} |
5848d7a7-4167-486f-8597-407e3fb8b0de | 3 | public static Matrix getMatrix(int rows, int cols, DataType dataType) {
Matrix matrix = null;
switch (dataType) {
case INTEGER:
matrix = new MatrixInteger(rows, cols);
break;
case DOUBLE:
matrix = new MatrixDouble(rows, cols);
break;
case ARRAY:
matrix = new MatrixArray(rows, cols);
break;
}
return matrix;
} |
146476bb-e032-4fb2-a937-e8a08d721c32 | 8 | public static void main(String[] args) throws NoSuchMethodException, IOException {
ExpressionFactory factory = new ExpressionFactoryImpl();
SimpleContext context = new SimpleContext();
// variables e, pi
context.setVariable("e", factory.createValueExpression(Math.E, double.class));
context.setVariable("pi", factory.createValueExpression(Math.PI, double.class));
// functions sin, cos, tan, exp, log, abs, sqrt, min, max, pow
context.setFunction("", "sin", Math.class.getMethod("sin", double.class));
context.setFunction("", "cos", Math.class.getMethod("cos", double.class));
context.setFunction("", "tan", Math.class.getMethod("tan", double.class));
context.setFunction("", "exp", Math.class.getMethod("exp", double.class));
context.setFunction("", "log", Math.class.getMethod("log", double.class));
context.setFunction("", "abs", Math.class.getMethod("abs", double.class));
context.setFunction("", "sqrt", Math.class.getMethod("sqrt", double.class));
context.setFunction("", "min", Math.class.getMethod("min", double.class, double.class));
context.setFunction("", "max", Math.class.getMethod("max", double.class, double.class));
context.setFunction("", "pow", Math.class.getMethod("pow", double.class, double.class));
// print out the rules of the game...
System.out.println("> Enter one expression per line (without \"${\" and \"}\"). An expressions matching");
System.out.println("> \"m[0-9]*\" saves the previous evaluation result to \"memory\". Other expressions");
System.out.println("> are simply evaluated. Functions are sin, cos, tan, exp, log, abs, sqrt, min,");
System.out.println("> max and pow, variables are e and pi. An empty line terminates the calculator.");
// read/evaluate expressions
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Object display = 0;
while (true) {
System.out.print("< ");
String line = reader.readLine();
if (line != null) {
line = line.trim();
}
if (line == null || line.length() == 0) {
System.out.println("> Good bye.");
System.exit(0);
}
try {
ValueExpression expr =
factory.createValueExpression(context, "${" + line + "}", Object.class);
if (line.matches("m[0-9]*")) { // "save to memory"
expr.setValue(context, display);
} else {
display = expr.getValue(context);
}
System.out.println("> " + display);
} catch (TreeBuilderException e) {
// demonstrate use of TreeBuilderException and create customized message...
StringBuilder message = new StringBuilder();
message.append("Syntax Error at position ");
// one-based position within line
message.append(e.getPosition()-1);
message.append(": encountered ");
// treat closing brace as end of file...
message.append(e.getPosition() == e.getExpression().length()-1 ? "<EOF>" : e.getEncountered());
message.append(", expected ");
message.append(e.getExpected());
System.out.println("> " + message);
} catch (ELException e) {
System.out.println("> " + e.getMessage());
}
}
} |
17f00d0f-68b3-4ded-bee1-a938727b53c5 | 5 | public double score(StringWrapper s,StringWrapper t)
{
computeTokenDistances();
BagOfTokens sBag = (BagOfTokens)s;
BagOfTokens tBag = (BagOfTokens)t;
double sim = 0.0;
for (Iterator i = sBag.tokenIterator(); i.hasNext(); ) {
Token tok = (Token)i.next();
double df = getDocumentFrequency(tok);
if (tBag.contains(tok)) {
double w = -Math.log( df/collectionSize );
sim += w;
} else {
Token matchTok = null;
double matchScore = tokenMatchThreshold;
for (Iterator j=tBag.tokenIterator(); j.hasNext(); ) {
Token tokJ = (Token)j.next();
double distItoJ = tokenDistance.score( tok.getValue(), tokJ.getValue() );
if (distItoJ>=matchScore) {
matchTok = tokJ;
matchScore = distItoJ;
}
}
if (matchTok!=null) {
df = neighborhoodDocumentFrequency(tok, matchScore);
double w = -Math.log( df/collectionSize );
sim += w;
} else {
double w = -Math.log( df/collectionSize );
sim -= w * mismatchFactor;
}
}
}
return sim;
} |
fa948757-1da4-437c-947f-e75110e04c64 | 8 | public boolean checkForNewVersion(boolean notifyNoUpdate) {
String currentVersion = versionManager.getVersion();
String newVersion = versionManager.checkForNewVersion();
boolean newVersionAvailable = false;
if (newVersion != null && currentVersion != null) {
if (Version.compare(newVersion, currentVersion) > 0) {
newVersionAvailable = true;
if (Version.isFinal(newVersion)
|| (Version.isBeta(newVersion) && properties.getOptionsCommonNotifyAboutNewBetaVersions())) {
showNewVersion(newVersion);
}
}
}
if (notifyNoUpdate && !newVersionAvailable) {
showLatestVersion(currentVersion);
}
return true;
} |
5e0b0841-cd74-41a5-8970-f36562863d51 | 5 | public void editAcc() throws FileNotFoundException, IOException
{
System.out.println("Which Account do you want to edit? (Account Number)");
Scanner impor = new Scanner(System.in);
String editLine = "hi";
int ach = impor.nextInt();
String path = accDir+ach+".txt";
String newline = System.getProperty("line.separator");
FileReader fr1 = new FileReader(path);
BufferedReader br1 = new BufferedReader(fr1);
int numberOfLines = 3;
String[] textData = new String[numberOfLines];
for (int b = 0; b < numberOfLines; b++) {
textData[b] = br1.readLine(); }
Scanner in = new Scanner(System.in);
System.out.println("-----------------------");
System.out.println(textData[0]);
System.out.println(textData[1]);
System.out.println(textData[2]);
System.out.println("-----------------------");
br1.close();
FileWriter fw = new FileWriter(path);
BufferedWriter bw = new BufferedWriter(fw);
System.out.println("What do you want to edit?");
System.out.println("type 1 for name");
System.out.println("type 2 for Address");
System.out.println("type 3 for Occupation");
String inc = in.nextLine();
System.out.println("What would you like to change it to?");
String editMade = in.nextLine();
switch (inc) {
case "1":
editLine = editMade + newline + textData[1] + newline + textData[2];
break;
case "2":
editLine = textData[0] + newline + editMade + newline + textData[2];
break;
case "3":
editLine = textData[0] + newline + textData[1] + newline + editMade;
break;
}
br1.close();
bw.write(editLine);
bw.flush();
bw.close();
FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr);
for (int b = 0; b < numberOfLines; b++) {
textData[b] = br.readLine(); }
System.out.println("-----------------------");
System.out.println(textData[0]);
System.out.println(textData[1]);
System.out.println(textData[2]);
System.out.println("-----------------------");
accMng();
} |
39a10e50-5821-4e96-b470-c0e58942087c | 7 | public static int discrete(double[] a) {
double EPSILON = 1E-14;
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
if (a[i] < 0.0) throw new IllegalArgumentException("array entry " + i + " is negative: " + a[i]);
sum = sum + a[i];
}
if (sum > 1.0 + EPSILON || sum < 1.0 - EPSILON)
throw new IllegalArgumentException("sum of array entries not equal to one: " + sum);
// the for loop may not return a value when both r is (nearly) 1.0 and when the
// cumulative sum is less than 1.0 (as a result of floating-point roundoff error)
while (true) {
double r = uniform();
sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
if (sum > r) return i;
}
}
} |
bc04a0dd-6388-43cc-8cd6-db0d0eb82af5 | 7 | public boolean isLine(){
int countUnblocked=0;
for(int i = 0; i < corridor.length; i++) {
if(corridor[i].getWeight()==1){
countUnblocked++;
}
}
if(countUnblocked == 2) {
if(corridor[0].getWeight() == 1 && corridor[2].getWeight() == 1){
return true;
}
else if(corridor[1].getWeight() == 1 && corridor[3].getWeight() == 1){
return true;
}
return false;
}
return false;
} |
0891cb54-d49e-443f-b655-834dd087a650 | 8 | private void drawTooltip() {
if (menuActionCount < 2 && itemSelected == 0 && spellSelected == 0) {
return;
}
String text;
if (itemSelected == 1 && menuActionCount < 2) {
text = "Use " + selectedItemName + " with...";
} else if (spellSelected == 1 && menuActionCount < 2) {
text = spellTooltip + "...";
} else {
text = menuActionName[menuActionCount - 1];
}
if (menuActionCount > 2) {
text = text + "@whi@ / " + (menuActionCount - 2) + " more options";
}
boldFont.method390(4, 0xffffff, text, Client.loopCycle / 1000, 15);
} |
169f2b0d-7133-4578-b222-7e04645debfb | 7 | SortedSet<Dimension> read() throws CubeXmlFileNotExistsException,
IOException, DocumentException {
Configuration conf = CubeConfiguration.getConfiguration();
FileSystem hdfs = FileSystem.get(conf);
Path dimensionXmlFile = new Path(PathConf.getDimensionXmlFilePath());
if (!hdfs.exists(dimensionXmlFile)) {
throw new CubeXmlFileNotExistsException();
}
FSDataInputStream in = hdfs.open(dimensionXmlFile);
SAXReader reader = new SAXReader();
Document document = reader.read(in);
SortedSet<Dimension> dimensions = new TreeSet<Dimension>();
List<?> dimensionNodeList = document
.selectNodes("//dimensions/dimension");
Node dimensionNode;
String dimensionName;
int dimensionOrderNumber;
SortedSet<Level> levels;
List<?> levelNodeList;
Node levelNode;
String levelName;
long levelLength;
long levelBegin;
int levelOrderNumber;
DimensionRange dimensionRange;
Node dimensionRangeNode;
long dimensionRangeStart;
long dimensionRangeEnd;
for (Iterator<?> dimensionNodeIter = dimensionNodeList.iterator(); dimensionNodeIter
.hasNext(); ) {
dimensionNode = (Node) dimensionNodeIter.next();
dimensionName = dimensionNode.selectSingleNode("name").getText();
dimensionOrderNumber = Integer.valueOf(dimensionNode
.selectSingleNode("orderNumber").getText());
levelNodeList = dimensionNode.selectNodes("level");
levels = new TreeSet<Level>();
for (Iterator<?> levelNodeIter = levelNodeList.iterator(); levelNodeIter
.hasNext(); ) {
levelNode = (Node) levelNodeIter.next();
levelName = levelNode.selectSingleNode("name").getText();
levelLength = Long.valueOf(levelNode.selectSingleNode("length")
.getText());
levelBegin = Long.valueOf(levelNode.selectSingleNode("begin")
.getText());
levelOrderNumber = Integer.valueOf(levelNode.selectSingleNode(
"orderNumber").getText());
levels.add(new Level(levelName, levelLength, levelBegin,
levelOrderNumber));
}
dimensionRangeNode = dimensionNode.selectSingleNode("range");
dimensionRangeStart = Long.valueOf(dimensionRangeNode
.selectSingleNode("start").getText());
dimensionRangeEnd = Long.valueOf(dimensionRangeNode
.selectSingleNode("end").getText());
dimensionRange = new DimensionRange(dimensionRangeStart,
dimensionRangeEnd);
dimensions.add(Dimension.getDimension(dimensionName, levels,
dimensionOrderNumber, dimensionRange));
}
return dimensions;
} |
0744cbd2-7962-4fac-8daa-ef061bb5159c | 5 | private int jjMoveStringLiteralDfa11_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(9, old0);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(10, active0);
return 11;
}
switch(curChar)
{
case 107:
if ((active0 & 0x4000L) != 0L)
return jjStartNfaWithStates_0(11, 14, 2);
break;
case 117:
return jjMoveStringLiteralDfa12_0(active0, 0x800L);
default :
break;
}
return jjStartNfa_0(10, active0);
} |
baec9ba4-2500-4631-b75e-56df8909dc2c | 4 | /* */ public void update(int time)
/* */ {
/* 58 */ if ((Math.abs(this.x - this.targetX) < 5.0F) && (Math.abs(this.y - this.targetY) < 5.0F)) {
/* 59 */ this.speedX = 0.0F;
/* 60 */ this.speedY = 0.0F;
/* 61 */ this.active = true;
/* */ }
/* 63 */ this.x += this.speedX;
/* 64 */ this.y += this.speedY;
/* */
/* 66 */ if (this.active)
/* 67 */ if (this.timer < this.duration) {
/* 68 */ this.timer += time;
/* */ } else {
/* 70 */ Core.effects.add(new GrenadeExplosion(300, (int)this.x - 24, (int)this.y - 24));
/* 71 */ this.visible = false;
/* */ }
/* */ } |
357047fd-a758-4dcf-98af-758bda241d38 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
RangeConstraint other = (RangeConstraint) obj;
if (after == null) {
if (other.after != null) {
return false;
}
} else if (!after.equals(other.after)) {
return false;
}
if (before == null) {
if (other.before != null) {
return false;
}
} else if (!before.equals(other.before)) {
return false;
}
return true;
} |
78612850-6c03-45ef-93d2-1601a2b5eb29 | 4 | private void updateViews() {
if(!cardViews.isEmpty()) {
for(CardView temCard : cardViews) {
remove(temCard);
}
cardViews.clear();
}
MouseListener mouseListener = new MouseListener();
List<Card> cards = player.getCardGroup().getCardList();
CardView cardView;
for(Card card : cards) {
cardView = new CardView(card);
cardView.addMouseListener(mouseListener);
cardView.addMouseMotionListener(mouseListener);
cardViews.add(cardView);
}
for(int i = cardViews.size()-1 ; i >= 0 ; i--) {
add(cardViews.get(i));
}
} |
12e56ff9-8066-47a8-af15-061fb7aba17a | 0 | public Rectangle getAbsoluteRect() {
Rectangle absRect = new Rectangle();
int unitVal = unit.value;
absRect.x = x * unitVal;
absRect.y = y * unitVal;
absRect.width = width * unitVal;
absRect.height = height * unitVal;
return absRect;
} |
a18d4eea-413e-49b2-8507-b0da965cae05 | 7 | public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
// Make the obfuscated header
FastVector v = new FastVector();
for (int i = 0; i < instanceInfo.numAttributes(); i++) {
Attribute oldAtt = instanceInfo.attribute(i);
Attribute newAtt = null;
switch (oldAtt.type()) {
case Attribute.NUMERIC:
newAtt = new Attribute("A" + (i + 1));
break;
case Attribute.DATE:
String format = oldAtt.getDateFormat();
newAtt = new Attribute("A" + (i + 1), format);
break;
case Attribute.NOMINAL:
FastVector vals = new FastVector();
for (int j = 0; j < oldAtt.numValues(); j++) {
vals.addElement("V" + (j + 1));
}
newAtt = new Attribute("A" + (i + 1), vals);
break;
case Attribute.STRING:
case Attribute.RELATIONAL:
default:
newAtt = (Attribute) oldAtt.copy();
System.err.println("Not converting attribute: " + oldAtt.name());
break;
}
v.addElement(newAtt);
}
Instances newHeader = new Instances("R", v, 10);
newHeader.setClassIndex(instanceInfo.classIndex());
setOutputFormat(newHeader);
return true;
} |
9ad4d89b-45e7-482e-8c9b-202966665746 | 0 | public LogWindow() {
super("Game History");
setLayout(new FlowLayout());
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setResizable(false);
list = new JList<String>(listModel);
list.setLayoutOrientation(JList.VERTICAL);
JScrollPane listScroller = new JScrollPane(list);
listScroller.setPreferredSize(new Dimension(230, 550));
add(listScroller);
} |
6f154e4f-9943-4029-a06a-17f05b6f626f | 4 | public static void main (String args[])
{
System.out.println("HTTPServer.java");
ServerSocket Server = null;
try
{
Server = new ServerSocket (5000, 10, InetAddress.getByName("192.168.43.247"));
}
catch (UnknownHostException e)
{
System.out.println("Unknown host");
}
catch (IOException e)
{
System.out.println("Socket cration failed");
}
System.out.println ("TCPServer Waiting for client on port 5000");
while(true)
{
Socket connected = null;
try
{
connected = Server.accept();
}
catch (IOException e)
{
System.out.println("Connexion failed");
}
(new HTTPServer(connected)).start();
}
} |
7679bc71-29fd-4078-92ab-a2e3306513cb | 7 | private Array createFixedWaysPath(Ways way, Array start,
GameContainer container, StateBasedGame game) throws SlickException {
Array currrentNode = start;
Array newNeighboor = null;
for (int i = 0; i < MIN_WAY_SIZE + (int) (Math.random() * MAX_WAY_SIZE); i++) {
switch (way) {
case NORTH:
newNeighboor = new Array(currrentNode.getPosX(),
currrentNode.getPosY() - 1, container, game);
break;
case SOUTH:
newNeighboor = new Array(currrentNode.getPosX(),
currrentNode.getPosY() + 1, container, game);
break;
case EAST:
newNeighboor = new Array(currrentNode.getPosX() + 1,
currrentNode.getPosY(), container, game);
break;
case WEST:
newNeighboor = new Array(currrentNode.getPosX() - 1,
currrentNode.getPosY(), container, game);
break;
default:
break;
}
if (!arrayAlreadyExist(newNeighboor, way)) {
if (this.findArrayByXYYo(newNeighboor.posX, newNeighboor.posY) != null)
System.out.println("pas biiieen !");
currrentNode.addNeighboor(newNeighboor, way);
this.addNeighboorIfExistsYo(newNeighboor, way);
plan.add(newNeighboor);
currrentNode = newNeighboor;
}
}
return currrentNode;
} |
dff2c2b0-de1d-4bcd-ac36-46cc011924c6 | 6 | public boolean equals(
Object o)
{
if ((o == null) || !(o instanceof DERUnknownTag))
{
return false;
}
DERUnknownTag other = (DERUnknownTag)o;
if(tag != other.tag)
{
return false;
}
if(data.length != other.data.length)
{
return false;
}
for(int i = 0; i < data.length; i++)
{
if(data[i] != other.data[i])
{
return false;
}
}
return true;
} |
78d82a97-f741-4901-a2ba-bd00715ca406 | 4 | public AudioServer(String [] args) {
isRunning = true; isPlaying = true;
/* Check port exists */
if (args.length < 1) {
System.out.println("Usage: ChatServerMain <port>");
System.exit(1);
}
/* Create the server socket */
try {
serverSocket = new ServerSocket(Integer.parseInt(args[0]));
System.out.println(serverSocket); //debug
} catch (IOException e) {
System.out.println("IOException: " + e);
System.exit(1);
}
System.out.println("1");
/* In the main thread, continuously listen for new clients and spin off threads for them. */
while (isRunning) {
try {
System.out.println("2");
/* Get a new client */
clientSocket = serverSocket.accept();
System.out.println("New connection from "+clientSocket.getInetAddress().toString());
/* Create a thread for it and start, giving it the right id. */
//clientThread.start();
playSound();
} catch (IOException e) {
System.out.println("Accept failed: " + e);
System.out.println("Server has stopped running.");
System.exit(1);
}
}
System.out.println("Server has stopped running.");
} |
15cd4f2c-11e0-4f8b-ac70-021af3e8ada3 | 6 | private void jButtonPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPesquisarActionPerformed
Cidadao cidadao = new Cidadao();
Bairro bairro = new Bairro();
Cidade cidade = new Cidade();
Estado estado = new Estado();
cidade.setEstado(estado);
bairro.setCidade(cidade);
cidadao.setBairro(bairro);
cidadao.setTelefones(new LinkedList<Telefone>());
cidadao.setCelulares(new LinkedList<Celular>());
if (!jTextFieldNomeCompleto.getText().isEmpty()) {
cidadao.setNomeCompleto(jTextFieldNomeCompleto.getText());
}
if (!jTextFieldLogradouro.getText().isEmpty()) {
cidadao.setLogradouro(jTextFieldLogradouro.getText());
}
if (jComboBoxEstadoUF.getSelectedIndex() > 0) {
estado.setCodigo(((Estado) jComboBoxEstadoUF.getSelectedItem()).getCodigo());
}
if (jComboBoxCidade.getSelectedIndex() > 0) {
cidade.setCodigo(((Cidade) jComboBoxEstadoUF.getSelectedItem()).getCodigo());
}
// if (jComboBoxDDD.getSelectedIndex() > 0) {
// dadoMaterial.setEditora((Editora) jComboBoxDDD.getSelectedItem());
// }
if (jComboBoxTelefone.getSelectedIndex() > 0) {
cidadao.getTelefones().add((Telefone) jComboBoxEstadoUF.getSelectedItem());
}
if (jComboBoxCelular.getSelectedIndex() > 0) {
cidadao.getCelulares().add((Celular) jComboBoxEstadoUF.getSelectedItem());
}
listaView.getCidadaosController().filtrar(cidadao);
}//GEN-LAST:event_jButtonPesquisarActionPerformed |
e35d086c-4bfa-4df0-92f1-b6ad7e5cc9e0 | 4 | public void setCells(Object[] cells)
{
if (cells != null)
{
if (singleSelection)
{
cells = new Object[] { getFirstSelectableCell(cells) };
}
List<Object> tmp = new ArrayList<Object>(cells.length);
for (int i = 0; i < cells.length; i++)
{
if (graph.isCellSelectable(cells[i]))
{
tmp.add(cells[i]);
}
}
changeSelection(tmp, this.cells);
}
else
{
clear();
}
} |
53faebf7-539d-4fb6-8083-0c7c62ff58cc | 0 | @Test
public void testGetX() {
System.out.println("getX");
assertEquals(1.0, new Orb(4,12,1,1).getX(), 0.00001);
} |
4e595696-6c6f-4689-bb5f-d94eeead7b77 | 1 | public static void disposeColors() {
for (Color color : m_colorMap.values()) {
color.dispose();
}
m_colorMap.clear();
} |
871587c8-0ffd-4b3a-b368-a46a7900bd54 | 9 | public static Equation parseEquation(String strEquation) throws InvalidEquationException{
//Create a list of expressions
ArrayList<Expression> expressionList = new ArrayList<Expression>();
//Create a queue of integers
LinkedList<Integer> digits = new LinkedList<Integer>();
//for each character in the answer string
for(int i = 0; i < strEquation.length(); i++){
if((Character.isDigit(strEquation.charAt(i)))){
String digit = strEquation.substring(i, i+1);
//Add the digit to the queue
digits.addLast(Integer.parseInt(digit));
//Make sure the next character is a digit, or there is a next character
if(strEquation.length() - 1 == i || !Character.isDigit(strEquation.charAt(i+1))){
//If it's not, get the integer represented by the digits
int val = ListToInt(digits);
//Add a numerical expression to the expression list
expressionList.add(new NumericalExpression(val));
//Clear the list of digits
digits.clear();
}
}
else if(strEquation.charAt(i) == '+'){
expressionList.add(new AdditionExpression());
}
else if(strEquation.charAt(i) == '-'){
expressionList.add(new SubtractionExpression());
}
else if(strEquation.charAt(i) == '*'){
expressionList.add(new MultiplicationExpression());
}
else if(strEquation.charAt(i) == '/' || strEquation.charAt(i) == '/'){
expressionList.add(new DivisionExpression());
}
}
return new Equation(expressionList);
} |
298a0c08-5da4-4e89-a5a9-ca5da27b8b21 | 3 | public Vector<BaseRace> getRankedRaces(int rank) {
Vector<BaseRace> br = new Vector<>();
for (ClassMap item : _classMap) {
if (item.getClassType().getName().equals(_class.getName())) {
if (item.getAverage() == rank) {
br.add(item.getRace());
}
}
}
return br;
} |
44cdb0ff-992b-450e-aec9-de07747e6179 | 2 | public static void main(String... args) throws IOException {
ServerSocket serverSocket = new ServerSocket(13800);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
Scanner scanner = new Scanner(inputStream);
OutputStream outputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream, true);
while (scanner.hasNextLine()) {
String temp = scanner.nextLine();
System.out.println(temp);
if (temp.equals("bye")) {
printWriter.write("byebye !!");
break;
}
}
printWriter.close();
scanner.close();
inputStream.close();
socket.close();
serverSocket.close();
} |
0fa714c3-fa5f-453b-a760-3e8731e1e0f5 | 8 | public static void main(String[] args) {
try {
File file = new File(Path);
Scanner scanner = new Scanner(file);
scanner.useDelimiter("#NEW RECORD\n");
int counter = 0;
while (scanner.hasNext()){
String document = scanner.next();
if(!document.equals("\n")){
StringTokenizer st = new StringTokenizer(document, "\n");
assert st.countTokens() == 5;
String pmid = st.nextToken();
String pubdate = st.nextToken();
String title = st.nextToken().substring(8);
String text = st.nextToken().substring(11);
while(title.endsWith(".")){
title = title.substring(0, title.length() - 1);
}
BufferedWriter bf = null;
try{
String fileName = "C:/TextCollection/" + DocPrefix + counter + ".txt";
File newFile = new File(fileName);
System.out.println(fileName);
bf = new BufferedWriter(new FileWriter(newFile));
bf.write(title + "\n" + text);
bf.close();
counter++;
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
finally {
if(bf != null){
bf.close();
}
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("File not found.");
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error in document processing.");
System.exit(1);
}
} |
225f39d4-28c9-43b0-908d-461c255715bb | 2 | public void test_convertText() {
BaseDateTimeField field = new MockBaseDateTimeField();
assertEquals(0, field.convertText("0", null));
assertEquals(29, field.convertText("29", null));
try {
field.convertText("2A", null);
fail();
} catch (IllegalArgumentException ex) {}
try {
field.convertText(null, null);
fail();
} catch (IllegalArgumentException ex) {}
} |
97d27f6a-c51c-4b69-8e8e-80bd758065f2 | 6 | private <T> StringConverter<T> findAnnotatedConverter(final Class<T> cls) {
Method toString = findToStringMethod(cls); // checks superclasses
if (toString == null) {
return null;
}
MethodConstructorStringConverter<T> con = findFromStringConstructor(cls, toString);
MethodsStringConverter<T> mth = findFromStringMethod(cls, toString, con == null); // optionally checks superclasses
if (con == null && mth == null) {
throw new IllegalStateException("Class annotated with @ToString but not with @FromString: " + cls.getName());
}
if (con != null && mth != null) {
throw new IllegalStateException("Both method and constructor are annotated with @FromString: " + cls.getName());
}
return (con != null ? con : mth);
} |
ff95c8bc-8152-4577-a4bd-860b0cb39914 | 3 | public void cargarProductos() {
try {
Connection conn = Conexion.GetConnection();
try {
st = conn.createStatement();
pro = st.executeQuery("SELECT * FROM Productos");
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, e.getErrorCode() + ": " + e.getMessage());
}
String[] columns = {"idProducto", "Nombre", "Tipo", "precio", "proveedor", "cantidad"};
DefaultTableModel tm = new DefaultTableModel(null, columns) {
@Override
public boolean isCellEditable(int rowIndex, int colIndex) {
return false;
}
};
while (pro.next()) {
String[] row = {pro.getString(1), pro.getString(2), pro.getString(3), "$ " + pro.getString(4), pro.getString(5), pro.getString(6)};
tm.addRow(row);
}
jTable1.setModel(tm);
} catch (SQLException e) {
Logger.getLogger(GameCrush.class.getName()).log(Level.SEVERE, null, e);
}
} |
f9bf6b21-6d83-4b99-9bc6-5d537537faa5 | 3 | public static boolean isCyclicUndirected(mxAnalysisGraph aGraph)
{
mxGraph graph = aGraph.getGraph();
mxIGraphModel model = graph.getModel();
Object[] cells = model.cloneCells(aGraph.getChildCells(graph.getDefaultParent(), true, true), true);
mxGraphModel modelCopy = new mxGraphModel();
mxGraph graphCopy = new mxGraph(modelCopy);
Object parentCopy = graphCopy.getDefaultParent();
graphCopy.addCells(cells);
// mxAnalysisGraph aGraphCopy = new mxAnalysisGraph(graphCopy, aGraph.getGenerator(), aGraph.getProperties());
mxAnalysisGraph aGraphCopy = new mxAnalysisGraph();
aGraphCopy.setGraph(graphCopy);
aGraphCopy.setGenerator(aGraph.getGenerator());
aGraphCopy.setProperties(aGraph.getProperties());
Object[] leaf = new Object[1];
do
{
leaf[0] = getUndirectedLeaf(aGraphCopy);
if (leaf[0] != null)
{
graphCopy.removeCells(leaf);
}
}
while (leaf[0] != null);
int vertexNum = aGraphCopy.getChildVertices(parentCopy).length;
if (vertexNum > 0)
{
return true;
}
else
{
return false;
}
}; |
82950cca-72c6-44ee-a860-201de2f07db4 | 5 | public List<Tuple<Integer,Integer>> reconstructPath ( HashMap<Tuple<Integer,Integer>,Tuple<Integer,Integer>> cameFrom, Tuple<Integer,Integer> currentNode ) {
int delayNearEndpoints = 3;
int roomNearEndpoints = 3;
//log.trace("reconstructPath: cameFrom size:" + cameFrom.size() );
List<Tuple<Integer,Integer>> path = new ArrayList<Tuple<Integer,Integer>>();
if ( cameFrom.containsKey(currentNode) ) {
path = reconstructPath( cameFrom, cameFrom.get(currentNode));
path.add(currentNode);
// experimenting -- stay still near endpoints
if ( nearEndpoints(currentNode, roomNearEndpoints) ) {
for ( int i = 0; i < delayNearEndpoints; i++ ) {
path.add(currentNode);
}
}
return path;
} else {
path.add(currentNode);
// experimenting -- stay still near endpoints
if ( nearEndpoints(currentNode,roomNearEndpoints) ) {
for ( int i = 0; i < delayNearEndpoints; i++ ) {
path.add(currentNode);
}
}
return path;
}
} |
064856a8-bf60-456e-9719-cc1e10654d5e | 6 | public void nextPermutation(int[] nums) {
if(nums.length <= 1) {
return;
}
int i = nums.length - 2;
for(; i >= 0; i--) {
if(nums[i+1] > nums[i]) {
break;
}
}
if(i == -1) {
reverse(nums, 0, nums.length-1);
return;
}
for(int j = nums.length-1; j > i; j--) {
if(nums[j] > nums[i]) {
swap(nums, i, j);
break;
}
}
reverse(nums, i+1, nums.length-1);
} |
6c983ad0-c78a-4308-b3d7-4b40bbc841be | 7 | public final DirkExpParser.equalityExpr_return equalityExpr() throws RecognitionException {
DirkExpParser.equalityExpr_return retval = new DirkExpParser.equalityExpr_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token set9=null;
DirkExpParser.relationalExpr_return relationalExpr8 = null;
DirkExpParser.relationalExpr_return relationalExpr10 = null;
CommonTree set9_tree=null;
try {
// F:\\antlr\\BoncExp.g:31:5: ( relationalExpr ( ( EQUALS | NOTEQUALS ) relationalExpr )* )
// F:\\antlr\\BoncExp.g:31:9: relationalExpr ( ( EQUALS | NOTEQUALS ) relationalExpr )*
{
root_0 = (CommonTree)adaptor.nil();
pushFollow(FOLLOW_relationalExpr_in_equalityExpr227);
relationalExpr8=relationalExpr();
state._fsp--;
adaptor.addChild(root_0, relationalExpr8.getTree());
// F:\\antlr\\BoncExp.g:31:24: ( ( EQUALS | NOTEQUALS ) relationalExpr )*
loop3:
do {
int alt3=2;
int LA3_0 = input.LA(1);
if ( ((LA3_0>=EQUALS && LA3_0<=NOTEQUALS)) ) {
alt3=1;
}
switch (alt3) {
case 1 :
// F:\\antlr\\BoncExp.g:31:25: ( EQUALS | NOTEQUALS ) relationalExpr
{
set9=(Token)input.LT(1);
set9=(Token)input.LT(1);
if ( (input.LA(1)>=EQUALS && input.LA(1)<=NOTEQUALS) ) {
input.consume();
root_0 = (CommonTree)adaptor.becomeRoot((CommonTree)adaptor.create(set9), root_0);
state.errorRecovery=false;
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
throw mse;
}
pushFollow(FOLLOW_relationalExpr_in_equalityExpr237);
relationalExpr10=relationalExpr();
state._fsp--;
adaptor.addChild(root_0, relationalExpr10.getTree());
}
break;
default :
break loop3;
}
} while (true);
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
}
return retval;
} |
8731abfd-0a0f-41f4-8720-ce6371d49c1c | 5 | public static boolean check(Robot paramRobot)
{
return (robotContainsBeacon(paramRobot)) || (lostOnlyPart(paramRobot, new Hermes().getClass())) ||
(lostOnlyPart(paramRobot, new Launcher().getClass())) ||
(lostOnlyPart(paramRobot, new Arachnae().getClass())) || (
(noRobotsLeft()) && (cantMakeACompleteRobot()));
} |
fa779757-004d-48d3-89ec-e4b42b359b8b | 2 | public List<String> getIP(String url) throws IOException{
URL u = new URL(url);
BufferedReader br = new BufferedReader(new InputStreamReader(u.openStream()));
String s = "";
List<String> ipList = new ArrayList<String>();
String regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
Pattern p = Pattern.compile(regex);
Matcher m ;
System.out.println("-------------------开始抓取"+url+"上的ip--------------------");
while((s = br.readLine()) != null){
m = p.matcher(s);
while (m.find()) {
ipList.add(m.group());
System.out.println(m.group());
}
}
return ipList;
} |
a47158f6-97aa-4473-8bb2-6cf43b050e6d | 0 | public static void main(String[] args) {
new Main();
} |
338aee82-b1b0-4691-9759-10562eb84195 | 1 | public E element() {
E rv;
if((rv = peek()) == null)
throw(new NoSuchElementException());
return(rv);
} |
defe827e-17aa-4fbc-b307-65d53d8458cb | 4 | public GUI() {
try {
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, fall back to cross-platform
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception ignored) {}
}
initComponents();
} |
19edf8bd-3252-4ed2-b411-408580a86cd5 | 2 | public static Object nartSubstitute(Object cyclObject, CycAccess access)
throws IOException {
if (!DefaultCycObject.isCycLObject(cyclObject)) {
throw new RuntimeException(DefaultCycObject.cyclify(cyclObject) + " is not a valid Cyc object.");
}
if (!(cyclObject instanceof CycObject)) { // @todo need a test that sees if the CycObject
// contains any CycLists any fast fail if not
return cyclObject;
}
return access.converseObject("(nart-substitute '" + DefaultCycObject.cyclifyWithEscapeChars(cyclObject, true) + ")");
} |
ea78d171-f7d8-4da0-8cbd-23b852983538 | 9 | public Alphabet(
String path,
String texFile, String alphaFile,
String mapFile, int numLines, int lineHigh
) {
// Basic initialisation routine here. The list of individual characters
// must be loaded first for comparison with scanned character blocks.
int charMap[] = null ;
final int mask[] = LoadService.getRGBA(path + texFile) ;
try {
FileInputStream mapS = new FileInputStream(new File(path + mapFile)) ;
charMap = new int[mapS.available()] ;
for(int n = 0 ; n < charMap.length ; n++) charMap[n] = mapS.read() ;
}
catch(IOException e) { I.add(" " + e) ; }
fontTex = Texture.loadTexture(path+texFile, path+alphaFile) ;
//
// This is where the actual scanning is done. A single texture is used for
// all characters to avoid frequent texture re-bindings during rendering.
// The procedure looks for 'gaps' in the initial texture relAlpha as cues for
// where to demarcate individual letters.
final int trueSize = fontTex.trueSize() ;
int x, y, ind, line = 0, maxMap = 0 ;
boolean scan = true ;
List <Letter> scanned = new List <Letter> () ;
Letter letter = null ;
for( ; line < numLines ; line++) {
y = lineHigh * line ;
ind = (y * trueSize) + (x = 0) ;
for( ; x < fontTex.xdim() ; x++, ind++) {
if((mask[ind] & 0xff000000) != 0) { //relAlpha value of pixel is nonzero.
if(scan) {
scan = false ; //a letter starts here.
letter = new Letter() ;
letter.umin = ((float) x) / trueSize ;
letter.map = (char) (charMap[scanned.size()]) ;
if (letter.map > maxMap) maxMap = letter.map ;
}
}
else {
if(! scan) {
//...and ends afterward on the first transparent pixel.
scan = true ;
letter.umax = ((float) x) / trueSize ;
letter.vmin = ((float) y) / trueSize ;
letter.vmax = ((float) y + lineHigh) / trueSize ;
letter.height = lineHigh ;
letter.width = (int) ((letter.umax - letter.umin) * trueSize) ;
scanned.addLast(letter) ;
}
}
}
}
map = new Letter[maxMap + 1] ;
letters = new Letter[scanned.size()] ;
ind = 0 ;
for (Letter sLetter : scanned)
map[(int) (sLetter.map)] = letters[ind++] = sLetter ;
} |
b736f215-cdf0-4e5b-953b-808593ba0338 | 8 | public void colorBiddableLand(Graphics g){
String player = Requests.teamName;
String owner;
Grid grid = request.operator.getGrid();
Point p;
for(int i = 0; i < s; i++){
for(int j = 0; j < s; j++) {
p = new Point(j,i);
owner=grid.getOwner(p);
if(!grid.exists(p)||owner==null){
//If no one owns it
fillSquare(g,brighterGold,p);
}
else if(!grid.isDrilled(p)&&owner.equals(player)){
//Just haven't drilled yet
fillSquare(g,brightGreen,p);
System.out.println("y:"+p.y);
System.out.println("p.y*squareSize:"+p.y*squareSize);
}
else if (grid.isDrilled(p)&&owner.equals(player)){
//Player's drilled
fillSquare(g,brightGreen,p);
}
else{
//Someone else owns it
fillSquare(g,red,p);
}
}
}
} |
3ca3f832-d163-4302-bf67-0a6754915dd6 | 1 | @Test
public void construction() {
int size = 30;
List<Calendar> dates = new ArrayList<>(30);
for (int i = 0; i < size; i++) {
dates.add(Calendar.getInstance());
}
IntervalList list = new IntervalList(dates);
assertEquals(size / 2, list.size());
} |
dc3008d9-6a43-42af-ba1f-9adfd3f98c18 | 9 | public void maintenence()// well, kind of what it sounds like. Kings pieces,
// checks for draws, etc...
{
for (int x = 0; x < 8; x++)// kinging.
{
if (theBoard[x][7].getPiece() == '@')
{
theBoard[x][7].king();
} else if (theBoard[x][0].getPiece() == '$')
{
theBoard[x][0].king();
}
}
int tempDollas = dollaNum;
int tempAts = atNum;
dollaNum = 0;
atNum = 0;
boolean at = false;// making sure the game's not over.
boolean cash = false;
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
if (theBoard[x][y].getPiece() == '@')
{
at = true;
atNum++;
} else if (theBoard[x][y].getPiece() == '$')
{
cash = true;
dollaNum++;
}
}
}
ats = at;
dollas = cash;
if (dollaNum != tempDollas || atNum != tempAts)
{
timeSinceJump = 0;
} else
{
timeSinceJump++;
}
} |
1806b5c0-a6ef-4a31-b9a5-38033b7c8c16 | 6 | public static void main(String[] args) {
int[] vals;
Scanner scan = new Scanner(System.in);
try {
while (true) {
try {
System.out.print("How long would you like the array to be? ");
int count = scan.nextInt();
vals = new int[count];
for (int i = 0; i < count; i++) {
while (true) {
try {
System.out.printf("Number %d of %d: ", i + 1, count);
vals[i] = scan.nextInt();
break;
} catch(java.util.InputMismatchException error) {
System.out.println(scan.next() + " is not a valid number.");
}
}
}
break;
} catch(java.util.InputMismatchException error) {
System.out.println(scan.next() + " is invalid input. Please try again.");
} catch(NegativeArraySizeException error) {
System.out.println("Array size must be positive.");
}
}
} finally {
scan.close();
}
System.out.println("Your normal array:");
ArrayIndeces.printArr(vals);
reverse(vals);
System.out.println("Your reversed entries are:");
ArrayIndeces.printArr(vals);
} |
12d93968-83b7-4a9b-9149-acb683c8b4df | 7 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(PatientOptionForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PatientOptionForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PatientOptionForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PatientOptionForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new PatientOptionForm().setVisible(true);
} catch (SQLException ex) {
Logger.getLogger(PatientOptionForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
} |
7e9d2355-a758-46c4-a08f-434f9d00d95b | 2 | public void testPropertySetDayOfWeek() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
DateTime copy = test.dayOfWeek().setCopy(4);
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2004-06-10T00:00:00.000+01:00", copy.toString());
try {
test.dayOfWeek().setCopy(8);
fail();
} catch (IllegalArgumentException ex) {}
try {
test.dayOfWeek().setCopy(0);
fail();
} catch (IllegalArgumentException ex) {}
} |
20528fc6-297f-434b-82ae-02fbc27b98e2 | 5 | public static int[][] adjoint(int[][] matrix){
//preconditions
if(matrix == null)throw new IllegalArgumentException("matrix must not be null");
for(int i = 0; i < matrix.length; i++){
if(matrix.length != matrix[i].length)throw new IllegalArgumentException("matrix must be square!");
}
int[][] newMatrix = new int[matrix.length][matrix.length];
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix.length; j++){
newMatrix[i][j] = (int)Math.pow(-1, i+j) * determinant(minor(matrix, i, j));
}
}
return newMatrix;
} |
be0cb1c4-5399-40cc-98dc-75bff4cd5340 | 4 | public String toString() {
String strType;
switch (type) {
case _AVERAGE:
strType = STR_AVERAGE;
break;
case _MIN:
strType = STR_MIN;
break;
case _MAX:
strType = STR_MAX;
break;
case _LAST:
strType = STR_LAST;
break;
default :
throw new RuntimeException("This should never happen");
}
return strType;
} |
cb6f4aa0-c235-4291-862e-02bf36b07f8b | 5 | public PolyEquationImpl(final BigInteger[] inCoeffs)
{
if (inCoeffs.length <= 0)
{
throw new SecretShareException("Must have at least 1 coefficient");
}
coefficients = new BigInteger[inCoeffs.length];
for (int i = 0, n = inCoeffs.length; i < n ; i++)
{
if (inCoeffs[i] == null)
{
throw new SecretShareException("Coefficient index=" + i +
" is null, and cannot be null");
}
coefficients[i] = inCoeffs[i];
}
// Constraint check:
for (Number n : coefficients)
{
if (n == null)
{
throw new SecretShareException("Programmer error - internal coefficient is null");
}
}
} |
803bb309-e490-4a5b-93bf-999f674dd06c | 4 | public void addOpdrachtToList(Opdracht opdracht) {
try {
if (opdrachten.size() != 0) {
if (!opdracht.equals(null) || !opdrachten.contains(opdracht)) {
Opdracht o = opdrachten.get(opdrachten.size() - 1);
opdracht.setId(o.getId() + 1);
}
} else {
opdracht.setId(opdrachten.size() + 1);
}
this.opdrachten.add(opdracht);
notifieerObservers();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
} |
4d5706f4-e8f3-4209-9ca7-3f7c81e449ab | 4 | @SuppressWarnings("resource")
public static void denyRdr() throws IOException{
if (!dnames.exists()){dnames.createNewFile();}
BufferedReader rfile = new BufferedReader(new FileReader(dnames));
String nme=null;
for (int i=0;i<6;i++){
nme=rfile.readLine();
if (nme!=null && !nme.isEmpty()){
deny.add(nme.toLowerCase().trim());
}
}
} |
79597992-3cc3-404a-812f-e4c7a94e2cd8 | 9 | public void finalizeMap(){
for (int i = 0; i < tiles.length; i++) {
for (int j = 0; j < tiles.length; j++) {
if (tiles[i][j] == 'S') {
myX = 25 + i * 50;
myY = 25 + j * 50 ;
}
if (tiles[i][j] == 'R') {
mySecondX = 25 + i * 50;
mysecondY = 25 + j * 50;
}
}
}
int count=0;
// code for the cherry
// code for the solid tiles
for (int i = 0; i < tiles.length; i++) {
for (int j = 1; j < tiles.length; j++) {
if(tiles[i][j]=='X' && (tiles[i][j-1]=='X' || tiles[i][j-1]=='x')){
tiles[i][j]='x';
}
}
}
} |
a8e8b1ac-e026-4785-a17d-8bf6ea286198 | 8 | protected static int partition(double[] arrayToSort, double[] linkedArray, int l, int r) {
double pivot = arrayToSort[(l + r) / 2];
double help;
while (l < r) {
while ((arrayToSort[l] < pivot) && (l < r)) {
l++;
}
while ((arrayToSort[r] > pivot) && (l < r)) {
r--;
}
if (l < r) {
help = arrayToSort[l];
arrayToSort[l] = arrayToSort[r];
arrayToSort[r] = help;
help = linkedArray[l];
linkedArray[l] = linkedArray[r];
linkedArray[r] = help;
l++;
r--;
}
}
if ((l == r) && (arrayToSort[r] > pivot)) {
r--;
}
return r;
} |
2ab75ca5-aeca-4d01-a293-c549906ca90c | 2 | public void testPropertyCompareToYear() {
YearMonth test1 = new YearMonth(TEST_TIME1);
YearMonth test2 = new YearMonth(TEST_TIME2);
assertEquals(true, test1.year().compareTo(test2) < 0);
assertEquals(true, test2.year().compareTo(test1) > 0);
assertEquals(true, test1.year().compareTo(test1) == 0);
try {
test1.year().compareTo((ReadablePartial) null);
fail();
} catch (IllegalArgumentException ex) {}
DateTime dt1 = new DateTime(TEST_TIME1);
DateTime dt2 = new DateTime(TEST_TIME2);
assertEquals(true, test1.year().compareTo(dt2) < 0);
assertEquals(true, test2.year().compareTo(dt1) > 0);
assertEquals(true, test1.year().compareTo(dt1) == 0);
try {
test1.year().compareTo((ReadableInstant) null);
fail();
} catch (IllegalArgumentException ex) {}
} |
682feec3-45c0-4d45-9e82-f4118129ad63 | 3 | private boolean hasSerialArrayListFlavor(DataFlavor[] arrDfIn)
{
if (this.dfSerial == null) return false;
for(int iCnt = 0; iCnt < arrDfIn.length; iCnt ++)
{
if (arrDfIn[iCnt].equals(this.dfSerial)) return true;
}
return false;
} |
1eeda8ac-2a0c-4f14-bec2-abd070ddb8d7 | 2 | public Berechtigung getBerechtigungzuidBerechtigung(int idBerechtigung) {
Berechtigung rueckgabe = null;
ResultSet resultSet;
try {
resultSet = db
.executeQueryStatement("SELECT * FROM Berechtigungen WHERE idBerechtigung = '"
+ idBerechtigung + "'");
if(resultSet.next())
rueckgabe = new Berechtigung(resultSet, db);
resultSet.close();
} catch (SQLException e) {
System.out.println("Zugriffschicht/getBerechtigungzuidBerechtigung :"+e);
}
return rueckgabe;
} |
632dea74-6def-49ef-9864-5cffb63c8672 | 8 | public static int removeHandler(Board theBoard, Army army, String team)
{
int r, c;
if(army.getCapacity() == army.getRemaining())
{
System.out.println("No armies to remove.");
return 0;
}
else
{
System.out.print("Enter row of piece to remove: ");
r = Integer.parseInt(""+input.next().charAt(0));
if((r<0)||(r>9))
{
System.out.println("Out of bounds.");
return 0;
}
System.out.print("Enter column of piece to remove: ");
c = Integer.parseInt(""+input.next().charAt(0));
if((c<0)||(c>9))
{
System.out.println("Out of bounds.");
return 0;
}
Location loc = new Location(c,r);
if(!theBoard.getPiece(loc).getTeam().equals(team)||
(theBoard.getPiece(loc).getType() == ' ')||
(theBoard.getPiece(loc).getType() == '#'))
{
System.out.println("Could not remove piece.");
return 0;
}
else
{
army.deallocatePiece(theBoard.getPiece(loc).getType());
theBoard.getPiece(loc).setType(' ');
theBoard.getPiece(loc).setTeam(" ");
return 1;
}
}
} |
19140b24-d100-4d45-bfe5-d2f7c0f7301f | 8 | public boolean actionBuild(Actor actor, Venue built) {
//
// Double the rate of repair again if you have proper tools and materials.
final boolean salvage = built.structure.needsSalvage() ;
final boolean free = GameSettings.buildFree ;
int success = actor.traits.test(HARD_LABOUR, ROUTINE_DC, 1) ? 1 : 0 ;
//
// TODO: Base assembly DC (or other skills) on a Conversion for the
// structure. Require construction materials for full efficiency.
if (salvage) {
success *= actor.traits.test(ASSEMBLY, 5, 1) ? 2 : 1 ;
final float amount = 0 - built.structure.repairBy(success * 5f / -2) ;
final float cost = amount * built.structure.buildCost() ;
if (! free) built.stocks.incCredits(cost * 0.5f) ;
}
else {
success *= actor.traits.test(ASSEMBLY, 10, 0.5f) ? 2 : 1 ;
success *= actor.traits.test(ASSEMBLY, 20, 0.5f) ? 2 : 1 ;
final boolean intact = built.structure.intact() ;
final float amount = built.structure.repairBy(success * 5f / 2) ;
final float cost = amount * built.structure.buildCost() ;
if (! free) built.stocks.incCredits((0 - cost) * (intact ? 0.5f : 1)) ;
}
return true ;
} |
7b68db99-79a6-483b-9124-b4f41f3c4938 | 4 | public void attack(){
for(int i = 0; i<enemies.size(); i++){
if((Driver.player.getX() > enemies.get(i).getX()-enemies.get(i).getRange()) && (Driver.player.getX() < enemies.get(i).getX()+enemies.get(i).getRange()) && (enemies.get(i).getY() == Driver.player.getY()))
enemies.get(i).attack();
}
} |
db642b61-09d5-4052-8139-4a7a13df4b3f | 9 | public void paint(Graphics g) {
// clear previous image
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
// draw grid
BufferedImage myImage = null;
try {
java.net.URL myImageURL = TicTacToe.class
.getResource("images/grid.png");
myImage = ImageIO.read(myImageURL);
} catch (IOException e) {
System.out.println("Image: grid error");
}
g.drawImage(myImage, 0, 0, this);
for(int i = 0; i < playedNodes.length; i++){
if(playedNodes[i] != null){
java.net.URL myImageURL;
if(playedNodes[i].getChar() == 'x'){
myImageURL = TicTacToe.class.getResource("images/x.png");
}
else{
myImageURL = TicTacToe.class.getResource("images/o.png");
}
try{
myImage = ImageIO.read(myImageURL);
}
catch(IOException e){
System.out.println("Image error");
}
int[] coord = playedNodes[i].getCoord();
int[] rectXY = createSelectionSquares(coord[0], coord[1]);
g.drawImage(myImage, rectXY[0] - _SquareSelect/2, rectXY[1]- _SquareSelect/2, this);
}
}
// draw choice
// if (p1X >= 0 && p1Y >= 0) {
// try {
// java.net.URL myImageURL;
// // toggle between O & X placement
// if (!blnXY)
// myImageURL = TicTacToe.class.getResource("images/o.png");
// else
// myImageURL = TicTacToe.class.getResource("images/x.png");
// myImage = ImageIO.read(myImageURL);
// } catch (IOException e) {
// System.out.println("Image: O error");
// }
// //*************temp*************
// p1X = p1X - (myImage.getWidth() / 2);
// p1Y = p1Y - (myImage.getHeight() / 2);
// //*************temp*************
// g.drawImage(myImage, p1X, p1Y, this);
// blnXY = !blnXY; // toggle XY placement
// }
// ************TEMP************
// create selection zones
if (showSquares) {
for (int row = 0; row < playableNodes.length; row++) {
if(playableNodes[row] != null){
int[] coord = playableNodes[row].getCoord();
int[] rectXY = createSelectionSquares(coord[0], coord[1]);
g.setColor(Color.GREEN);
g.drawRect(rectXY[0], rectXY[1], _SquareSelect, _SquareSelect);
}
}
}
if(clickedOn != null){
int[] coord = clickedOn.getCoord();
int[] rectXY = createSelectionSquares(coord[0], coord[1]);
g.setColor(Color.BLUE);
g.drawRect(rectXY[0] + 5, rectXY[1] + 5, _SquareSelect - 10, _SquareSelect - 10);
}
// ************TEMP************
} |
987de6d1-2103-439f-9d76-1b489360c21d | 4 | @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
try {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "The server doesn't have a PIN!");
return true;
}
Player player = (Player)sender;
if (HyperPVP.getStorage().readString("SELECT password FROM users WHERE username = '" + player.getName() + "'").length() != 0) {
sender.sendMessage(ChatColor.RED + "You have already made your account.");
}
if (HyperPVP.getStorage().entryExists("SELECT code FROM pincodes WHERE name = '" + player.getName() + "'")) {
player.sendMessage(ChatColor.GREEN + "Your pin code is " + ChatColor.WHITE + HyperPVP.getStorage().readString("SELECT code FROM pincodes WHERE name = '" + player.getName() + "'"));
} else {
sender.sendMessage(ChatColor.RED + "You haven't registered, use the " + ChatColor.WHITE + "/register" + ChatColor.RED + "command!");
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
} |
1837b7b2-9389-4574-a308-04bcf87fe6f4 | 3 | public void svg2pngUsingInkscape(File svgFile, File pngFile) throws ConverterException {
if(inkscapePath==null)
throw new ConverterException("No runtime defined for Inkscape");
// inkscape classDiag.svg -e classDiag.png -d 200
ProcessBuilder pb = new ProcessBuilder(
asList(inkscapePath, //
svgFile.getAbsolutePath(),//
"-e", //
pngFile.getAbsolutePath(),//
"-d", "200"));
try {
Process process = pb.start();
process.waitFor();
}
catch (InterruptedException e) {
throw new ConverterException("Fail to convert svg to png", e);
}
catch (IOException e) {
throw new ConverterException("Fail to convert svg to png", e);
}
} |
1ebe0062-7b51-4162-ab5e-39fd3a8a9b57 | 3 | @Override
public void update(GameContainer container, StateBasedGame sbg, int delta) throws SlickException {
xpos=container.getInput().getMouseX();
ypos=container.getInput().getMouseY();
bonusButton.update(delta);
updateEntities(delta);
if(time > 0){
time -= delta*1/1000f;
if(time%10 == 0){
count -= 1;
}
}
else{
time = 0;
}
if(time == 0){
enterEndState(sbg);
}
} |
95185200-9f39-4a92-978f-a0cfc218817d | 1 | int putIndexed(int tag, Object obj1, int index1, int index2) {
Key key = new Key(tag, obj1, index2);
Integer indexObj = (Integer) entryToIndex.get(key);
if (indexObj != null) {
/* Maybe this was a reserved, but not filled entry */
int index = indexObj.intValue();
indices1[index] = index1;
indices2[index] = index2;
return index;
}
grow(count + 1);
tags[count] = tag;
indices1[count] = index1;
indices2[count] = index2;
entryToIndex.put(key, new Integer(count));
return count++;
} |
c2475e00-515f-426f-9ac3-2cffe61e7a0b | 2 | @Override
public void init(boolean isServer) {
timer = 0;
tiles = new Tile[99][99];
for(int x = 0; x < tiles.length; x++)
for(int y = 0; y < tiles[x].length; y++)
tiles[x][y] = new Tile(this, x, y);
entities = new ArrayList<Entity>();
//for(int i = 0; i < 7; i++)
//entities.add(new RandomWalkEntity(this, tiles[49][49]));
Entity entity = new RandomWalkEntity(this, tiles[49][49]);
entities.add(entity);
perspective = new EntityPerspective(this, entity);
} |
379a48fc-3c02-4593-8609-b7d38df4f4b4 | 4 | public void disconnect() {
//windowController.getSendTextArea().setDisable(true);
//windowController.getSubmitButton().setDisable(true);
shutdownReconnectWorker();
if(connectionCheckTimer != null) {
connectionCheckTimer.cancel();
}
if(!echoSocket.isClosed()) {
preDisconnect();
/*if(sockObjIn != null) {
try {
sockObjIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}*/
if(sockObjOut != null) {
writeObject(Commands.CMD_CLT_DISCONNECT + " ");
/*try {
sockObjOut.close();
} catch (IOException e) {
e.printStackTrace();
}*/
}
try {
echoSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
postDisconnect();
}
//windowController.updateUsersList(new HashMap<Integer, String>());
sendNewInfo("Disconnected from the server");
} |
93147196-631c-4611-a6b5-706b78a8d6a6 | 5 | private void pop(char c) throws JSONException {
if (this.top <= 0) {
throw new JSONException("Nesting error.");
}
char m = this.stack[this.top - 1] == null ? 'a' : 'k';
if (m != c) {
throw new JSONException("Nesting error.");
}
this.top -= 1;
this.mode = this.top == 0
? 'd'
: this.stack[this.top - 1] == null
? 'a'
: 'k';
} |
32b4122c-03f1-4758-88c4-efe651a38aab | 1 | public static void main(String[] args) {
Integer i = new Integer(253);
if((i & 0x01) == 1){
System.out.println("CARRY");
}
System.out.println(Integer.toBinaryString(i));
i = i >> 1;
System.out.println(Integer.toBinaryString(i));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.