method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
c0729ba0-94d9-45a0-8dd0-b760bb3855b2
| 7
|
@Override
public byte[] pingMsdp(final Session session, final Map<Object,Object> reportables)
{
try
{
if(reportables.size()==0)
return null;
List<Object> broken=null;
synchronized(reportables)
{
Object newValue;
for(final Entry<Object,Object> e : reportables.entrySet())
{
newValue=getMsdpComparable(session, (MSDPVariable)e.getKey());
if(!e.getValue().equals(newValue))
{
reportables.put(e.getKey(),newValue);
if(broken==null)
broken=new LinkedList<Object>();
broken.add(e.getKey());
}
}
}
if(broken==null)
return null;
final ByteArrayOutputStream buf=new ByteArrayOutputStream();
buf.write(Session.TELNET_IAC);buf.write(Session.TELNET_SB);buf.write(Session.TELNET_MSDP);
for(final Object var : broken)
{
buf.write(processMsdpSend(session,var.toString()));
}
buf.write((char)Session.TELNET_IAC);buf.write((char)Session.TELNET_SE);
return buf.toByteArray();
}
catch(final IOException e)
{
return null;
}
}
|
5121fa5f-4202-4f28-8bd5-2b7c5f3738fd
| 5
|
public static void main(String[] args) {
int op = 0;
boolean exit = false;
do{
try{
Prints.printlnWithColor("GREEN","1- Login");
Prints.printlnWithColor("GREEN","2- Crear Usuario");
Prints.printlnWithColor("GREEN","3- Salir");
System.out.print("Seleccione: ");
op = rd.nextInt();
switch (op){
case 1:
//Llamar Login
login();
break;
case 2:
//Llamar CrearUsuario
break;
case 3:
exit = true;
break;
}
}catch (InputMismatchException e){
rd.next();
Prints.printlnWithColor("RED","Ingrese un numero\n");
}
}while(!exit);
}
|
b0f4f83b-cfad-41e1-98f5-aa845edd1d42
| 1
|
public static void main(String[] args) {
if (args.length > 0) {
CommandLineMode commandLineMode = new CommandLineMode(args[0],
new PlotterController());
} else {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
PlotterGUI gui = new PlotterGUI(new PlotterController());
gui.setVisible(true);
}
});
}
}
|
52ae126f-bed0-439e-aabb-0a436f3a2be7
| 4
|
public double distance(DatasetObject o_1, DatasetObject o_2)
{
int dist=0;
TreeMap q_knp=ros.kNearestReferenceObjects(o_1,ks);
Iterator q_iter=q_knp.keySet().iterator();
int q_p_pos=0;
while(q_iter.hasNext())
{
q_p_pos++;
Integer q_p=(Integer)q_knp.get(q_iter.next());
int obj_p_pos=0;
boolean found=false;
TreeMap knp=ros.kNearestReferenceObjects(o_2,ks);
Iterator obj_iter=knp.keySet().iterator();
while(obj_iter.hasNext()&&!found)
{
obj_p_pos++;
Integer obj_p=(Integer) knp.get(obj_iter.next());
if(obj_p.equals(q_p))
found=true;
}
dist+=java.lang.Math.abs(q_p_pos-obj_p_pos);
}
return dist;
}
|
72d6dc14-6ce2-4e5e-9da7-cb05eec76727
| 9
|
public boolean verifySquenceOfBST(int[] squence , int start , int end){
if(squence == null || end < start ){
throw new NullPointerException("Input is null.");
}
int root = squence[end];
int i = start ;
for(; i < end ; i++){
if(squence[i] > root){
break;
}
}
int j = i ;
for( ; j < end ; j++){
if(squence[j] < root)
return false;
}
boolean left = true;
if(i > start){
left = verifySquenceOfBST(squence, start, i-1);
}
boolean right = true;
if(i < end -1 ){
right = verifySquenceOfBST(squence, i, end-1);
}
return (left && right);
}
|
c2e0082a-33b0-47b5-83ec-b83b90334ba1
| 1
|
public void modifierVitesse(float c) {
if (c != vitesse) {
vitesse = c;
timer.cancel();
timer.purge();
timer = new Timer();
timer.scheduleAtFixedRate(new Timing(this), 0, (int) (50.0f / vitesseBase));
}
}
|
b1604123-a497-4969-99e0-00db885b2399
| 4
|
public void paint(Graphics g) {
super.paint(g);
LOGGER.info("Desenhando Cliente:\t" + cliente.toString() );
if (fase != null && cliente != null && cliente.getMario() != null && cliente.getLuigi() != null) {
g.drawImage(fase.getBackground(), 0,0, this);
g.drawImage(fase.getMarioDirImg(), cliente.getMario().getPosicao().getX(), cliente
.getMario().getPosicao().getY(), this);
g.drawImage(fase.getLuigiDirImg(), cliente.getLuigi().getPosicao().getX(), cliente
.getLuigi().getPosicao().getY(), this);
g.drawImage(fase.getEstrelaFinal(), 690, 336, this);
}
}
|
3cfd8374-b7f0-4876-b23a-d36f9c58bbeb
| 8
|
public ParseException generateParseException() {
jj_expentries.clear();
boolean[] la1tokens = new boolean[11];
if (jj_kind >= 0) {
la1tokens[jj_kind] = true;
jj_kind = -1;
}
for (int i = 0; i < 6; i++) {
if (jj_la1[i] == jj_gen) {
for (int j = 0; j < 32; j++) {
if ((jj_la1_0[i] & (1<<j)) != 0) {
la1tokens[j] = true;
}
}
}
}
for (int i = 0; i < 11; i++) {
if (la1tokens[i]) {
jj_expentry = new int[1];
jj_expentry[0] = i;
jj_expentries.add(jj_expentry);
}
}
int[][] exptokseq = new int[jj_expentries.size()][];
for (int i = 0; i < jj_expentries.size(); i++) {
exptokseq[i] = jj_expentries.get(i);
}
return new ParseException(token, exptokseq, tokenImage);
}
|
91e52d75-636a-4e91-a55b-fc739f431056
| 0
|
public void setCount(int value) {
this._count = value;
}
|
817a42cd-5b24-4dc7-9746-9d66c9e052ef
| 1
|
public Exponential(double lambda) throws ParameterException {
if (lambda <= 0) {
throw new ParameterException("Exponential parameter lambda > 0.");
} else {
this.lambda = lambda;
unif = new ContinuousUniform(0, 1);
}
}
|
d5cc9e3c-92c6-4271-9a43-f495dad3aa9c
| 0
|
public MyComparer(int rId, Settings settings)
{
_rId = rId;
MAX_WORDS_BETWEEN_RESULTS = settings.getCompareJumpLength();
NUM_WORDS_TO_COMPARE = settings.getCompareSentenceLength();
THRESHOLD = ((double) settings.getThreshold()) / 100;
}
|
8d1c7b81-1af1-428e-af6a-9cac207e55e8
| 2
|
@Override
public void performEmptyAction(GameObject gameObj) {
if(gameObj instanceof Unit) {
((Unit)gameObj).kill();
} else if(gameObj instanceof Building) {
((Building)gameObj).destroy();
}
}
|
b7c3cd00-64c5-4fc9-8c85-cf6d4cca0d22
| 4
|
public static String zeroString(String str, int size)
{
str = str == null ? "" : str.trim();
char[] ch = str.toCharArray();
int len = ch.length;
int lens = size - len;
if (lens <= 0) {
return str;
}
String rStr = "";
for (int i = 0; i < size; i++) {
if (lens > i) {
rStr = rStr + "0";
}
else
rStr = rStr + ch[(i - lens)];
}
return rStr;
}
|
8e06080c-fd25-4ce2-b625-557ed1bb1ac2
| 0
|
public void removeOldImagesIfNecessary() {
removeOldImagesIfDatabaseIsFull();
removeOldImagesAfter2DaysPeriod();
}
|
b6fb29a1-7de8-4504-9699-b5751b1adbce
| 0
|
@Override
public void init(ILogger logger, IRemoteServerConnection rsc) throws Exception {
synchronized (this) {
doInit(logger, rsc);
}
}
|
ed9b2371-f1ed-4469-be26-f9e62aa2212d
| 4
|
public void update(double time) {
Vector2d _location = new Vector2d(location.getX(), location.getY());
location.add(Vector2d.multiply(velocity, time));
if (Collision.isBulletIntersectingMap(this)) {
if (bounces <= 0) {
destroyed = true;
return;
}
bounces--;
location = _location;
Vector2d xIncrease = Vector2d.multiply(velocity, time);
xIncrease.setY(0);
location.add(xIncrease);
if (Collision.isBulletIntersectingMap(this)) {
velocity.setX(-velocity.getX());
}
location = _location;
Vector2d yIncrease = Vector2d.multiply(velocity, time);
xIncrease.setX(0);
location.add(yIncrease);
if (Collision.isBulletIntersectingMap(this)) {
velocity.setY(-velocity.getY());
}
location = _location;
}
}
|
7bdf9097-0810-4246-baa2-461b4e189820
| 3
|
public void setMasterVolume(float volume) {
// I know I that this may be 'overkill', but, i'd rather make the point
// in the logs that the volume control wasn't found for volume many
// times, to make it easier to find if it's gone wrong
if (volumeControl == null)
logger.error(new NullPointerException(), "Volume mixer null");
if (volume < 0 || volume > 1)
logger.error(new IllegalArgumentException(), "Percentage must be between 0 and 100");
masterVolume = volume;
// Open the port
volumeControl.setValue(volume);
logger.info("changed volume to ", volume);
}
|
9455f1b9-1d28-4752-9b3c-2336aac41258
| 5
|
public boolean start() {
if (doing) {
System.out.println("Server already runnning!");
return false;
}
if (ipaddress == null) {
Socket s;
try {
s = new Socket("google.com", 80);
ipaddress = (s.getLocalAddress().getHostAddress());
if (ipaddress == null) {
noInternet = true;
ipaddress = "None";
}
s.close();
}
catch (Throwable t) {
}
if (!noInternet)
Game.Settings.currentNetworkState = NetworkState.CONNECTED_TO_NETWORK_NO_INTERNET;
System.out.println("Your ip address is: " + ipaddress);
}
clientAddress = null;
doing = true;
self = new Thread(this);
self.start();
return true;
}
|
14e9b9e0-00dd-401c-90cb-09c8eafe0082
| 3
|
@Override
public String toString() {
String rval = "";
if(type.equalsIgnoreCase(TYPE_RECT)) {
rval = "Rectangle(x=" + rect.x +
", y=" + rect.y +
", width=" + rect.width +
", height=" + rect.height + ")";
}
else if(type.equalsIgnoreCase(TYPE_POLY)) {
rval = "Polygon(xpoints=" + Arrays.toString(poly.xpoints) +
", ypoints=" + Arrays.toString(poly.ypoints) +
", npoints=" + poly.npoints + ")";
}
else if (type.equalsIgnoreCase(TYPE_CIRCLE)) {
rval = "Circle(x=" + circle.getCenterPoint().x +
", y=" + circle.getCenterPoint().y +
", radius=" + circle.getRadius() + ")";
}
return rval;
}
|
52e74140-310a-45e6-804f-4da01f4c2afe
| 9
|
public int compareTo( Object obj ) {
if( obj == null ) {
return( 1 );
}
else if( obj instanceof GenKbSecUserByUEMailIdxKey ) {
GenKbSecUserByUEMailIdxKey rhs = (GenKbSecUserByUEMailIdxKey)obj;
if( getRequiredClusterId() < rhs.getRequiredClusterId() ) {
return( -1 );
}
else if( getRequiredClusterId() > rhs.getRequiredClusterId() ) {
return( 1 );
}
{
int cmp = getRequiredEMailAddress().compareTo( rhs.getRequiredEMailAddress() );
if( cmp != 0 ) {
return( cmp );
}
}
return( 0 );
}
else if( obj instanceof GenKbSecUserBuff ) {
GenKbSecUserBuff rhs = (GenKbSecUserBuff)obj;
if( getRequiredClusterId() < rhs.getRequiredClusterId() ) {
return( -1 );
}
else if( getRequiredClusterId() > rhs.getRequiredClusterId() ) {
return( 1 );
}
{
int cmp = getRequiredEMailAddress().compareTo( rhs.getRequiredEMailAddress() );
if( cmp != 0 ) {
return( cmp );
}
}
return( 0 );
}
else {
throw CFLib.getDefaultExceptionFactory().newUnsupportedClassException( getClass(),
"compareTo",
"obj",
obj,
null );
}
}
|
e781cbc2-32eb-44cf-8871-4daa4f6c78d0
| 5
|
private void doSaveImage() {
BufferedImage image = board.getImage(); // The image currently displayed in the MosaicPanel.
JFileChooser fileDialog = new JFileChooser();
String defaultName = "pentominos_" + rows + "x" + cols + ".png"; // Default name for file to be saved.
File selectedFile = new File(defaultName);
fileDialog.setSelectedFile(selectedFile);
fileDialog.setDialogTitle("Save Image as PNG File");
int option = fileDialog.showSaveDialog(board); // Presents the "Save File" dialog to the user.
if (option != JFileChooser.APPROVE_OPTION)
return; // user canceled
selectedFile = fileDialog.getSelectedFile(); // The file the user has elected to save.
if (selectedFile.exists()) {
int response = JOptionPane.showConfirmDialog(board,
"The file \"" + selectedFile.getName() + "\" already exists.\nDo you want to replace it?",
"Replace file?",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (response == JOptionPane.NO_OPTION)
return; // user does not want to replace existing file
}
try {
if ( ! ImageIO.write(image,"PNG",selectedFile) ) // This actually writes the image to the file.
JOptionPane.showMessageDialog(board,"Sorry, it looks like PNG files are not supported!");
}
catch (Exception e) {
JOptionPane.showMessageDialog(board,"Sorry, an error occurred while trying to save the file:\n" + e.getMessage());
}
}
|
58caab9f-0c7d-462c-be33-a50b12dead9b
| 9
|
private double[] refactorDistApart(double[] distApart, double threshold) {
for (int i = 0; i < window; i++) {
distApart[i] = threshold;
}
for (int i = distApart.length - window; i < distApart.length; i++) {
distApart[i] = threshold;
}
for (int i = 0; i < distApart.length; i++) {
// Find only the local minimum
if (distApart[i] < threshold) {
int startIndex = i;
double localMinimum = Double.POSITIVE_INFINITY;
int localMinimumIndex = i;
while (i < distApart.length - window
&& distApart[i] < threshold) {
if (distApart[i] < localMinimum) {
localMinimum = distApart[i];
localMinimumIndex = i;
}
i++;
}
for (int k = startIndex; k < i; k++) {
if (k != localMinimumIndex)
distApart[k] = threshold;
}
}
}
return distApart;
}
|
c46ca999-0fb2-4fec-81ae-52813afee571
| 1
|
public void setShortMessageFontsize(int fontsize) {
if (fontsize <= 0) {
this.shortMessageFontSize = UIFontInits.SHORTMESSAGE.getSize();
} else {
this.shortMessageFontSize = fontsize;
}
somethingChanged();
}
|
28522b90-04bf-45e8-8697-f397ad48336f
| 3
|
public void addSICCode(String code) throws Exception {
if (null == Sic) {
Sic = new ArrayList<String>();
} else if (1000 == Sic.size()) {
throw new Exception("Maxiumum of 1000 SIC codes are allowed for Search");
}
if (!Sic.contains(code)) {
Sic.add(code);
}
}
|
f00b7dbf-41b3-49e5-8231-54ee6feb7b63
| 7
|
public void testStopPositons() throws IOException {
StringBuilder sb = new StringBuilder();
ArrayList a = new ArrayList();
for (int i=0; i<20; i++) {
String w = English.intToEnglish(i).trim();
sb.append(w).append(" ");
if (i%3 != 0) a.add(w);
}
log(sb.toString());
String stopWords[] = (String[]) a.toArray(new String[0]);
for (int i=0; i<a.size(); i++) log("Stop: "+stopWords[i]);
Set stopSet = StopFilter.makeStopSet(stopWords);
// with increments
StringReader reader = new StringReader(sb.toString());
StopFilter stpf = new StopFilter(false, new WhitespaceTokenizer(reader), stopSet);
doTestStopPositons(stpf,true);
// without increments
reader = new StringReader(sb.toString());
stpf = new StopFilter(false, new WhitespaceTokenizer(reader), stopSet);
doTestStopPositons(stpf,false);
// with increments, concatenating two stop filters
ArrayList a0 = new ArrayList();
ArrayList a1 = new ArrayList();
for (int i=0; i<a.size(); i++) {
if (i%2==0) {
a0.add(a.get(i));
} else {
a1.add(a.get(i));
}
}
String stopWords0[] = (String[]) a0.toArray(new String[0]);
for (int i=0; i<a0.size(); i++) log("Stop0: "+stopWords0[i]);
String stopWords1[] = (String[]) a1.toArray(new String[0]);
for (int i=0; i<a1.size(); i++) log("Stop1: "+stopWords1[i]);
Set stopSet0 = StopFilter.makeStopSet(stopWords0);
Set stopSet1 = StopFilter.makeStopSet(stopWords1);
reader = new StringReader(sb.toString());
StopFilter stpf0 = new StopFilter(false, new WhitespaceTokenizer(reader), stopSet0); // first part of the set
stpf0.setEnablePositionIncrements(true);
StopFilter stpf01 = new StopFilter(false, stpf0, stopSet1); // two stop filters concatenated!
doTestStopPositons(stpf01,true);
}
|
a1953779-84d0-4b6c-83f1-51532a368852
| 4
|
boolean startsWithBreakPoint()
{
for ( int i=0;i<rows.size();i++ )
{
Row r = rows.get(i);
if ( r.cells.size()>0 && r.versions.nextSetBit(base)==base )
{
FragList fl = r.cells.get(0);
if ( fl.fragments.size()>0 )
{
Atom a = fl.fragments.get(0);
return a.startsWithBreakPoint();
}
}
}
return false;
}
|
1b7c13c4-878b-4af0-a5b8-d7d602f4d150
| 7
|
public boolean checkIfSubTree(Node T1, Node T2) {
if (T1 == null && T2 == null)
return true;
if (T1 == null && T2 != null)
return false;
if (T1 != null && T2 == null)
return false;
if (T1.value == T2.value) {
checkIfSubTree(T1.left, T2.left);
checkIfSubTree(T1.right, T2.right);
} else {
return false;
}
return true;
}
|
23976909-462b-471a-a31a-aa11537580ed
| 6
|
@EventHandler
public void SpiderWeakness(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.getSpiderConfig().getDouble("Spider.Weakness.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getSpiderConfig().getBoolean("Spider.Weakness.Enabled", true) && damager instanceof Spider && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.WEAKNESS, plugin.getSpiderConfig().getInt("Spider.Weakness.Time"), plugin.getSpiderConfig().getInt("Spider.Weakness.Power")));
}
}
|
86dfa3cd-415e-4bc9-9f0e-dee7451f53d1
| 1
|
private Allocation allocate(int payLoad) {
int offset = currentItemOffset.addAndGet(ItemMeta.META_SIZE + payLoad);
if (capacity < offset)
return null;
return new Allocation(offset - ItemMeta.META_SIZE - payLoad);
}
|
dea1e708-407c-4afc-a44b-162854a9270d
| 1
|
public static SingleWriter getInstance(String fileName) throws IOException {
if (instance == null) {
instance = new SingleWriter();
}
out = new PrintWriter(fileName, "UTF-8");
return instance;
}
|
045d48ae-93c6-49fd-80f0-fe87bf9da810
| 8
|
private double[][] read(Scanner scanner) throws IOException {
st = new StringTokenizer(scanner.nextLine());
if (st == null || st.countTokens() != 2) {
throw new IOException("Input data is incorrect");
}
r = Integer.parseInt(st.nextToken());
c = Integer.parseInt(st.nextToken());
checkNegationSize(r, c);
double[][] tmp = new double[r][c];
for (int i = 0; i < r; i++) {
if (!scanner.hasNextLine()) {
throw new IOException();
}
st = new StringTokenizer(scanner.nextLine());
if (st == null || st.countTokens() != c) {
throw new IOException("Not enough data in " + (i + 1) + " line");
}
for (int j = 0; j < c; j++) {
try {
tmp[i][j] = Double.parseDouble(st.nextToken());
} catch (NumberFormatException e) {
throw new NumberFormatException("Input data in the " + (i + 1) + " line on the " + (j + 1) + " position is incorrect");
}
}
}
return tmp;
}
|
f8c7fd8b-c282-4064-a8f4-20697440defc
| 8
|
public static Integer[] solveLargestFirst(Graph graph) {
ArrayList<Integer> cache = new ArrayList<>(graph.graph.size());
Integer[] result = new Integer[graph.graph.size()];
for (int i = 0; i < result.length; ++i) {
result[i] = -1;
}
int color = 0;
while (cache.size() < graph.graph.size()) {
int indexLargest = 0;
int largestNeighbour = 0;
for (int i = 0; i < graph.graph.size(); ++i) {
if (cache.contains(i)) {
continue;
}
if (largestNeighbour == 0) {
indexLargest = i;
largestNeighbour = graph.graph.get(i).size();
continue;
}
if (graph.graph.get(i).size() > largestNeighbour) {
indexLargest = i;
largestNeighbour = graph.graph.get(i).size();
}
}
color = 0;
cache.add(indexLargest);
int i = 0;
while (i < graph.graph.get(indexLargest).size()) {
if (result[graph.graph.get(indexLargest).get(i)] == color) {
i = 0;
color++;
} else {
++i;
}
}
result[indexLargest] = color;
}
return result;
}
|
dce90ead-713d-48ad-83b5-512186bdb5dd
| 1
|
@Override
public void addItems(String fromDirectory, Collection<String> items) throws IOException {
for (String item : items) {
addItem(fromDirectory, item);
}
}
|
eaee2a61-00cb-4a42-8cc7-b41be046830e
| 8
|
public int candy(int[] ratings) {
if (ratings.length == 0) {
return 0;
}
if (ratings.length == 1) {
return 1;
}
int[] candy = new int[ratings.length];
int result = candy.length;
for (int i = 1; i < candy.length; i++) {
if (ratings[i] > ratings[i - 1]) {
candy[i] = candy[i - 1] + 1;
}
}
for (int i = candy.length - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1] && candy[i] <= candy[i + 1]) {
candy[i] = candy[i + 1] + 1;
}
}
for (int i = 0; i < candy.length; i++) {
result += candy[i];
}
return result;
}
|
0fdf5f04-8d2e-484a-97b1-b4a8740e5643
| 0
|
protected void outOfOrder() {
JOptionPane.showMessageDialog(frame,
"That action is inappropriate for this step!", "Out of Order",
JOptionPane.ERROR_MESSAGE);
}
|
35186ffa-b807-43e3-8a9c-47f91309ae5d
| 9
|
public boolean containsNaive() throws Exception {
Stack<StackElement> stack = new Stack<>();
int currentLiteralPos = 0;
calcViewPositions();
//List<Literal> remainingLiterals = new ArrayList<>();
//remainingLiterals.addAll(Arrays.asList(query.literals));
//Literal firstLiteral = remainingLiterals.remove(0);
Literal firstLiteral = query.literals[currentLiteralPos];
List<Mapping> possibleMappings = getMappings(firstLiteral);
if(possibleMappings.isEmpty())
return false;
Mapping mapping = new Mapping();
//stack.push(new StackElement(mapping,possibleMappings,remainingLiterals));
stack.push(new StackElement(mapping, possibleMappings, currentLiteralPos));
while (!stack.empty()) {
StackElement curStackElem = stack.pop();
mapping = new Mapping(curStackElem.mapping);
possibleMappings = new ArrayList<>(curStackElem.possibleMappings);
//remainingLiterals = new ArrayList<>(curStackElem.remainingLiterals);
currentLiteralPos = curStackElem.literalPos;
if (!possibleMappings.isEmpty()) {
Mapping currentMapping = possibleMappings.remove(0);
if (possibleMappings.size() > 0)
stack.push(new StackElement(new Mapping(mapping), new ArrayList<>(possibleMappings), currentLiteralPos));
if (mapping.isCompatible(currentMapping)) {
mapping.mergeMapping(currentMapping);
//if(remainingLiterals.isEmpty()){
if (currentLiteralPos >= query.literals.length) {
try {
// System.out.println(mapping);
Literal mapped = new Literal(query.head, mapping);
if (view.head.containsAll(mapped)) {
return true;
}
} catch (IllegalArgumentException e) {
}
} else {
//firstLiteral = remainingLiterals.remove(0);
firstLiteral = query.literals[currentLiteralPos];
currentLiteralPos++;
possibleMappings = getMappings(firstLiteral);
if (possibleMappings.size() > 0)
stack.push(new StackElement(mapping, possibleMappings, currentLiteralPos));
}
}
}
}
return false;
}
|
eab33d20-2228-48aa-845c-3874828a7f5b
| 7
|
public void insert(BatBitmap b, int x, int y){
//Fills this bitmap with b, at (x,y)
int x0 = x;
int x1 = x0 + b.width;
int y0 = y;
int y1 = y0 + b.height;
if(x0 < 0) x0 = 0;
if(y0 < 0) y0 = 0;
if(x1 > this.width) x1 = this.width;
if(y1 > this.height) y1 = this.height;
int fillWidth = x1 - x0;
int tp, sp;
for(int yy = y0; yy < y1; yy++){
tp = yy * width + x0;
sp =(yy - y) * b.width + (x0 - x);
tp -= sp;
for(int xx = sp; xx < sp + fillWidth; xx++){
int color = b.pixels[xx];
if (color < 0) this.pixels[tp + xx] = color;
}
}
}
|
1e112c93-69f3-40e2-9938-20c44a70ae1a
| 5
|
public void update(float delta) {
timer += delta / 1000;
if (timer > minSpawnTime) {
Random rng = new Random(System.currentTimeMillis());
int r1 = rng.nextInt();
int spawnTime = maxSpawnTime - minSpawnTime;
if ((int) r1 % spawnTime == 0 || timer > (spawnTime)) {
timer = 0;
spawn();
}
}
for (int i = 0; i < enemies.size(); i++) {
if (enemies.get(i).getPosition().x < 0) {
enemies.remove(enemies.get(i));
}
}
}
|
27649227-f2a2-48c9-b03c-4fbf63ad528a
| 8
|
@Override
public void requestCS(int pid) {
choosing[pid]=true;
for (int i = 0; i < n; i++){
if(number[i] > number[pid]){
number[pid]=number[i];
}
}
number[pid]++;
choosing[pid]=false;
for (int i = 0; i < n; i++) {
while(choosing[i]);
while((number[i]!= 0) &&
((number[i]< number[pid]) ||
((number[i]== number[pid]) && i <pid))
);
}
}
|
95f6fcff-1aaf-4196-b8bf-f8171ea82293
| 4
|
public void onStartUp()
{
if (this.fileLocation == null) {
this.file = new File(this.plugin.getDataFolder(), this.fileName + this.fileExtension);
} else {
this.file = new File(this.fileLocation, this.fileName + this.fileExtension);
}
try
{
this.fileConfig = YamlConfiguration.loadConfiguration(this.file);
if (!this.file.exists())
{
this.file.getParentFile().mkdirs();
this.file.createNewFile();
if (this.plugin.getResource(this.fileName + this.fileExtension) != null) {
copy(this.plugin.getResource(this.fileName + this.fileExtension), this.file);
}
}
}
catch (Exception e)
{
e.getCause();
}
}
|
36f844d5-4577-445b-9ebd-5096afd59425
| 5
|
private MoveResult determineGameResult() {
MoveResult result;
boolean isBlueWinner = board.checkIfPlayerLost(HantoPlayerColor.RED);
boolean isRedWinner = board.checkIfPlayerLost(HantoPlayerColor.BLUE);
if (isBlueWinner && isRedWinner) {
result = MoveResult.DRAW;
}
else if (isBlueWinner) {
result = MoveResult.BLUE_WINS;
}
else if (isRedWinner) {
result = MoveResult.RED_WINS;
}
else if (!anyPiecesLeftToPlay()) { // check for draw
result = MoveResult.DRAW;
}
else {
result = MoveResult.OK;
}
return result;
}
|
a4c8e6c3-84aa-438f-b671-2f12b202aa07
| 0
|
public AnswerCombination getAnswer() {
return answer;
};
|
cc89ceb4-4195-42bf-a927-598bc37aed25
| 5
|
public void drawInput(Graphics2D g, InputConnector ip) {
int[] xs = null, ys = null;
if (ip.pos == Position.left) {
xs = new int[] { x - connectorSize / 2, x + connectorSize / 2,
x - connectorSize / 2 };
ys = new int[] { y + height / 2 - connectorSize / 2,
y + height / 2, y + height / 2 + connectorSize / 2 };
} else if (ip.pos == Position.top) {
xs = new int[] { x + width / 2 - connectorSize / 2, x + width / 2,
x + width / 2 + connectorSize / 2 };
ys = new int[] { y - connectorSize / 2, y + connectorSize / 2,
y - connectorSize / 2 };
} else if (ip.pos == Position.bottom) {
xs = new int[] { x + width / 2 - connectorSize / 2, x + width / 2,
x + width / 2 + connectorSize / 2 };
ys = new int[] { y + height + connectorSize / 2,
y + height - connectorSize / 2,
y + height + connectorSize / 2 };
} else {
xs = new int[] { x + width + connectorSize / 2,
x + width - connectorSize / 2,
x + width + connectorSize / 2 };
ys = new int[] { y + height / 2 - connectorSize / 2,
y + height / 2, y + height / 2 + connectorSize / 2 };
}
if (xs != null && ys != null)
g.drawPolygon(xs, ys, 3);
}
|
352ab66c-bb50-4d40-b1e4-a7576ca6c981
| 8
|
public static void writeFile(RuleSet ruleSets, String ruleFileOutputName, ErrorLogs errorLogs, String errorFileOutputName) {
// The name of the file to open.
if(ruleFileOutputName == "" || errorFileOutputName == ""){
errorLogs.getErrorMsgs().add("The specified output path(s) are empty");
}
System.out.println("Output Rule File Path: " + ruleFileOutputName);
System.out.println("Output Error File Path: " + errorFileOutputName);
int ruleSize = ruleSets.getRuleSet().size();
int errorSize = errorLogs.getErrorMsgs().size();
System.out.println("rule size : " + ruleSize);
System.out.println("error size: " + errorSize);
try {
PrintWriter writer = new PrintWriter(ruleFileOutputName);
if(ruleSize >0){
for (int i = 0; i < ruleSize; i++) {
writer.println(ruleSets.getRuleSet().get(i));// get each rule set and print the result
}
}else{
errorLogs.getErrorMsgs().add("No Rules could be generated under these input parameters.");
}
writer.close();
} catch (IOException ex) {
System.out
.println("Error writing to file: '" + ruleFileOutputName + "'");
}
try {
PrintWriter error_writer = new PrintWriter(errorFileOutputName);
if(errorSize >0){
for (int i = 0; i < errorLogs.getErrorMsgs().size(); i++) {
error_writer.println(errorLogs.getErrorMsgs().get(i));// get each rule set and print the result
}
}else{
error_writer.println("No Error's Occured in Rule Generation. Excellent Job!");
}
error_writer.close();
} catch (IOException ex) {
System.out
.println("Error writing to file: '" + errorFileOutputName + "'");
}
}
|
93be36d6-8c39-42ed-89cb-bea9d586859c
| 5
|
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CallendarAdapter that = (CallendarAdapter) o;
if (events != null ? !events.equals(that.events) : that.events != null) return false;
return true;
}
|
f5168977-7756-463e-856a-20c0b0539bbd
| 3
|
public double variance(int col) {
int n = 0;
double mean = columnMean(col);
double sum = 0;
for (List<Double> row : data) {
double val = row.get(col) - mean;
if (val != UNKNOWN_VALUE) {
sum += (val * val);
n++;
}
}
return n == 1 ? 0 : sum / (n - 1);
}
|
7eb20fda-40a3-4a53-ae8e-796e6802ac5a
| 1
|
protected JPanel getSamplePanel()
{
if (samplePanel == null)
{
Border titledBorder = BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), ("Sample"));
Border empty = BorderFactory.createEmptyBorder(5, 10, 10, 10);
Border border = BorderFactory.createCompoundBorder(titledBorder, empty);
samplePanel = new JPanel();
samplePanel.setLayout(new BorderLayout());
samplePanel.setBorder(border);
samplePanel.add(getSampleTextField(), BorderLayout.CENTER);
}
return samplePanel;
}
|
e100248e-c643-4a37-978c-155ddd2b5bc7
| 3
|
public void hanoiIteratif2(int n, Tour depart,Tour arrivee, Tour intermediaire){
int i = 0;
int hauteur = depart.getHauteur();
if(n%2==0)
while(arrivee.getHauteur()!= hauteur){
deplacementPetit(i,depart,arrivee,intermediaire);
deplacementAutre(i,depart,arrivee,intermediaire);
i++;
}
else{
while(arrivee.getHauteur()!= hauteur){
deplacementPetit(i,depart,intermediaire,arrivee);
deplacementAutre(i,depart,intermediaire,arrivee);
i++;
}
}
}
|
0e7ca3ed-aa88-4fb7-87cf-ca9978df3334
| 3
|
public void dailyBonus(Player player)
{
switch (this) {
case GOLD_MINE:
player.addResource(ResourceType.GOLD, 1000);
break;
case ORE_MINE:
player.addResource(ResourceType.ORE, 1);
break;
case WOOD_MINE:
player.addResource(ResourceType.WOOD, 2);
break;
default:
}
}
|
a4996202-cf98-42c3-8316-843abfe8bd84
| 6
|
public boolean start() {
synchronized (optOutLock) {
// Did we opt out?
if (isOptOut()) {
return false;
}
// Is metrics already running?
if (task != null) {
return true;
}
// Begin hitting the server with glorious data
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
private boolean firstPost = true;
public void run() {
try {
// This has to be synchronized or it can collide with the disable method.
synchronized (optOutLock) {
// Disable Task, if it is running and the server owner decided to opt-out
if (isOptOut() && task != null) {
task.cancel();
task = null;
}
}
// We use the inverse of firstPost because if it is the first time we are posting,
// it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING!
postPlugin(!firstPost);
// After the first post we set firstPost to false
// Each post thereafter will be a ping
firstPost = false;
} catch (IOException e) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
}
}, 0, PING_INTERVAL * 1200);
return true;
}
}
|
bddc4fdc-cbc5-489c-8a14-0693218ff461
| 5
|
GenericGFPoly addOrSubtract(GenericGFPoly other) {
if (!field.equals(other.field)) {
throw new IllegalArgumentException("GenericGFPolys do not have same GenericGF field");
}
if (isZero()) {
return other;
}
if (other.isZero()) {
return this;
}
int[] smallerCoefficients = this.coefficients;
int[] largerCoefficients = other.coefficients;
if (smallerCoefficients.length > largerCoefficients.length) {
int[] temp = smallerCoefficients;
smallerCoefficients = largerCoefficients;
largerCoefficients = temp;
}
int[] sumDiff = new int[largerCoefficients.length];
int lengthDiff = largerCoefficients.length - smallerCoefficients.length;
// Copy high-order terms only found in higher-degree polynomial's coefficients
System.arraycopy(largerCoefficients, 0, sumDiff, 0, lengthDiff);
for (int i = lengthDiff; i < largerCoefficients.length; i++) {
sumDiff[i] = GenericGF.addOrSubtract(smallerCoefficients[i - lengthDiff], largerCoefficients[i]);
}
return new GenericGFPoly(field, sumDiff);
}
|
a664960b-74ef-49e2-a88d-940e01d20958
| 5
|
private void replaceNodeInParent(FineNode<T> curr, FineNode<T> _new) {
if (curr.getParent() != null) {
if (curr == curr.getParent().getLeft()) {
curr.getParent().setLeft(_new);
} else {
curr.getParent().setRight(_new);
}
} else {
if (_new == null) {
root.setValue(null);
} else {
root = _new;
}
}
if (_new != null) {
_new.setParent(curr.getParent());
}
if (curr.getLock().isHeldByCurrentThread()) {
curr.unlock();
}
}
|
63a86e23-4674-4d9f-9b1b-8dbaf55fb6ae
| 8
|
public static void invokePlugin(final String pluginName, final PluginRef plugin, final List<Variable> variables) {
try {
if (pluginMethods.get(pluginName) == null) {
throw new AzotException("Plugin '" + pluginName + "' not found.");
}
final List<Variable> inheritedVariables = new ArrayList<Variable>();
inheritedVariables.addAll(variables);
final List<Variable> pluginVariables = plugin.getVariables();
for (final Variable pluginVariable : pluginVariables) {
final String newValue = VariableHelper.substituteVariables(pluginVariable.getValue(), inheritedVariables);
VariableHelper.addOrUpdateVariable(pluginVariable.getId(), newValue, true, false, inheritedVariables);
}
final Properties inProperties = new Properties();
if (inheritedVariables != null) {
for (final Variable variable : inheritedVariables) {
inProperties.setProperty(variable.getId(), variable.getValue());
}
}
final Object returnedValue = pluginMethods.get(pluginName).invoke(null, new Object[] {inProperties});
if (returnedValue instanceof Properties) {
final Properties outProperties = (Properties) returnedValue;
//System.out.println("Variables received by Azot:");
Set<Object> keyObjects = outProperties.keySet();
for (Object keyObject : keyObjects) {
final String key = (String)keyObject;
final String value = outProperties.getProperty(key);
//System.out.println("key: '" + key + "', value: '" + value + "'");
println("Plugin returns the property '" + key + "' with value '" + value + "'");
VariableHelper.addOrUpdateVariable(key, value, true, false, variables);
}
}
} catch (Exception e) {
println("Error: plugin invocation failed");
if (AzotConfig.GLOBAL.VERBOSE) {
System.out.print("Cause: ");
e.printStackTrace();
}
}
}
|
4840dbf4-1b2d-489a-a6af-f805e4806b97
| 2
|
public void JoinGame(InetAddress adr)
{
Player player = new Player();
if(player.connect(adr)){
StartGame(player);
} else {
JOptionPane.showMessageDialog(null, "Could not connect to: "+adr, "IP conflict", WIDTH);
try{
player.disconnect();
}
catch (Exception e) {
System.out.println("Exception Lobby player.disconnect(): "+e.getMessage());
}
}
}
|
059dc770-b9b2-4ca4-8517-7dbe87c5f4fc
| 9
|
static byte DispenserFix(byte data, String kierunek)
{
if (kierunek.equals("right"))
{
if (data == 2) {
return 5;
}
if (data == 4) {
return 2;
}
if (data == 5) {
return 3;
}
if (data == 3) {
return 4;
}
}
else
{
if (data == 5) {
return 2;
}
if (data == 2) {
return 4;
}
if (data == 3) {
return 5;
}
if (data == 4) {
return 3;
}
}
return data;
}
|
30baf2f7-0eba-4fd8-8f89-5fcc1bbd41ab
| 9
|
private void paivitaPeli(){
RuutuTyyli tormays = paivitaMato();
if(tormays == RuutuTyyli.Hedelma){
hedelmatSyoty++;
pisteet += seuraavanHedelmanPisteet;
uusiHedelma();
}
if(tormays == RuutuTyyli.Hedelma && (hedelmatSyoty % 5) == 0){
uusiRandomHedelma();
}
if(tormays == RuutuTyyli.IsoHedelma){
this.onkoIsoHedelma = false;
hedelmatSyoty++;
pisteet += seuraavanIsonHedelmanPisteet;
}
if(tormays == RuutuTyyli.LyhentavaHedelma){
hedelmatSyoty++;
for(int i = 0; i < 3; i++){
Point hanta = mato.removeLast();
board.setRuutu(hanta, null);
}
}
if(seuraavanIsonHedelmanPisteet > 100){
seuraavanIsonHedelmanPisteet = seuraavanIsonHedelmanPisteet -20;
}
if(tormays == RuutuTyyli.MatoBody){
onkoHavinnyt = true;
kello.setPause(true);
}
if(seuraavanHedelmanPisteet > 10){
seuraavanHedelmanPisteet--;
}
}
|
34e20de5-df4d-4078-ae16-44a6352062ee
| 7
|
public int candy(int[] ratings) {
if (ratings == null || ratings.length == 0)
return 0;
int[] A = new int[ratings.length];
A[0] = 1;
for (int i = 1; i < ratings.length; i++) {
if (ratings[i] > ratings[i - 1])
A[i] = A[i - 1] + 1;
else
A[i] = 1;
}
for (int i = ratings.length - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1])
A[i] = Math.max(A[i], A[i + 1] + 1);
}
int sum = 0;
for (int i = 0; i < A.length; i++) {
sum += A[i];
}
return sum;
}
|
3174dbe1-adc9-4c1f-8594-7bad7c229f03
| 7
|
public void serialEvent(SerialPortEvent event) {
String finalString = "";
if(event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
sleep(100);
try {
byte[] readBuffer = new byte[40];
while(inputStream.available() > 0) {
inputStream.read(readBuffer);
}
finalString = new String(readBuffer).trim();
if(isSetupCompleted && finalString.equals("z") && !isConnected) {
isConnected = true;
out("[" + comport.getName() + "] found BT Zeppelin!");
write("p", false);
owner.onZeppelinFound(this);
} else if(finalString.equals("p")) {
write("p", false);
out("[" + comport.getName() + "] responding to ping.");
// Take note of the last received ping, the GUI will update
owner.setLastPing(System.currentTimeMillis());
} else {
out("[" + comport.getName() + "] read: '" + finalString + "'");
}
} catch (IOException e) {
}
}
}
|
627d6d1a-eb80-4150-b527-f4419bdea876
| 4
|
@Override
public void run() {
try {
while(!closed) {
if (run) {
this.sleep(1000);
while (run) {
time.setSeconds(time.getSeconds() - 1);
notifyListeners();
this.sleep(1000);
}
}
this.sleep(100);
}
} catch (InterruptedException e) {
ExceptionLog.println("Ошибка: Не удалось вызвать метод sleep для потока таймера.");
ExceptionLog.println(e);
}
}
|
31370923-25be-421d-b5e0-f9f7cfb7af7d
| 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.");
}
|
adb9533b-f405-46ee-aa49-ef33c64d80db
| 9
|
public static void main(String[] args) throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Ariyalur");
XStream xStream = new XStream();
xStream.alias("office", Office.class);
xStream.alias("offices", Offices.class);
xStream.addImplicitCollection(Offices.class, "offices");
FileInputStream file = new FileInputStream(new File("tamilnadu_ariyalur.xml"));
Offices offices = (Offices) xStream.fromXML(file);
int index = 0;
for (Office office : offices.getOffices()) {
HSSFRow officeNameRow = sheet.createRow(index);
officeNameRow.createCell(0).setCellValue("OfficeName");
officeNameRow.createCell(1).setCellValue(office.getName());
index++;
HSSFRow pinCodeRow = sheet.createRow(index);
pinCodeRow.createCell(0).setCellValue("Pincode");
pinCodeRow.createCell(1).setCellValue(office.getPinCode());
index++;
HSSFRow statusRow = sheet.createRow(index);
statusRow.createCell(0).setCellValue("status");
statusRow.createCell(1).setCellValue(office.getStatus());
index++;
if (office.getSuboffice() != null && office.getSuboffice().trim().length() > 0) {
HSSFRow subOfficeRow = sheet.createRow(index);
subOfficeRow.createCell(0).setCellValue("SubOffice");
subOfficeRow.createCell(1).setCellValue(office.getSuboffice());
index++;
}
if (office.getHeadoffice() != null && office.getHeadoffice().trim().length() > 0) {
HSSFRow headOfficeRow = sheet.createRow(index);
headOfficeRow.createCell(0).setCellValue("HeadOffice");
headOfficeRow.createCell(1).setCellValue(office.getHeadoffice());
index++;
}
if (office.getLocation() != null && office.getLocation().trim().length() > 0) {
HSSFRow headOfficeRow = sheet.createRow(index);
headOfficeRow.createCell(0).setCellValue("Location");
headOfficeRow.createCell(1).setCellValue(office.getLocation());
index++;
}
if (office.getTelephone() != null && office.getTelephone().trim().length() > 0) {
HSSFRow headOfficeRow = sheet.createRow(index);
headOfficeRow.createCell(0).setCellValue("Telephone");
headOfficeRow.createCell(1).setCellValue(office.getTelephone());
index++;
}
}
FileOutputStream out = new FileOutputStream(new File("Ariyalur.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
}
|
eb462e81-0366-4495-9585-2815bda5e75c
| 7
|
public static int getOptimizationByDirect01(int[] vs, int[] ws, int[] nums, int c){
int length = 0;
for(int num : nums){
length += num;
}
int[] vs1 = new int[length];
int[] ws1 = new int[length];
int index = 0;
for(int i=0; i<vs.length; i++){
int v = vs[i];
int w = ws[i];
int num = nums[i];
while (num-- != 0){
vs1[index] = v;
ws1[index] = w;
index++;
}
}
int[][] s = new int[length+1][c+1];
for(int i=1; i<length+1; i++){
for(int j=1; j<c+1; j++){
s[i][j] = s[i-1][j];
int v = vs1[i-1];
int w = ws1[i-1];
if(j>=v && (s[i-1][j-v]+w)>s[i][j]){
s[i][j] = s[i-1][j-v]+w;
}
}
}
Print.print2DArray(s);
return s[length][c];
}
|
1e15bd04-c8ca-4b6f-81b9-4d8f00a05490
| 1
|
public static String getFileExtension(File f) {
String filename=f.getName();
return (filename.lastIndexOf(".")==-1)?"":
filename.substring(filename.lastIndexOf(".")+1,filename.length())
.toLowerCase();
}
|
645d4272-6522-4bbb-8ab0-0e82a3189ae7
| 4
|
private static boolean saveOpenDocumentList() {
// Harvest Data to save and close each document
ArrayList openFileList = new ArrayList();
Iterator it = Outliner.documents.getDefaultOpenDocumentIterator();
while (it.hasNext()) {
OutlinerDocument doc = (OutlinerDocument) it.next();
if (OutlinerWindowMonitor.closeInternalFrame(doc)) {
if (!doc.isModified()) { // Don't store untitled docs that haven't been saved.
openFileList.add(doc.getDocumentInfo());
}
} else {
return false;
}
}
// Save the file
StringBuffer buf = new StringBuffer();
buf.append(XMLTools.getXMLDeclaration());
String line_ending = "\n";
buf.append(line_ending);
PropertyContainerUtil.writeXML(buf, openFileList, 0, line_ending);
try {
FileTools.dumpStringToFile(new File(Outliner.OPEN_FILES_FILE), buf.toString(), "UTF-8");
} catch (IOException ioe) {
ioe.printStackTrace();
}
return true;
}
|
36aa4daf-7f81-49f7-aa07-af2ad32ebdcf
| 6
|
public int findLargestSumPair(int[] nums) {
if (nums.length == 0)
return 0;
if (nums.length == 1)
return nums[0];
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int i=0; i<nums.length; i++) {
int t = nums[i];
if (t >= first) {
int temp = first;
first = t;
second = temp;
}
if (second == Integer.MIN_VALUE && t != first)
second = t;
}
return first + second;
}
|
febbab26-9e7d-4960-b0dd-eb31927c7382
| 9
|
public void juagadaMin(int dato)
{
Nodo busqueda = this.reducirArbol(dato);
if(busqueda != null)
{
if(busqueda.getAcumulado() <= MiniMax.getLimit() - 1)
{
if(busqueda.getAcumulado() < this.acumuladoMaximo)
{
do
{
Random rnd = new Random();
int op = rnd.nextInt(4-1+1) + 1;
switch(op)
{
case 1: super.raiz = busqueda.getOpt1();
break;
case 2: super.raiz = busqueda.getOpt2();
break;
case 3: super.raiz = busqueda.getOpt3();
break;
case 4: super.raiz = busqueda.getOpt4();
break;
}
}
while(super.raiz == null);
}
else
{
super.raiz = this.mejorOpcion(busqueda);
if(super.raiz == null)
this.estado = 2;
}
}
else
this.estado = 1;
}
else
this.estado = 1;
}
|
48682693-c004-46d1-9933-a411ad92bbd0
| 3
|
void attackPlaceVerticallyBelow(int position, char[] boardElements, int dimension, int numberOfLinesBelow) {
while (numberOfLinesBelow > 0) {
if (isPossibleToPlaceOnNextLine(boardElements, elementVerticallyBelow(dimension, position, numberOfLinesBelow))
&& isBoardElementEmpty(boardElements[elementVerticallyBelow(dimension, position, numberOfLinesBelow)])) {
boardElements[elementVerticallyBelow(dimension, position, numberOfLinesBelow)] = FIELD_UNDER_ATTACK_CHAR;
}
numberOfLinesBelow--;
}
}
|
510fb618-f698-46ab-9ae7-db52ef3f85d2
| 4
|
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String command =e.getActionCommand();
if(command.equals("regame"))
{
clean();
gameRunning = false;
freshMessage("遊戲進行中");
}
else
{
String[] press = command.split(" ");
int x = Integer.parseInt(press[0]);
int y = Integer.parseInt(press[1]);
if(!gameRunning)
{
resetGame(x,y);
gameRunning = true;
}
if(!isPressed[x][y]&&!gameOver)
{
System.out.println("Invoke click "+x+" "+y);
click(x,y);
isPressed[x][y] = true;
}
}
}
|
2a4f4726-ce31-4395-892f-8e4e8646d2e2
| 3
|
@Override
@Deprecated
public void mouseExited(MouseEvent event) {
int radiusBase = AppliWindow.getInstance().getTilesSize();
int xM = event.getX(), yM = event.getY();
int distX = 0, distY = 0;
for(Base b : Game.getInstance().getBaseManager().getBases()){
distX = (int) Math.abs(xM - b.getPosition().getX());
distY = (int) Math.abs(yM - b.getPosition().getY());
if(distX > radiusBase && distY > radiusBase) {
break;
}
else{
return;
}
}
}
|
b2a524ff-1cca-4605-afc2-80ac4ae64c37
| 0
|
public void setLeft(boolean left) {
this.left = left;
}
|
3572a9b8-0672-46dd-8d6a-8bd4387f3897
| 2
|
public static GroundItem getSpice() {
return GroundItems.getNearest(new Filter<GroundItem>() {
public boolean accept(GroundItem item) {
if (item == null)
return false;
boolean valid = item.getId() >= 7480 && item.getId() <= 7495;
return valid;
}
});
}
|
22266f6c-171a-40e0-a957-6ed01ebcbbda
| 8
|
static Object create(Context cx, Class cl, Callable function)
{
if (!cl.isInterface()) throw new IllegalArgumentException();
Scriptable topScope = ScriptRuntime.getTopCallScope(cx);
ClassCache cache = ClassCache.get(topScope);
InterfaceAdapter adapter;
adapter = (InterfaceAdapter)cache.getInterfaceAdapter(cl);
ContextFactory cf = cx.getFactory();
if (adapter == null) {
Method[] methods = cl.getMethods();
if (methods.length == 0) {
throw Context.reportRuntimeError2(
"msg.no.empty.interface.conversion",
String.valueOf(function),
cl.getClass().getName());
}
boolean canCallFunction = false;
canCallFunctionChecks: {
Class[] argTypes = methods[0].getParameterTypes();
// check that the rest of methods has the same signature
for (int i = 1; i != methods.length; ++i) {
Class[] types2 = methods[i].getParameterTypes();
if (types2.length != argTypes.length) {
break canCallFunctionChecks;
}
for (int j = 0; j != argTypes.length; ++j) {
if (types2[j] != argTypes[j]) {
break canCallFunctionChecks;
}
}
}
canCallFunction= true;
}
if (!canCallFunction) {
throw Context.reportRuntimeError2(
"msg.no.function.interface.conversion",
String.valueOf(function),
cl.getClass().getName());
}
adapter = new InterfaceAdapter(cf, cl);
cache.cacheInterfaceAdapter(cl, adapter);
}
return VMBridge.instance.newInterfaceProxy(
adapter.proxyHelper, cf, adapter, function, topScope);
}
|
9d200d90-b96c-4e5c-bfe2-f2fabb1e90f5
| 2
|
public void updateGrid(final Modele plateau) {
if (!plateau.getFin()) {
if (!SwingUtilities.isEventDispatchThread()) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
updateGrid(plateau);
}
});
return;
}
grid.updateGrid(plateau.getColorGrid());
pieces.updatePiece(plateau.getSuivantes());
}
}
|
1bf26ad0-62ef-4b3f-8508-81c362a2474d
| 4
|
private void drawElement(Integer i, Node currentNode, boolean isDeletedNode, Graphics2D g2d, int nextLeft,
int numberNextLeft, int numberIncrementLeft, int dimensionTop, int numberTop) {
// Drawing rectangle
BasicStroke bs2 = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
g2d.setStroke(bs2);
g2d.drawRect(nextLeft, dimensionTop, DIMENSION_WIDTH, DIMENSION_HEIGHT);
// Setting color to rectangle
g2d.setColor(isDeletedNode ? Color.RED : Color.WHITE);
g2d.fillRect(nextLeft + SIDE_OFFSET, dimensionTop + SIDE_OFFSET, DIMENSION_WIDTH + OFFSET, DIMENSION_HEIGHT + OFFSET);
g2d.setColor(Color.BLACK);
// Drawing position
if (i != null) {
g2d.drawString(String.valueOf(i), numberIncrementLeft, NUMBER_POS);
}
// Drawing tree.node key
g2d.drawString(isDeletedNode ? "Deleted" : currentNode != null ? String.valueOf(currentNode.getKey()) : "",
numberNextLeft, numberTop);
}
|
bdc1416f-1189-4e66-a477-089c4b179222
| 7
|
protected static boolean reportError(final Electronics me, final Software controlI, final MOB mob, final String literalMessage, final String controlMessage)
{
if((mob!=null) && (mob.location()==CMLib.map().roomLocation(me)) && (literalMessage!=null))
mob.tell(literalMessage);
if(controlMessage!=null)
{
if(controlI!=null)
controlI.addScreenMessage(controlMessage);
else
if((mob!=null)&&(me!=null))
mob.tell(CMLib.lang().L("A panel on @x1 reports '@x2'.",me.name(mob),controlMessage));
}
return false;
}
|
12ea76f6-1b72-4e6c-a4e4-677809b8a6e1
| 3
|
private boolean isPositionOutOfFrame(LifePosition lifePosition) {
return lifePosition.getPosition()[0] < 0 || lifePosition.getPosition()[1] < 0
|| lifePosition.getPosition()[0] >(frame.height()-1) || lifePosition.getPosition()[1] > (frame.width()-1);
}
|
fc73b286-94e7-4ce6-98fa-4237c3f27636
| 8
|
private void keyEventProcess(final KeyEvent ke){
if( ke.isShiftDown() ){
final java.awt.Component comp = ke.getComponent();
switch( ke.getKeyCode() ){
case KeyEvent.VK_RIGHT:
rotarFocus(true, comp);
break;
case KeyEvent.VK_LEFT:
rotarFocus(false, comp);
break;
}
return;
}
switch( ke.getKeyCode() ){
case KeyEvent.VK_RIGHT:
rotarFecha(true, Calendar.DAY_OF_YEAR);
break;
case KeyEvent.VK_LEFT:
rotarFecha(false, Calendar.DAY_OF_YEAR);
break;
case KeyEvent.VK_PAGE_UP:
rotarFecha(true, Calendar.WEEK_OF_YEAR);
break;
case KeyEvent.VK_PAGE_DOWN:
rotarFecha(false, Calendar.WEEK_OF_YEAR);
break;
case KeyEvent.VK_HOME:
updateScreenAllByDate( new java.util.Date() );
break;
}
}
|
06f7503e-502d-49a2-a9d6-4256428f7298
| 3
|
private void jButton0MouseMouseClicked(MouseEvent event) {
String sql = jTextField0.getText();
if(sql == null || "".equals(sql)){
jLabel1.setForeground(Color.red);
}else{
jLabel1.setForeground(Color.black);
}
if (";".equals(sql.substring(sql.length()-1,sql.length()))){
System.out.println("substring");
sql = sql.substring(0, sql.length()-1);
}
UpdateData.upData(sql);
}
|
d28cde12-461e-42f0-b2f0-587bda9d33b8
| 1
|
public void load() throws IOException {
URL url2 = new URL(url);
int begin = url.lastIndexOf("/");
if (begin == -1) {
System.out.println("index of url = -1");
return;
}
String name = url.substring(begin + 1, url.length());
Path path = Paths.get("images\\" + name);
// InputStream in = new BufferedInputStream(url2.openConnection().getInputStream());
// FileOutputStream out = new FileOutputStream(path.toFile());
// byte[] bytes = new byte[1024];
// int count = 0;
// while ( (count = in.read(bytes)) != -1) {
// if (count < 1024) System.out.print("warning");
// System.out.println(count);
// out.write(bytes, 0, count);
// }
// out.close();
// in.close();
ReadableByteChannel rbc = Channels.newChannel(url2.openStream());
FileOutputStream fos = new FileOutputStream(path.toFile());
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
// URL link = new URL(url);
// InputStream in = new BufferedInputStream(link.openStream());
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// byte[] buf = new byte[1024];
// int n = 0;
// while (-1!=(n=in.read(buf)))
// {
// out.write(buf, 0, n);
// }
// out.close();
// in.close();
// byte[] response = out.toByteArray();
// FileOutputStream fos = new FileOutputStream(path.toFile());
// fos.write(response);
// fos.close();
// InputStream in = new BufferedInputStream(url2.openStream());
// int count = 0;
// byte[] bytes = new byte[8];
// try (FileChannel fileChannel = (FileChannel)Files.newByteChannel(path,
// StandardOpenOption.READ,
// StandardOpenOption.CREATE,
// StandardOpenOption.WRITE)) {
// MappedByteBuffer map = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, 8);
// while ((count = in.read(bytes)) != -1) {
// byte[] bytes2 = Arrays.copyOf(bytes, count);
// System.out.println(bytes.length);
// map.rewind();
// map.put(bytes2);
// System.out.println(count);
// }
// } catch (IOException e) {
// System.out.println("IOException" + e);
// }
// InputStream in = new BufferedInputStream(url2.openStream());
// int count = 0;
// try (FileChannel fileChannel = (FileChannel)Files.newByteChannel(path,
// StandardOpenOption.CREATE,
// StandardOpenOption.WRITE)
// ) {
// ByteBuffer buff = ByteBuffer.allocate(2048);
// while ((count = in.read(buff.array())) != -1) {
// buff.rewind();
// //////////////////////
// // if (count < 1024) {
// // System.out.print("warning");
// // }
// // System.out.println(count);
// /////////////////////
// buff.limit(count);
// if (fileChannel.write(buff) != count) {
// System.out.println("Error");
// } else {
// System.out.println(buff.position() + " " + count);
// }
// }
// } catch (IOException e) {
// System.out.println("IOException" + e);
// }
}
|
d8aedaf9-57a9-40a4-b012-c2d188324eca
| 7
|
public static void updateInsuranceInfo(int studentID, String insName, String policyNum, String start, String end, float copayment){
try{
if(start == null || start.isEmpty())
start = "13-APR-2014";
if(end == null || end.isEmpty())
end = "15-APR-2016";
if(copayment == 0)
copayment = 30;
int rows = statement.executeUpdate("UPDATE health_insurance set ins_name='" +
insName + "', policy_num='" + policyNum + "', start_date=to_date('" +
start + "', 'DD-MON-YYYY'), end_date=to_date('" + end + "', 'DD-MON-YYYY'), "
+ "copayment=" + copayment + " WHERE s_id=" + studentID);
if(rows == 0){
System.out.println("Invalid insurance information provided.");
}
else{
System.out.println("Insurance information updated.");
}
} catch(SQLException e){
System.out.println(e.getMessage());
}
}
|
d52c311a-6853-4f69-b585-4017b7b0e4ec
| 3
|
public final void reset() {
grass.clear();
wall.clear();
entities.clear();
step = 0;
final int fieldWidth = Parameter.FIELD_WIDTH.getValue();
final int fieldHeight = Parameter.FIELD_HEIGHT.getValue();
final int fieldSize = fieldWidth * fieldHeight;
/* place initial food */
final int foodCount = (fieldSize * Parameter.INITIAL_FOOD.getValue())
/ Parameter.PERCENT;
for (int i = 0; i < foodCount; ++i) {
addRandomGrass();
}
/* place initial walls */
final int wallCount = (fieldSize * Parameter.INITIAL_WALL.getValue())
/ Parameter.PERCENT;
for (int i = 0; i < wallCount; ++i) {
addRandomWall();
}
/* place initial population */
for (int i = 0; i < Parameter.INITIAL_POPULATION.getValue(); ++i) {
addEntity(new Entity(
100,
new Program(Command.MOVE),
getRandomValidPoint(),
Direction.getRandom()));
}
setChanged();
notifyObservers();
}
|
57dccb9f-7b42-440d-997f-cf208a06136a
| 7
|
public ButtonImageListener(final AbstractButton button, final ImageIcon idleImg, final ImageIcon hoverImg, final ImageIcon clickImg) {
button.setContentAreaFilled(false);
button.setBorder(BorderFactory.createEmptyBorder());
if (idleImg != null) {
try {
setIcon(button, idleImg);
} catch (InvalidIconException e) {
e.printStackTrace();
}
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseExited(MouseEvent event) {
try {
setIcon(button, idleImg);
} catch (InvalidIconException e) {
e.printStackTrace();
}
}
});
}
if (hoverImg != null) {
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent event) {
try {
setIcon(button, hoverImg);
} catch (InvalidIconException e) {
e.printStackTrace();
}
}
});
}
if (clickImg != null) {
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
try {
setIcon(button, clickImg);
} catch (InvalidIconException e) {
e.printStackTrace();
}
}
});
}
}
|
4f0396e6-cdc5-4881-a602-132310b52b45
| 4
|
private int [] calcTilePattern (int numWindows) {
// local vars
int numColumns;
int windowsAccountedFor;
// no pattern for no windows
if (numWindows < 1) {
return null ;
}
// calculate pattern engine parameters
int numRows = Math.round((float)Math.sqrt(numWindows));
boolean uneven = (numWindows % numRows) > 0;
int weightChangeRow = numRows - (numWindows % numRows);
int regularRowSize = Math.round((float)((numWindows/numRows) - 0.5));
int fatRowSize = regularRowSize + 1;
int [] pattern = new int[numRows + 2];
int fatCounter = 0;
// for each row of the pattern
for (int rowCounter = 1; rowCounter <= numRows; rowCounter++) {
// add its number of columns to the pattern
// if itza fat row ...
if (uneven && (rowCounter > weightChangeRow)) {
pattern[rowCounter -1] = fatRowSize;
// may as well count fat rows while we're here
// data comes in handy for tiling styling
fatCounter++;
// else itza regular row
} else {
pattern[rowCounter -1] = regularRowSize;
}
}
// stick a data tail on the pattern donkey
pattern[numRows] = regularRowSize;
pattern[numRows + 1] = fatCounter;
// return the pattern
return pattern;
}
|
a64c238d-8f14-420c-bd13-9b360a91557f
| 4
|
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("usage: java Converter srcfile dstfile");
return;
}
try {
Media.convert(args[0], args[1]);
} catch (InvalidMediaFormatException imfe) {
System.out.println("Unable to convert " + args[0] + " to "
+ args[1]);
System.out.println("Expecting " + args[0] + " to conform to "
+ imfe.getExpectedFormat() + " format.");
System.out.println("However, " + args[0] + " conformed to "
+ imfe.getExistingFormat() + " format.");
} catch (FileNotFoundException fnfe) {
} catch (IOException ioe) {
}
}
|
cb0244bb-73eb-49bf-ab76-6617b3c81732
| 8
|
public static Simulator initSim( long initialTime ) {
Room r0 = new Room(64, 64, 4, SimpleBlock.EMPTY_STACK);
for( int y=r0.getHeight()-1; y>=0; --y )
for( int x=r0.getWidth()-1; x>=0; --x ) {
r0.blockField.setStack(x, y, 0, SimpleBlock.GRASS.stack);
}
CellCursor c = new CellCursor();
CellCursor c1 = new CellCursor();
Random rand = new Random();
for( int i=0; i<100; ++i ) {
c.set(r0, rand.nextInt(64), rand.nextInt(64), 1);
int r = rand.nextInt(3);
for( int dy=0; dy<=1+r; ++dy )
for( int dx=0; dx<=1+r; ++dx ) {
c1.set(c);
c1.changePosition(dx, dy, 0);
c1.setStack( SimpleBlock.FOLIAGE.stack );
}
}
for( int i=0; i<20; ++i ) {
c.set(r0, rand.nextInt(64), rand.nextInt(64), 1);
for( int dy=-1; dy<=1; ++dy )
for( int dx=-1; dx<=1; ++dx ) {
c1.set(c);
c1.changePosition(dx, dy, 0);
c1.setStack( SimpleBlock.WALL.stack );
}
}
r0.neighbors.add(new Neighbor(r0, 64, 32, 0));
r0.neighbors.add(new Neighbor(r0, -64, -32, 0));
r0.neighbors.add(new Neighbor(r0, 64, -32, 0));
r0.neighbors.add(new Neighbor(r0, -64, 32, 0));
r0.neighbors.add(new Neighbor(r0, 0, -64, 0));
r0.neighbors.add(new Neighbor(r0, 0, 64, 0));
final Simulator sim = new Simulator();
final AvatarianTranceiver[] playerTranceivers = AvatarianTranceiver.makePair(0, sim.internalUpdater);
sim.playerRemoteTranceiverPort = playerTranceivers[1].port;
final Avatar player = new Avatar( playerTranceivers[0], sim.getInternalUpdater() );
player.walkReadyTime = initialTime;
sim.move(player, new Location(r0, 2.51f, 2.51f, 1.51f, Affixions.NONE) );
sim.commandee = player;
sim.characters.add(player);
final WalkingCharacter bot = new Bot( sim.getInternalUpdater() );
bot.walkStepInterval = 75;
sim.move(bot, new Location(r0, 3.51f, 3.51f, 1.51f, Affixions.NONE) );
bot.startWalking( 1, 1, 0);
sim.characters.add(bot);
final WalkingCharacter bot2 = new Bot( sim.getInternalUpdater() );
bot2.walkStepInterval = 125;
sim.move(bot2, new Location(r0, 4.51f, 3.51f, 1.51f, Affixions.NONE) );
bot2.startWalking( 1, 1, 0);
sim.characters.add(bot2);
final WalkingCharacter bot3 = new Bot( sim.getInternalUpdater() );
sim.move(bot3, new Location(r0, 1.51f, 3.51f, 1.51f, Affixions.NONE) );
bot3.startWalking( 1, 1, 0);
sim.characters.add(bot3);
sim.internalUpdater.addTimer(initialTime, null, null);
return sim;
}
|
b2c1e75c-123d-4bc7-9ee6-78c279789dbc
| 5
|
public void visitFormalTypeParameter(final String name) {
if (type == TYPE_SIGNATURE
|| (state != EMPTY && state != FORMAL && state != BOUND))
{
throw new IllegalStateException();
}
CheckMethodAdapter.checkIdentifier(name, "formal type parameter");
state = FORMAL;
if (sv != null) {
sv.visitFormalTypeParameter(name);
}
}
|
016d9d1e-9194-4584-97a0-50dc6ffb1afd
| 2
|
public ItemStack[] getArmorContents()
{
ItemStack[] stack = new ItemStack[Armor.length];
for (int i = 0; i < stack.length; i++)
{
if (Armor[i] != null)
stack[i] = Armor[i].clone();
}
return stack;
}
|
af7c7282-014a-4d68-9d5b-7c852f2a95a2
| 1
|
public TCPClientBlockManagerDataReceive(Registry r, TCPClient c, ObjectOutputStream o, Object d, int sc, int cs, boolean asThread, boolean more) {
registry = r;
client = c;
output = o;
blockChunk = (short[][]) d;
//blockChunkByteArray = (byte[]) d;
currentStartCollumn = sc;
collumnChunkSize = cs;
sendMore = more;
if (asThread) {
start();
} else {
sendBlockMangerData();
}
}
|
224d10ad-4eaa-440a-b8ec-2830ee879828
| 9
|
private BufferedImage makeRGBABufferedImageFromImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage) image;
}
// This code ensures that all the pixels in the image are loaded
image = new ImageIcon(image).getImage();
// Determine if the image has transparent pixels; for this method's
// implementation, see Determining If an Image Has Transparent Pixels
boolean hasAlpha = hasAlpha(image);
// Create a buffered image with a format that's compatible with the screen
BufferedImage bImage = null;
try {
// graphics environment calls can through headless exceptions so
// proceed with caution.
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
// Determine the type of transparency of the new buffered image
int transparency = Transparency.OPAQUE;
if (hasAlpha) {
transparency = Transparency.BITMASK;
}
// Create the buffered image
int width = image.getWidth(null);
int height = image.getHeight(null);
if (width == -1 || height == -1) {
return null;
}
bImage = gc.createCompatibleImage(
image.getWidth(null), image.getHeight(null), transparency);
} catch (HeadlessException e) {
// The system does not have a screen
}
if (bImage == null) {
// Create a buffered image using the default color model
int type = BufferedImage.TYPE_INT_RGB;
if (hasAlpha) {
type = BufferedImage.TYPE_INT_ARGB;
}
int width = image.getWidth(null);
int height = image.getHeight(null);
if (width == -1 || height == -1) {
return null;
}
bImage = new BufferedImage(width, height, type);
}
// Copy image to buffered image
Graphics g = bImage.createGraphics();
// Paint the image onto the buffered image
g.drawImage(image, 0, 0, null);
g.dispose();
image.flush();
return bImage;
}
|
5ce405eb-19b8-487f-ba3a-a1dfa3dafce0
| 2
|
@Override
public void render(Graphics g) {
for (Path3D p : line)
p.render(g);
for (Path3D p : cross)
p.render(g);
}
|
f9157069-4a6c-43f3-b00e-440dd4edf69c
| 2
|
private AndroidEntryPointCreator createEntryPointCreator() {
AndroidEntryPointCreator entryPointCreator = new AndroidEntryPointCreator
(new ArrayList<String>(this.entrypoints));
Map<String, List<String>> callbackMethodSigs = new HashMap<String, List<String>>();
for (String className : this.callbackMethods.keySet()) {
List<String> methodSigs = new ArrayList<String>();
callbackMethodSigs.put(className, methodSigs);
for (AndroidMethod am : this.callbackMethods.get(className))
methodSigs.add(am.getSignature());
}
entryPointCreator.setCallbackFunctions(callbackMethodSigs);
return entryPointCreator;
}
|
e9e85d18-353e-46a4-a5b8-579a7ea138fc
| 7
|
public void characters(char[] buffer, int start, int length) throws SAXException {
StringBuffer buf = new StringBuffer();
if (parentElement.equals(ROOT_ELEMENT)) {
if (currentElement.equals("date")) {
try {
transactionSearchResult.setDate(DateParserUTC.parse(buf.append(buffer, start, length).toString()));
} catch (ParseException e) {
throw new SAXException(e);
}
} else if (currentElement.equals("currentPage")) {
transactionSearchResult.setPage(Integer.parseInt(buf.append(buffer, start, length).toString()));
} else if (currentElement.equals("resultsInThisPage")) {
transactionSearchResult.setResultsInThisPage(Integer.parseInt(buf.append(buffer, start, length)
.toString()));
} else if (currentElement.equals("totalPages")) {
transactionSearchResult.setTotalPages(Integer.parseInt(buf.append(buffer, start, length).toString()));
}
} else if (currentElement.equals("transaction")) {
xmlTransaction.append(buffer, start, length);
}
}
|
1d7a4bcd-e75b-48ff-96ad-843db38381bc
| 8
|
public String toString(){
StringBuffer sb = new StringBuffer();
switch(type){
case TYPE_VALUE:
sb.append("VALUE(").append(value).append(")");
break;
case TYPE_LEFT_BRACE:
sb.append("LEFT BRACE({)");
break;
case TYPE_RIGHT_BRACE:
sb.append("RIGHT BRACE(})");
break;
case TYPE_LEFT_SQUARE:
sb.append("LEFT SQUARE([)");
break;
case TYPE_RIGHT_SQUARE:
sb.append("RIGHT SQUARE(])");
break;
case TYPE_COMMA:
sb.append("COMMA(,)");
break;
case TYPE_COLON:
sb.append("COLON(:)");
break;
case TYPE_EOF:
sb.append("END OF FILE");
break;
}
return sb.toString();
}
|
b2d2e7e2-1e39-4a7c-8c88-cfe26b65ef3e
| 5
|
private void addMenuItemToColumn(final TableColumn column, final int index) {
// create menu item
final MenuItem itemName = new MenuItem(tableHeaderMenu, SWT.CHECK,
index);
itemName.setText(column.getText());
itemName.setSelection(column.getResizable());
itemName.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
if (itemName.getSelection()) {
column.setWidth(100);
column.setResizable(true);
} else {
column.setWidth(0);
column.setResizable(false);
}
}
});
// Setting the right sorter
column.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
int dir = tableViewer.getTable().getSortDirection();
switch (dir) {
case SWT.UP:
dir = SWT.DOWN;
break;
case SWT.DOWN:
dir = SWT.NONE;
break;
case SWT.NONE:
dir = SWT.UP;
break;
}
tableSorter.setColumn(index, dir);
tableViewer.getTable().setSortDirection(dir);
if (dir == SWT.NONE) {
tableViewer.getTable().setSortColumn(null);
} else {
tableViewer.getTable().setSortColumn(column);
}
tableViewer.refresh();
}
});
}
|
0b03b2dd-52d0-4e84-8822-1e4b5afe448b
| 3
|
public static void fillLibraryBeanToModel(DefaultTableModel model, LibraryBean[] libraryBeans){
model.getDataVector().removeAllElements();
if(libraryBeans == null || libraryBeans.length == 0){
model.setColumnIdentifiers(new String[]{"Nothing was found"});
return;
}
model.setColumnIdentifiers(columnIdentifiers);
for(int i = 0; i < libraryBeans.length; i++){
Object[] row = new Object[columnIdentifiers.length];
row[0] = libraryBeans[i].getName();
row[1] = libraryBeans[i].getShortDescription();
row[2] = libraryBeans[i].getLanguage().name();
row[3] = libraryBeans[i].getVersion();
row[4] = String.format("%.1f", libraryBeans[i].getRaiting());
row[5] = new SimpleDateFormat("dd.MM.yyyy").format(libraryBeans[i].getDate());
model.insertRow(i, row);
}
}
|
02c73849-09e0-472d-9122-665e43ac20d0
| 4
|
public Date calculateAlarmTime() {
if(!enabled) {
return new Date(0);
}
Calendar cal = new GregorianCalendar();
Date currentTime = new Date();
cal.setTime(currentTime);
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, 0);
if(repeating) {
if(repeatDays.size() > 0) {
calculateDayOfWeek(cal, currentTime);
}
}
Date alarmTime = cal.getTime();
if(alarmTime.before(currentTime)) {
cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) + 1);
alarmTime = cal.getTime();
}
System.out.println("alarm: " + alarmTime);
return alarmTime;
}
|
0cb9cfff-cb7f-4feb-9b4c-f98ae54849b4
| 3
|
private void update(int[] x, int bowlId, int round) {
if (bowlIds.contains(bowlId+round*nplayer)==false) {
info.add(x.clone());
bowlIds.add(bowlId+round*nplayer);
}
mu=0;
for(int[] y:info){
mu+=score(y);
}
mu=mu/info.size();
sigma=0;
scores.clear();
for(int[] y:info){
int s=score(y);
sigma+=(s-mu)*(s-mu);
scores.add(s);
}
//sigma+=2*13*25*bowSize/12.0;
sigma/=info.size();
sigma=Math.sqrt(sigma);
}
|
4c71f082-0a17-413c-9c3f-d49887a0440e
| 5
|
public boolean contains(Vector3 point)
{
Vector3 min = this.getMinimumPoint();
Vector3 max = this.getMaximumPoint();
return (point.x >= min.x && point.x <= max.x &&
point.y >= min.y && point.y <= max.y &&
point.z >= min.z && point.z <= max.z);
}
|
3ebad566-7afd-40ec-b0a4-487fffb33016
| 4
|
public void update(Avatar player, Map map) {
if (x != -1 && y != -1) {
if (missile.canbeShoot()) {
if (playerIsTargetable(player, map))
direcVect = new Point2D.Float(player.getX() - this.x,
player.getY() - this.y);
else
direcVect = null;
missile.shoot(direcVect);
missile.setCanbeShoot(false);
}
missile.update(map);
missileKillsPlayer(player, missile);
}
}
|
48fabd22-bf16-4bae-a9a4-5f58667b5e04
| 5
|
public int zigZag(int[] arr) {
int n = arr.length;
int[][] z = new int[n][2];
int maxZigZagCount = 0;
for (int i = 0; i < n; i++) {
z[i][0] = 1;
z[i][1] = 1;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
if((arr[i] - arr[j]) > 0){
z[i][0] = max(z[i][0] , (z[j][1] + 1));
}else if ((arr[i] - arr[j] < 0)){
z[i][1] = max(z[i][1] , z[j][0] + 1);
}
}
maxZigZagCount = max(max(z[i][0],z[i][1]),maxZigZagCount);
}
return maxZigZagCount;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.