text stringlengths 14 410k | label int32 0 9 |
|---|---|
public static boolean matches(String ptn, String src) {
if (src.equals(ptn))
return true;
else if (ptn.charAt(0) == '#') {
return Pattern.matches(ptn.substring(1), src);
} else if (ptn.charAt(0) == '*' && ptn.charAt(ptn.length() - 1) == '*') {
ptn = ptn.substring(1, ptn.length() - 1);
return src.contains(ptn);
} else if (ptn.charAt(0) == '*') {
ptn = ptn.substring(1);
return src.endsWith(ptn);
} else if (ptn.charAt(ptn.length() - 1) == '*') {
ptn = ptn.substring(0, ptn.length() - 1);
return src.startsWith(ptn);
} else if (ptn.indexOf('*') > 0) {
String part = ptn.substring(0, ptn.indexOf('*'));
if (src.startsWith(part)) {
part = ptn.substring(ptn.indexOf('*') + 1);
return src.endsWith(part);
}
return false;
}
return false;
} | 8 |
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(TextInput.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TextInput.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TextInput.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TextInput.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TextInput().setVisible(true);
}
});
} | 6 |
public static boolean XMLPreserveWhiteSpace(Node element, TagTable tt)
{
AttVal attribute;
/* search attributes for xml:space */
for (attribute = element.attributes; attribute != null; attribute = attribute.next)
{
if (attribute.attribute.equals("xml:space"))
{
if (attribute.value.equals("preserve"))
return true;
return false;
}
}
/* kludge for html docs without explicit xml:space attribute */
if (Lexer.wstrcasecmp(element.element, "pre") == 0
|| Lexer.wstrcasecmp(element.element, "script") == 0
|| Lexer.wstrcasecmp(element.element, "style") == 0)
return true;
if ( (tt != null) && (tt.findParser(element) == getParsePre()) )
return true;
/* kludge for XSL docs */
if (Lexer.wstrcasecmp(element.element, "xsl:text") == 0)
return true;
return false;
} | 9 |
@Override
public void process() throws Exception
{
Logger.getInstance().logDebug("NotifyQueueManager running...", null, null);
Notification notification = getNotifyQueue().take();
if (notification instanceof GatewayStatusNotification)
{
if (Service.getInstance().getGatewayStatusNotification() != null)
{
GatewayStatusNotification n = (GatewayStatusNotification) notification;
Service.getInstance().getGatewayStatusNotification().process(n.getGateway(), n.getOldStatus(), n.getNewStatus());
}
}
else if (notification instanceof CallNotification)
{
if (Service.getInstance().getCallNotification() != null)
{
CallNotification n = (CallNotification) notification;
Service.getInstance().getCallNotification().process(n.getGateway(), n.getCallerId());
}
}
else if (notification instanceof InboundMessageNotification)
{
if (Service.getInstance().getInboundMessageNotification() != null)
{
InboundMessageNotification n = (InboundMessageNotification) notification;
Service.getInstance().getInboundMessageNotification().process(n.getGateway(), n.getMsgType(), n.getMsg());
}
}
else if (notification instanceof OutboundMessageNotification)
{
if (Service.getInstance().getOutboundMessageNotification() != null)
{
OutboundMessageNotification n = (OutboundMessageNotification) notification;
Service.getInstance().getOutboundMessageNotification().process(n.getGateway(), n.getMsg());
}
}
Logger.getInstance().logDebug("NotifyQueueManager end...", null, null);
} | 8 |
public void setData(KeyDataType value) {
this.data = value;
} | 0 |
@Test
public void testCreditCardStringInt() {
assertEquals("John Doe", this.card2.getCardHolder());
assertEquals(3000, this.card2.getCreditLimit());
assertEquals(0, this.card2.getBalance());
} | 0 |
public boolean magicAttack(Monster theMonster){
System.out.println("How much damage would you like to do?");
System.out.println("Mana: " + this.getMana());
System.out.print("command: ");
Scanner input = new Scanner(System.in);
try{
String theMagicDamage = input.next();
int magicDamage = Integer.parseInt(theMagicDamage);
if(magicDamage > this.getMana()){
System.out.println("Not enough mana!");
magicDamage = input.nextInt();
while(magicDamage > this.getMana()){
System.out.println("Not enough mana!");
System.out.println("Enter in a different value!");
magicDamage = input.nextInt();
}
}else{
boolean monsterDead = false;
theMonster.setHealthOnAttack(magicDamage);
this.setManaOnUse(magicDamage);
System.out.println("The " + theMonster.getName() + " has taken " + magicDamage + " damage!");
if(theMonster.getHealth() <= 0){
theMonster.setHealth(0);
monsterDead = true;
System.out.println("the monster is now at " + theMonster.getHealth() + " health!");
}
if(monsterDead){
System.out.println("The " + theMonster.getName() + " has died!");
return monsterDead;
}
}
}
catch(NumberFormatException e){
System.err.print("You fail casting your magic!\n");
}
return false;
} | 5 |
public String execWithPars(Problem problem, String file)
{
String line = null;
try
{
Service service = null;
Host host = null;
if (problem != null) {
host = problem.getHost();
service = problem.getService();
}
String pluginOutput = "";
if (service != null)
pluginOutput = service.getParameter("plugin_output");
else if (host != null)
pluginOutput = host.getParameter("plugin_output");
String [] args = { file, problem != null ? problem.getHost().getHostName() : "", service != null ? service.getServiceName() : "", problem != null ? problem.getCurrent_state() : "", pluginOutput };
System.out.println("Invoking " + file);
Process p = Runtime.getRuntime().exec(args);
p.waitFor();
BufferedReader output = new BufferedReader(new InputStreamReader(p.getInputStream()));
line = output.readLine();
if (line == null || line.equals("")) {
BufferedReader errStreamReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
line = errStreamReader.readLine();
errStreamReader.close();
}
System.out.println(file + " returned: " + line);
output.close();
p.destroy();
}
catch(Exception e)
{
line = e.toString();
showException(e);
}
return line;
} | 9 |
@Override
public void init(){
btnExit = new GameButton("X",GamePanel.WIDTH-60,10);
addComponent(btnExit);
btnExit.addButtonListener(new ButtonListener(){
public void buttonClicked() {
client.close();
client.stop();
setState(GameStateManager.MULTI_PLAYER_STATE);
}
});
btnMinimize = new GameButton("_",GamePanel.WIDTH-110,10);
addComponent(btnMinimize);
btnMinimize.addButtonListener(new ButtonListener(){
public void buttonClicked() {
GamePanel.parent.setState(JFrame.ICONIFIED);
}
});
btnReady = new GameButton("Ready!",GamePanel.WIDTH-100,GamePanel.HEIGHT-50);
btnReady.setFont("Arial", 16);
addComponent(btnReady);
btnReady.addButtonListener(new ButtonListener(){
public void buttonClicked() {
ReadyState r= new ReadyState();
r.clientReady=true;
client.sendTCP(r);
btnReady.setEnabled(false);
}
});
chatInput = new TextBox("Enter text here...",10,GamePanel.HEIGHT-300+90);
chatInput.setFocus(false);
chatInput.setMultiLine(false);
chatInput.setWidth(GamePanel.WIDTH-300);
chatInput.setFont("Arial", 12);
chatInput.resizeHeight();
chatInput.addKeyListener(new KeyListener(){
@Override
public void KeyTyped(int keyCode, char keyChar) {
if(keyCode == Keys.VK_ENTER){
ChatMessage request = new ChatMessage();
String toSend = chatInput.getText().trim();
if(toSend.length()==0)return;
request.text =toSend;
client.sendTCP(request);
chatInput.setText("");
}
}
});
chatInput.addMouseListener(new ButtonListener(){
@Override
public void buttonClicked() {
if(firstClick){
firstClick = false;
chatInput.setText("");
}
}
});
chatLog= new TextBox(10,85,GamePanel.WIDTH-300,GamePanel.HEIGHT-300);
chatLog.setFont("Arial", 12);
chatLog.setEditable(false);
chatLog.setMultiLine(true);
chatLog.setText("WELCOME TO 4 P O N G chat lobby:\n");
addComponent(chatInput);
addComponent(chatLog);
//Network code
users = new String[0];
client = new Client();
Network.register(client);
new Thread(client).start();
client.addListener(new Listener(){
public void connected(Connection c)
{
chatLog.appendText("Connected to Chat!\n");
RegisterName registerName = new RegisterName();
registerName.name = userName;
client.sendTCP(registerName);
}
public void received(Connection connection, Object object){
if(object instanceof ChatMessage)
{
ChatMessage response = (ChatMessage)object;
chatLog.appendText(response.text+"\n");
}
if(object instanceof RegisteredNames)
{
RegisteredNames names = (RegisteredNames)object;
users = names.names;
ready = names.ready;
}
if(object instanceof BeginGame)
{
client.close();
client.stop();
setState(GameStateManager.MULTI_PLAYER_GAME_STATE);
}
}
public void disconnected(Connection c)
{
setState(GameStateManager.MULTI_PLAYER_STATE);
}
});
new Thread(){
public void run(){
try{
chatLog.appendText("Connecting to server \n");
client.connect(5000, "67.188.28.76", Network.TCPport,Network.UDPport);
}catch(IOException ex){chatLog.appendText(ex.getMessage());
chatLog.appendText("\nConnecting to LAN server \n");
try{
InetAddress addr = client.discoverHost(Network.UDPport, 10000);
client.connect(5000, addr, Network.TCPport,Network.UDPport);
}catch(Exception e){chatLog.appendText(e.getMessage());setState(GameStateManager.MULTI_PLAYER_STATE);}
}
}
}.start();
} | 8 |
private ImageProcessor doSmoothing(ImageProcessor minSuppres, ImageProcessor adjusted){
ImageProcessor adj = adjusted.convertToFloatProcessor();
ImageProcessor ip = minSuppres.duplicate();
adj.resetMinAndMax();
if(adj.getMax() > 0.0) adj.multiply(1.0/adj.getMax());
adj.resetMinAndMax();
ip.copyBits(adj, 0, 0, Blitter.MULTIPLY);
ip.blurGaussian(10);
//tempSmooth.setMinAndMax(0, 1.0);
return ip;
} | 1 |
@Override
public void run() {
try {
while(!Thread.interrupted()) {
// Blocks until next piece of toast is available
Sandwich s = sandwichQueue.take();
// Verify that the sandwich is coming in order,
// and that all are jellied and peanutbettered:
if(s.getId() != counter++
|| s.getTop().getStatus() != Toast.Status.JELLIED
|| s.getBottom().getStatus() != Toast.Status.PEANUTBUTTERED) {
print(">>>> Error: " + s);
System.exit(1);
} else
print("NumNum! " + s);
}
} catch(InterruptedException e) {
print("SandwichEater interruped");
}
print("SandwichEater off");
} | 5 |
public static boolean createSuggestion(String subject, String description) {
Suggestion suggestion = new Suggestion();
suggestion.setSubject(subject);
suggestion.setDescription(description);
suggestion.setAuthor(FOTE.getUser().getId());
if (isValidSuggestion(suggestion)) {
if (MongoHelper.save(suggestion, "suggestions")) {
return true;
} else {
return false;
}
} else {
return false;
}
} | 2 |
private boolean isEnnemyTouch(laser tmp){
vaisseau touche = null;
//si un vaisseau est sur le trajet
if ((touche = empire.containAndRetrieve((int) tmp.posFinx, (int) tmp.posFiny)) != null
|| (touche = republic.containAndRetrieve((int) tmp.posFinx, (int) tmp.posFiny)) != null) {
//si c'est pas un tir de son propre camp
if (touche.estRepublic && !tmp.estRepublic || !touche.estRepublic && tmp.estRepublic) {
if (tmp.grosLaser) {
touche.life-=2;//CEDI est un DPS
} else {
touche.life-=1;
}
return true;
}
}
return false;
} | 7 |
public SplitCell(ProcessedCell src, List<ProcessedCell> dst){
this.src = src;
this.dst = dst;
} | 0 |
public static void compexch(Comparable[] a, int i, int j)
{
if (less(a[j], a[i]))
exch(a, j, i);
} | 1 |
private void closest(CommandSender sender) {
if (!(sender instanceof Player)) {
noConsole(sender);
return;
}
if (!sender.hasPermission("graveyard.command.closest")) {
noPermission(sender);
return;
}
Player player = (Player) sender;
Spawn point = SpawnPoint.getClosestAllowed(player);
commandLine(sender);
if (point != null) {
sender.sendMessage(ChatColor.WHITE + "Closest spawn point is: " + ChatColor.RED + SpawnPoint.getClosestAllowed(player).getName());
} else {
sender.sendMessage(ChatColor.WHITE + "Could not find the closest spawn point to your location.");
}
commandLine(sender);
} | 3 |
public static Document deepCloneDocument(Document doc, DOMImplementation impl) {
Element root = doc.getDocumentElement();
Document result = impl.createDocument(root.getNamespaceURI(),
root.getNodeName(),
null);
Element rroot = result.getDocumentElement();
boolean before = true;
for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n == root) {
before = false;
if (root.hasAttributes()) {
NamedNodeMap attr = root.getAttributes();
int len = attr.getLength();
for (int i = 0; i < len; i++) {
rroot.setAttributeNode((Attr)result.importNode(attr.item(i),
true));
}
}
for (Node c = root.getFirstChild();
c != null;
c = c.getNextSibling()) {
rroot.appendChild(result.importNode(c, true));
}
} else {
if (n.getNodeType() != Node.DOCUMENT_TYPE_NODE) {
if (before) {
result.insertBefore(result.importNode(n, true), rroot);
} else {
result.appendChild(result.importNode(n, true));
}
}
}
}
return result;
} | 7 |
public boolean chequeDateCheck(String currentDate){
this.currentDateSplit(currentDate);
if(year>=this.currentYear){
if(month>=this.currentMonth){
if(date>=this.currentDate){
return true;
}
}
}
return false;
} | 3 |
public void run() {
while (active) {
int mod = timeElapsed % 5;
switch(mod)
{
case 0:
log.info("info level log.");
break;
case 1:
log.debug("debug level log.");
break;
case 2:
log.warn("warn level log");
break;
case 3:
log.error("error level log");
break;
case 4:
log.fatal("fatal level log");
break;
}
try {
Random r = new Random();
int i = r.nextInt(6) + 5;
timeElapsed += i;
Thread.sleep(i*1000);
} catch (Exception e) {
log.error("Thread interrupted " + e.getMessage(), e);
}
}
} | 7 |
public void initBall() {
double[] a = coords.get("BALL");
a[DX] = speedX;
Random rand = new Random();
int temp = rand.nextInt(10);
if(temp < 5) {
a[DY] = 1;
}
if(temp > 5) {
a[DY] = -1;
}
if(temp == 5 || temp < 0) {
temp = rand.nextInt(10);
}
coords.put("BALL", a);
} | 4 |
public static boolean writeWikiSample(BookmarkReader reader, List<Bookmark> userSample, String filename, List<int[]> catPredictions) {
try {
FileWriter writer = new FileWriter(new File("./data/csv/" + filename + ".txt"));
BufferedWriter bw = new BufferedWriter(writer);
int userCount = 0;
// TODO: check encoding
for (Bookmark bookmark : userSample) {
bw.write("\"" + reader.getUsers().get(bookmark.getUserID()).replace("\"", "") + "\";");
bw.write("\"" + reader.getResources().get(bookmark.getWikiID()).replace("\"", "") + "\";");
bw.write("\"" + bookmark.getTimestamp().replace("\"", "") + "\";\"");
int i = 0;
for (int tag : bookmark.getTags()) {
bw.write(URLEncoder.encode(reader.getTags().get(tag).replace("\"", ""), "UTF-8"));
if (++i < bookmark.getTags().size()) {
bw.write(',');
}
}
bw.write("\";\"");
List<Integer> userCats = (catPredictions == null ?
bookmark.getCategories() : Ints.asList(catPredictions.get(userCount++)));
i = 0;
for (int cat : userCats) {
bw.write(URLEncoder.encode((catPredictions == null ? reader.getCategories().get(cat).replace("\"", "") : reader.getTags().get(cat)).replace("\"", ""), "UTF-8"));
if (++i < userCats.size()) {
bw.write(',');
}
}
bw.write("\"");
if (bookmark.getRating() != -2) {
bw.write(";\"" + bookmark.getRating() + "\"");
}
bw.write("\n");
}
bw.flush();
bw.close();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
} | 9 |
@Override
public boolean load() {
try {
DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(inputFileName)));
width = dis.readInt();
height = dis.readInt();
data = new float[height][width];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
data[i][j] = dis.readFloat();
}
}
dis.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(RawCutter.class.getName()).log(Level.SEVERE, null, ex);
return false;
} catch (IOException ex) {
Logger.getLogger(RawCutter.class.getName()).log(Level.SEVERE, null, ex);
return false;
}
return true;
} | 4 |
private static <T extends Comparable<T>> void printNodeInternal(List<TreeNode<T>> nodes, int level, int maxLevel) {
if (nodes.isEmpty() || BTreePrinter.isAllElementsNull(nodes))
return;
int floor = maxLevel - level;
int endgeLines = (int) Math.pow(2, (Math.max(floor - 1, 0)));
int firstSpaces = (int) Math.pow(2, (floor)) - 1;
int betweenSpaces = (int) Math.pow(2, (floor + 1)) - 1;
BTreePrinter.printWhitespaces(firstSpaces);
List<TreeNode<T>> newNodes = new ArrayList<TreeNode<T>>();
for (TreeNode<T> node : nodes) {
if (node != null) {
System.out.print(node.data);
newNodes.add(node.leftNode);
newNodes.add(node.rightNode);
} else {
newNodes.add(null);
newNodes.add(null);
System.out.print(" ");
}
BTreePrinter.printWhitespaces(betweenSpaces);
}
System.out.println("");
for (int i = 1; i <= endgeLines; i++) {
for (int j = 0; j < nodes.size(); j++) {
BTreePrinter.printWhitespaces(firstSpaces - i);
if (nodes.get(j) == null) {
BTreePrinter.printWhitespaces(endgeLines + endgeLines + i + 1);
continue;
}
if (nodes.get(j).leftNode != null)
System.out.print("/");
else
BTreePrinter.printWhitespaces(1);
BTreePrinter.printWhitespaces(i + i - 1);
if (nodes.get(j).rightNode != null)
System.out.print("\\");
else
BTreePrinter.printWhitespaces(1);
BTreePrinter.printWhitespaces(endgeLines + endgeLines - i);
}
System.out.println("");
}
printNodeInternal(newNodes, level + 1, maxLevel);
} | 9 |
private void refreshChannel() {
synchronized (this) {
OutputStream stream = new OutputStream();
stream.writeString(ownerDisplayName);
String ownerName = Utils.formatPlayerNameForDisplay(owner);
stream.writeByte(getOwnerDisplayName().equals(ownerName) ? 0 : 1);
if (!getOwnerDisplayName().equals(ownerName))
stream.writeString(ownerName);
stream.writeLong(Utils.stringToLong(getChannelName()));
stream.writeByte(getWhoCanKickOnChat());
stream.writeByte(getPlayers().size());
for (Player p : getPlayers()) {
String displayName = p.getDisplayName();
String name = Utils.formatPlayerNameForDisplay(p.getUsername());
stream.writeString(displayName);
stream.writeByte(displayName.equals(name) ? 0 : 1);
if (!displayName.equals(name))
stream.writeString(name);
stream.writeShort(1);
int rank = getRank(p.getUsername());
stream.writeByte(rank);
stream.writeString(Settings.SERVER_NAME);
}
dataBlock = new byte[stream.getOffset()];
stream.setOffset(0);
stream.getBytes(dataBlock, 0, dataBlock.length);
for (Player player : players)
player.getPackets().sendFriendsChatChannel();
}
} | 6 |
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
OutputStreamWriter wr = null;
InputStream in = null;
OutputStream out = null;
try {
Map<String,Object> reqMap = new HashMap<String,Object>();
Enumeration<?> en = req.getParameterNames();
String key = new String();
/**
* Converting all Map Keys into Upper Case
**/
while(en.hasMoreElements()){
key = (String)en.nextElement();
reqMap.put(key.toUpperCase(), req.getParameter(key));
}
wmsParamBean wmsBean = new wmsParamBean();
BeanUtils.populate(wmsBean, reqMap);
HttpSession session = req.getSession(true);
/**
* Reading the saved SLD
**/
String sessionName = wmsBean.getLAYER();
if( sessionName.length() < 1 )
sessionName = wmsBean.getLAYERS();
if( session.getAttribute(sessionName) != null) {
wmsBean.setSLD_BODY(
(String)session.getAttribute(
sessionName) );
wmsBean.setSLD("");
wmsBean.setSTYLES("");
}
/**
* Generating Map from GeoServer
**/
URL geoURL = new URL(this.geoserverURL);
URLConnection geoConn = geoURL.openConnection();
geoConn.setDoOutput(true);
wr = new OutputStreamWriter(geoConn.getOutputStream(),"UTF-8");
wr.write( wmsBean.getURL_PARAM() );
wr.flush();
in = geoConn.getInputStream();
out = res.getOutputStream();
res.setContentType(wmsBean.getFORMAT());
int b;
while((b = in.read()) != -1 ) {
out.write(b);
}
} catch (Exception e) {
//e.printStackTrace();
}
finally {
if( out != null ) {
out.flush();
out.close();
}
if( in != null ) {
in.close();
}
if( wr != null ) {
wr.close();
}
}
} | 9 |
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int N = in.nextInt(); // the number of points used to draw the surface of Mars.
in.nextLine();
int LAND_X = 0;
int LAND_Y = 0;
for (int i = 0; i < N; i++) {
LAND_X = in.nextInt(); // X coordinate of a surface point. (0 to 6999)
LAND_Y = in.nextInt(); // Y coordinate of a surface point. By linking all the points together in a sequential fashion, you form the surface of Mars.
in.nextLine();
}
// game loop
while (true) {
int X = in.nextInt();
int Y = in.nextInt();
int HS = in.nextInt(); // the horizontal speed (in m/s), can be negative.
int VS = in.nextInt(); // the vertical speed (in m/s), can be negative.
int F = in.nextInt(); // the quantity of remaining fuel in liters.
int R = in.nextInt(); // the rotation angle in degrees (-90 to 90).
int P = in.nextInt(); // the thrust power (0 to 4).
in.nextLine();
// Write an action using System.out.println()
// To debug: System.err.println("Debug messages...");
if(VS < 0 && Y < LAND_Y+1250) {
P = P+1;
if(P > 4) P = 4;
System.out.println("0 " + P);
}
else {
P = P - 1;
if(P < 0) P = 0;
System.out.println("0 " + P);
}
}
} | 6 |
protected void linkProgram(List<VertexAttrib> attribLocations) throws LWJGLException {
if (!valid())
throw new LWJGLException("trying to link an invalid (i.e. released) program");
uniforms.clear();
// bind user-defined attribute locations
if (attribLocations != null) {
for (VertexAttrib a : attribLocations) {
if (a != null)
glBindAttribLocation(program, a.location, a.name);
}
}
attachShaders();
glLinkProgram(program);
int comp = glGetProgrami(program, GL_LINK_STATUS);
int len = glGetProgrami(program, GL_INFO_LOG_LENGTH);
String err = glGetProgramInfoLog(program, len);
if (err != null && err.length() != 0)
log = err + "\n" + log;
if (log != null)
log = log.trim();
if (comp == GL11.GL_FALSE)
throw new LWJGLException(log.length()!=0 ? log : "Could not link program");
fetchUniforms();
fetchAttributes();
} | 9 |
public static String insertLineBreaks(String message, int lineBreak,
String lineBreakSymbol, String padString, boolean breakBeforeLineBreak) {
StringBuilder sb = new StringBuilder();
StringTokenizer st = new StringTokenizer(message != null ? message : "",
" ");
if (st.hasMoreElements()) {
sb.append(st.nextElement().toString());
}
int length = sb.length();
int pos;
int count = 0;
while (st.hasMoreElements()) {
String tmp = st.nextElement().toString();
if ((lineBreak < Integer.MAX_VALUE)
&& ((length >= lineBreak) || (breakBeforeLineBreak && (length + tmp
.length()) >= lineBreak))) {
sb.append(lineBreakSymbol);
if (padString != null) {
sb.append(padString);
}
count++;
length = 0;
} else {
sb.append(' ');
}
// Append current element
sb.append(tmp);
// Change length
if ((pos = tmp.indexOf(lineBreakSymbol)) >= 0) {
length = tmp.length() - pos - lineBreakSymbol.length();
} else {
length += tmp.length() + 1;
}
}
return sb.toString();
} | 9 |
protected void loadBean() throws IntrospectionException {
propertyMap = new HashMap<String, PropertyDescriptor>();
BeanInfo info = Introspector.getBeanInfo(beanClass);
PropertyDescriptor[] properties = info.getPropertyDescriptors();
for (int i = 0; i < properties.length; i++) {
propertyMap.put(properties[i].getName(), properties[i]);
}
} | 1 |
private void layoutContainerHorizontally(Container parent)
{
int components = parent.getComponentCount();
int visibleComponents = getVisibleComponents( parent );
if (components == 0) return;
// Determine space available for components using relative sizing
float relativeTotal = 0.0f;
Insets insets = parent.getInsets();
int spaceAvailable = parent.getSize().width
- insets.left
- insets.right
- ((visibleComponents - 1) * gap)
- (2 * borderGap);
for (int i = 0 ; i < components ; i++)
{
Component component = parent.getComponent(i);
if (! component.isVisible()) continue;
Float constraint = constraints.get(component);
if (constraint == null)
{
Dimension d = component.getPreferredSize();
spaceAvailable -= d.width;
}
else
{
relativeTotal += constraint.doubleValue();
}
}
// Allocate space to each component using relative sizing
int[] relativeSpace = allocateRelativeSpace(parent, spaceAvailable, relativeTotal);
// Position each component in the container
int x = insets.left + borderGap;
int y = insets.top;
int insetGap = insets.top + insets.bottom;
int parentHeight = parent.getSize().height - insetGap;
for (int i = 0 ; i < components ; i++)
{
Component component = parent.getComponent(i);
if (! component.isVisible()) continue;
if (i > 0)
x += gap;
Dimension d = component.getPreferredSize();
if (fill)
d.height = parentHeight - fillGap;
Float constraint = constraints.get(component);
if (constraint == null)
{
component.setSize( d );
int locationY = getLocationY(component, parentHeight) + y;
component.setLocation(x, locationY);
x += d.width;
}
else
{
int width = relativeSpace[i];
component.setSize(width, d.height);
int locationY = getLocationY(component, parentHeight) + y;
component.setLocation(x, locationY);
x += width;
}
}
} | 9 |
public JSONWriter object() throws JSONException {
if (this.mode == 'i') {
this.mode = 'o';
}
if (this.mode == 'o' || this.mode == 'a') {
this.append("{");
this.push(new JSONObject());
this.comma = false;
return this;
}
throw new JSONException("Misplaced object.");
} | 3 |
public byte[] get(int id) {
try {
byte header[] = new byte[6];
index.seek(id * 6);
index.readFully(header);
int length = ((header[0] & 0xff) << 16) + ((header[1] & 0xff) << 8) + (header[2] & 0xff);
int position = ((header[3] & 0xff) << 16) + ((header[4] & 0xff) << 8) + (header[5] & 0xff); // 24 bit
if (position > 0) {
int offset = 0;
int blockOffset = 0;
byte file[] = new byte[length];
while (offset < length) {
byte header2[] = new byte[8];
int pos = position * 520;
data.seek(pos);
// data.seek(pos < 0 ? 0 : pos);
data.readFully(header2);
position = ((header2[4] & 0xff) << 16) + ((header2[5] & 0xff) << 8) + (header2[6] & 0xff);
while (offset < length && blockOffset < 512) {
file[offset] = (byte) data.read();
offset++;
blockOffset++;
}
blockOffset = 0;
}
return file;
}
} catch(Exception e) {
e.printStackTrace();
}
return null;
} | 5 |
public boolean generate(World var1, Random var2, int var3, int var4, int var5) {
int var11;
for(boolean var6 = false; ((var11 = var1.getBlockId(var3, var4, var5)) == 0 || var11 == Block.leaves.blockID) && var4 > 0; --var4) {
;
}
for(int var7 = 0; var7 < 4; ++var7) {
int var8 = var3 + var2.nextInt(8) - var2.nextInt(8);
int var9 = var4 + var2.nextInt(4) - var2.nextInt(4);
int var10 = var5 + var2.nextInt(8) - var2.nextInt(8);
if(var1.isAirBlock(var8, var9, var10) && ((BlockFlower)Block.blocksList[this.field_28058_a]).canBlockStay(var1, var8, var9, var10)) {
var1.setBlock(var8, var9, var10, this.field_28058_a);
}
}
return true;
} | 6 |
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == jRecoverPanel.getCancelButton())
{
setVisible(false);
jLoginFrame.setVisible(true);
dispose();
}
else if (ae.getSource() == jRecoverPanel.getRecoveryButton())
{
String szEmail = jRecoverPanel.getEmailField();
String szUsername = jRecoverPanel.getUsernameField();
String szAnswer = jRecoverPanel.getSecurityAnswerField();
String szQuestion = jRecoverPanel.getSecurityQuestionField();
if(! (szEmail.isEmpty() || szUsername.isEmpty() ||
szAnswer.isEmpty() || szQuestion.isEmpty()) )
{
try
{
String rec = ub.recover(szUsername,szEmail,szQuestion,szAnswer);
if(rec!=null)
{
JOptionPane.showMessageDialog(null,"Your passcode is\r\n"+
rec);
setVisible(false);
jLoginFrame.setVisible(true);
dispose();
}
else
JOptionPane.showMessageDialog(null,"Your passcode could not be recovered.\r\nVerify you've entered the fields correctly");
}
catch(IOException e)
{
JOptionPane.showMessageDialog(null,e.getMessage());
}
}
else
JOptionPane.showMessageDialog(null,"Recovery fields can not be empty");
}
} | 8 |
public void mousePressed(MouseEvent e){
if(SwingUtilities.isLeftMouseButton(e)){
dragging = true;
startPoint = e.getLocationOnScreen();
startBounds = e.getComponent ().getBounds();
}
} | 1 |
void secondGuessUpdate(int a, int b, int a1, int b1){
if (a + b == 3) {
updateAnsSet("4567", a1, b1);
} else if (a == 0 && b == 2) {
updateAnsSet("0168", a1, b1);
} else if (a == 1 && b == 1) {
updateAnsSet("0167", a1, b1);
} else if (a == 2 && b == 0) {
updateAnsSet("1067", a1, b1);
} else if (a + b == 1) {
updateAnsSet(guessNumber, a1, b1);
} else{
updateAnsSet(guessNumber, a1, b1);
}
} | 8 |
public int value() {
return count.get();
} | 0 |
@Override
public void setValueAt(Object value, int row, int col) {
switch (col) {
case 0:
sortedElements.get(row).setStatus((Status) value);
try {
model.saveStatusFile();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"Error saving status file: " + e);
}
model.fireCourseStatusChanged(selected);
break;
case 2:
sortedElements.get(row).setDuration((Integer) value);
saveModelAndInform();
break;
default:
throw new RuntimeException("Column " + col
+ " should not be editable");
}
} | 3 |
private void reload() throws IOException {
new Thread() {
@Override
public void run() {
try {
if (debug)
logger.log(Level.DEBUG, "Reloading devices...");
// Load ADB devices
deviceMap.clear();
DefaultListModel model = new DefaultListModel();
for (Device dev : adbController.getConnectedDevices()) {
model.addElement(dev.toString());
deviceMap.put(dev, new ImageIcon(this.getClass().getResource("/eu/m4gkbeatz/androidtoolkit/resources/device/status_" + String.valueOf(dev.getState()).toLowerCase() + ".png")));
}
jList1.setModel(model);
// Load fastboot devices.
model = new DefaultListModel();
for (String str : adbController.getFastbootController().getConnectedDevices())
model.addElement(str);
jList2.setModel(model);
jList1.setSelectedIndex(SELECTED_DEVICE);
if (jList2.getSelectedValue() == null || jList2.getSelectedIndex() == -1 && jList2.getModel().getSize() != 0)
jList2.setSelectedIndex(0);
} catch (IOException ex) {
exception = ex;
}
interrupt();
}
}.start();
if(exception != null)
throw exception;
} | 8 |
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(MainFame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainFame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainFame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFame.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 MainFame().setVisible(true);
}
});
} | 6 |
public Backup[] getBackups(){
String [] bdirs = new File(BACKUP_DIR).list();
Backup[] backups = new Backup[bdirs.length];
for (int i = 0;i<bdirs.length;i++){
String path = BACKUP_DIR+bdirs[i];
String name = getName(path);
String date = getDate(path);
String number = getNumber(path);
backups[i] = new Backup(name,path,date,number);
}
return backups;
} | 1 |
private void setProperAnimation() {
if (isFalling()) {
setProperFallingAnimation();
return;
}
if (facing == 1) {
if (!getCurrentAnimation().equals(Characters.WALK_RIGHT)) {
setCurrentAnimation(Characters.WALK_RIGHT);
}
return;
}
if (facing == -1) {
if (!getCurrentAnimation().equals(Characters.WALK_LEFT)) {
setCurrentAnimation(Characters.WALK_LEFT);
}
return;
}
if (!getCurrentAnimation().equals(Characters.IDLE)) {
setCurrentAnimation(Characters.IDLE);
}
return;
} | 6 |
public void draw()
{
Display.fill(
shipColour.getRed(),
shipColour.getGreen(),
shipColour.getBlue(),
shipColour.getAlpha());
if(drawLines)
{ Display.stroke(0); }
else
{ Display.noStroke(); }
if(drawDeadCells)
{
if(shipColour.getAlpha()>4)
{
shipColour = new Color(
shipColour.getRed(),
shipColour.getGreen(),
shipColour.getBlue(),
shipColour.getAlpha() - 4);
}
else
{
shipColour = new Color(
shipColour.getRed(),
shipColour.getGreen(),
shipColour.getBlue(),
0);
good2ReSpawn = true;
drawDeadCells = false;
perent.setMessage("Hit fire to Respawn!");
}
explosionCount+=2;
}
if(!good2ReSpawn)
{
for(int count1 = 0; count1<shipCells.length; count1++)
{
if(drawDeadCells)
{
Display.pushMatrix();
Display.translate(
(explosionNums[count1][0]*explosionCount),
(explosionNums[count1][1]*explosionCount),
((explosionNums[count1][2]*5)*explosionCount));
Display.rotateY((explosionNums[count1][3]*explosionCount)/5);
Display.rotateX((explosionNums[count1][4]*explosionCount)/5);
}
Display.beginShape();
for(int count2 = 0; count2<shipCells[count1].length; count2++)
{
Display.vertex(
shipCells[count1][count2][0],
shipCells[count1][count2][1],
shipCells[count1][count2][2]);
}
Display.endShape();
if(drawDeadCells)
{ Display.popMatrix(); }
}
}
} | 8 |
public static int compare(ItalianDeckCard card1,ItalianDeckCard card2, ItalianDeckSuit suit){
if(card1.getSuit().toString().equals(suit.toString())&&!card2.getSuit().toString().equals(suit.toString())){
//TODO The player with life takes the card
return 1;
} else if(card2.getSuit().toString().equals(suit.toString())&&!card1.getSuit().toString().equals(suit.toString())){
//TODO The player with life takes the card
return -1;
} //else
return card1.getRank().getCardNumber() - card2.getRank().getCardNumber();
} | 4 |
public void createBufferedReader()
{
try {
fileReader = Files.newBufferedReader(file);
} catch (IOException | SecurityException e) {
System.err.format("IOException: %s%n", e);
try {
if (fileReader != null) { fileReader.close(); }
} catch (IOException x) {}
}
}//end of FileHandler::createBufferedReader | 3 |
@Override
public void deserialize(Buffer buf) {
guildOwner = buf.readString();
worldX = buf.readShort();
if (worldX < -255 || worldX > 255)
throw new RuntimeException("Forbidden value on worldX = " + worldX + ", it doesn't respect the following condition : worldX < -255 || worldX > 255");
worldY = buf.readShort();
if (worldY < -255 || worldY > 255)
throw new RuntimeException("Forbidden value on worldY = " + worldY + ", it doesn't respect the following condition : worldY < -255 || worldY > 255");
subAreaId = buf.readShort();
if (subAreaId < 0)
throw new RuntimeException("Forbidden value on subAreaId = " + subAreaId + ", it doesn't respect the following condition : subAreaId < 0");
nbMount = buf.readByte();
nbObject = buf.readByte();
price = buf.readInt();
if (price < 0)
throw new RuntimeException("Forbidden value on price = " + price + ", it doesn't respect the following condition : price < 0");
} | 6 |
public void keyPressed(KeyEvent e)
{
int keycode = e.getKeyCode();
System.out.println("key pressed: ");
switch(keycode)
{
case KeyEvent.VK_UP:
System.out.println("up");
Sounds.move.play();
ShipShopWeaponsMenu.moveSelectionOvalUp();
break;
case KeyEvent.VK_DOWN:
System.out.println("down");
Sounds.move.play();
ShipShopWeaponsMenu.moveSelectionOvalDown();
break;
case KeyEvent.VK_LEFT:
System.out.println("left");
Sounds.move.play();
ShipShopWeaponsMenu.moveSelectionOvalLeft();
break;
case KeyEvent.VK_RIGHT:
System.out.println("right");
Sounds.move.play();
ShipShopWeaponsMenu.moveSelectionOvalRight();
break;
case KeyEvent.VK_ENTER:
System.out.println("enter");
System.out.println(ShipShopWeaponsMenu.getSelection());
Sounds.select.play();
try {
ShipShopWeaponsMenuEventHandler.handleEvent(ShipShopWeaponsMenu.getSelection());
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
}
} | 6 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ArCustomer other = (ArCustomer) obj;
if (!Objects.equals(this.szCustomerId, other.szCustomerId)) {
return false;
}
return true;
} | 3 |
@Override
public void rotateY(int angle) {
base = DimensionalTrasform.rotateY(angle, base);
setColoredExes();
} | 0 |
private static String trimLineTextWithWidth(String text, int width) {
String tText = text.trim();
if ("".equals(tText)) return "";
if (text.length() <= width) return text;
StringBuilder sb = new StringBuilder();
int currLoc = 0, nextLoc = 0;
do {
currLoc = 0;
nextLoc = tText.lastIndexOf(" ", width);
if (nextLoc < currLoc) {
nextLoc = tText.indexOf(" ", currLoc);
if (nextLoc < 0) nextLoc = tText.length();
}
sb.append(tText.substring(currLoc, nextLoc));
tText = (tText.length() > nextLoc + 1) ? tText.substring(nextLoc + 1).trim() : "";
if (tText.length() > 0) {
sb.append(LINE_SEPARATOR);
if (tText.length() < width + 1) {
sb.append(tText);
tText = "";
}
}
} while (tText.length() > 0);
return sb.toString();
} | 8 |
private void init() throws NoInputException {
printInitialScenario490();
initialPurchasesOfPlayer690();
initialShootingRanking920();
screen.clear();
print("<i>** Your trip is about to begin... **</i>");
print();
for (int j = 0; j < 20; j++) {
if (m > 2039) {
madeIt3190(j);
break;
}
print("<b>Monday, " + da[j] + ", 1847</b>. You are " + whereAreWe());
print();
if (f < 6) {
print("<b>** You're low on food. Better buy some or go hunting soon. **");
print();
}
if (ks == 1 || kh == 1) {
t = t - 10;
if (t < 0) {
needDoctorBadly3010(j);
}
print("Doctor charged <b>$10</b> for his services");
print("to treat your " + (ks == 1 ? "illness." : "injuries."));
}
// MP flag to be done?
m = (int) (m + .5);
print("Total mileage to date is: <b>" + ((int) m) + "</b>");
m += 200 + (a - 110) / 2.5 + 10 * rnd();
print();
// Calculate how far we travel in 2 weeks
print("Here's what you now have (no. of bullets, $ worth of other items) :");
printInventory3350();
question1000(j);
eating1310(j);
screen.clear();
riders1390(j);
// print();
events1800(j);
// print();
montains2640(j);
if (skb.hasMore()) {
screen.clear();
}
}
} | 8 |
public ImagePlus apply()
{
final int width = input.getWidth();
final int height = input.getHeight();
final int depth = input.getStackSize();
//final ImagePlus imageOutput = input.duplicate();
//final ImageStack imageStackOutput = imageOutput.getStack();
final ImageStack inputStack = input.getStack();
final ImagePlus binaryOutput = input.duplicate();
final ImageStack binaryStackOutput = binaryOutput.getStack();
// Initialize binary output image
// Binarize output image
for (int k = 0; k < depth; ++k)
for (int i = 0; i < width; ++i)
for (int j = 0; j < height; ++j)
binaryStackOutput.setVoxel(i, j, k, 1);
// Apply 3x3x3 minimum filter
IJ.log(" Minimum filtering...");
final long t0 = System.currentTimeMillis();
final double[][][] localMinValues = filterMin3D( input );
if( null == localMinValues )
return null;
final long t1 = System.currentTimeMillis();
IJ.log(" Filtering took " + (t1-t0) + " ms.");
// find regional minima
IJ.showStatus( "Finding regional minima..." );
final AtomicInteger ai = new AtomicInteger(0);
final int n_cpus = Prefs.getThreads();
final int dec = (int) Math.ceil((double) depth / (double) n_cpus);
Thread[] threads = ThreadUtil.createThreadArray(n_cpus);
for (int ithread = 0; ithread < threads.length; ithread++)
{
threads[ithread] = new Thread() {
public void run() {
for (int k = ai.getAndIncrement(); k < n_cpus; k = ai.getAndIncrement())
{
int zmin = dec * k;
int zmax = dec * ( k + 1 );
if (zmin<0)
zmin = 0;
if (zmax > depth)
zmax = depth;
findMinimaRange( zmin, zmax, inputStack,
binaryStackOutput, localMinValues );
}
}
};
}
ThreadUtil.startAndJoin(threads);
IJ.showProgress(1.0);
//(new ImagePlus("valued minima", imageStackOutput)).show();
ImagePlus output = new ImagePlus("regional-minima-" + input.getTitle(), binaryStackOutput);
output.setCalibration( input.getCalibration() );
return output;
} //apply | 8 |
@EventHandler
public void onRightClick(PlayerInteractEvent ev) {
if (ev.getAction() == Action.RIGHT_CLICK_BLOCK) {
Player p = ev.getPlayer();
if (mahData.checkMuddles(mudz.parseLocation(ev.getClickedBlock().getLocation()))) {
if (!isInCooldown(p.getUniqueId())) {
MuddleUtils.randomTeleport(ev.getPlayer());
MuddleUtils.outputDebug("LISTENER 2 OK!");
kewlDowwwwn.put(p.getUniqueId(), System.currentTimeMillis() + coolteim);
} else {
p.sendMessage(ChatColor.RED + "You may only use this once every 10 minutes.");
}
}
}
} | 3 |
public static String getIDFromFile(String filename, String setting) {
JSONObject file = null;
try {
file = Util.readJSONFile("./" + filename);
} catch (IOException ex) {
Logger.error("IDHelper.getIDFromFile", "Failed to load external ID file!", false, ex);
return null;
}
JSONArray modsArray = (JSONArray) file.get("mode");
if (modsArray != null) {
for (Object obj : modsArray.toArray()) {
JSONObject mod = (JSONObject) obj;
String modname = (String) mod.get("name");
if (setting.contains(modname)) {
int rangeStart = Integer.parseInt((String) mod.get("range"));
int bump = 0;
if (IDRanges.containsKey(modname)) {
bump = IDRanges.get(modname);
}
IDRanges.put(modname, bump + 1);
return Integer.toString(rangeStart + bump);
}
}
}
return null;
} | 5 |
private void loadBeanDefinitionsFromImportedResources(final Map<String, Class<? extends BeanDefinitionReader>> importedResources) {
final Map<Class<?>, BeanDefinitionReader> readerInstanceCache = new HashMap<Class<?>, BeanDefinitionReader>();
for (final Map.Entry<String, Class<? extends BeanDefinitionReader>> entry : importedResources.entrySet()) {
final String resource = entry.getKey();
final Class<? extends BeanDefinitionReader> readerClass = entry.getValue();
if (!readerInstanceCache.containsKey(readerClass)) {
try {
// Instantiate the specified BeanDefinitionReader
final BeanDefinitionReader readerInstance = readerClass.getConstructor(BeanDefinitionRegistry.class).newInstance(this.registry);
// Delegate the current ResourceLoader to it if possible
if (readerInstance instanceof AbstractBeanDefinitionReader) {
final AbstractBeanDefinitionReader abdr = ((AbstractBeanDefinitionReader) readerInstance);
abdr.setResourceLoader(this.resourceLoader);
abdr.setEnvironment(this.environment);
}
readerInstanceCache.put(readerClass, readerInstance);
} catch (final Exception ex) {
throw new IllegalStateException("Could not instantiate BeanDefinitionReader class [" + readerClass.getName() + "]");
}
}
final BeanDefinitionReader reader = readerInstanceCache.get(readerClass);
// TODO SPR-6310: qualify relative path locations as done in AbstractContextLoader.modifyLocations
reader.loadBeanDefinitions(resource);
}
} | 9 |
private static boolean updateJoinCardinality(Join j, Map<String, Integer> tableAliasToId,
Map<String, TableStats> tableStats) {
DbIterator[] children = j.getChildren();
DbIterator child1 = children[0];
DbIterator child2 = children[1];
int child1Card = 1;
int child2Card = 1;
String[] tmp1 = j.getJoinField1Name().split("[.]");
String tableAlias1 = tmp1[0];
String pureFieldName1 = tmp1[1];
String[] tmp2 = j.getJoinField2Name().split("[.]");
String tableAlias2 = tmp2[0];
String pureFieldName2 = tmp2[1];
boolean child1HasJoinPK = Database.getCatalog()
.getPrimaryKey(tableAliasToId.get(tableAlias1).intValue()).equals(pureFieldName1);
boolean child2HasJoinPK = Database.getCatalog()
.getPrimaryKey(tableAliasToId.get(tableAlias2).intValue()).equals(pureFieldName2);
if (child1 instanceof Operator) {
Operator child1O = (Operator) child1;
boolean pk = updateOperatorCardinality(child1O, tableAliasToId, tableStats);
child1HasJoinPK = pk || child1HasJoinPK;
child1Card = child1O.getEstimatedCardinality();
child1Card = child1Card > 0 ? child1Card : 1;
} else if (child1 instanceof SeqScan) {
child1Card = tableStats.get(((SeqScan) child1).getTableName()).estimateTableCardinality(1.0);
}
if (child2 instanceof Operator) {
Operator child2O = (Operator) child2;
boolean pk = updateOperatorCardinality(child2O, tableAliasToId, tableStats);
child2HasJoinPK = pk || child2HasJoinPK;
child2Card = child2O.getEstimatedCardinality();
child2Card = child2Card > 0 ? child2Card : 1;
} else if (child2 instanceof SeqScan) {
child2Card = tableStats.get(((SeqScan) child2).getTableName()).estimateTableCardinality(1.0);
}
j.setEstimatedCardinality(JoinOptimizer.estimateTableJoinCardinality(j.getJoinPredicate()
.getOperator(), tableAlias1, tableAlias2, pureFieldName1, pureFieldName2, child1Card,
child2Card, child1HasJoinPK, child2HasJoinPK, tableStats, tableAliasToId));
return child1HasJoinPK || child2HasJoinPK;
} | 9 |
@Override
public void runTask(InstallTasksQueue queue) throws IOException {
if (this.zipExtractLocation != null)
unzipFile(this.copyTaskQueue, this.cacheLocation, this.zipExtractLocation, this.filter);
if (sourceUrl != null && (!this.cacheLocation.exists() || (fileVerifier != null && !fileVerifier.isFileValid(this.cacheLocation))))
downloadFile(this.downloadTaskQueue, this.sourceUrl, this.cacheLocation, this.fileVerifier, this.friendlyFileName);
} | 5 |
public static void parse( String queryString,
String encoding,
Map<String,String> destination )
throws NullPointerException,
UnsupportedEncodingException {
if( queryString == null )
throw new NullPointerException( "Cannot parse null-query." );
String[] split = queryString.split( "\\&" );
for( int i = 0; i < split.length; i++ ) {
// Split is empty?
// (should not happen in well-formed query strings, but this might be more secure)
if( (split[i] = split[i].trim()).length() == 0 )
continue;
String key = null;
String value = null;
int index = split[i].indexOf("=");
// Split consists of '=' only?
if( split[i].length() == 1 )
continue;
if( index == 0 ) {
// Key is empty
key = "";
value = split[i].substring( 1, split[i].length() ).trim();
} else if( index == -1 ) {
// No '=' at all (key only)
key = split[i];
value = "";
} else if( index+1 >= split[i].length() ) {
// value is empty
key = split[i].substring( 0, split[i].length()-1 ).trim();
value = "";
} else {
// Both are present
key = split[i].substring( 0, index ).trim();
value = split[i].substring( index+1, split[i].length() ).trim();
}
// Decode both
// (might throw UnsupportedEncodingException)
key = URLDecoder.decode( key, encoding );
value = URLDecoder.decode( value, encoding );
// Store in map
destination.put( key, value );
}
} | 7 |
@Override
public void mouseEntered(MouseEvent e) {
} | 0 |
private static GeneralNameValueConfig getConfigByField(String field,ArrayList<GeneralNameValueConfig> fieldSet) {
for(GeneralNameValueConfig cfg : fieldSet) {
if(cfg.fieldName.equalsIgnoreCase(field)) {
return cfg;
}
}
return null;
} | 2 |
public void test_set_RP_int_intarray_int() {
OffsetDateTimeField field = new MockOffsetDateTimeField();
int[] values = new int[] {10, 20, 30, 40};
int[] expected = new int[] {10, 20, 30, 40};
int[] result = field.set(new TimeOfDay(), 2, values, 30);
assertEquals(true, Arrays.equals(result, expected));
values = new int[] {10, 20, 30, 40};
expected = new int[] {10, 20, 29, 40};
result = field.set(new TimeOfDay(), 2, values, 29);
assertEquals(true, Arrays.equals(result, expected));
values = new int[] {10, 20, 30, 40};
expected = new int[] {10, 20, 30, 40};
try {
field.set(new TimeOfDay(), 2, values, 63);
fail();
} catch (IllegalArgumentException ex) {}
assertEquals(true, Arrays.equals(values, expected));
values = new int[] {10, 20, 30, 40};
expected = new int[] {10, 20, 30, 40};
try {
field.set(new TimeOfDay(), 2, values, 2);
fail();
} catch (IllegalArgumentException ex) {}
assertEquals(true, Arrays.equals(values, expected));
} | 2 |
public boolean isNoiseWord(String string) {
// TODO Auto-generated method stub
string = string.toLowerCase().trim();
Pattern MY_PATTERN = Pattern.compile(".*[a-zA-Z]+.*");
Matcher m = MY_PATTERN.matcher(string);
// filter @xxx and URL
if (string.matches(".*www\\..*") || string.matches(".*\\.com.*")
|| string.matches(".*http:.*"))
return true;
if (!m.matches()) {
return true;
} else
return false;
} | 4 |
@Override
public void run() {
this.mJoinLock.lock();
try {
MusicPlayerException exception = null;
boolean failure = false;
try {
if ( this.mAlreadyStarted ) {
throw new IllegalStateException( "has alredy been started once!" );
}
this.mAlreadyStarted = true;
int bytesRead = 0;
Audio audio = this.mAudio;
AudioDevice dev = this.mAudioDevice;
AudioFormat format = audio.getAudioFormat();
if ( format != null ) {
int bufferSize = (int) format.getSampleRate() *
format.getFrameSize();
byte[] data = new byte[bufferSize];
while ( bytesRead != -1 ) {
this.mPause.probe();
if ( !this.mStopped ) {
bytesRead = audio.read( data, 0, bufferSize );
if ( bytesRead != -1 ) {
dev.write( data, 0, bytesRead );
}
}
else {
break;
}
}
}
else {
throw new IllegalStateException( "The AudioFormat was null" );
}
}
catch (Exception e) {
//catch all the exceptions so the user can handle them even if he can do that only via the listener
failure = true;
exception = new MusicPlayerException(
"An Exception occured during Playback",
e
);
this.mPlayerRunnableListener
.onException(
new MusicExceptionEvent(
this.mMusicPlayer,
exception
)
);
}
finally {
MusicEndEvent.Type type = failure ? MusicEndEvent.Type.FAILURE
: MusicEndEvent.Type.SUCCESS;
if ( this.mStopped ) {
type = MusicEndEvent.Type.MANUALLY_STOPPED;
}
this.mStopped = true;
final MusicEndEvent.Type finalType = type;
StreamPlayerRunnable.this.mPlayerRunnableListener
.onEnd(
new MusicEndEvent(
StreamPlayerRunnable.this.mMusicPlayer,
finalType
)
);
this.mJoinCondition.signal();
this.mDone = true;
}
}
finally {
this.mJoinLock.unlock();
}
} | 8 |
public void visit_ddiv(final Instruction inst) {
stackHeight -= 4;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
stackHeight += 2;
} | 1 |
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new MainFrame();
} catch (Exception e) {
e.printStackTrace();
}
}
});
} | 1 |
String checkSecurity(int iLevel, javax.servlet.http.HttpSession session, javax.servlet.http.HttpServletResponse response, javax.servlet.http.HttpServletRequest request){
try {
Object o1 = session.getAttribute("UserID");
Object o2 = session.getAttribute("UserRights");
boolean bRedirect = false;
if ( o1 == null || o2 == null ) { bRedirect = true; }
if ( ! bRedirect ) {
if ( (o1.toString()).equals("")) { bRedirect = true; }
else if ( (new Integer(o2.toString())).intValue() < iLevel) { bRedirect = true; }
}
if ( bRedirect ) {
response.sendRedirect("Login.jsp?querystring=" + toURL(request.getQueryString()) + "&ret_page=" + toURL(request.getRequestURI()));
return "sendRedirect";
}
}
catch(Exception e){};
return "";
} | 7 |
public String formatResultAccordingToWeatherLocation(String output, boolean weather, String ownloaction) {
String weatherReportOrLocation=null;
if(weather==false && ownloaction==null){
weatherReportOrLocation=output.substring(0, output.indexOf("maps.google.co.in"));
System.out.println("Location:"+weatherReportOrLocation);
}
if(weather==true && (ownloaction==null || ownloaction!=null)){
String temp,humidity,windspeed;
System.out.println(output);
try{
/*System.out.println("OUT:"+output.substring(0,100));
System.out.println("0."+output.indexOf("|"));
System.out.println("1."+output.indexOf("Wind")+4);
System.out.println("2."+output.indexOf("Humidity"));
System.out.println("3."+output.indexOf("Humidity")+9);
System.out.println("4."+output.indexOf("Humidity")+15);*/
temp=output.substring(0, output.indexOf("|"));
windspeed=output.substring(output.indexOf("Wind")+4,output.indexOf("Humidity"));
humidity=output.substring(output.indexOf("Humidity")+9,output.indexOf("Humidity")+14);
weatherReportOrLocation=temp+",\n Wind Speed "+windspeed+",\n Humidity "+humidity;
}catch(StringIndexOutOfBoundsException e){
String forcastedString=output.substring(output.indexOf("Wed")+3, output.indexOf("Detailed"));
String tempforcasted[]=forcastedString.split(" ");
String ToDay="ToDay Max Tempaerature "+tempforcasted[1]+" Min Temparature "+tempforcasted[2];
String Tomorrow="Tomorrow Max Tempaerature "+tempforcasted[3]+" Min Temparature "+tempforcasted[4];
String DayAfterTomorrow="DayAfterTomorrow Max Tempaerature "+tempforcasted[5]+" Min Temparature "+tempforcasted[6];
String TwoDaysAfter="TwoDaysAfter Max Tempaerature "+tempforcasted[7]+" Min Temparature "+tempforcasted[8];
weatherReportOrLocation=ToDay+"\n"+Tomorrow+"\n"+DayAfterTomorrow+"\n"+TwoDaysAfter;
}
System.out.println(weatherReportOrLocation);
}
return weatherReportOrLocation;
} | 6 |
public static boolean isParityAdjusted(
byte[] key,
int offset)
throws InvalidKeyException
{
if ((key.length - offset) < DES_KEY_LEN)
{
throw new InvalidKeyException("key material too short in DESKeySpec.isParityAdjusted");
}
for (int i = 0; i < DES_KEY_LEN; i++)
{
byte keyByte = key[i + offset];
int count = 0;
while (keyByte != 0)
{
/*
* we increment for every "on" bit
*/
if ((keyByte & 0x01) != 0)
{
count++;
}
keyByte >>>= 1;
}
if ((count & 1) == 1)
{
if ((key[i + offset] & 1) == 1)
{
return false;
}
}
else if ((key[i + offset] & 1) != 1)
{
return false;
}
}
return true;
} | 7 |
@Override
public void unInvoke()
{
if(canBeUninvoked())
{
if((affected!=null)&&(affected instanceof MOB)&&(!aborted)&&(!helping))
{
final MOB mob=(MOB)affected;
if(failed)
commonTell(mob,L("You failed to get the fire started."));
else
{
if(lighting==null)
{
final Item I=CMClass.getItem("GenItem");
I.basePhyStats().setWeight(50);
I.setName(L("a roaring campfire"));
I.setDisplayText(L("A roaring campfire has been built here."));
I.setDescription(L("It consists of dry wood, burning."));
I.recoverPhyStats();
I.setMaterial(RawMaterial.RESOURCE_WOOD);
mob.location().addItem(I);
lighting=I;
}
final Ability B=CMClass.getAbility("Burning");
B.setAbilityCode(512); // item destroyed on burn end
B.invoke(mob,lighting,true,durationOfBurn);
}
lighting=null;
}
}
super.unInvoke();
} | 7 |
int stripeForObject(Object o) {
if (o == null)
return 0;
Integer sh = null;
if (shiftsForClasses != null) {
Class<?> cl = o.getClass();
while (cl != Object.class && (sh = shiftsForClasses.get(cl)) == null)
cl = cl.getSuperclass();
}
if (sh == null)
sh = 0;
return sh + (o.hashCode() & mask);
} | 6 |
public static String extractTrackFrom(String filePath)
/*
* The extractTrackFrom method checks the ID3 version of the mp3 file and
* extracts the track number from the MP3 file.
*/
{
String track = null;
try
{
Mp3File mp3File = new Mp3File(filePath);
if (mp3File.hasId3v2Tag())
{
ID3v2 id3v2Tag = mp3File.getId3v2Tag();
track = id3v2Tag.getTrack();
}
else if (mp3File.hasId3v1Tag())
{
ID3v1 id3v1Tag = mp3File.getId3v1Tag();
track = id3v1Tag.getTrack();
}
} catch (UnsupportedTagException e)
{
e.printStackTrace();
}
catch (InvalidDataException e)
{
System.out.println("Invalid Data");
return " - Unknown Track Number";
//e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
if(track.equals(null))
track = "Unknown Track number";
} catch (Exception e)
{track = "Unknown Track number";
//e.printStackTrace();
}
return track;
} | 7 |
public double getKokRegula() {
double a1 = getBas();
double b1 = getSon();
double fa = 0;
double fb = 0;
double fc = 0;
do {
fa = 0;
fb = 0;
fc = 0;
for (int i = 0; i < katsayilar.length; i++) {
fa += (katsayilar[i] * Math.pow(a1, i));
fb += (katsayilar[i] * Math.pow(b1, i));
}
if (fa * fb >= 0) {
if (fa == 0) {
return getBas();
} else if (fb == 0) {
return getSon();
} else {
return -111222333;
}
}
double temp = (a1 * fb);
temp -= (b1 * fa);
temp /= (fb - fa);
setAra(temp);
for (int i = 0; i < katsayilar.length; i++) {
fc += katsayilar[i] * Math.pow(getAra(), i);
}
if ((fa * fc) < 0) {
b1 = getAra();
} else if ((fa * fc) > 0) {
a1 = getAra();
}
} while (Math.abs(fc) > epsilon);
return getAra();
} | 8 |
private void btnenvoyerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnenvoyerActionPerformed
OffreStage o1 = new OffreStage (MainProjet.lesEntreprises.get(jComboNomE.getSelectedIndex()),
jTextLibellé.getText() ,
jComboDomaine.getSelectedItem().toString() ,
jTextDdebutstage.getText() , jTextDuree.getText(),
jTextCheminStockage.getText() , jTextDescriptif.getText());
MainProjet.lesOffres.add(o1);
// Vérification des champs, si un champ est vide, le message s'affiche
if (jTextLibellé.getText().isEmpty() ||
jTextDdebutstage.getText().isEmpty() ||
jTextDuree.getText().isEmpty() ||
jTextCheminStockage.getText().isEmpty()
|| jTextDescriptif.getText().isEmpty())
{
JOptionPane.showMessageDialog(this, "Veuillez remplir tous les champs"
+ " s'il vous plaît");
// Affichage d'une fenetre avec le message
//"Veuillez remplir tous les champs s'il vous plait"
}
String nom = evt.getActionCommand();
if (nom.equals("Envoyer"))
{
JOptionPane.showMessageDialog(this, "Offre ajouté");
//une petite fenetre s'ouvre en affichant le messsage "Offre ajouté"
this.dispose();
}
// TODO add your handling code here:
}//GEN-LAST:event_btnenvoyerActionPerformed | 6 |
public double weightedStandardDeviation_of_ComplexModuli() {
boolean hold = Stat.nFactorOptionS;
if (nFactorReset) {
if (nFactorOptionI) {
Stat.nFactorOptionS = true;
} else {
Stat.nFactorOptionS = false;
}
}
boolean hold2 = Stat.nEffOptionS;
if (nEffReset) {
if (nEffOptionI) {
Stat.nEffOptionS = true;
} else {
Stat.nEffOptionS = false;
}
}
boolean holdW = Stat.weightingOptionS;
if (weightingReset) {
if (weightingOptionI) {
Stat.weightingOptionS = true;
} else {
Stat.weightingOptionS = false;
}
}
double varr = Double.NaN;
if (!weightsSupplied) {
System.out.println("weightedStandardDeviation_as_Complex: no weights supplied - unweighted value returned");
varr = this.standardDeviation_of_ComplexModuli();
} else {
double[] cc = this.array_as_modulus_of_Complex();
double[] wc = amWeights.array_as_modulus_of_Complex();
varr = Stat.standardDeviation(cc, wc);
}
Stat.nFactorOptionS = hold;
Stat.nEffOptionS = hold2;
Stat.weightingOptionS = holdW;
return varr;
} | 7 |
public void updateTotalWeekHours(){
int totalHours = 0;
int totalMinutes = 0;
for(int x = 1; x < tableColumns; x++)
{
if(tableData[tableRows-1][x]!=null)
{
totalHours += timeToCode(tableData[tableRows-1][x])/100;
totalMinutes += timeToCode(tableData[tableRows-1][x])%100;
}
}
//Dealing with an excess of minutes
if(totalMinutes > 60)
{
totalHours = totalHours + totalMinutes / 60;
totalMinutes = totalMinutes%60;
}
if(totalMinutes < 10)
totalHoursLabel.setText("Time worked this week: " + totalHours + ":0" + totalMinutes);
else
totalHoursLabel.setText("Time worked this week: " + totalHours + ":" + totalMinutes);
} | 4 |
private void runUpdater() {
if (this.url != null && (this.read() && this.versionCheck())) {
// Obtain the results of the project's file feed
if ((this.versionLink != null) && (this.type != UpdateType.NO_DOWNLOAD)) {
String name = this.file.getName();
// If it's a zip file, it shouldn't be downloaded as the plugin's name
if (this.versionLink.endsWith(".zip")) {
name = this.versionLink.substring(this.versionLink.lastIndexOf("/") + 1);
}
this.saveFile(name);
} else {
this.result = UpdateResult.UPDATE_AVAILABLE;
}
}
if (this.callback != null) {
new BukkitRunnable() {
@Override
public void run() {
runCallback();
}
}.runTask(this.plugin);
}
} | 7 |
public static Vector<String> printEventDist(EventDistance e_dis, Event cur_e){
Vector<String> changes=new Vector<String>(0);
if(printLoc(e_dis.x_dis, e_dis.z_dis, cur_e.x, cur_e.z)==null){
}
else{
String loc_str=""+printLoc(e_dis.x_dis, e_dis.z_dis, cur_e.x, cur_e.z)+";\n";
changes.add(loc_str);
}
if(e_dis.health_dis!=0){
String heal_str= "Health level "+printHeal(e_dis.health_dis, cur_e.curHealth)+";\n";
changes.add(heal_str);
}
if(e_dis.hasAmmo_dis==1){
String ammo_str= "Ammo "+printBoolean(e_dis.hasAmmo_dis)+";\n";
changes.add(ammo_str);
}
if(e_dis.emeDistance_dis!=0){
String heal_str= "Enemy "+printEme(e_dis.emeDistance_dis,cur_e.emeDistance)+";\n";
changes.add(heal_str);
}
if(e_dis.reachableItem_dis==1){
String heal_str= "Some reachable items "+printBoolean(e_dis.reachableItem_dis)+";\n";
changes.add(heal_str);
}
String state_str=printBehave(e_dis);
if(state_str!=null){
state_str+=";\n";
changes.add(state_str);
}
String reward_str=printConsequence(cur_e);
if(reward_str!=null){
reward_str+=";\n";
changes.add(reward_str+"\n");
}
changes.add("\n");
return changes;
} | 7 |
public void map(Text key, Text value, Context context) throws IOException,
InterruptedException {
try {
if (!value.toString().contains("PRIVMSG #")) {
return;
}
RecentChange rc = RecentChange.parse(key.toString()+"\t"+value.toString());
//Don't incude anonymous edits, bots, minor edits, edits to non-articles
if (rc.isAnonymous() || rc.isBot() || rc.getNamespace()!=null || rc.isMinor()) {
return;
}
//Include Simple English or not
/*if ("#simple.wikipedia".equals(rc.getChannel())) {
return;
//rc.setChannel("#en.wikipedia");
}*/
//If the user account is a local account
//(from having consulted the Central Authorization database)
//then prepend the language edition and a colon to the username to avoid
if (localAccounts.contains("*:"+rc.getUser()) ||
localAccounts.contains(rc.getLanguage()+":"+rc.getUser())) {
rc.setUser(rc.getLanguage()+":"+rc.getUser());
}
String username = rc.getUser();
outKey.set(username);
//val.set(rc.getLanguage());
val.set(rc.toJson().toString());
context.write(outKey, val);
} catch (Exception e) {
e.printStackTrace();
}
} | 8 |
@Override
protected void paintChildren(Graphics gc) {
super.paintChildren(gc);
if (mDragOverNode != null) {
Rectangle bounds = getDragOverBounds();
gc.setColor(DockColors.DROP_AREA);
gc.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
gc.setColor(DockColors.DROP_AREA_INNER_BORDER);
gc.drawRect(bounds.x + 1, bounds.y + 1, bounds.width - 3, bounds.height - 3);
gc.setColor(DockColors.DROP_AREA_OUTER_BORDER);
gc.drawRect(bounds.x, bounds.y, bounds.width - 1, bounds.height - 1);
}
} | 1 |
private void test4thLevel() {
for (Map.Entry<String, HashMap<String, HashMap<String, HashMap<String, SentiWord>>>> map2 : this.sentimentMap.sentiMap.entrySet()) {
String word1 = map2.getKey();
for (Map.Entry<String, HashMap<String, HashMap<String, SentiWord>>> map3 : map2.getValue().entrySet()) {
String word2 = map3.getKey();
for (Map.Entry<String, HashMap<String, SentiWord>> map4 : map3.getValue().entrySet()) {
String word3 = map4.getKey();
for (Map.Entry<String, SentiWord> entry : map4.getValue().entrySet()) {
if (entry.getKey().length() > 0) {
Integer size = entry.getValue().posVals.size();
System.out.println(word1 + " " + word2 + " " + word3 + " " + entry.getKey());
System.out.println(entry.getValue().getWC());
for (int i = 0; i < size; i++) {
System.out.println(entry.getValue().posVals.get(i) + "\t" + entry.getValue().negVals.get(i));
}
System.out.println("\n");
}
}
}
}
}
} | 6 |
SerializedProxy(Class proxy, MethodFilter f, MethodHandler h) {
filter = f;
handler = h;
superClass = proxy.getSuperclass().getName();
Class[] infs = proxy.getInterfaces();
int n = infs.length;
interfaces = new String[n - 1];
String setterInf = ProxyObject.class.getName();
for (int i = 0; i < n; i++) {
String name = infs[i].getName();
if (!name.equals(setterInf))
interfaces[i] = name;
}
} | 2 |
public void recoverTree(TreeNode root) {
if (root == null)
return;
ArrayList<Bundle> arr = inOrderTraversal(root);
if (arr.size() < 2)
return;
Bundle first = null, second = null;
for (int i = 0; i < arr.size() - 1; i++) {
if (arr.get(i).val > arr.get(i + 1).val) {
first = arr.get(i);
break;
}
}
for (int i = arr.size() - 1; i > 0; i--) {
if (arr.get(i).val < arr.get(i - 1).val) {
second = arr.get(i);
break;
}
}
if (first == null || second == null)
return;
int temp = first.node.val;
first.node.val = second.node.val;
second.node.val = temp;
} | 8 |
private byte[] getContents(PDFObject pageObj) throws IOException {
// concatenate all the streams
PDFObject contentsObj = pageObj.getDictRef("Contents");
if (contentsObj == null) {
throw new IOException("No page contents!");
}
PDFObject contents[] = contentsObj.getArray();
// see if we have only one stream (the easy case)
if (contents.length == 1) {
return contents[0].getStream();
}
// first get the total length of all the streams
int len = 0;
for (int i = 0; i < contents.length; i++) {
byte[] data = contents[i].getStream();
if (data == null) {
throw new PDFParseException("No stream on content " + i +
": " + contents[i]);
}
len += data.length;
}
// now assemble them all into one object
byte[] stream = new byte[len];
len = 0;
for (int i = 0; i < contents.length; i++) {
byte data[] = contents[i].getStream();
System.arraycopy(data, 0, stream, len, data.length);
len += data.length;
}
return stream;
} | 5 |
public String getComponentTitle() {
return "Multiple Run";
} | 0 |
private void setStats(long start) {
if(this.stats != null) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
String duration = "";
if(start != 0) {
duration = " [" + (cal.getTimeInMillis() - start) + "ms]";
}
String validation = " <Not Validated>";
try {
String xml = this.textArea.getText();
if(!Utilities.isNullOrWhitespace(xml)) {
Document doc = Utilities.parseXml(xml);
Utilities.validate(doc);
if(this.validator != null) {
this.validator.validate(doc);
}
validation = " <Valid>";
}
} catch (Exception e) {
validation = " <Validation Error: " + e.getMessage() + ">";
}
this.stats.setText("Last Query: " + dateFormat.format(cal.getTime()) + duration + validation);
}
} | 5 |
public boolean findString(String words) {
if (root==null) return false;
for (StringNode temp = root;!temp.value.equals(words);) { //increment statement in loop
if (words.compareTo(temp.value)<0) {//go left if words < temp
if (temp.left==null) return false;//can't go left, you have run out of things to search
temp=temp.left;//move the temp pointer to the left
}//end if
if (words.compareTo(temp.value)>0) {//same same, just to the right
if (temp.right==null) return false;
temp=temp.right;
}//end if
deletePoint=temp;
}//end for
//if you make it out of the for loop
//temp is pointing to the string you want now
return true;
} | 6 |
@Override
public void render(GameContainer arg0, StateBasedGame arg1, Graphics arg2)
throws SlickException {
if (ended) {
arg2.drawImage(winOrLose, 250, 200);
}
if (initDone && constructDone) {
Player play = players[mIndex];
if (play != null) {
float px = play.getPos().x;
float py = play.getPos().y;
float rad = ((Circle) play.getShape()).getRadius();
float scale = 15.625f / rad;
if (scale * Dimensions.pixelToMeter(arg0.getScreenWidth()) < Dimensions
.pixelToMeter(Dimensions.SCREEN_WIDTH)) {
scale = 0.5f;
}
arg2.scale(scale, scale);
arg2.translate(Dimensions.meterToPixel(-px * scale)
+ (Dimensions.SCREEN_WIDTH / 2),
Dimensions.meterToPixel(-py * scale)
+ (Dimensions.SCREEN_HEIGHT / 2));
}
for (int i = 0; i < players.length; i++) {
Player player = players[i];
if (player != null) {
player.draw(arg2);
}
}
for (Entity e : npcs) {
e.draw(arg2);
}
for (Wall w : walls) {
w.draw(arg2);
}
arg2.resetTransform();
}
} | 9 |
public void reset() {
for (int i = 0; i < tx; i++) {
for (int j = 0; j < ty; j++) {
this.brd[i][j] = Counter.EMPTY;
}
}
} | 2 |
public OrderQuest() {
super(QuestType.ORDERQUEST);
goTo="";
} | 0 |
public void setProducto(Producto producto) {
this.producto = producto;
} | 0 |
public static VisitBankAndDepositGold getSingleton(){
// needed because once there is singleton available no need to acquire
// monitor again & again as it is costly
if(singleton==null) {
synchronized(VisitBankAndDepositGold.class){
// this is needed if two threads are waiting at the monitor at the
// time when singleton was getting instantiated
if(singleton==null)
singleton = new VisitBankAndDepositGold();
}
}
return singleton;
} | 2 |
public void testSyntaxSet1() {
if (syntax.equals("traditional")) {
try {
JPL.setTraditional(); // should succeed silently
} catch (Exception e) {
fail("setTraditional() under traditional syntax threw exception: " + e);
}
} else {
try {
JPL.setTraditional();
} catch (JPLException e) { // expected exception class, but is it correct in detail?
if (e.getMessage().endsWith("traditional syntax after Prolog is initialised")) {
// OK: an appropriate exception was thrown
} else {
fail("setTraditional() under modern syntax threw incorrect JPLException: " + e);
}
} catch (Exception e) {
fail("setTraditional() under modern syntax threw unexpected class of exception: " + e);
}
}
} | 5 |
boolean isAgent(int memberType) {
if (memberType == GameController.passiveUser || memberType == GameController.userContributor || memberType == GameController.userBugReporter ||
memberType == GameController.userTester || memberType == GameController.userCommitter || memberType == GameController.userLeader)
{
return false;
} else {
return true;
}
} | 6 |
public void fileDialogAction (MyFileDialog f, int action) {
if (action == MyFileDialog.OKAY) {
if (f.getMode() == MyFileDialog.LOAD) {
WindowRegistry.saveCursors();
WindowRegistry.setAllCursors (WAIT_CURSOR);
try {
if (f.isURL())
new SynthWindow (f.getURL()).show();
else
new SynthWindow (f.getF()).show();
}
catch (Exception e) { new ExceptionDialog (this, e).show(); }
finally {
WindowRegistry.restoreCursors();
}
}
else {
OutputStream fout = null;
WindowRegistry.saveCursors();
WindowRegistry.setAllCursors (WAIT_CURSOR);
try {
fout = f.getOutputStream();
fout = new FileOutputStream (f.getF());
synthCanvas.save (fout);
if (f.isURL()) {
url = f.getURL();
file = null;
name = url.toString();
} else {
file = f.getF();
url = null;
name = file.toString();
}
setTitle();
saveMenuItem.enable();
}
catch (Exception e) { new ExceptionDialog (this, e).show(); }
finally {
try {
if (fout != null) fout.close();
} catch (IOException e) {}
WindowRegistry.restoreCursors();
}
}
}
} | 8 |
public Connection getConnection() {
return connection;
} | 0 |
public static Relation valueOf(int s) throws ParseException
{
switch(s) {
case 0: return UNCONFIRMED;
case 1: return BUDDY;
case 2: return DECLINED;
case 3: return STRANGER;
case 4: return BANNED;
default: throw new ParseException("Invalid relation value:"+s+", expected 0,1,2,3,4.");
}
} | 5 |
public JSONWriter object() throws JSONException {
if (this.mode == 'i') {
this.mode = 'o';
}
if (this.mode == 'o' || this.mode == 'a') {
this.append("{");
this.push(new JSONObject());
this.comma = false;
return this;
}
throw new JSONException("Misplaced object.");
} | 3 |
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
if(mob.location().getArea().getTimeObj().getTODCode()!=TimeClock.TimeOfDay.NIGHT)
{
mob.tell(L("This chant can only be done at night."));
return false;
}
if(!mob.location().getArea().getClimateObj().canSeeTheMoon(mob.location(), null))
{
mob.tell(L("You can't see the moon from here."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,null,this,verbalCastCode(mob,null,auto),auto?"":L("^S<S-NAME> chant(s) to the moon, and it begins to change shape.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
final Area mobA=mob.location().getArea();
if(mobA!=null)
{
Ability A=mobA.fetchEffect(ID());
if(A==null)
A=this.beneficialAffect(mob, mobA, asLevel, 0);
if(A!=null)
{
mob.location().showHappens(CMMsg.MSG_OK_VISUAL,L("The moon begins pushing and pulling on the tides in new ways!"));
A.setAbilityCode(A.abilityCode()+1);
mob.tell(L(mobA.getTimeObj().getTidePhase(mob.location()).getDesc()));
}
}
}
}
else
return beneficialWordsFizzle(mob,null,L("<S-NAME> chant(s) to the moon, but the magic fades"));
// return whether it worked
return success;
} | 9 |
private Runnable rawplay(final AudioFormat targetFormat, final AudioInputStream din) {
Runnable blah = new Runnable(){
public void run() {
SourceDataLine line = null;
try {
byte[] data = new byte[4096];
try {
line = getLine(targetFormat);
} catch (LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (line != null) {
// Start
line.start();
int nBytesRead = 0;
@SuppressWarnings("unused")
int nBytesWritten = 0;
while (nBytesRead != -1) {
nBytesRead = din.read(data, 0, data.length);
if (nBytesRead != -1)
nBytesWritten = line.write(data, 0, nBytesRead);
}
// Stop
line.drain();
line.stop();
line.close();
din.close();
// Notify the listeners if there are any objects waiting for
// this message.
for(EndOfSongListener listener : listeners) {
EndOfSongEvent eose = new EndOfSongEvent(fileName,
new GregorianCalendar());
if (!EventQueue.isDispatchThread()) {
try {
EventQueue.invokeAndWait(new EDTListener(eose, listener));
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
listener.songFinishedPlaying(eose);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
} };
return blah;
} | 9 |
@Override
protected void read(InputBuffer b) throws IOException, ParsingException {
int first = b.get(0) & 0xFF;
byte[] varInt;
if (first < 0xfd) {
varInt = new byte[] { (byte) first };
} else {
varInt = b.get(1, 1 << first - 0xfc);
}
// Add a zero prefix to get a length of 8.
byte[] tmp = new byte[8];
for (int i = 0; i < tmp.length; i++) {
int index = i + varInt.length - tmp.length;
if (index >= 0) {
tmp[i] = varInt[index];
}
}
n = Util.getLong(tmp);
} | 3 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.