method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
2c264a69-485e-41d5-8e83-8ffba6b14319 | 7 | @Override
public void run() {
int selected = 0;
ArrayList<MonitoredAS> monitoredASs = new ArrayList<MonitoredAS>(
allUpdates.keySet());
for (int i = start; i <= end; i++) {
MonitoredAS monitoredAS = monitoredASs.get(i - 1);
SingleASspikes spikes = allUpdates.get(monitoredAS);
if (spikes.getCurrentUpdateSum() == 0) {
continue;
}
for (Long time = spikes.getCurrentMinTime(); time <= spikes
.getCurrentMaxTime(); time++) {
if (spikes.hasSpikeAtTime(time)) {
int size = spikes.getSpikeAtTime(time).getSpikeSize();
if ((size < maxSize) && (size >= minSize)) {// select spike
// Attention! this part of code
// "contains a sequence of calls to a concurrent" hash
// map. However, it should not be a problem since
// different threads work with different monitoredASs
// check if there are already selected spikes from this
// monitoredAS
if (!selectedSpikesWithPredefinedSize
.containsKey(monitoredAS)) {
// create hash map entry for monitoredAS with empty
// spikes
// I will add spikes at the code below
selectedSpikesWithPredefinedSize.put(monitoredAS,
new SingleASspikes());// need
// to
// copy
// monitoredAS?
}
// copy spike object
ArrayList<Destination> destinations = spikes
.getSpikeAtTime(time).copyPrefixSet();
Spike selectedSpike = new Spike(destinations);
// add spike to selected (entry with monitored AS is
// already created)
selectedSpikesWithPredefinedSize.get(monitoredAS)
.addSpike(time, selectedSpike);
selected++;
}
}
}
}
logger.info(selected + " spikes with size from " + minSize + " to "
+ (maxSize - 1) + " selected by current thread.");
} |
790d9356-d081-4a07-834d-14e69617b645 | 5 | private void getGroups() {
String[] temp = manager.getGroupNames();
//build a new array to hold all our names plus the new value
if (temp != null) {
groupNames = new String[temp.length + 1];
groupNames[0] = "<New>";
for (int i = 0; i < temp.length; ++i) {
groupNames[i + 1] = temp[i];
}
} else {
//no groups
groupNames = new String[]{"<New>"};
}
if (groupList != null) {
//update our model for our list display
groupList.setModel(new javax.swing.AbstractListModel() {
String[] strings = groupNames;
@Override
public int getSize() {
return strings.length;
}
@Override
public Object getElementAt(int i) {
return strings[i];
}
});
this.repaint();
//search our groups and select the one with matching name to
// whatever group the user is working on
if (editingFilt != null) {
int res = Arrays.binarySearch(groupNames, editingFilt.getName());
if (res >= 0) {
groupList.setSelectedIndex(res);
} else {
groupList.setSelectedIndex(0);
}
} else {
//they are working on a new group
groupList.setSelectedIndex(0);
}
}
} |
c597574a-b495-48f2-b528-1c1b407457e2 | 4 | @Override
public void redo() {
if (oldKey == null) {
if (newKey == null) {
// Do Nothing, since this should never happen.
} else {
node.setAttribute(newKey, newValue, newReadOnly);
}
} else {
if (newKey == null) {
node.removeAttribute(oldKey);
} else {
if (!oldKey.equals(newKey)) {
node.removeAttribute(oldKey);
}
node.setAttribute(newKey, newValue, newReadOnly);
}
}
} |
c6e5547f-3397-4628-aaec-739368d65c7d | 7 | @Override
public void execute(CommandSender sender, String[] args) {
if (args.length == 0) {
sender.sendMessage(new TextComponent(ChatColor.RED + "Usage: /irckick <user> [message ...]"));
return;
}
if (!IRC.sock.isConnected()) {
sender.sendMessage(new TextComponent(ChatColor.RED + "The proxy is not connected to IRC."));
return;
}
String uid = Util.getUidByNick(args[0]);
String chan = BungeeRelay.getConfig().getString("server.channel");
if (chan.isEmpty()) chan = BungeeRelay.getConfig().getString("server.chanprefix") + ((ProxiedPlayer) sender).getServer().getInfo().getName();
ArrayList<String> chanusers = IRC.chans.get(chan).users;
if (!chanusers.contains(uid)) {
sender.sendMessage(new TextComponent(ChatColor.RED + args[0] + " is not in this IRC channel."));
return;
}
String msg;
if (args.length == 1) {
msg = BungeeRelay.getConfig().getString("formats.defaultkick");
}else{
ArrayList<String> list = new ArrayList<String>(Arrays.asList(args));
list.remove(0);
StringBuilder sb = new StringBuilder();
for (String a : list) sb.append(a).append(" ");
msg = sb.toString().trim();
}
IRC.out.println(":" + IRC.uids.get(sender) + " KICK " + chan + " " + uid + " :" + msg);
IRC.chans.get(chan).users.remove(uid);
for (ProxiedPlayer p : Util.getPlayersByChannel(chan)) {
p.sendMessage(new TextComponent(ChatColor.translateAlternateColorCodes('&', BungeeRelay.getConfig().getString("formats.kick")
.replace("{SENDER}", sender.getName())
.replace("{TARGET}", args[0])
.replace("{REASON}", msg))));
}
} |
c9112bc7-560a-4639-b386-ea7d995b0737 | 8 | public HDR64Buffer scale( HDR64Buffer in, int w, int h ) {
// TODO: Flip instead of ignoring negatives
int sx0, sx1, sy0, sy1;
if( w < 0 ) {
sx0 = in.width;
sx1 = -1;
w = -w;
} else {
sx0 = 0;
sx1 = in.width;
}
if( h < 0 ) {
sy0 = in.height;
sy1 = -1;
h = -h;
} else {
sy0 = 0;
sy1 = in.height;
}
if( h < 0 ) h = -h;
HDR64Buffer out = new HDR64Buffer(w, h);
int spp = samplePointCount;
for( int y=0; y<h; ++y ) {
for( int x=0; x<w; ++x ) {
int sampleCount = 0;
long v = 0;
for( int i=spp*2-1; i>=0; ) {
int ix = (int)(sx0 + (x + samplePoints[i--]) * (sx1-sx0) / w);
int iy = (int)(sy0 + (y + samplePoints[i--]) * (sy1-sy0) / h);
long sample = in.data[ix + iy*in.width];
if( (sample & HDR64Util.HDR_ALPHA_MASK) != 0 ) {
++sampleCount;
v += sample;
}
}
if( sampleCount >= spp/2 ) {
v = HDR64Util.divide(v, sampleCount) | HDR64Util.HDR_ALPHA_MASK;
} else {
v = 0;
}
out.data[x + y*w] = v;
}
}
return out;
} |
edbe1e21-64b0-4aa3-9baa-2a1bd96b6ac7 | 1 | @Override
public void run() {
if (!EventQueue.isDispatchThread()) {
EventQueue.invokeLater(this);
} else {
super.run();
}
} |
6d1f59cc-25f5-4c80-a9c2-7e7eeeea42e5 | 3 | public Quaternion SLerp(Quaternion dest, float lerpFactor, boolean shortest)
{
final float EPSILON = 1e3f;
float cos = this.Dot(dest);
Quaternion correctedDest = dest;
if(shortest && cos < 0)
{
cos = -cos;
correctedDest = new Quaternion(-dest.GetX(), -dest.GetY(), -dest.GetZ(), -dest.GetW());
}
if(Math.abs(cos) >= 1 - EPSILON)
return NLerp(correctedDest, lerpFactor, false);
float sin = (float)Math.sqrt(1.0f - cos * cos);
float angle = (float)Math.atan2(sin, cos);
float invSin = 1.0f/sin;
float srcFactor = (float)Math.sin((1.0f - lerpFactor) * angle) * invSin;
float destFactor = (float)Math.sin((lerpFactor) * angle) * invSin;
return this.Mul(srcFactor).Add(correctedDest.Mul(destFactor));
} |
52067f32-3935-4b96-becf-4ba41977deb8 | 9 | private static int scoreMatchingTokens(List<String> array1, List<String> array2)
{
HashMap<String, Integer> array1Counts = new HashMap<String, Integer>();
HashMap<String, Integer> array2Counts = new HashMap<String, Integer>();
for (String t : array1)
{
if (array1Counts.containsKey(t))
{
array1Counts.put(t, new Integer(array1Counts.get(t).intValue() + 1));
}
else
{
array1Counts.put(t, new Integer(1));
}
}
for (String t : array2)
{
if (array1Counts.containsKey(t))
{
if (array2Counts.containsKey(t))
{
array2Counts.put(t, new Integer(array2Counts.get(t).intValue() + 1));
}
else
{
array2Counts.put(t, new Integer(1));
}
}
}
int result = 0;
String token;
if (array2Counts.keySet().size() > 0)
{
result = array2Counts.keySet().size() == 1 ? 1 : (int) Math.pow(3.0, (double) array2Counts.keySet().size());
Iterator<String> array2CountsIterator = array2Counts.keySet().iterator();
while (array2CountsIterator.hasNext())
{
token = array2CountsIterator.next();
int array1Count = array1Counts.get(token).intValue();
int array2Count = array2Counts.get(token).intValue();
if (array1Count < array2Count)
{
result = result + ((token.length() - 1) * array1Count);
}
else
{
result = result + ((token.length() - 1) * array2Count);
}
}
}
return result;
} |
d50e1b75-01ce-42a9-ba19-ef69a4dd11d3 | 6 | @SuppressWarnings("unchecked")
public void load() {
File configFile = plugin.getConfigFile("gates.yml");
int counter = 0;
try {
Yaml yaml = new Yaml();
Map<String, Object> gatesYaml = (Map<String, Object>) yaml.load(new FileInputStream(configFile));
if (gatesYaml == null) {
plugin.log.info(plugin.getNameBrackets() + "empty gates.yml - initializing");
return;
}
for (Map.Entry<String, Object> thisGate : gatesYaml.entrySet()) {
String gateName = thisGate.getKey();
Map<String, Object> gateData = (Map<String, Object>) thisGate.getValue();
DataGate newGate = new DataGate(plugin, gateName);
newGate.setLocation(
(String) gateData.get("world"),
(Double) gateData.get("locX"),
(Double) gateData.get("locY"),
(Double) gateData.get("locZ"),
((Double) gateData.get("locYaw")).floatValue(),
((Double) gateData.get("locP")).floatValue());
newGate.setToll((Double) gateData.get("toll"));
newGate.setDenySilent((Boolean) gateData.get("denysilent"));
add(newGate);
counter++;
}
for (Map.Entry<String, Object> thisGate : gatesYaml.entrySet()) {
String gateName = thisGate.getKey();
Map<String, Object> gateData = (Map<String, Object>) thisGate.getValue();
if (gateData.get("target") != null) {
DataGate thisTarget = get((String) gateData.get("target"));
if (thisTarget == null) {
plugin.log.warning(plugin.getNameBrackets() + "ignored invalid destination for gate " + gateName);
} else {
get(gateName).linkTo(thisTarget, false);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
plugin.log.info(plugin.getNameBrackets() + "loaded " + counter + " gates");
} |
583ff01d-26f1-469f-b3e7-103713dccb13 | 0 | public void startLoad() {
new Thread(this).start();
} |
834679db-8dba-416e-b108-48b63def21ee | 3 | public static Task[] getTasksByUserMail(String userMail) {
XStream xstream = new XStream(new DomDriver());
Task[] allTasks = new Task[0];
try {
File file = new File((String) Server.prop.get("taskFilePath"));
allTasks = (Task[]) xstream.fromXML(file);
} catch (Exception e) {
}
List<Task> retList = new ArrayList<Task>();
for (Task task : allTasks) {
if (task.getCreator().equals(userMail)) {
retList.add(task);
}
}
return retList.toArray(new Task[0]);
} |
ab3b51f6-cf51-4dff-9b30-01f095d6d203 | 1 | public static void main(String[] args){
String address = args[0];
int port = Integer.parseInt(args[1]);
try{
new AudioClient(new Socket(address, port)); } catch (Exception e) {}
} |
11e596d6-cb44-451b-8189-b7e2255c29a9 | 9 | public Model createNarfModelFromAB(String anMid, NucleicAcid aNucleicAcid, List<Cycle<Nucleotide, InteractionEdge>> acycleList){
boolean basepaironly = true;
Random r_i = new Random();
int rand_i = r_i.nextInt()+1;
Model rm = ModelFactory.createDefaultModel();
//add mcb computation resource
Resource mcb_computation = rm.createResource(
Vocab.narf_resource + CycleSerializer.MD5("mcb_computation"+rand_i));
//type it
mcb_computation.addProperty(Vocab.rdftype, Vocab.narf_mcb_computation);
rm.add(Vocab.narf_mcb_computation, Vocab.rdftype, Vocab.rdfs_class);
mcb_computation.addProperty(Vocab.rdftype, Vocab.named_individual);
//add a software resource
Resource sw_res = rm.createResource(Vocab.narf_resource+CycleSerializer.MD5("software"+rand_i));
sw_res.addProperty(Vocab.rdftype, Vocab.narf_software);
rm.add(Vocab.narf_software, Vocab.rdftype, Vocab.rdfs_class);
sw_res.addProperty(Vocab.rdftype, Vocab.named_individual);
//add a mcb resource
Resource mcb_res = rm.createResource(Vocab.narf_resource+CycleSerializer.MD5("mcb"+rand_i));
mcb_res.addProperty(Vocab.rdftype, Vocab.narf_mcb);
rm.add(Vocab.narf_mcb, Vocab.rdftype, Vocab.rdfs_class);
mcb_res.addProperty(Vocab.rdftype, Vocab.named_individual);
mcb_res.addLiteral(Vocab.rdfslabel, "Minimum Cycle Basis");
//connect them back to the mcb_computation
mcb_computation.addProperty(Vocab.has_attribute, sw_res);
mcb_computation.addProperty(Vocab.has_attribute, mcb_res);
//create a resource for the pdb_structure
Resource pdb_struct_resource = rm.createResource("http://freebase.com"+anMid);
mcb_res.addProperty(Vocab.derived_from, pdb_struct_resource);
for (Cycle<Nucleotide, InteractionEdge> acyc : acycleList) {
Random rp = new Random();
int randp = rp.nextInt() + 1;
// create a cycle resource
Resource cycleRes = rm.createResource(Vocab.narf_resource
+ CycleSerializer.MD5(acyc.toString()+anMid));
// type it as a cycle
cycleRes.addProperty(Vocab.rdftype, Vocab.narf_cycle);
rm.add(Vocab.narf_cycle, Vocab.rdftype, Vocab.rdfs_class);
cycleRes.addProperty(Vocab.rdftype, Vocab.named_individual);
mcb_res.addProperty(Vocab.has_member, cycleRes);
// add a label
String lbl = "Cycle found in AptamerBase: " + anMid + " of size: "
+ acyc.size();
cycleRes.addLiteral(Vocab.rdfslabel, lbl);
//add 1st degree neighbour cycle set
//all the cycles that share one or more vertices with acyc
List<Cycle<Nucleotide, InteractionEdge>> firstDegNeigh = aNucleicAcid.findMCBNeighbours(acyc);
if(firstDegNeigh.size()>0){
String r = "r"+randp;
Resource firstDegCNS = rm.createResource(Vocab.narf_resource+CycleSerializer.MD5(r));
String lb = "First degree cycle neighbourset";
//add a label
firstDegCNS.addLiteral(Vocab.rdfslabel, lb);
//type it as a 1st degree neighbour cycle set
firstDegCNS.addProperty(Vocab.rdftype, Vocab.narf_firstDegreeCycleNeighbourSet);
rm.add(Vocab.narf_firstDegreeCycleNeighbourSet, Vocab.rdftype, Vocab.rdfs_class);
firstDegCNS.addProperty(Vocab.rdftype, Vocab.named_individual);
cycleRes.addProperty(Vocab.has_attribute, firstDegCNS);
//now iterate over the neighbours
for (Cycle<Nucleotide, InteractionEdge> an : firstDegNeigh) {
//create a resource for each
Resource an_res = rm.createResource(Vocab.narf_resource+CycleSerializer.MD5(an.toString()+anMid));
//attach them to firstDegCNS using hasmember
firstDegCNS.addProperty(Vocab.has_member, an_res);
}
}
// add the size attribute
Resource sizeRes = rm.createResource(Vocab.narf_resource
+ CycleSerializer.MD5("size" + randp));
// type it as a size
sizeRes.addProperty(Vocab.rdftype, Vocab.narf_cycle_size);
rm.add(Vocab.narf_cycle_size, Vocab.rdftype, Vocab.rdfs_class);
sizeRes.addProperty(Vocab.rdftype, Vocab.named_individual);
//add a label
String l = "Cycle size";
sizeRes.addLiteral(Vocab.rdfslabel, l);
// add the value
sizeRes.addLiteral(Vocab.has_value, (int) acyc.size());
// connect the sizeRes to the cycleRes
cycleRes.addProperty(Vocab.has_attribute, sizeRes);
//create a gccontent res System.out.println(CycleHelper.computeCycleGCContent(acyc));
Resource gcCont = rm.createResource(Vocab.narf_resource+CycleSerializer.MD5("gcContent"+randp+acyc.hashCode()));
gcCont.addProperty(Vocab.rdftype, Vocab.narf_gc_content);
rm.add(Vocab.narf_gc_content, Vocab.rdftype, Vocab.rdfs_class);
//add a label
String l2 = "Cycle gc content";
gcCont.addLiteral(Vocab.rdfslabel, l2);
gcCont.addProperty(Vocab.rdftype, Vocab.named_individual);
double gc_cont = CycleHelper.computeCycleGCContent(acyc);
gcCont.addLiteral(Vocab.has_value,gc_cont);
cycleRes.addProperty(Vocab.has_attribute, gcCont);
if(basepaironly){
Resource lvl_1 = rm.createResource(Vocab.narf_resource+CycleSerializer.MD5("lvl_1"+randp));
lvl_1.addProperty(Vocab.rdftype, Vocab.narf_cycle_profile_level_1);
rm.add(Vocab.narf_cycle_profile_level_1, Vocab.rdftype, Vocab.rdfs_class);
lvl_1.addProperty(Vocab.rdftype, Vocab.named_individual);
//add a label
String l3 = "Cycle profile level 1 ";
lvl_1.addLiteral(Vocab.rdfslabel, l3);
//get the level 1 normalized version of this string
String lvl_1_str = CycleHelper.findMinmalNormalization(aNucleicAcid, acyc, true).toString();
lvl_1.addLiteral(Vocab.has_value,"#"+lvl_1_str);
lvl_1.addLiteral(Vocab.hasMD5,CycleSerializer.MD5(lvl_1_str));
cycleRes.addProperty(Vocab.has_attribute, lvl_1);
}
// get the interaction edges
List<InteractionEdge> edges = acyc.getEdgeList();
for (InteractionEdge anEdge : edges) {
Set<NucleotideInteraction> interactions = anEdge
.getInteractions();
Random ra = new Random();
int rand = ra.nextInt() + 1;
for (NucleotideInteraction ni : interactions) {
if (ni instanceof BasePair) {
// get the first nucleotide
Nucleotide fN = ((BasePair) ni).getFirstNucleotide();
Nucleotide sN = ((BasePair) ni).getSecondNucleotide();
// create a bio2rdf resource for each nucleotide
Resource firstNucRes = rm
.createResource(Vocab.ab_resource + CycleSerializer.MD5(anMid
+ "/chemicalComponent_"
+ fN.getChainId()
+ fN.getResiduePosition()));
Resource secondNucRes = rm
.createResource(Vocab.ab_resource +CycleSerializer.MD5(anMid
+ "/chemicalComponent_"
+ sN.getChainId()
+ sN.getResiduePosition()));
// type them
firstNucRes.addProperty(Vocab.rdftype,
Vocab.ab_residue);
rm.add(Vocab.ab_residue, Vocab.rdftype, Vocab.rdfs_class);
firstNucRes.addProperty(Vocab.rdftype, Vocab.named_individual);
secondNucRes.addProperty(Vocab.rdftype,
Vocab.ab_residue);
secondNucRes.addProperty(Vocab.rdftype, Vocab.named_individual);
// add these nucleotide resources as members of the
// cycle
cycleRes.addProperty(Vocab.has_part, firstNucRes);
cycleRes.addProperty(Vocab.has_part, secondNucRes);
// create a base pair resource
Resource bpRes = rm.createResource(Vocab.narf_resource
+ CycleSerializer.MD5(fN.toString()
+ sN.toString()));
// create a resource from the rnaoclass
String rnaoClassStr = ((BasePair) ni).inferRnaOClass();
Resource rnaoClass = rm.createResource(rnaoClassStr);
if (rnaoClass != null) {
// type it using the rnaoClass resource
bpRes.addProperty(Vocab.rdftype, rnaoClass);
rm.add(rnaoClass, Vocab.rdftype, Vocab.rdfs_class);
bpRes.addProperty(Vocab.rdftype, Vocab.named_individual);
}else{
bpRes.addProperty(Vocab.rdftype, rm.createResource("http://purl.obolibrary.org/obo/RNAO_0000001"));
bpRes.addProperty(Vocab.rdftype, Vocab.named_individual);
rm.add(rm.createResource("http://purl.obolibrary.org/obo/RNAO_0000001"),Vocab.rdftype, Vocab.rdfs_class);
}
// base pair has part residues
bpRes.addProperty(Vocab.has_part, firstNucRes);
bpRes.addProperty(Vocab.has_part, secondNucRes);
// add the paried with property between the residues
firstNucRes
.addProperty(Vocab.paired_with, secondNucRes);
// add the base pair label
bpRes.addLiteral(Vocab.rdfslabel,
((BasePair) ni).toString());
cycleRes.addProperty(Vocab.has_attribute, bpRes);
} else if (ni instanceof PhosphodiesterBond) {
// get the first nucleotide
Nucleotide fN = ((PhosphodiesterBond) ni)
.getFirstNucleotide();
Nucleotide sN = ((PhosphodiesterBond) ni)
.getSecondNucleotide();
// create a bio2rdf resource for each nucleotide
Resource firstNucRes = rm
.createResource(Vocab.ab_resource + CycleSerializer.MD5(anMid
+ "/chemicalComponent_"
+ fN.getChainId()
+ fN.getResiduePosition()));
Resource secondNucRes = rm
.createResource(Vocab.ab_resource + CycleSerializer.MD5(anMid
+ "/chemicalComponent_"
+ sN.getChainId()
+ sN.getResiduePosition()));
// type them
firstNucRes.addProperty(Vocab.rdftype,
Vocab.ab_residue);
firstNucRes.addProperty(Vocab.rdftype, Vocab.named_individual);
secondNucRes.addProperty(Vocab.rdftype,
Vocab.ab_residue);
secondNucRes.addProperty(Vocab.rdftype, Vocab.named_individual);
// add these nucleotide resources as members of the
// cycle
cycleRes.addProperty(Vocab.has_part, firstNucRes);
cycleRes.addProperty(Vocab.has_part, secondNucRes);
// create a phosphodiesterbond resource
Resource phdbRes = rm.createResource(Vocab.narf_resource
+ CycleSerializer.MD5("phdb" + rand));
// type it as a narf phdb
phdbRes.addProperty(Vocab.rdftype,
Vocab.narf_phosphodiester_bond);
rm.add(rm.createResource(Vocab.narf_phosphodiester_bond), Vocab.rdftype, Vocab.rdfs_class);
phdbRes.addProperty(Vocab.rdftype, Vocab.named_individual);
// phosphodiester bond has part residuies
phdbRes.addProperty(Vocab.has_part, firstNucRes);
phdbRes.addProperty(Vocab.has_part, secondNucRes);
// add the covalently connected to property between the
// residues
firstNucRes.addProperty(Vocab.covalenty_connected_to,
secondNucRes);
// add the phosphodiester bond label
phdbRes.addLiteral(Vocab.rdfslabel,
((PhosphodiesterBond) ni).toString());
cycleRes.addProperty(Vocab.has_attribute, phdbRes);
}
}
}
}
return rm;
} |
7a942dd5-47dd-468e-a672-b6b41e2607b9 | 1 | @Override
public void start(Stage primaryStage) throws Exception {
Group root = new Group();
primaryStage.setTitle("Circle Fit");
primaryStage.setScene(new Scene(root));
//Draw the random generate circles
Canvas canvas = new Canvas(PANEL_WIDTH, PANEL_HEIGHT);
root.getChildren().add(canvas);
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setStroke(Color.BLACK);
circles.stream().forEach(c -> gc.strokeOval(c.center_x-c.radius, c.center_y-c.radius, c.radius*2, c.radius*2));
//Update population and draw best solution
Canvas canvas2 = new Canvas(PANEL_WIDTH, PANEL_HEIGHT);
root.getChildren().add(canvas2);
GraphicsContext gc2 = canvas2.getGraphicsContext2D();
gc2.setFill(Color.RED);
new AnimationTimer(){
public void handle(long currentNanoTime){
gc2.clearRect(0, 0, PANEL_WIDTH, PANEL_HEIGHT);
pop.newGeneration();
Chromo<Integer> best = pop.getFittestChromo();
Circle c = new Circle(best.getGenes().get(0), best.getGenes().get(1), best.getGenes().get(2));
gc2.fillOval(c.center_x-c.radius, c.center_y-c.radius, c.radius*2, c.radius*2);
if (pop.getNumberOfGenerations() >= MAX_GENERATIONS)
this.stop();
}
}.start();
primaryStage.show();
} |
b62eae6a-daae-48f7-972e-1d9567c4d2da | 0 | public static void main(String[] args) {
Game game = new Game();
game.play();
} |
07374aab-ed8b-484b-8ef6-320bcc700bc1 | 6 | private NoteLengthEnum shiftNoteLength(NoteLengthEnum lastBeat, double remaining, int change) {
NoteLengthEnum beat = lastBeat;
NoteLengthEnum [] allNoteLengths = NoteLengthEnum.values();
while(change > 0) {
//if there is a noteLength you could increment to...
if(beat.ordinal() + 1 < allNoteLengths.length){
NoteLengthEnum potentialBeat = allNoteLengths[beat.ordinal() + 1];
//...and this note will not block the rest of the measure
if(canFinishMeasure(remaining, potentialBeat.getRatio())){
beat = potentialBeat;
}
}
change--;
}
while(change < 0) {
//if there is a noteLength you could increment to...
if(beat.ordinal() - 1 >= 0){
NoteLengthEnum potentialBeat = allNoteLengths[beat.ordinal() - 1];
//...and this note will not block the rest of the measure
if(canFinishMeasure(remaining, potentialBeat.getRatio())){
beat = potentialBeat;
}
}
change++;
}
return beat;
} |
6376ffb5-4511-4588-a86b-9ad9fe06821a | 5 | private Object getObjectAs(ResultSet rset, ResultSetMetaData rsmd, int colIndex) throws SQLException {
int colType = rsmd.getColumnType(colIndex);
if(colType == Types.INTEGER)
return rset.getInt(colIndex);
else if(colType == Types.FLOAT || colType == Types.DECIMAL || colType == Types.DOUBLE || colType == Types.REAL)
return rset.getBigDecimal(colIndex);
return rset.getObject(colIndex);
} |
fa2cca86-2f4c-4fb8-a274-26c92b49e458 | 0 | public void updateCornerRects() {
int width = 7;
int height = 7;
Point fi = new Point(((Rectangle) getShape()).x - 5, ((Rectangle) getShape()).y - 5);
Point sec = new Point(((Rectangle) getShape()).x + ((Rectangle) getShape()).width, ((Rectangle) getShape()).y - 5);
Point thi = new Point(((Rectangle) getShape()).x + ((Rectangle) getShape()).width, ((Rectangle) getShape()).y + ((Rectangle) getShape()).height);
Point four = new Point(((Rectangle) getShape()).x - 5, ((Rectangle) getShape()).y + ((Rectangle) getShape()).height);
firstCorner = (new Rectangle(fi.x, fi.y, width, height));
secondCorner = (new Rectangle(sec.x, sec.y, width, height));
thirdCorner = (new Rectangle(thi.x, thi.y, width, height));
fourthCorner = (new Rectangle(four.x, four.y, width, height));
} |
7d2d09a5-0bd1-4d0c-8e28-06e9ae4fe9ed | 0 | @Basic
@Column(name = "quantity_purchased")
public int getQuantityPurchased() {
return quantityPurchased;
} |
24338ced-d481-4047-8698-5e3fb821dd4e | 0 | public final void addDragListeners(final Node n) {
n.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
startDragX = me.getSceneX();
startDragY = me.getSceneY();
root.setStyle("-fx-opacity:.7;");
}
});
n.setOnMouseReleased(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
root.setStyle("-fx-opacity:1;");
}
});
n.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
stage.setX(me.getScreenX() - startDragX);
stage.setY(me.getScreenY() - startDragY);
}
});
} |
ec83eafa-c59c-4700-96d0-e2b140d2cab9 | 2 | public static void main(String[] args) {
System.out.println ("Please enter a value for a");
Scanner sc = new Scanner(System.in);
double a = sc.nextDouble();
System.out.println(a);
System.out.println ("Please enter a value for b");
double b = sc.nextDouble();
System.out.println(b);
System.out.println ("Please enter a value for c");
double c = sc.nextDouble();
System.out.println(c);
double x = 0;
x = (-b + (Math.sqrt((b*b - ((4 * a * c))))))/ (2 * a);
double y = 0;
y = (-b - (Math.sqrt((b*b - ((4*a*c))))))/ (2 * a);
if (((b*b - ((4 * a * c))) < 0) == true) {
System.out.println ("There are no real roots");
}
if (((b*b - ((4 * a * c))) < 0) == false) {
System.out.println ("The Roots are " + x + " or " + y );
}
} |
d2939bc4-a6c2-4852-ba93-b3033bb4e486 | 2 | public String getCitedList(int id) {
String query = "select paperid from dblpcitation where citationid="
+ id + " order by paperid asc";
ResultSet rs = sqLconnection.Query(query);
String list = "";
try {
while (rs.next()) {
int citedid = rs.getInt("paperid");
list += citedid + ",";
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
} |
aab1b73b-07fe-47b0-9cd5-01484ab25de5 | 8 | public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
for (String token : tokens) {
if (token.charAt(0) >= '0' && token.charAt(0) <= '9' || token.length() != 1) {
stack.push(Integer.parseInt(token));
} else {
Integer opB = stack.pop();
Integer opA = stack.pop();
if (token.equals("+"))
stack.push(opA + opB);
else if (token.equals("-"))
stack.push(opA - opB);
else if (token.equals("*"))
stack.push(opA * opB);
else
stack.push(opA / opB);
}
}
if (stack.isEmpty()) return 0;
return stack.pop();
} |
0fdcea2a-14df-499b-8f41-36da9b65d9af | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(FrmPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FrmPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FrmPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FrmPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new FrmPrincipal().setVisible(true);
}
});
} |
84d421a2-04d6-4b6a-a8ae-90872880ef72 | 5 | public int getAllowedGuiRows(Player player) {
if (player.hasPermission("trade.gui.rows.6"))
return 6;
if (player.hasPermission("trade.gui.rows.5"))
return 5;
if (player.hasPermission("trade.gui.rows.4"))
return 4;
if (player.hasPermission("trade.gui.rows.3"))
return 3;
if (player.hasPermission("trade.gui.rows.2")) {
return 2;
}
return plugin.yamlHandler.configYaml.getInt("default-rows", 4);
} |
f5f5435e-87e6-4795-8077-0b35bc1609cd | 3 | public void run(){
try {
while(true){
message = in.readLine();
switch(message){
case "jeu" : JoueurDIXIT.pretJouer = true; System.out.println("JEU");break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
} |
fb3954e1-2b18-4983-9f49-bfb8ff6972d0 | 9 | private boolean interfaceIsSelected(RSInterface class9)
{
if(class9.valueCompareType == null)
return false;
for(int i = 0; i < class9.valueCompareType.length; i++)
{
int j = extractInterfaceValues(class9, i);
int k = class9.requiredValues[i];
if(class9.valueCompareType[i] == 2)
{
if(j >= k)
return false;
} else
if(class9.valueCompareType[i] == 3)
{
if(j <= k)
return false;
} else
if(class9.valueCompareType[i] == 4)
{
if(j == k)
return false;
} else
if(j != k)
return false;
}
return true;
} |
7257e1da-15b3-44e7-9596-d264f8f92937 | 4 | public static boolean eqParamTypes(String desc1, String desc2) {
if (desc1.charAt(0) != '(')
return false;
for (int i = 0; true; ++i) {
char c = desc1.charAt(i);
if (c != desc2.charAt(i))
return false;
if (c == ')')
return true;
}
} |
5ef84178-749c-4499-adc0-51e5492900a4 | 8 | @Override
public MapObject doNextAction(MapEngine engine, double s_elapsed) {
if (is_cloaked && is_visible && visible_time_left < 0.0) {
is_visible = false;
}
if (shields < 0) {
return (has_death_spin ? doNextDeathSpinAction(engine, s_elapsed) : handleDeath(engine, s_elapsed));
}
previous_turn = (next_action != null ? next_action.turn : TurnDirection.NONE);
MultipleObject created_objects = new MultipleObject();
int less_half_shields = half_shields - shields;
if (less_half_shields > 0 &&
Math.random() * MIN_TIME_BETWEEN_DAMAGED_EXPLOSIONS < less_half_shields / (half_shields + 1.0) *
s_elapsed) {
created_objects.addObject(createDamagedExplosion());
}
created_objects.addObject(super.doNextAction(engine, s_elapsed));
return created_objects;
} |
159adf20-7771-41c6-917f-955661b4eaa1 | 2 | public void setParticleEvent(int newEvent) {
if (newEvent < 0 || newEvent > 4) {
throw new IllegalArgumentException("Can only change to a particle event between 0 and 3, inclusive!");
}
selectedParticleEvent = newEvent;
} |
b2cdb9c1-3fc3-45e0-84ba-0c781583b05b | 0 | public int getId() {
return id;
} |
22193f9f-a7cc-4275-9f58-46def23070e5 | 6 | ArrayList<movePair> possibleMoves(Point[] grid, Pair pr) {
ArrayList<movePair> possible = new ArrayList<movePair>();
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
Point currentPoint = pointAtGridIndex(grid, i, j);
if (currentPoint.value == 0) {
continue;
}
for (Pair d : directionsForPair(pr)) {
if (isValidBoardIndex(i + d.p, j + d.q)){
Point possiblePairing = pointAtGridIndex(grid, i + d.p, j + d.q);
if (currentPoint.value == possiblePairing.value) {
possible.add(new movePair(true, currentPoint, possiblePairing));
possible.add(new movePair(true, possiblePairing, currentPoint));
}
}
}
}
}
return possible;
} |
42dea606-4aaa-4887-81f8-b03e03071a84 | 2 | public boolean isEnabled(){
return triggeredSite == null || triggeredSite == this || handlersAllowed.contains( name );
} |
5e3ae1d4-efc8-45c8-b190-99bb56ffa65a | 6 | public Object getValueAt(int row, int column) {
try {
Class c = rows.get(row).getClass();
BeanInfo beanInfo = Introspector.getBeanInfo(c, Object.class);
PropertyDescriptor pd = beanInfo.getPropertyDescriptors()[column];
Method m = pd.getReadMethod();
if (m != null) {
Object objVal = m.invoke(rows.get(row), null);
return (objVal != null) ? objVal : "";
}
} catch (IllegalAccessException ex) {
Logger.getLogger(GenericTableModel.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(GenericTableModel.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(GenericTableModel.class.getName()).log(Level.SEVERE, null, ex);
} catch (IntrospectionException ex) {
Logger.getLogger(GenericTableModel.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
} |
475f2112-d7fb-4d3e-a7a2-4351c85ee7ef | 4 | private long getCPtrAddRefBitcoinServer(BitcoinServer element) {
// Whenever adding a reference to the list, I remove it first (if already there.)
// That way we never store more than one reference per actual contained object.
//
for(int intIndex = 0; intIndex < elementList.size(); intIndex++)
{
Object theObject = elementList.get(intIndex);
if ((theObject == null) || !(theObject instanceof BitcoinServer))
continue;
BitcoinServer tempRef = (BitcoinServer)(theObject);
if ((BitcoinServer.getCPtr(tempRef) == BitcoinServer.getCPtr(element)))
{
elementList.remove(tempRef); // It was already there, so let's remove it before adding (below.)
break;
}
}
// Now we add it...
//
BitcoinServer tempLocalRef = element;
elementList.add(tempLocalRef);
return BitcoinServer.getCPtr(element);
} // Hope I get away with overloading this for every type. Otherwise, |
44cb9270-c82a-48c3-a851-dbefb33054f2 | 3 | private boolean matchArgs(String[] subcommand, String[] args) {
if(args.length < subcommand.length)
return false;
else for(int i = 0; i < subcommand.length; i++)
if(!subcommand[i].equalsIgnoreCase(args[i]))
return false;
return true;
} |
73bcaded-746f-4c22-8fbd-2389b5003625 | 0 | public double getWrapWidth() {
return wrapWidth.get();
} |
f8809dcb-1b85-4137-9d8f-440dd193bb18 | 2 | public List<Player> findAll() {
List<Player> allUsers = new ArrayList<Player>();
try {
Statement statement = base.createStatement();
ResultSet resultSet = statement
.executeQuery("SELECT * FROM player");
resultSet.beforeFirst();
while (resultSet.next()) {
allUsers.add(new Player(resultSet.getInt(1), resultSet
.getString(2), resultSet.getString(3), resultSet
.getInt(4)));
}
}
catch (SQLException e) {
throw new RuntimeException(e);
}
return allUsers;
} |
bff9b59a-dd7b-48e9-9015-723e5bf96613 | 1 | @Override
public void endSetup(Attributes atts) {
String def = atts.getValue(AbstractPreference.A_DEFAULT);
String cur = Outliner.prefs.getTempValue(getCommand());
setDef(def);
if (cur != null) {
setCur(cur);
setTmp(cur);
} else {
setCur(def);
setTmp(def);
}
} |
fe5510af-4840-4166-b066-79121c6ece8b | 2 | public static void toggleCommentInheritanceForSingleNode(Node node, CompoundUndoable undoable) {
int oldValue = node.getCommentState();
int newValue = Node.COMMENT_INHERITED;
boolean isComment = node.isComment();
if (oldValue == Node.COMMENT_INHERITED) {
if (isComment) {
node.setCommentState(Node.COMMENT_TRUE);
newValue = Node.COMMENT_TRUE;
} else {
node.setCommentState(Node.COMMENT_FALSE);
newValue = Node.COMMENT_FALSE;
}
} else {
node.setCommentState(Node.COMMENT_INHERITED);
}
undoable.addPrimitive(new PrimitiveUndoableCommentChange(node, oldValue, newValue));
} |
be86b4a5-937f-4e10-a345-02cb422ddba2 | 7 | public static void main(String[] args) throws InterruptedException{
//zainiacjalizuj bufor
for(int i=0; i<rozmiarBufora; i++)
bufor[i]=i;
producenci = new Thread[iloscProducentow];
konsumenci = new Thread[iloscKonsumetow];
for(int i=0; i<iloscProducentow; ++i){
producenci[i] = new Producent(i);
}
for(int i=0; i<iloscKonsumetow; ++i){
konsumenci[i] = new Konsument(i);
}
wypisz.start();
for(int i=0; i<iloscProducentow; ++i){
producenci[i].start();
}
for(int i=0; i<iloscKonsumetow; ++i){
konsumenci[i].start();
}
for(int i=0; i<iloscProducentow; ++i){
producenci[i].join();
}
for(int i=0; i<iloscKonsumetow; ++i){
konsumenci[i].join();
}
} |
83b78285-ee56-4197-a647-5d307586db98 | 8 | private static void zeroMatrix(int[][] matrix, int m, int n) {
boolean[] rows = new boolean[m];
boolean[] columns = new boolean[n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (!columns[j]) {
if (matrix[i][j] == 0) {
columns[j] = true;
rows[i] = true;
}
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (rows[i] || columns[j]) {
matrix[i][j] = 0;
}
}
}
} |
43983b01-23a8-496c-be3d-aacd1ad39694 | 8 | public boolean animate(ActionListener callback) {
if (timer != null && timer.isRunning()) {
return false;
}
this.callbackListener = callback;
this.direction = isTargetAtBaseLocation() ? SimpleShutterAnimation.DIRECTION_UP : SimpleShutterAnimation.DIRECTION_DOWN;
step = 0;
timer = new Timer(10, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (step < 100) {
double h = target.getHeight() - base;
target.setLocation(new Point(target.getX(), new Double(h * Math.pow(2.98, -0.054 * step) * Math.cos(0.086 * step) - (direction == DIRECTION_UP ? h : 0 - base)).intValue() * (direction == DIRECTION_UP ? 1 : -1)));
step++;
} else {
target.setLocation(new Point(target.getX(), direction == DIRECTION_UP ? target.getBounds().y : new Double(0 - base).intValue()));
timer.stop();
if (callbackListener != null) {
callbackListener.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "finish"));
}
}
}
});
timer.start();
return true;
} |
d37e46ab-16c2-4300-a469-80bed2d71393 | 6 | protected static Ptg calcN( Ptg[] operands )
{
Object o = operands[0].getValue();
if( (o instanceof Double) || (o instanceof Integer) || (o instanceof Float) || (o instanceof Long) )
{
Double d = new Double( o.toString() );
return new PtgNumber( d );
}
if( o instanceof Boolean )
{
Boolean b = (Boolean) o;
boolean bo = b;
if( bo )
{
return new PtgInt( 1 );
}
}
return new PtgInt( 0 );
} |
915dcc6b-a1bc-4759-a0b5-25a889efb506 | 3 | boolean setMatch(int is, int js, int l) {
int[] a = new int[26];
for (int i = 0; i < l; i++) {
a[s1.charAt(is + i) - 'a']++;
a[s2.charAt(js + i) - 'a']--;
}
for (int i = 0; i < 26; i++) {
if (a[i] != 0) {
return false;
}
}
return true;
} |
8068c69f-6597-42eb-9ab1-cc8b6419ebad | 6 | private String match(String targetNumber){
if (targetNumber.isEmpty())
return "";
if (hmPartialResults.containsKey(targetNumber))
return hmPartialResults.get(targetNumber);
int minWordCount = Integer.MAX_VALUE;
String localResult = null;
for (int i = targetNumber.length(); i>0; i--){
String localsub = targetNumber.substring(0,i);
if (hm.containsKey(localsub)){
String subResult = match(targetNumber.substring(i, targetNumber.length()));
if ( subResult != null){
String temp = hm.get(localsub) + " " + subResult;
int tempcount =temp.split(" ").length;
if ( tempcount < minWordCount){
localResult = temp;
minWordCount = tempcount;
}
}
}
}
hmPartialResults.put(targetNumber, localResult);
return localResult;
} |
ccec01ab-8673-49fb-87c5-8d760952eb07 | 2 | public static ErrorLogs parameterLogs(String supMsg, String confMsg){
ErrorLogs logs = new ErrorLogs();
String parameterError = "Parameter Input Error: ";
String parameterRange = " Must be between 0.0 and 1.0, inclusively";
if (!supMsg.equals("")) {
logs.getErrorMsgs().add(
parameterError + " Min Support Level is " + supMsg
+ parameterRange);
}
if (!confMsg.equals("")) {
logs.getErrorMsgs().add(
parameterError + " Min Confidence Level is " + confMsg
+ parameterRange);
}
return logs;
} |
6e370fa8-f0c1-4875-bd3b-765dfb139a47 | 7 | public void updateMidiOutSelectedItems(String[] midiOutDevices) {
for (int i = 0; i < midiOutMenu.getItemCount(); i++) {
String name = midiOutMenu.getItem(i).getText();
if (name == null || name.equals("No MIDI Output Devices Enabled")) {
continue;
}
String[] pieces = name.split("MIDI Output: ");
boolean found = false;
for (int j = 0; j < midiOutDevices.length; j++) {
if (midiOutDevices[j] == null) {
continue;
}
if (pieces[1].compareTo(midiOutDevices[j]) == 0) {
midiOutMenu.getItem(i).setSelected(true);
found = true;
}
}
if (!found) {
midiOutMenu.getItem(i).setSelected(false);
}
}
} |
25a8d61b-6088-497d-a6b1-8f85897566b9 | 2 | public void onStart(ISuite suite)
{
List<Long> testSetIds = populateTestSetIds(suite);
if (testSetIds != null && !testSetIds.isEmpty()) {
this.testInstances = populateTestInstances(testSetIds);
}
} |
2a75d95c-b216-433e-a271-8de6ae8c4c99 | 4 | public boolean sendContent( long msg_id, int type, String suffix, byte[] content ){
int flag = -1;
switch( type ){
case MessageUtil.TYPE_LONG:
flag = rsc_handler.addLongResource( msg_id, content );
break;
case MessageUtil.TYPE_IMAGE:
flag = rsc_handler.addImageResource( msg_id, suffix, content );
break;
case MessageUtil.TYPE_VOICE:
flag = rsc_handler.addVoiceResource( msg_id, suffix, content );
break;
}
if( flag != MessageUtil.SUCCESS ){
System.out.println( "MessageService : failed to upload resource file " + msg_id );
return false;
}
return true;
} |
f98de2a0-05e4-4e3a-9ee6-c1f891033216 | 3 | private Vector3D getAcceleration(Body body1) {
// Uses system mass instead of accounting for moons
Vector3D aTotal = new Vector3D();
for (int i = 0; i < bodies.size(); i++) {
Body body2 = bodies.get(i);
if (body1 == body2) {
break;
}
double mass = getSimpleMass(body1, body2);
if (mass == 0) {
break;
}
Vector3D diff = body2.position.clone().subtract(body1.position);
double mag = diff.magnitude();
Vector3D a = diff.multiply(mass / Math.pow(mag, 3));
aTotal.add(a);
}
return aTotal.multiply(Astrophysics.G);
} |
62edcb83-a9a4-4963-9f02-d60738a1c08c | 0 | public void setFooter(JPanel footer) {
this.footer = footer;
} |
63dbc3c0-6e76-4d9d-9be9-f3aad03c68bc | 0 | public String getStatus() {
return status;
} |
4dbcae8b-f8a8-47c7-ba96-83a76c50f5ea | 1 | public void printMeetings(List<Meeting> contactMeetings) {
for (int i = 0; i < contactMeetings.size(); i++) {
System.out.println("Meeting ID: " + contactMeetings.get(i).getID());
System.out.println("Date: "
+ df.format(contactMeetings.get(i).getDate().getTime()));
System.out.print("Attendees: ");
printContacts(contactMeetings.get(i).getContacts());
}
} |
1520c0f5-df6c-468c-9c9a-0e60fe82555a | 1 | public static Object quoteIfString(Object obj) {
return (obj instanceof String ? quote((String) obj) : obj);
} |
e1b27c5e-7b74-431c-a66b-5f0fbed0faec | 0 | @Override
public int filterRGB(int x, int y, int rgb) {
return (rgb & 0xff000000) | amount;
} |
3ff5ceae-ee9f-44f1-8566-ee8b29bb4d53 | 4 | public JSONObject toJSONObject(JSONArray names) throws JSONException {
if (names == null || names.length() == 0 || length() == 0) {
return null;
}
JSONObject jo = new JSONObject();
for (int i = 0; i < names.length(); i += 1) {
jo.put(names.getString(i), this.opt(i));
}
return jo;
} |
c9225953-4e89-4f39-a8e2-9bbeb6fd23e7 | 8 | public static void main(String[] args) {
final String home = "/Users/Dean/Documents/workspace/Intel/GCJ/googlecodejam/";
final String input = home + "AlienLanguage/io/A-large-practice.in";
final String output = home + "AlienLanguage/io/A-large-practice.out";
try {
Scanner sc = new Scanner(new FileReader(input));
PrintWriter pw = new PrintWriter(output);
String[] vals = sc.nextLine().split(" ");
int l = Integer.valueOf(vals[0]), d = Integer.valueOf(vals[1]), n = Integer.valueOf(vals[2]);
Set<String> dict = new HashSet<>();
for(int i = 0; i < d; i++) {
dict.add(sc.nextLine());
}
for(int j = 0; j < n; j++) {
char[] line = sc.nextLine().toCharArray();
StringBuffer sb = new StringBuffer();
sb.append('^');
for(char c : line) {
if(c == '(') sb.append('[');
else if(c == ')') sb.append(']');
else sb.append(c);
}
sb.append('$');
int matches = 0;
Pattern pattern = Pattern.compile(sb.toString());
for(String s : dict) {
if(pattern.matcher(s).matches()) matches++;
}
pw.write("Case #" + (j+1) + ": " + matches + "\n");
}
pw.flush();
pw.close();
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} |
35fc6479-d32c-4ae0-9a1a-734676501ee1 | 3 | private int getRealisticByteModification(int fileSize, ModificationPart part) {
int byteStart;
switch(part) {
case B:
byteStart = 0;
break;
case E:
byteStart = -1;
break;
case M:
default:
int offset = (int)(fileSize*0.1F);
int start = offset;
int end = fileSize-offset;
byteStart = start + random.nextInt(end - start + 1);
break;
}
return byteStart;
} |
09bfe047-2748-4281-91bf-993816b82056 | 6 | public static void main(String[] args) {
String input = JOptionPane.showInputDialog("Input the chickens' quantity");
double n = Double.parseDouble(input);
// checking of the right chicken quantity's input
while (n <= 0 || n%(int)n>0){
input = JOptionPane.showInputDialog("Uncorrect input! \nTry again please!");
n = Double.parseDouble(input);
}
input = JOptionPane.showInputDialog("N = " + (int)n + " chickens\n"
+ "Input the chicken's cost");
double m = Double.parseDouble(input);
// checking of the right price input
while (m <= 0){
input = JOptionPane.showInputDialog("N = " + (int)n + " chickens\n"
+ "Uncorrect input! \nTry again please!");
m = Double.parseDouble(input);
}
input = JOptionPane.showInputDialog("N = " + (int)n + " chickens\n"
+ "M = " + m + "$ for 1 chicken\n"
+ "Input the the eggs' quantity per week");
double x = Double.parseDouble(input);
// checking of the right quantity's input
while (x <= 0 || x%(int)x>0){
input = JOptionPane.showInputDialog("N = " + (int)n + " chickens\n"
+ "M = " + m + "$ for 1 chicken\n"
+ "Uncorrect input! \nTry again please!");
x = Double.parseDouble(input);
}
input = JOptionPane.showInputDialog("N = " + (int)n + " chickens\n"
+ "M = " + m + "$ for 1 chicken\n"
+ "X = " + (int)x + " eggs make 1 chick per week\n"
+ "Input the price for 10 eggs");
double z = Double.parseDouble(input);
// checking of the right price input
while (z <= 0){
input = JOptionPane.showInputDialog("N = " + (int)n + " chickens\n"
+ "M = " + m + "$ for 1 chicken\n"
+ "X = " + (int)x + " eggs make 1 chick per week\n"
+ "Uncorrect input! \nTry again please!");
z = Double.parseDouble(input);
}
// breakeven point calculating and showing
JOptionPane.showMessageDialog(null,"N = " + (int)n + " chickens\n"
+ "M = " + m + "$ for 1 chicken\n"
+ "X = " + (int)x + " eggs make 1 chick per week\n"
+ "Z = " + z + " $ for 10 eggs"
+"\n\n" + "You need "+Math.round(m*n/(n*x/7*z/10))+" days for cover your outlay.");
} |
5faeb35e-8c43-4405-9ff8-186693658d04 | 2 | public void setLength(int length) {
if( (length < 1) || (length > MAX_NMER_SIZE) ) throw new RuntimeException("Nmer max length must be between 1 and " + coder.basesPerWord());
this.length = length;
} |
4ab56c51-3afc-42c2-be99-e257dada5d84 | 9 | public static boolean iterate() {
boolean didFind = false;
for(int i=0; i<n; i++) {
// update what Company i owns
int[] cOwn = new int[n];
for(int j=0; j<n; j++) {
int test = ownership[i][j];
if(test >= 50 && test != 100) {
test = 100;
didFind = true;
}
cOwn[j] = test;
if(test==100 && (j!=i && used[i][j]==false)) {
for(int k=0; k<n; k++) {
ownership[i][k] = Math.min(100, ownership[i][k] + ownership[j][k]);
if(ownership[i][k]==100) {
didFind = true;
}
}
used[i][j] = true;
}
}
}
return didFind;
} |
5e7203db-6def-43d7-a85b-4c4f893973d0 | 7 | public String longestPrefixOf(String s) {
if (s == null || s.length() == 0)
return null;
int length = 0;
Node x = root;
int i = 0;
while (x != null && i < s.length()) {
char c = s.charAt(i);
if (c < x.c)
x = x.left;
else if (c > x.c)
x = x.right;
else {
i++;
if (x.val != null)
length = i;
x = x.mid;
}
}
return s.substring(0, length);
} |
80524cf3-d7e9-4ae8-b700-3c57b34e0ade | 2 | private void putText (Graphics2D g2d, String t, int i) {
Integer fWidth = MainWindow.setupData.getPrintElementSetupList().getPrintElementSetup (i).getFieldWidth();
Font font = MainWindow.setupData.getPrintElementSetupList().getPrintElementSetup (i).getPrintFont();
Integer fontSize = font.getSize();
Integer minFontSize = fontSize / 2;
g2d.setFont(font);
while ((fWidth < g2d.getFontMetrics().getStringBounds(t, g2d).getWidth()) &&
( fontSize > minFontSize )) {
fontSize = fontSize -1;
g2d.setFont(font.deriveFont((float)fontSize));
}
g2d.setColor(MainWindow.setupData.getPrintElementSetupList().getPrintElementSetup (i).getPrintColor());
Point a = MainWindow.setupData.getPrintElementSetupList().getPrintElementSetup (i).getAnchorPoint();
g2d.drawString(t, a.x, a.y);
} |
3aa7acff-6cda-4cbe-b7bb-6ad284253943 | 7 | @Override
public void doPost(HttpServletRequest req, HttpServletResponse res){
session = req.getSession(true);
sc=getServletContext();
if(!req.getParameter("naziv").equals("")){
naziv=req.getParameter("naziv");
}
else{
prazno = true;
greska = "Ime proizvoda nije uneto.<br>";
proslediGresku(greska,req,res);
greska="";
}
if(!req.getParameter("opis").equals("")){
opis=req.getParameter("opis");
}
else{
prazno = true;
greska = "Opis nije prosleđen.<br>";
proslediGresku(greska,req,res);
greska="";
}
if(!req.getParameter("kolicina").equals("")){
kolicina=Integer.parseInt(req.getParameter("kolicina"));
}
else{
prazno = true;
greska = "Kolicina nije prosleđena.<br>";
proslediGresku(greska,req,res);
greska="";
}
if(!req.getParameter("cena").equals("")){
cena=Double.parseDouble(req.getParameter("cena"));
}
else{
prazno = true;
greska = "Cena nije prosleđena.<br>";
proslediGresku(greska,req,res);
greska="";
}
// if(!req.getParameter("datumPoslednjeIzmene").equals("")){
// datumPoslednjeIzmene=req.getParameter("datumPoslednjeIzmene");
// }
// else{
// prazno = true;
// greska = "Datum poslednje izmene nije prosleđen.<br>";
// proslediGresku(greska,req,res);
// greska="";
// }
//
// if(!req.getParameter("adminPoslednjeIzmene").equals("")){
// adminPoslednjeIzmene = req.getParameter("adminPoslednjeIzmene");
// }
// else{
// prazno = true;
// greska = "Naziv administratorske izmene nije prosledjen.<br>";
// proslediGresku(greska,req,res);
// greska="";
// }
if(!req.getParameter("slika").equals("")){
slika=req.getParameter("slika");
}
else{
prazno = true;
greska = "Slika proizvoda nije prosledjena.<br>";
proslediGresku(greska,req,res);
greska="";
}
try {
if(!prazno){
izvrsi(req,res);
pozoviJSP(req,res);
}else{
throw new Exception();
}
}
catch (Exception e){
greska="Doslo je do greske! Pokusajte ponovo!";
proslediGresku(greska, req, res);
greska="";
}
} |
31574281-f78f-4c9d-9485-0ac0e472a170 | 3 | private void printTable() throws SQLException {
rs = st.executeQuery("SELECT * FROM products");
ResultSetMetaData rsMetaData = rs.getMetaData();
System.out.print("Row\t|\t");
for (int i = 0; i < rsMetaData.getColumnCount(); i++) {
System.out.print(rsMetaData.getColumnName(i + 1) + "\t|\t");
}
System.out.println();
if (rs == null) {
System.out.println("Null resultset");
return;
}
while (rs.next()) {
System.out.println(rs.getRow() + ".\t|\t" + rs.getInt(1) + "\t|\t" + rs.getString(2)+ "\t\t|");
}
System.out.println("_________________________");
} |
cd79ca81-eb34-4fd8-9a6e-5e297b8432c4 | 6 | public static byte[] readBytes(final InputStream ins) throws IOException {
if (null == ins) throw new IllegalArgumentException("input stream is null");
byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
BufferedInputStream in = null;
ByteArrayOutputStream baos = null;
in = new BufferedInputStream(ins, BUFFER_SIZE);
baos = new ByteArrayOutputStream();
try {
while ((len = in.read(buffer)) > 0) {
baos.write(buffer, 0, len);
}
return baos.toByteArray();
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException(e);
} finally {
if (null != in) {
in.close();
in = null;
}
if (null != baos) {
baos.close();
baos = null;
}
}
} |
7882dec4-8fcf-4343-bb6a-42883d148b19 | 2 | private Object handleStruct(Object tag, int fields) throws IOException {
ReadHandler h = lookup(handlerLookup, tag);
if (h == null)
h = (ReadHandler) standardExtensionHandlers.get(tag);
if (h == null)
return new TaggedObject(tag, readObjects(fields));
else
return h.read(this, tag, fields);
} |
6bb00e41-ea47-412b-9e7d-f01652f611a2 | 4 | public void insertChild(IXMLElement child,
int index) {
if (child == null) {
throw new IllegalArgumentException("child must not be null");
}
if ((child.getName() == null) && (! this.children.isEmpty())) {
IXMLElement lastChild = (IXMLElement) this.children.get(this.children.size() - 1);
if (lastChild.getName() == null) {
lastChild.setContent(lastChild.getContent()
+ child.getContent());
return;
}
}
((XMLElement) child).parent = this;
this.children.add(index, child);
} |
be76f4a0-3ad2-4c8f-b9a1-33d8652b2ca7 | 7 | public final void parseDoc(Document doc) {
if (doc == null) {
throw new IllegalArgumentException("Xml document cannot be null");
}
Element elem = (Element) doc.getElementsByTagName("KeyedFile").item(0);
fileName = elem.getAttribute("path");
if (fileName == null || "".equals(fileName)) {
throw new RuntimeException("Keyed File name cannot be empty");
}
keyLength = Integer.parseInt(elem.getAttribute("keySize"));
if (keyLength <= 0) {
throw new RuntimeException("Key length must be a positive integer");
}
recordSize = Integer.parseInt(elem.getAttribute("recordSize"));
if (recordSize <= 0) {
throw new RuntimeException("Record size must be a positive integer");
}
Node parent = doc.getElementsByTagName("DefaultRecord").item(0);
NodeList xFields = doc.getElementsByTagName("Field");
int n = xFields.getLength();
ArrayList al = new ArrayList(n);
KFileField kff;
for (int k = 0; k < n; k++) {
elem = (Element) xFields.item(k);
if (elem.getParentNode().equals(parent))
{
kff = new KFileField();
kff.name = elem.getAttribute("name");
kff.start = Integer.parseInt(elem.getAttribute("position"));
kff.size = Integer.parseInt(elem.getAttribute("size"));
kff.end = kff.start + kff.size;
kff.type = elem.getAttribute("type");
al.add(kff);
kff = null;
}
}
Collections.sort(al);
fields = new KFileField[al.size()];
al.toArray(fields);
} |
5590de3c-dfc1-4623-8f7c-789a9a07a19c | 5 | public String CallCropModel(String filename,String pathname,String DistrictID, String Crop)
{ String CropOutput = "0";
try{
Properties properties = new Properties();
// Read the properties file
File file = new File("Data/2011-07-21/188");
//File file = new File("Data/"+pathname+"/"+DistrictID);
//Process p1=Runtime.getRuntime().exec("./DSSATCSM40 D Mo-23.5-73.5-0-SandyClLoam.INP",null,file);
//Process p1=Runtime.getRuntime().exec("./DSSATCSM40 D Mo-23.5-73.5-0-SandyLoam.INP",null,file);
Process p1=Runtime.getRuntime().exec("./DSSATCSM40 D "+filename,null,file);
p1.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(p1.getInputStream()));
String line=reader.readLine();
while(line!=null) {
//System.out.println(line);
if(line.contains("YIELD"))
{
System.out.println(line);
//System.out.println(line.substring(39,43));
CropOutput = line.substring(39,43);
}
//else
//CropOutput = "0";
//CropYeild.concat(line);
//if(line.contains("Invalid format in file.")) return "Error";
//if(line.contains("End-of-file encountered in input file.")) return "Error";
line=reader.readLine();
//System.out.println(CropYeild);
}
}
catch(IOException e1) {return null;}
catch(InterruptedException e2) {System.out.println(e2);}
catch(Exception e) {System.out.println(e);}
//System.out.println("Done");
return CropOutput;
} |
0ac20c42-4b01-4060-aa86-10e139fa0312 | 7 | private void instanceMain(String[] args) {
if (args.length < 1) {
usage("Must specify at least one directory.");
}
int directoryCount = 0;
for (int i = 0; i < args.length; i++) {
if (args[i].startsWith("-")) {
if (args[i].equalsIgnoreCase("-components")) {
if (args.length <= i + 1) {
usage("Components not specified.");
}
setComponents(args[++i]);
} else {
usage("Invalid argument: " + args[i]);
}
} else {
try {
addDirectory(args[i]);
directoryCount++;
} catch (IOException ioe) {
usage("Directory does not exist: " + args[i]);
}
}
}
if (directoryCount == 0) {
usage("Must specify at least one directory.");
}
analyze();
} |
c821def2-9420-4913-b9fd-2d55576eaed6 | 4 | @Override
public void display(UserInterface ui) {
if (!variablesWithNewValues.isEmpty()) {
UserInterface.print("New values were set for variables: ");
for (String v : variablesWithNewValues.keySet()) {
UserInterface.print(v + " ");
}
UserInterface.println("");
}
UserInterface.println("Local variables:");
int i = 0;
for (String v : variablesWithOffsets.keySet()) {
UserInterface.print(" " + v);
for (int j = 0; j < 30 - v.length(); j++) {
UserInterface.print(" ");
}
UserInterface.println(variableValues.get(i++));
}
UserInterface.println("");
} |
beb4e589-c921-4fe2-8f9c-65ad6a6661d1 | 3 | public void addContacts(List<EzimContact> lIn)
{
if (this.contacts != null)
{
synchronized(this.contacts)
{
for(EzimContact ecTmp: lIn)
{
if (! this.contacts.contains(ecTmp))
{
this.contacts.add(ecTmp);
}
}
}
this.updateContactNames();
}
} |
5c3550da-f999-48f9-a23f-a2dec8e07153 | 0 | public int getSequence() {
return this._sequence;
} |
2e31c4cd-e058-4838-a6b4-b9bebe44697a | 8 | boolean handleMouseMoved(int x, int y) {
if (selectedComponent instanceof LineComponent) {
if (((LineComponent) selectedComponent).nearEndPoint(x, y) > 0) {
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
return true;
}
} else if (selectedComponent instanceof RectangleComponent) {
if (Draw.selectHandleCursorForRectangularShape(this, ((RectangleComponent) selectedComponent).nearHandle(x, y)))
return true;
} else if (selectedComponent instanceof EllipseComponent) {
if (Draw.selectHandleCursorForRectangularShape(this, ((EllipseComponent) selectedComponent).nearHandle(x, y)))
return true;
} else if (selectedComponent instanceof TriangleComponent) {
if (((TriangleComponent) selectedComponent).nearHandle(x, y) != -1) {
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
return true;
}
}
setCursor(UserAction.getCursor(actionID));
return false;
} |
9fcb6446-e949-4048-b21d-45612d5b9974 | 1 | @Test
public void test_empty_num_when_in_thirty_three_car() {
for(int i = 0; i < 33; i ++) {
manager.in(new Car(String.valueOf(i)));
Assert.assertEquals(manager.getEmptyNum(), 33 - i - 1);
}
} |
20111ea3-98f8-4769-9b5b-a2c5f7e80a3e | 9 | private boolean checkAndLogin() throws Exception{
if(qq == -1 || pwd == null)
throw new IllegalArgumentException("qq和密码不能为空");
String checkIdUrl = "http://ptlogin2.qq.com/check?appid=1003903&uin="+qq;
String res = getUrl(checkIdUrl);
//ptui_checkVC('0','!ZLE');返回这个就不需要获取验证码了。验证码就是!ZLE
//ptui_checkVC('1','95ab7db15e5ab17f50f25d33598259e83ccc098c4af2f8a4');这个长字符串就需要使用了
Pattern p = Pattern. compile("\\,\\'([!\\w]+)\\'");
Matcher m = p. matcher(res);
String checkType = "";
if(m.find()){
checkType = m.group(1);
}
String check = "";
if(!checkType.startsWith("!")){
//需要输入验证码
String getCheckImageUrl = "http://captcha.qq.com/getimage?aid=1003903&uin="+qq+"&vc_type="+checkType;
String file = readCheckImage(getCheckImageUrl);
log("请打开"+file+",并且在这里输入其中的字符串,然后回车:");
InputStreamReader ins = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ins);
check = br.readLine();
}else{
//不需要输入验证码
check = checkType;
}
//开始登陆
String loginUrl = "http://ptlogin2.qq.com/login?u="+qq+"&" +
"p=" +mdP(pwd, check)+
"&verifycode="+check+"&remember_uin=1&aid=1003903" +
"&u1=http%3A%2F%2Fweb2.qq.com%2Floginproxy.html%3Fstrong%3Dtrue" +
"&h=1&ptredirect=0&ptlang=2052&from_ui=1&pttype=1&dumy=&fp=loginerroralert";
res = getUrl(loginUrl);
// ptuiCB('0','0','http://web2.qq.com/loginproxy.html?strong=true','0','登录成功!');
// ptuiCB('4','0','','0','您输入的验证码有误,请重试。');
p = Pattern.compile("登录成功!");//提取最后一个字符串,看看是不是 登录成功!
m = p. matcher(res);
if(m.find()){
log("登陆成功");
}else{
//登陆失败
log(checkType);
return false;
}
//从cookie中提取ptwebqq,skey
p = Pattern.compile("ptwebqq=(\\w+);");
m = p.matcher(cookie);
if(m.find()){
ptwebqq = m.group(1);
}
p = Pattern.compile("skey=(@\\w+);");
m = p.matcher(cookie);
if(m.find()){
skey = m.group(1);
}
log("ptwebqq="+ptwebqq+",skey="+skey);
//再次登陆,只有这次登陆,才算真正登陆qq,这个时候,如果你qq已经登陆,会把你的qq踢下线,而且此次登陆才算上线。
String channelLoginUrl = "http://web2-b.qq.com/channel/login";
String content = "{\"status\":\"\",\"ptwebqq\":\""+ptwebqq+"\",\"passwd_sig\":\"\",\"clientid\":\""+clientid+"\"}";
content = URLEncoder.encode(content);//urlencode
content = "r="+content;//post的数据
res = postUrl(channelLoginUrl, content);//post
//这次登陆基本上不会发生什么问题
//下面提取很重要的2个数据psessionid ,vwebqq,通用采用正则表达式,虽然结果是个json
p = Pattern.compile("\"vfwebqq\":\"(\\w+)\"");
m = p.matcher(res);
if(m.find()){
vfwebqq = m.group(1);
}
p = Pattern.compile("\"psessionid\":\"(\\w+)\"");
m = p.matcher(res);
if(m.find()){
psessionid = m.group(1);
}
log("vwebqq="+vfwebqq+","+"psessionid="+psessionid);
//到此,登陆就算完成了,后面可以调用发送qq信息等接口了
return true;
} |
211feaa6-4709-470c-8bc4-cdf1ddbbc553 | 7 | @Override
public int loop() {
try {
if (Game.getClientState() != Game.INDEX_MAP_LOADED) {
return 1000;
}
if (client != Bot.client()) {
WidgetCache.purge();
Bot.context().getEventManager().addListener(this);
client = Bot.client();
}
if (Game.isLoggedIn()) {
for (Node node : jobsCollection) {
if (node!= null && node.activate()) {
node.execute();
return Random.nextInt(50, 100);
}
}
}
return Random.nextInt(50, 100);
} catch (NullPointerException e) {
e.printStackTrace();
}
return Random.nextInt(50, 100);
} |
fba5b806-f6fe-4710-bede-19bf72bac325 | 3 | private static NodeWith2Ptr deepCopy(NodeWith2Ptr n){
HashMap<NodeWith2Ptr, NodeWith2Ptr> m = new HashMap<NodeWith2Ptr, NodeWith2Ptr>();
NodeWith2Ptr h = null;
NodeWith2Ptr curr = h;
while(n!=null){
if(h==null){
h = new NodeWith2Ptr(n.v);
h.arbitrary = n.arbitrary;
curr = h;
} else {
curr.next = new NodeWith2Ptr(n.v);
curr.next.arbitrary = n.arbitrary;
curr = curr.next;
}
m.put(n, curr);
n=n.next;
}
curr = h;
while(curr!=null){
curr.arbitrary = m.get(curr.arbitrary);
curr = curr.next;
}
return h;
} |
a4d53b01-a405-40df-b698-ae810ed80c5d | 6 | public static weighted readMyFile(String FileName){
System.out.println("BEGIN READ FILE");
weighted w = null;
String record = null;
String recordArray [] = null;
String linesplit = " ";
try {
FileReader dataSize = new FileReader(FileName);
BufferedReader LineCounterBuffer = new BufferedReader(dataSize);
w = new weighted(0);
int size = -1;
int counter = 0;
// Find File Size
//int FileLength = 0;
//while ((record = LineCounterBuffer.readLine()) != null) {
// FileLength++;
// }
//System.out.println("File Size is: " + FileLength + " Lines Long.");
//Using the FileLenght Create an Array to hold the subjects.
//int objects[][] = new int[FileLength][FileLength];
// Read File Into Student [] Array.
FileReader Subjectdata = new FileReader("paths.txt");
BufferedReader SubjectReadBuffer = new BufferedReader(Subjectdata);
record = new String();
// File Length is looped to each array placement.
//FileLength = 0;
while ((record = SubjectReadBuffer.readLine()) != null) {
// Read and split the lines and insert them as required
recordArray = record.split(linesplit);
//for (int i = 0; i < recordArray.length; i++){
if (size == -1){
size = Integer.parseInt(recordArray[0]);
//System.out.println(recordArray[i]);
w = new weighted(size);
}else if (size >= 0 && counter < size){
System.out.println(recordArray[0]);
System.out.println(recordArray[1]);
System.out.println(recordArray[2]);
w.addEdge(Integer.parseInt(recordArray[0]), Integer.parseInt(recordArray[1]), Integer.parseInt(recordArray[2]), true);
counter ++;
}else if (counter == size){
loadnamestxt(w,recordArray[0]);
}
//}
}
// After this while loop all Subjects are loaded correctly into the global method.
LineCounterBuffer.close();
SubjectReadBuffer.close();
} catch (IOException e){
// catch possible io errors from readLine()
System.out.println("File not Found.");
e.printStackTrace();
}
return w;
} |
74915e80-5b3a-474d-9806-3a9a34ab42c3 | 1 | public int validateAndConvert() throws ValidointiPoikkeus {
ValidointiVirheet virheet = new ValidointiVirheet();
Validator validoija = new Validator();
validoija.validateInt(vuosistr, "vuosi", "Vuosi", true, false);
if (validoija.getVirheet().size() > 0) {
virheet = validoija.getVirheet();
throw new ValidointiPoikkeus(virheet);
}
else {
int vuosi = Integer.parseInt(vuosistr) ;
return vuosi;
}
} |
e418c4fc-35e0-4b2b-87e4-371365a9e605 | 4 | private void lisaaButtonActionPerformed(ActionEvent evt) {
if (!ryhmaField.getText().isEmpty()) {
if (ryhmaField.getText().length() > 30) {
JOptionPane.showMessageDialog(this, "Ryhmän nimi voi olla enintään 30 merkkiä pitkä.", "Virhe", JOptionPane.ERROR_MESSAGE);
} else {
Ryhma uusiRyhma = new Ryhma(ryhmaField.getText());
if (Database.lisaaRyhma(uusiRyhma)) {
ryhmaField.setText("");
}
}
} else if (ryhmaField.getText().isEmpty()) {
JOptionPane.showMessageDialog(this, "Ryhmän nimi ei voi olla tyhjä.", "Taktinen Virhe", JOptionPane.ERROR_MESSAGE);
} else {
String message = "Tapahtui vakava tuntematon virhe!\n" + "Ottakaa välittömästi yhteys tirehtööriin!\n" + "Sähköposti: Henry.Heikkinen@majavapaja.fi";
JOptionPane.showMessageDialog(this, message, "Error #???", JOptionPane.ERROR_MESSAGE);
}
} |
3261a990-90c0-4fe3-8350-c0091e2e2302 | 9 | public void writePointRdfModel(String specs) throws UnsupportedEncodingException, FileNotFoundException
{
FeatureIterator iterator = featureCollection.features();
int position = 0;
long t_start = System.currentTimeMillis();
long dt = 0;
try
{
System.out.println(UtilsLib.getGMTime() + " Started processing features...");
while(iterator.hasNext()) {
SimpleFeatureImpl feature = (SimpleFeatureImpl) iterator.next();
Geometry geometry = (Geometry) feature.getDefaultGeometry();
//Attempt to transform geometry into the target CRS
if (transform != null)
try {
geometry = JTS.transform(geometry, transform);
} catch (Exception e) {
e.printStackTrace();
}
String featureAttribute = "featureWithoutID";
//Process non-spatial attributes for name and type
handleNonGeometricAttributes(feature);
if (feature.getAttribute(configuration.attribute) != null) {
featureAttribute = feature.getAttribute(configuration.attribute).toString();
}
if (!featureAttribute.equals(configuration.ignore))
{
String encodingType =
URLEncoder.encode(configuration.type,
UtilsConstants.UTF_8).replace(STRING_TO_REPLACE,
REPLACEMENT);
String encodingResource =
URLEncoder.encode(featureAttribute,
UtilsConstants.UTF_8).replace(STRING_TO_REPLACE,
REPLACEMENT);
String aux = encodingType + SEPARATOR + encodingResource;
//Type according to application schema
insertResourceTypeResource(
configuration.nsUri + aux,
configuration.nsUri + URLEncoder.encode(
configuration.type, UtilsConstants.UTF_8).replace(
STRING_TO_REPLACE, REPLACEMENT));
//Label using the given attribute (usually an id)
insertLabelResource(configuration.nsUri + aux,
featureAttribute, configuration.defaultLang);
//Point geometries ONLY
if (geometry.getGeometryType().equals(Constants.POINT))
{
if (specs.equals("Virtuoso"))
insertVirtuosoPoint(aux, geometry);
else if (specs.equals("wgs84_pos"))
insertWGS84Point(aux, geometry);
}
} else {
LOG.log(Level.INFO, "writeRdfModel: Not processing feature attribute in position {0}", position);
}
if (position%1000 ==0)
System.out.print(UtilsLib.getGMTime() + " Processed " + position + " records..." + "\r");
++position;
}
}
finally {
iterator.close();
}
dt = System.currentTimeMillis() - t_start;
System.out.println(UtilsLib.getGMTime() + " Parsing completed for " + position + " records in " + dt + " ms.");
System.out.println(UtilsLib.getGMTime() + " Starting to write triplets to file...");
//Count the number of statements
long numStmt = model.listStatements().toSet().size();
//Export model to a suitable format
FileOutputStream out = new FileOutputStream(configuration.outputFile);
model.write(out, configuration.outFormat);
dt = System.currentTimeMillis() - t_start;
System.out.println(UtilsLib.getGMTime() + " Process concluded in " + dt + " ms. " + numStmt + " triples successfully exported to " + configuration.outFormat + " file: " + configuration.outputFile + ".");
} |
e3a785e6-e0a9-4f30-9187-866e63157c80 | 1 | @RequestMapping(value = "/init", method = RequestMethod.GET)
public String init(ModelMap model) {
if (studentSystem == null) {
model.addAttribute("message",
"Error filling in data. studentSystem == null");
} else {
int john = studentSystem.addStudent("John McClane");
int jane = studentSystem.addStudent("Jane Fonda");
int inf5750 = studentSystem.addCourse("INF5750",
"Open Source Development");
int inf5761 = studentSystem.addCourse("INF5761",
"Health management information systems");
int master = studentSystem.addDegree("Master");
int bachelor = studentSystem.addDegree("Bachelor");
int phd = studentSystem.addDegree("PhD");
studentSystem.addAttendantToCourse(inf5750, john);
studentSystem.addAttendantToCourse(inf5750, jane);
studentSystem.addAttendantToCourse(inf5761, john);
studentSystem.addAttendantToCourse(inf5761, jane);
studentSystem.addRequiredCourseToDegree(master, inf5761);
model.addAttribute("message", "Filled in data OK");
}
model.addAttribute("message", "Filling in data");
populateModel(model);
return "index";
} |
f54b7bee-71af-4523-a118-0d3f4b780639 | 3 | protected static short[][] unpackFromStrings(String[] sa)
{
// Concatanate initialization strings.
StringBuffer sb = new StringBuffer(sa[0]);
for (int i=1; i<sa.length; i++)
sb.append(sa[i]);
int n=0; // location in initialization string
int size1 = (((int)sb.charAt(n))<<16) | ((int)sb.charAt(n+1)); n+=2;
short[][] result = new short[size1][];
for (int i=0; i<size1; i++) {
int size2 = (((int)sb.charAt(n))<<16) | ((int)sb.charAt(n+1)); n+=2;
result[i] = new short[size2];
for (int j=0; j<size2; j++)
result[i][j] = (short) (sb.charAt(n++)-2);
}
return result;
} |
5538f6cc-5b73-4c02-9745-40d7b52336d6 | 1 | private void textNameKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textNameKeyPressed
int key = evt.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
saveFormtoState();
}
}//GEN-LAST:event_textNameKeyPressed |
173ea4e6-343f-4137-ba62-a0af9b536004 | 7 | @Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(view.getInputText())){
view.getResults().clear();
try{
search(view.getInputText().getText());
}
catch(NullPointerException n){
JOptionPane.showMessageDialog(view, "No Concerts found");
}
}
else if(e.getActionCommand().equals("attend")){
if(view.getResultList().getSelectedValue()==null){
JOptionPane.showMessageDialog(view, "No Concert selected");
}else{
GeoEvent event = (GeoEvent)view.getResultList().getSelectedValue();
attend(event.getEventUrl());
}
}
else if(e.getActionCommand().equals("attended")){
getAttended();
}
else if(e.getActionCommand().equals("recommend")){
updateRecomendations();
}
else if(e.getActionCommand().equals("getRecArtist")){
placeGeoElementOnScreen(eventList.get(indexForList));
}
} |
95aa89ec-cc22-49b3-90a2-fce6ed176b19 | 2 | public void run()
{
while (true)
{
try
{
repaint();
Thread.sleep(30);
}
catch (InterruptedException ie)
{
stop();
}
}
} |
3f0622e8-c00f-40a6-870c-f5b4d073f237 | 3 | public void setRefreshing(boolean refreshing) {
if(refreshJob == null) {
refreshJob = new RefreshJob();
}
boolean prev = isRefreshing;
isRefreshing = refreshing;
if(refreshing && !prev) {
Thread t = new Thread(refreshJob);
t.start();
}
} |
f41ece06-7ca5-4547-a9d9-68e61fff66d3 | 5 | @Override
public void play(long currentTime) {
super.play(currentTime);
if (drawRequest) {
this.drawCard();
drawRequest = false;
}
if (playRequest != null) {
if (eightSuiteRequest >= 0 && playRequest.value == Card.EIGHT) {
this.playEight(playRequest, eightSuiteRequest);
eightSuiteRequest = -1;
}
else {
this.playCard(playRequest);
}
playRequest = null;
}
if (endTurnRequest) {
this.endPlay();
endTurnRequest = false;
}
} |
96b04468-9906-4f19-b4a2-403109aa7ada | 1 | @Override
public ArrayList<String> getCategories() {
System.out.println("Hello from SessionBean getCategories");
ArrayList<String> categories = new ArrayList<String>();
List<Category> obtainedCategories = (List<Category>) emgr.createNamedQuery("Category.findAll", Category.class).getResultList();
for (int i = 0; i < obtainedCategories.size(); i++) {
categories.add(obtainedCategories.get(i).getCategoryName());
System.out.println("Current ArrayList of categories = " + categories);
}
return categories;
} |
3eabecf0-e69e-493d-9f78-da1b87caa02c | 7 | public void compFinalResult() {
do {
iStage++;
compAllocation();
if (compDistribution()) {
/* deadline can not be satisfied */
if (!bDeadline) {
System.out.println("THE DEADLINE CAN NOT BE SATISFIED!");
return;
} else {
System.out.println("\nNEW ROUND WITHOUT CHECKING:");
dEval = 1;
}
} else {
compExecTime();
}
// System.out.println("Evaluation Value =========="+dEval);
} while (dEval > 0);
// while (evaluateResults());
// System.out.println("==================Distribution=====================");
for (int i = 0; i < iClass; i++) {
// System.out.print("FinalDistribution[" + i + "] ");
for (int j = 0; j < iSite; j++) {
dmDist[i][j] = Math.round(dmDist[i][j]);
// System.out.print(dmDistribution[i][j] + ",");
}
// System.out.println();
}
// System.out.println("==================Allocation=====================");
for (int i = 0; i < iClass; i++) {
System.out.print("FinalAllocation[" + i + "] ");
for (int j = 0; j < iSite; j++) {
dmAlloc[i][j] = Math.round(dmAlloc[i][j]);
// System.out.print(dmAllocation[i][j] + ",");
}
// System.out.println();
}
// System.out.println("Stage = " + iStage);
} |
f494550c-d07d-4f82-a830-e1cf9139abc1 | 6 | public void startStrategy() throws Exception {
//get the instance of the IClient interface
final ITesterClient client = TesterFactory.getDefaultInstance();
//set the listener that will receive system events
client.setSystemListener(new ISystemListener() {
@Override
public void onStart(long processId) {
LOGGER.info("Strategy started: " + processId);
updateButtons();
}
@Override
public void onStop(long processId) {
LOGGER.info("Strategy stopped: " + processId);
resetButtons();
// File reportFile = new File("C:\\report.html");
try {
// client.createReport(processId, reportFile);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
if (client.getStartedStrategies().size() == 0) {
//Do nothing
}
}
@Override
public void onConnect() {
LOGGER.info("Connected");
}
@Override
public void onDisconnect() {
//tester doesn't disconnect
}
});
LOGGER.info("Connecting...");
//connect to the server using jnlp, user name and password
//connection is needed for data downloading
client.connect(jnlpUrl, userName, password);
//wait for it to connect
int i = 10; //wait max ten seconds
while (i > 0 && !client.isConnected()) {
Thread.sleep(1000);
i--;
}
if (!client.isConnected()) {
LOGGER.error("Failed to connect Dukascopy servers");
System.exit(1);
}
//set instruments that will be used in testing
final Set<Instrument> instruments = new HashSet<Instrument>();
instruments.add(Instrument.EURUSD);
LOGGER.info("Subscribing instruments...");
client.setSubscribedInstruments(instruments);
//setting initial deposit
client.setInitialDeposit(Instrument.EURUSD.getSecondaryCurrency(), 50000);
//load data
LOGGER.info("Downloading data");
Future<?> future = client.downloadData(null);
//wait for downloading to complete
future.get();
//start the strategy
LOGGER.info("Starting strategy");
client.startStrategy(
new CopyOfRSI(),
new LoadingProgressListener() {
@Override
public void dataLoaded(long startTime, long endTime, long currentTime, String information) {
LOGGER.info(information);
}
@Override
public void loadingFinished(boolean allDataLoaded, long startTime, long endTime, long currentTime) {
}
@Override
public boolean stopJob() {
return false;
}
}, this, this
);
//now it's running
} |
2188cbad-ae0f-4f77-8e2a-b6a244cbcb6c | 1 | public void ajouterBut(String compteur, String equipe, int periode, long tempsPeriodeMs){
listeBut.add(new But(compteur, equipe, periode, tempsPeriodeMs));
if(equipe.equals(equipeD))
++butD;
else
++butV;
} |
9cf2c536-5bfd-4304-a77c-71c111f19fbe | 2 | private List<Integer> getSortedNodes(LinkedList[] graph){
List<Pair<Integer,Integer>> list= new ArrayList<Pair<Integer, Integer>>();
for(int i=0;i<graph.length;++i){
list.add(new Pair<Integer, Integer>(i,graph[i].size()));
}
Collections.sort(list, new Comparator<Pair<Integer, Integer>>() {
@Override
public int compare(Pair<Integer, Integer> o1, Pair<Integer, Integer> o2) {
return o1.getValue()-o2.getValue();
}
});
List<Integer> result=new ArrayList<Integer>();
for(Pair<Integer,Integer> pair: list){
result.add(pair.getKey());
}
return result;
} |
037c81dc-4e5b-43f1-8f42-42a7e63f13be | 7 | private JSONWriter append(String string) throws JSONException {
if (string == null) {
throw new JSONException("Null pointer");
}
if (this.mode == 'o' || this.mode == 'a') {
try {
if (this.comma && this.mode == 'a') {
this.writer.write(',');
}
this.writer.write(string);
} catch (IOException e) {
throw new JSONException(e);
}
if (this.mode == 'o') {
this.mode = 'k';
}
this.comma = true;
return this;
}
throw new JSONException("Value out of sequence.");
} |
c0711456-220a-43c8-9aad-90af97804937 | 7 | @Override
public int compare(OutputModel o1, OutputModel o2) {
long outputSumValue1 = o1.getSumValue();
long outputSumValue2 = o2.getSumValue();
long outputIndex1 = o1.getTargetIndex();
long outputIndex2 = o2.getTargetIndex();
if (outputSumValue1 > outputSumValue2)
{
return -1;
} else if ((outputSumValue1 == outputSumValue2) && (outputIndex1 < outputIndex2)) {
return -1;
}
else if ((outputSumValue1 == outputSumValue2) && (outputIndex1 == outputIndex2))
{
return 0;
} else if ((outputSumValue1 == outputSumValue2) && (outputIndex1 > outputIndex2)) {
return 1;
}
else {
return 1;
}
} |
b8822a2f-8cd1-494b-a83b-1f931f30c457 | 9 | private void jPAltConfirmaSenhaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPAltConfirmaSenhaKeyTyped
// TODO add your handling code here:
if (evt.getKeyChar() == KeyEvent.VK_ENTER){
if(evt.getSource() == jPAltConfirmaSenha){
String senha = jPAltSenha.getText().trim();
String confirmaSenha = jPAltConfirmaSenha.getText().trim();
String senhaDefinidaCrip = EncriptaSenha.encripta(senha).trim();
String senhaConfirmadaCrip = EncriptaSenha.encripta(confirmaSenha).trim();
if(!senha.equals("") && (!confirmaSenha.equals(""))){
if (senha.equals(confirmaSenha)){
Connection conn = null;
PreparedStatement stmt = null;
String updateSQL = "update usuario set senha = ? where username = ?";
try {
conn = GerenciaConexaoSQLServer.abreConexao();
stmt = conn.prepareStatement(updateSQL);
stmt.setString(1, senhaDefinidaCrip);
stmt.setString(2, this.usuario);
stmt.executeUpdate();
JOptionPane.showMessageDialog(this, "Senha alterada com sucesso!");
this.setVisible(false);
} catch (SQLException e) {
e.printStackTrace();
}catch(RuntimeException ex2){
JOptionPane.showMessageDialog(null, "Erro: "+ex2);
}finally{
try {
stmt.close();
conn.close();
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, "Erro ao alterar a senha do usuario. Mensagem: "+e);
}catch(RuntimeException e2){
JOptionPane.showMessageDialog(null, "Erro: "+e2);
}
}
}else{
JOptionPane.showMessageDialog(this, "Erro: As senhas digitadas sao diferentes!");
}
}
}
}
}//GEN-LAST:event_jPAltConfirmaSenhaKeyTyped |
60e1ec90-21a0-4c05-8abb-2a152f7b2465 | 4 | public void recursivePrint(LeftistTree tree, LeftistTreeNode node, int parentPosition, Node innerNode, Node p, int i) {
Node innerParent;
int position;
if (node != null) {
int height = tree.heightRootToNode(node);
int nextTop = getRectNextTop(height);
if (innerNode != null)
innerParent = innerNode;
else
innerParent = p;
if (node.parent.left != null && node.parent.left.equals(node)) {
position = getRectNextLeft(parentPosition, height);
innerNode = makeNode(node.value + "<br/>npl: " + tree.npl(node, -1), new Point(position, nextTop), Node.COLOR_LEFT, i);
} else {
position = getRectNextRight(parentPosition, height);
innerNode = makeNode(node.value + "<br/>npl: " + tree.npl(node, -1), new Point(position, nextTop), Node.COLOR_RIGHT, i);
}
innerNode.setParent(innerParent);
parentPosition = position;
// --
recursivePrint(tree, node.left, parentPosition, innerNode, p, i);
recursivePrint(tree, node.right, parentPosition, innerNode, p, i);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.