method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
b1a5fcb5-2cec-4835-9e16-ad0beafbcbf5 | 2 | private double getGameDuration() {
// Return nothing if we don't have sufficient information.
if(this.roundStats.size() == 0)
return -1;
// Get our round duration
double seconds = 0;
for(RoundStats curRoundStats : this.roundStats)
seconds += curRoundStats.getDuration();
return seconds;
} |
f75b09e2-1e60-4d92-a634-2c374aa6862b | 7 | @Override
protected void run(Player player, String[] args) {
if(player.isOp()){//TODO add permissions
if (args[0].equalsIgnoreCase("set")) {
SetCommand.set(player, args);
} else if (args[0].equalsIgnoreCase("replace")) {
ReplaceCommand.replace(player, args);
} else if (args[0].equalsIgnoreCase("wand")) {
WandCommand.wand(player, args);
} else if (args[0].equalsIgnoreCase("expand")) {
ExpandCommand.expand(player, args);
} else if (args[0].equalsIgnoreCase("count")) {
CountCommand.count(player, args);
} else if (args[0].equalsIgnoreCase("undo")) {
UndoCommand.undo(player, args);
} else {
Util.sendMessage(player, ChatColor.RED+"Unknown Command.");
}
}
} |
962620c4-b872-429e-bfe6-f4197378d7c9 | 0 | private static void startDisruptor() {
// 创建处理查询消息的disruptor
_disruptor =
new Disruptor<TicketQueryArgs>
(
TicketPoolService.QueryFactory,
EXECUTOR,
new SingleThreadedClaimStrategy(RING_SIZE),
new BlockingWaitStrategy()
);
// @brucesea
// 另外用Disruptor,推荐用DisruptorWizard,
// 这样EventProcessor之间的关系会比较清晰
_disruptor
// 注册日志和备份线程
.handleEventsWith(_journalist, _replicator)
// 事件处理线程只能在日志和备份线程之后处理它
.then(_eventProcessor);
// 启动disruptor,等待publish事件
_ringBuffer = _disruptor.start();
} |
6958fd33-f3d8-44b5-a56b-d89fdb4250d8 | 5 | public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char grade = in.next().charAt(0);
switch (grade) {
case 'A':
System.out.println("Excellent");
break;
case 'B':
System.out.println("Good");
break;
case 'C':
System.out.println("So so");
break;
case 'D':
System.out.println("Fails");
break;
case 'F':
System.out.println("Get lost");
break;
default:
System.out.println("Invalid");
break;
}
} |
2254f3a1-ca09-44d8-bee4-ba4ae3dc309f | 7 | public void handleLeftClick(double x, double y, SUIComponent concerned){
if(save.equals(concerned))
exit(true);
else if(cancel.equals(concerned))
exit(false);
else if(leftCtrl.equals(concerned))
current = InteractivePanel.LEFT;
else if(rightCtrl.equals(concerned))
current = InteractivePanel.RIGHT;
else if(upCtrl.equals(concerned))
current = InteractivePanel.UP;
else if(shootCtrl.equals(concerned))
current = InteractivePanel.SHOOT;
else if(powerCtrl.equals(concerned))
current = InteractivePanel.POWER;
} |
a3bc0641-0259-450c-bad5-d0b6bfc42979 | 5 | public static void main(String args []) throws ParseException
{
EG1 parser = new EG1(System.in);
while (true)
{
System.out.println("Reading from standard input...");
System.out.print("Enter an expression like \u005c"1+(2+3)*4;\u005c" :");
try
{
switch (EG1.one_line())
{
case 0 :
System.out.println("OK.");
break;
case 1 :
System.out.println("Goodbye.");
break;
default :
break;
}
}
catch (Exception e)
{
System.out.println("NOK.");
System.out.println(e.getMessage());
EG1.ReInit(System.in);
}
catch (Error e)
{
System.out.println("Oops.");
System.out.println(e.getMessage());
break;
}
}
} |
7c7d9dab-f956-46b5-b8b5-d2010aee71ab | 7 | private Predicate[] getSearchPredicates(UserBE searchParameters, Root<UserBE> root) {
CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();
List<Predicate> predicatesList = new ArrayList<Predicate>();
String firstName = searchParameters.getFirstName();
if (firstName != null && !"".equals(firstName)) {
predicatesList.add(builder.like(root.<String> get("firstName"), '%' + firstName + '%'));
}
String lastName = searchParameters.getLastName();
if (lastName != null && !"".equals(lastName)) {
predicatesList.add(builder.like(root.<String> get("lastName"), '%' + lastName + '%'));
}
String userName = searchParameters.getUserName();
if (userName != null && !"".equals(userName)) {
predicatesList.add(builder.like(root.<String> get("userName"), '%' + userName + '%'));
}
GroupBE group = searchParameters.getGroup();
if (group != null) {
predicatesList.add(builder.equal(root.get("group"), group));
}
return predicatesList.toArray(new Predicate[predicatesList.size()]);
} |
92aeba81-1a5a-496d-a31b-dc80df916ea6 | 8 | public void actionPerformed(ActionEvent e){
if (e.getSource() == JMINowaGra){
//JOptionPane.showMessageDialog(null, "Nowa gra");
this.setEnabled(false);//zablokowanie okna
Goptions = new GameOptions(this);
Goptions.setVisible(true);
}
if (e.getSource() == JMIReset){
JOptionPane.showMessageDialog(null, "Reset");
Gboard.resetGUIBoard(ResetStrona);
Gboard.setAi(ResetAi);
}
if (e.getSource() == JMIWyjdz){
JOptionPane.showMessageDialog(null, "Wyjscie");
this.dispose();
}
if (e.getSource() == JMITest){
Gboard.testGUIBoard();
Gboard.setAi(true);
}
//-------------------------------------------
if (e.getSource() == JMICofnij){
Gboard.backMove();
}
//------------------------------------------
if (e.getSource() == JMIGameInfo){
if(Ginfo.isVisible())
Ginfo.setVisible(false); else Ginfo.setVisible(true);
}
//------------------------------------------
if (e.getSource() == JMIInfo){
URL index = ClassLoader.getSystemResource("HelpHtml/index.html");
//URL index = ClassLoader.class.getResource("Help/index.html");
new HelpWindow("Warcaby", index);
}
} |
de277781-3eeb-4cb8-b641-1416d394ba5a | 5 | private void fireMouseExitedToSource(DropTargetDropEvent e)
{
try
{
Transferable transferableProxy = e.getTransferable();
Class<?> proxyClass = transferableProxy.getClass();
Field dropTargetContextPeerField = proxyClass.getDeclaredField("transferable");
dropTargetContextPeerField.setAccessible(true);
Object dropTargetContextPeer = dropTargetContextPeerField.get(transferableProxy);
Class<?> dropTargetContextPeerClass = dropTargetContextPeer.getClass();
Class<?> sunDropTargetContextPeerClass = dropTargetContextPeerClass.getSuperclass();
Field transferableField = sunDropTargetContextPeerClass.getDeclaredField("local");
transferableField.setAccessible(true);
Object transferable = transferableField.get(dropTargetContextPeer);
if (transferable instanceof CommandHandler)
{
CommandHandler handler = (CommandHandler) transferable;
JComponent component = handler.getComponent();
int absX = MouseInfo.getPointerInfo().getLocation().x;
int absY = MouseInfo.getPointerInfo().getLocation().y;
int x = absX - component.getLocationOnScreen().x;
int y = absY - component.getLocationOnScreen().y;
component.dispatchEvent(new MouseEvent(component, MouseEvent.MOUSE_EXITED, System.currentTimeMillis(),
MouseEvent.BUTTON1_DOWN_MASK, x, y, absX, absY, 1, false, MouseEvent.BUTTON1));
component.dispatchEvent(new MouseEvent(component, MouseEvent.MOUSE_RELEASED, System.currentTimeMillis(),
MouseEvent.BUTTON1_DOWN_MASK, x, y, absX, absY, 1, false, MouseEvent.BUTTON1));
}
}
catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex)
{
ex.printStackTrace();
}
} |
3a144698-fc61-45b4-944d-1d10c1fe075f | 8 | private boolean matchTree(TreeNode<?> root1, TreeNode<?> root2) {
if (root1 == null && root2 == null) {
return true;
}
if (root1 == null || root2 == null) {
return false;
}
if (root1.data != root2.data) {
return false;
}
return matchTree(root1.left, root2.left)
&& matchTree(root1.right, root2.right);
} |
33178b5f-b76a-40b7-8d24-f79d32552952 | 1 | public static void main(String[] argsv) {
// Setting op a bank.
Bank christmasBank = new Bank();
christmasBank.addAccount(new BankAccount(BigInteger.valueOf(100)));
christmasBank.addAccount(new BankAccount(BigInteger.valueOf(50), BigInteger.valueOf(-1000)));
// Print the balance of all accounts with a balance not below some threshold.
System.out.print("Enter the threshold for the balance: ");
Scanner inputStreamScanner = new Scanner(System.in);
BigInteger threshold = BigInteger.valueOf(inputStreamScanner.nextLong());
Set<BankAccount> accountsBalanceNotBelowThreshold =
christmasBank.getAccountsBalanceNotBelow(threshold);
for (BankAccount account: accountsBalanceNotBelowThreshold)
System.out.println(account.getBalance());
} |
ab63f8f8-7f7f-4204-bd65-3041dd71e222 | 3 | @Override
public void execute(CommandSender sender, String[] args) {
if (!sender.hasPermission("bungeeutils.admin")) {
sender.sendMessage(new ComponentBuilder("").append(plugin.prefix + plugin.messages.get(EnumMessage.NOPERM)).create());
return;
}
if (args.length != 1) {
sender.sendMessage(new ComponentBuilder("").append(plugin.prefix + ChatColor.RED + "Usage: " + ChatColor.GOLD + "/removeserver [name]").create());
return;
}
String name = args[0];
if (ProxyServer.getInstance().getServers().remove(name) == null) {
sender.sendMessage(new ComponentBuilder("").append(plugin.prefix + ChatColor.RED + "Could not find server " + ChatColor.GOLD + name).create());
} else {
sender.sendMessage(new ComponentBuilder("").append(plugin.prefix + ChatColor.GREEN + "Removed server " + ChatColor.GOLD + name).create());
}
} |
48c4abee-828a-4347-b72a-1cff24ae12dd | 8 | public final void decodeFilename(byte[] filename, char escape, StringBuilder sb) {
for (int i = 0; i < filename.length; i++) {
byte b = filename[i];
char c = decode(b);
if ((c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A) || (c >= 0x30 && c <= 0x39) || " !'._-".indexOf(c) != -1) {
sb.append(c);
} else {
sb.append(escape);
sb.append(Hex.b(c));
}
}
} |
55a95e4a-9213-46b3-a9f6-4e1c7eabcee3 | 9 | public void addStaffInfo(Vector<StaffInfo> staff, JTextField[] staffTF, JList positionList, JList qualificationList,
String hospitalList, JTable table) {
DB.db.openConnection();
try {
int posid = -1;
int qualid = -1;
int hospId = -1;
String[] tmp = new String[staffTF.length];
for (int i = 0; i < staffTF.length; i++) {
tmp[i] = staffTF[i].getText();
}
if (positionList == null || qualificationList == null) {
throw new Exception();
}
// make login and password
String login = JOptionPane.showInputDialog("Enter desired login");
String password = null;
JPasswordField passwordField = new JPasswordField();
passwordField.setEchoChar('*');
Object[] obj = {"Please enter the password:\n\n", passwordField};
Object stringArray[] = {"OK", "Cancel"};
if (JOptionPane.showOptionDialog(null, obj, "Desired password",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, stringArray, obj) == JOptionPane.YES_OPTION) {
password = new String(passwordField.getPassword());
}
// login and password done
ResultSet rs = DB.db.position(positionList.getSelectedValue().toString());
while (rs.next()) {
posid = rs.getInt("id");
}
rs = DB.db.qualification(qualificationList.getSelectedValue().toString());
while (rs.next()) {
qualid = rs.getInt("id");
}
Auth t = new Auth(login, password);
DB.db.addStaff(tmp, qualid, posid, t.getLogin(), t.getPasswHash());
DB.db.close();
staff.removeAllElements();
this.fillStaff((Vector<T>) staff);
rs = (ResultSet) DB.db.hospital(hospitalList);
while (rs.next()) {
hospId = rs.getInt("id");
}
for (int i = 0; i < 7; i++) {
DB.db.editStaffHospitalSchedual(staff.lastElement().getId(), hospId, table.getValueAt(i, 0),
table.getValueAt(i, 1), table.getValueAt(i, 2));
}
DB.db.close();
} catch (Exception ex) {
Logger.getLogger(Func.class.getName()).log(Level.SEVERE, null, ex);
DB.db.close();
}
} |
4a8ae848-5211-4efd-9efe-cca2b54157e1 | 3 | public void printRules() {
if ((rules != null) && (rules.size() > 0)) {
OutputWriter.println(MSG_LIST_OF_RULES);
for (Rule rule : rules) {
OutputWriter.println(rule.toString());
}
} else {
OutputWriter.println(MSG_EMPTY_LIST_OF_RULES);
}
} |
edb8edf8-aacd-4882-8fe8-d4b46cadab0d | 4 | public void recalculateBytes()
{
chan.setValues(vol.getValue(),freq.getValue(),dur.getValue(),eq.getText());
int duration = (int) (dur.getValue() / 1000.0 * sps);
myEnviron.put("sps",sps);
myEnviron.put("bps",sps);
myEnviron.put("dur",duration);
myEnviron.put("period",sps / (double) freq.getValue());
myEnviron.put("freq",freq.getValue());
myEnviron.put("vol",vol.getValue());
byte[] ret = new byte[duration];
myEnviron.put("z",ret);
String script = "function calc(x) { return " + eq.getText() + "; }";
script += " for (i = 0; i < " + duration + "; i++) z[i] = calc(i); z;";
try
{
ret = (byte[]) myEnviron.engine.eval(script);
}
catch (ScriptException e)
{
System.err.println(e.getMessage());
}
// byte[] ret = new byte[duration];
// for (int i = 0; i < ret.length; i++)
// {
// ret[i] = (byte) (vol.getValue() * Math.sin(i / (sps / (double) freq.getValue()) * 2 * Math.PI));
// // ret[i] = (byte) eval(eq.getText(),"x=" + i + ", freq=" + freq.getValue() + ", vol="
// // + vol.getValue());
// }
for (int i = 0; i < 100 && i < ret.length; i++)
System.out.print(ret[i] + ", ");
System.out.println();
waveData = ret;
if (renderPane != null)
{
renderPane.renew();
renderPane.updateUI();
}
} |
4642ac2a-550e-4cca-b969-d915e7d4c07e | 0 | public InetAddress getDccInetAddress() {
return _dccInetAddress;
} |
45dffdb5-77eb-48e3-92f0-398418404696 | 8 | public void upgrade(int building, int advance) {
if (88 == advance) {//adjusting for UnitTypes
advance = 58;
} else if (90 == advance) {
advance = 59;
} else if (89 == advance) {
advance = 103;
} else if (91 == advance) {
advance = 104;
} else if (97 == advance) {
advance = 106;
} else if (99 == advance) {
advance = 107;
} else if (96 == advance) {
advance = 61;
} else if (98 == advance) {
advance = 62;
}
String message = "COMMAND " + building + " 14 " + advance + " \n";
sendAndReceiveMessage(message, true);
System.out.println("-----------------------UPGRADE"+ this.getCurrCycle());
} |
0ab37494-b800-4346-a7f2-95c5a4f10566 | 3 | public static void pointsRemoved(String prestige, int ap){
pointsSpent -= ap;
//update the trees points spent
for(ClassTree ct : takenPrestigeTrees){
if(ct.getPrestige().equalsIgnoreCase(prestige))
ct.removeAp(ap);
}
if(prestige.equalsIgnoreCase(characterRace))
racialTree.removeAp(ap);
} |
c87d750e-580d-414d-b719-9dc9a08a9b43 | 1 | public BotWindow(String title, Bot bot) {
super(title);
this.bot = bot;
setClosable(true);
setResizable(true);
setIconifiable(true);
setMaximizable(true);
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent ze) {
if (ze.getKeyCode() == KeyEvent.VK_ENTER) {
handleCommand(textField.getText());
textField.setText("");
}
}
});
textField.setForeground(Color.WHITE);
textField.setBackground(Color.BLACK);
getContentPane().add(textField, BorderLayout.SOUTH);
textField.setColumns(10);
scrollPane = new JScrollPane();
getContentPane().add(scrollPane, BorderLayout.CENTER);
textPane = new JTextPane();
textPane.setForeground(Color.WHITE);
textPane.setBackground(Color.BLACK);
scrollPane.setViewportView(textPane);
setVisible(true);
bot.init();
} |
732aa1c2-1dba-4322-b809-dbaf1459d3c7 | 7 | @Override
public void affectCharStats(MOB affectedMOB, CharStats affectedStats)
{
if(EQadjCharStats==null)
{
setMiscText(text());
/*
* ************************* Armor-based Resistances
* *************************
*/
}
if((affected!=null)&&(affected instanceof Armor)&&(!(affected instanceof Shield))&&(activated)
&&(!((Armor)affected).amWearingAt(Wearable.IN_INVENTORY)))
{
for(final int i : CharStats.CODES.SAVING_THROWS())
affectedStats.setStat(i,affectedStats.getStat(i)+EQadjCharStats.getStat(i));
}
super.affectCharStats(affectedMOB,affectedStats);
} |
b8e1426a-1082-4a78-9e2f-e814266e404d | 9 | public Color brighter() {
int r = red;
int g = green;
int b = blue;
/*
* From 2D group: 1. black.brighter() should return grey 2. applying
* brighter to blue will always return blue, brighter 3. non pure color
* (non zero rgb) will eventually return white
*/
int i = (int) (1.0 / (1.0 - FACTOR));
if (r == 0 && g == 0 && b == 0) {
return new Color(i, i, i);
}
if (r > 0 && r < i)
r = i;
if (g > 0 && g < i)
g = i;
if (b > 0 && b < i)
b = i;
return new Color(Math.min((int) (r / FACTOR), 255), Math.min(
(int) (g / FACTOR), 255), Math.min((int) (b / FACTOR), 255));
} |
f0c78647-4fbc-45de-aa2b-6be378f2c7b9 | 6 | protected void createSubbands()
{
int i;
if (mode == Header.SINGLE_CHANNEL)
for (i = 0; i < num_subbands; ++i)
subbands[i] = new SubbandLayer1(i);
else if (mode == Header.JOINT_STEREO)
{
for (i = 0; i < header.intensity_stereo_bound(); ++i)
subbands[i] = new SubbandLayer1Stereo(i);
for (; i < num_subbands; ++i)
subbands[i] = new SubbandLayer1IntensityStereo(i);
}
else
{
for (i = 0; i < num_subbands; ++i)
subbands[i] = new SubbandLayer1Stereo(i);
}
} |
0408ae6f-f2ae-4151-bb3a-42470de7bcf2 | 2 | void destruct() {
playerListSize = 0;
for(int i = 0; i < maxPlayerListSize; i++) playerList[i] = null;
npcListSize = 0;
for(int i = 0; i < maxNPCListSize; i++) npcList[i] = null;
absX = absY = -1;
mapRegionX = mapRegionY = -1;
currentX = currentY = 0;
resetWalkingQueue();
} |
802fc376-8820-4fb4-bca0-f8c40c1d0d04 | 2 | public boolean accept(File pathname)
{
if (pathname != null
&& pathname.getName().toUpperCase().endsWith(mFilter))
{
return true;
}
return false;
} |
c7b79b75-2842-47ac-a16a-38a7b5762c56 | 0 | public static int getID(Packets packet){
return packet.id;
} |
9ae77f2b-a0b0-40ec-ba0c-38555aa1a20c | 6 | @EventHandler
public void EndermanHarm(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.getEndermanConfig().getDouble("Enderman.Harm.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getEndermanConfig().getBoolean("Enderman.Harm.Enabled", true) && damager instanceof Enderman && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.HARM, plugin.getEndermanConfig().getInt("Enderman.Harm.Time"), plugin.getEndermanConfig().getInt("Enderman.Harm.Power")));
}
} |
0f902b4c-4ca0-41d6-9fea-7cdd1472b69a | 8 | public static Throwable getCause(final Throwable exception) {
// Figure out which exception should actually be logged -- if the given exception is
// a wrapper, unwrap it
Throwable cause = null;
if (exception != null) {
if (exception instanceof CoreException) {
// Workaround: CoreException contains a cause, but does not actually implement getCause().
// If we get a CoreException, we need to manually unpack the cause. Otherwise, use
// the general-purpose mechanism. Remove this branch if CoreException ever implements
// a correct getCause() method.
final CoreException ce = (CoreException) exception;
cause = ce.getStatus().getException();
} else {
// use reflect instead of a direct call to getCause(), to allow compilation against JCL Foundation (bug 80053)
try {
final Method causeMethod = exception.getClass().getMethod("getCause", new Class[0]); //$NON-NLS-1$
final Object o = causeMethod.invoke(exception, new Object[0]);
if (o instanceof Throwable) {
cause = (Throwable) o;
}
} catch (final NoSuchMethodException e) {
// ignore
} catch (final IllegalArgumentException e) {
// ignore
} catch (final IllegalAccessException e) {
// ignore
} catch (final InvocationTargetException e) {
// ignore
}
}
if (cause == null) {
cause = exception;
}
}
return cause;
} |
f09893aa-28a8-4735-a152-5b90ab85c13f | 3 | @Override
public void publish(LogRecord record) {
if(open&&!closing) {
Level l = record.getLevel();
String loggerName = record.getLoggerName();
String message = record.getMessage();
Calendar c = Calendar.getInstance();
c.setTimeInMillis(record.getMillis());
String time = new SimpleDateFormat("dd.HH.yyyy-HH:mm:ss:SSS").format(c.getTime());
String[] lines = message.split("\n");
StringBuilder sb;
int i = 1;
for(String s : lines) {
sb = new StringBuilder();
sb.append("[").append(time).append("]\u0009");
sb.append("[").append(l).append("]\u0009");
sb.append("[").append(loggerName).append("]\u0009");
sb.append("[Line:").append(String.format("%03d", i)).append("/").append(String.format("%03d", lines.length)).append("]\u0009");
sb.append(s);
sb.append("\n");
doLog(sb.toString());
i++;
}
}
} |
7fc68c35-c661-423a-ba8f-7933703d8a43 | 9 | float next(final float len) {
final float targetLength = lenAtLastSplit + len;
while (lenAtNextT < targetLength) {
if (done) {
lastSegLen = lenAtNextT - lenAtLastSplit;
return 1f;
}
goToNextLeaf();
}
lenAtLastSplit = targetLength;
final float leaflen = lenAtNextT - lenAtLastT;
float t = (targetLength - lenAtLastT) / leaflen;
// cubicRootsInAB is a fairly expensive call, so we just don't do it
// if the acceleration in this section of the curve is small enough.
if (!haveLowAcceleration(0.05f)) {
// We flatten the current leaf along the x axis, so that we're
// left with a, b, c which define a 1D Bezier curve. We then
// solve this to get the parameter of the original leaf that
// gives us the desired length.
final float[] _flatLeafCoefCache = flatLeafCoefCache;
if (_flatLeafCoefCache[2] < 0) {
float x = 0f + curLeafCtrlPolyLengths[0],
y = x + curLeafCtrlPolyLengths[1];
if (curveType == 8) {
float z = y + curLeafCtrlPolyLengths[2];
_flatLeafCoefCache[0] = 3f * (x - y) + z;
_flatLeafCoefCache[1] = 3f * (y - 2f * x);
_flatLeafCoefCache[2] = 3f * x;
_flatLeafCoefCache[3] = -z;
} else if (curveType == 6) {
_flatLeafCoefCache[0] = 0f;
_flatLeafCoefCache[1] = y - 2f * x;
_flatLeafCoefCache[2] = 2f * x;
_flatLeafCoefCache[3] = -y;
}
}
float a = _flatLeafCoefCache[0];
float b = _flatLeafCoefCache[1];
float c = _flatLeafCoefCache[2];
float d = t * _flatLeafCoefCache[3];
// we use cubicRootsInAB here, because we want only roots in 0, 1,
// and our quadratic root finder doesn't filter, so it's just a
// matter of convenience.
int n = Helpers.cubicRootsInAB(a, b, c, d, nextRoots, 0, 0, 1);
if (n == 1 && !Float.isNaN(nextRoots[0])) {
t = nextRoots[0];
}
}
// t is relative to the current leaf, so we must make it a valid parameter
// of the original curve.
t = t * (nextT - lastT) + lastT;
if (t >= 1f) {
t = 1f;
done = true;
}
// even if done = true, if we're here, that means targetLength
// is equal to, or very, very close to the total length of the
// curve, so lastSegLen won't be too high. In cases where len
// overshoots the curve, this method will exit in the while
// loop, and lastSegLen will still be set to the right value.
lastSegLen = len;
return t;
} |
c4a5054a-0eba-4038-b132-364e65343ce5 | 5 | @Override
public void update() {
paddleLeft.update();
paddleRight.update();
movingPaddleLeft.update();
movingPaddleRight.update();
ball.update();
if (ballCollides(paddleLeft)) {
playerScore++;
ball.onCollideWith(paddleLeft);
Resources.hit.play();
} else if (ballCollides(paddleRight)) {
playerScore++;
ball.onCollideWith(paddleRight);
Resources.hit.play();
} else if (ballCollides(movingPaddleLeft)) {
playerScore = 0;
ball.onCollideWith(movingPaddleLeft);
Resources.hit.play();
} else if (ballCollides(movingPaddleRight)) {
playerScore = 0;
ball.onCollideWith(movingPaddleRight);
Resources.hit.play();
} else if (ball.isDead()) {
playerScore -= 3;
ball.reset();
}
} |
beb27ab0-fda2-4e99-a9e1-0b6994658f37 | 8 | void generateLeafNodeList()
{
height = (int)((double)heightLimit * heightAttenuation);
if (height >= heightLimit)
{
height = heightLimit - 1;
}
int i = (int)(1.3819999999999999D + Math.pow((leafDensity * (double)heightLimit) / 13D, 2D));
if (i < 1)
{
i = 1;
}
int ai[][] = new int[i * heightLimit][4];
int j = (basePos[1] + heightLimit) - leafDistanceLimit;
int k = 1;
int l = basePos[1] + height;
int i1 = j - basePos[1];
ai[0][0] = basePos[0];
ai[0][1] = j;
ai[0][2] = basePos[2];
ai[0][3] = l;
j--;
while (i1 >= 0)
{
int j1 = 0;
float f = layerSize(i1);
if (f < 0.0F)
{
j--;
i1--;
}
else
{
double d = 0.5D;
for (; j1 < i; j1++)
{
double d1 = scaleWidth * ((double)f * ((double)rand.nextFloat() + 0.32800000000000001D));
double d2 = (double)rand.nextFloat() * 2D * Math.PI;
int k1 = MathHelper.floor_double(d1 * Math.sin(d2) + (double)basePos[0] + d);
int l1 = MathHelper.floor_double(d1 * Math.cos(d2) + (double)basePos[2] + d);
int ai1[] =
{
k1, j, l1
};
int ai2[] =
{
k1, j + leafDistanceLimit, l1
};
if (checkBlockLine(ai1, ai2) != -1)
{
continue;
}
int ai3[] =
{
basePos[0], basePos[1], basePos[2]
};
double d3 = Math.sqrt(Math.pow(Math.abs(basePos[0] - ai1[0]), 2D) + Math.pow(Math.abs(basePos[2] - ai1[2]), 2D));
double d4 = d3 * branchSlope;
if ((double)ai1[1] - d4 > (double)l)
{
ai3[1] = l;
}
else
{
ai3[1] = (int)((double)ai1[1] - d4);
}
if (checkBlockLine(ai3, ai1) == -1)
{
ai[k][0] = k1;
ai[k][1] = j;
ai[k][2] = l1;
ai[k][3] = ai3[1];
k++;
}
}
j--;
i1--;
}
}
leafNodes = new int[k][4];
System.arraycopy(ai, 0, leafNodes, 0, k);
} |
f20c4c38-2a88-475d-8225-2ab431724051 | 6 | private Rectangle adjustWindowPositionToScreen(final Rectangle windowPosition) {
// Get the size of the screen
final Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
if (windowPosition.width > dim.width) {
windowPosition.width = dim.width;
}
if (windowPosition.height > dim.height) {
windowPosition.height = dim.height;
}
if (windowPosition.x < 0) {
windowPosition.x = 0;
} else if (windowPosition.x > dim.width - windowPosition.width) {
windowPosition.x = dim.width - windowPosition.width;
}
if (windowPosition.y < 0) {
windowPosition.y = 0;
} else if (windowPosition.y > dim.height - windowPosition.height) {
windowPosition.y = dim.height - windowPosition.height;
}
return windowPosition;
} |
c8217b2b-5d10-4603-a42b-2d5f48c6f261 | 7 | private void writeHtmlScrptExpr(FileWriter fwriter) throws IOException {
int exprIndexPointer = 0;
int indexExpr = 0;
int sizeExprIndex = expresionIndex.size();
int scrptIndexPointer = 0;
int indexScrpt = 0;
int sizeScrptIndex = scriptletIndex.size();
for (int i = 0; i < html.size(); i++) {
String str = html.get(i);
str = str.replace("\"", "\\\"");
fwriter.write("out.write(\"" + str + "\\r\\n\");");
fwriter.write("\r\n");
if (sizeScrptIndex < 1) {
indexScrpt = -1;
} else {
indexScrpt = scriptletIndex.get(scrptIndexPointer);
}
if (sizeExprIndex < 1) {
indexExpr = -1;
} else {
indexExpr = expresionIndex.get(exprIndexPointer);
}
if (i == indexScrpt) {
fwriter.write("\r\n");
fwriter.write(scriptlet.get(scrptIndexPointer));
if (scrptIndexPointer < sizeScrptIndex - 1) {
scrptIndexPointer++;
}
}
if (i == indexExpr) {
fwriter.write("out.print( " + expression.get(exprIndexPointer)
+ " );");
fwriter.write("\r\n");
if (exprIndexPointer < sizeExprIndex - 1) {
exprIndexPointer++;
}
}
}
} |
c0442326-52fc-4771-bf8b-396ee326e9e0 | 0 | public int getMaxMP() {
return maxMP;
} |
e90ab945-12a2-4da4-a502-bb5cb304ab35 | 5 | public int draw(boolean fromDiscard){
//Make sure there are the correct number of cards in play
assert(dealing || (draw_count+discard_count == rack_size*2 && !action));
turns++;
action = true;
int card;
if (fromDiscard){
assert(discard_count != 0);
card = discard[--discard_count];
}
else{
assert(draw_count != 0);
card = draw[--draw_count];
}
in_play[card-1] = true;
if (!shuffling && gui != null)
gui.draw(card, fromDiscard);
return card;
} |
f211c452-dd17-4eb9-bb50-84054cd29f42 | 8 | static final public String EqualityExpression() throws ParseException {
String tmp1="",tmp3="";Token tmp2=null;
tmp1 = RelationalExpression();
if (jj_2_22(2)) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 93:
tmp2 = jj_consume_token(93);
break;
case 94:
tmp2 = jj_consume_token(94);
break;
case 95:
tmp2 = jj_consume_token(95);
break;
case 96:
tmp2 = jj_consume_token(96);
break;
default:
jj_la1[25] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
tmp3 = EqualityExpression();
} else {
;
}
{if (true) return "%exp1% %exp2% %exp3%".replace("%exp1%",tmp1).replace("%exp2%",tmp2!=null?tmp2.toString():"").replace("%exp3%",tmp3).trim();}
throw new Error("Missing return statement in function");
} |
001b03e8-b0f7-4d16-acc6-2e032e74fda3 | 2 | public int score(Collection<String> names) {
int sum = 0;
for( String name : names ) {
if( scoreByName.get(name) == null ) throw new RuntimeException("Error: Entry '" + name + "' not found!");
sum += scoreByName.get(name);
}
return sum;
} |
bcff3f06-35af-42cb-9e37-a9c9d02ef07a | 4 | public static String countAndSay(int n) {
String seed = "1";
for (int i = 1; i < n; i++) {
int index = 0;
String seed2 = "";
char say = seed.charAt(index);
int count = 0;
int outIndex = 0;
while (index < seed.length()) {
if (say == seed.charAt(index)) {
count++;
} else {
seed2 += "" + count + say;
say = seed.charAt(index);
count = 1;
outIndex = index;
}
index++;
}
if (outIndex < index) {
seed2 += "" + count + say;
}
seed = seed2;
}
return seed;
} |
eb475af5-2e95-45c1-82ba-2c65d1729b25 | 5 | public static String stripHTML( String rep )
{
// first convert newlines
rep = rep.replaceAll( "<[B,b][R,r]?>", "\r\n" );
rep = rep.replaceAll( "<[B,b][R,r]?/>", "\r\n" );
rep = rep.replaceAll( "<[L,l][I,i]?>", "\r\n\r\n" );
StringBuffer ret = new StringBuffer();
char[] cx = rep.toCharArray();
boolean skipping = false;
for( int t = 0; t < cx.length; t++ )
{
char tt = cx[t];
// begin match
if( tt == '<' )
{
skipping = true;
t++;
}
else if( tt == '>' )
{
skipping = false;
}
if( !skipping && (tt != '>') )
{
ret.append( cx[t] );
}
}
return ret.toString();
} |
ccac60d0-7781-4ff7-842e-80281bae1e94 | 4 | public void itemStateChanged(ItemEvent ie) {
if (ie.getSource().equals(jcb)) {
cl.show(p, jcb.getSelectedItem().toString());
page[jcb.getSelectedIndex()].refreshScale();
back.setEnabled(jcb.getSelectedIndex() == 0 ? false: true);
forward.setEnabled(jcb.getSelectedIndex() == jcb.getItemCount()-1 ? false:true);
this.validate();
}
if (ie.getSource().equals(rcb)) {
scale = ((Resolution) rcb.getSelectedItem()).getResolution();
page[jcb.getSelectedIndex()].refreshScale();
this.validate();
}
} |
8f0f86ee-c02d-43dd-bb86-413adb11e313 | 4 | private void closure() {
HashSet selected = new HashSet();
GrammarTableModel model = choiceTable.getGrammarModel();
for (int i = 0; i < model.getRowCount() - 1; i++)
if (choiceTable.isRowSelected(i))
selected.add(model.getProduction(i));
if (selected.size() == 0) {
JOptionPane.showMessageDialog(parent,
"Select an item (or items) in the right table.",
"Nothing Selected", JOptionPane.ERROR_MESSAGE);
return;
}
Set closureSet = Operations.closure(grammar, selected);
closureSet.removeAll(alreadyChosen);
Iterator it = closureSet.iterator();
while (it.hasNext())
addItem((Production) it.next());
} |
5d2f8b09-ddf0-4182-9b4f-b3f7fc571769 | 8 | public void addingTreesForDomSet(ArrayList<Integer> terminalsId) {
HashSet<ElkinItem> realChosenItem = new HashSet<ElkinItem>();
realChosenPseudo = new HashSet<PseudoNode>();
int [][]P = uninformedAdjMatrix.getP2PPath();
double [][]MCPmatrix = uninformedAdjMatrix.getP2PCost();
for (int i = 0; i < terminalsId.size(); i++) {
double minCost = -1;
Iterator<ElkinItem> itensIt = chosenItem.iterator();
ElkinItem minItem = null;
while (itensIt.hasNext()) {
ElkinItem item = itensIt.next();
if (item.getNode().getId() == terminalsId.get(i).intValue()) {
double cost = edgeWeight.getWeight(item.getPseudo().getInformed().getId(), item.getPseudo().getUninformed().getId(), globalAdjl) + MCPmatrix[item.getPseudo().getUninformed().getId()][item.getNode().getId()];
if ((cost < minCost) || (minCost == -1)) {
minItem = item.copy();
minCost = cost;
}
}
}
realChosenItem.add(minItem);
realChosenPseudo.add(new PseudoNode(new Node(minItem.getPseudo().getInformed().getId()), new Node(minItem.getPseudo().getUninformed().getId())));
}
//independent part
Iterator<ElkinItem> itensIt = realChosenItem.iterator();
while (itensIt.hasNext()) {
ElkinItem item = itensIt.next();
int prev = item.getNode().getId();//terminal
int s = item.getPseudo().getUninformed().getId();
if (s == prev) { //the uninformed node of the pseudo node is a terminal
quasiArborescence.checkInsertEdge(item.getPseudo().getInformed().getId(), prev, edgeWeight.getWeight(item.getPseudo().getInformed().getId(), prev, globalAdjl));
} else {
while (P[s][prev] != s) {
quasiArborescence.checkInsertEdge(P[s][prev], prev, MCPmatrix[P[s][prev]][prev]);
prev = P[s][prev];
}
quasiArborescence.checkInsertEdge(P[s][prev], prev, MCPmatrix[P[s][prev]][prev]);
}
double cost = edgeWeight.getWeight(item.getPseudo().getInformed().getId(), item.getPseudo().getUninformed().getId(), globalAdjl);
quasiArborescence.checkInsertEdge(item.getPseudo().getInformed().getId(), item.getPseudo().getUninformed().getId(), cost);
}
} |
e5ce7acd-8265-47bf-840d-74366114c051 | 9 | public static BrainState getRandomBrainState(AntColour colour) {
// Create a new BrainState with i as the stateId
BrainState brainState = new BrainState();
// Set the Instruction
Instruction instruction = getRandom(Instruction.class);
brainState.setInstruction(instruction);
// Determine the additional Tokens needed
TokenType[] tokenTypes = getTokens(instruction);
// Loop through the additional tokens that we require
for (int j = 0; j < tokenTypes.length; j++) {
switch (tokenTypes[j]) {
case NEXTSTATE:
brainState.setNextIdState(r.nextInt(STATE_MAX));
break;
case ALTNEXTSTATE:
brainState.setAltNextIdState(r.nextInt(STATE_MAX));
break;
case SENSEDIRECTION:
brainState.setSenseDirection(getRandom(SenseDirection.class));
break;
case SENSECONDITION:
SenseCondition sc = getRandom(SenseCondition.class);
brainState.setSenseCondition(sc);
if (sc.equals(SenseCondition.MARKER)) {
brainState.setMarker(r.nextInt(MARKER_MAX), colour);
}
break;
case LEFTRIGHT:
brainState.setLeftRight(getRandom(LeftRight.class));
break;
case RANDINT:
brainState.setRandomInt(r.nextInt(FLIP_MAX));
break;
case MARKER:
brainState.setMarker(r.nextInt(MARKER_MAX), colour);
break;
}
}
return brainState;
} |
c00845bf-d3eb-46bc-89d7-42469d21ad82 | 6 | private void addEdges()
{
for(int i=initialGraphSize;i<graph.getSize();i++)
{
int numberOfEdges=(int) (2+Math.random()*6);
int [] adjacent = new int[numberOfEdges];
for(int j=0; j<numberOfEdges; j++)
{
int id= (int) ((Math.random()*(graph.getSize()))+1);
for(int k=0;k<j;k++)// ensures all edges are distinct
{
while(id== adjacent[k])
{
id= (int) ((Math.random()*(graph.getSize()))+1);
k=0;
}
}
adjacent[j]=id;
}
int [] weights = new int[numberOfEdges];
for(int l=0; l<numberOfEdges; l++)
{
weights[l]= (int) (100+Math.random()*1900);
}
Node city=graph.getCity(i);
for(int m=0; m<numberOfEdges; m++)
{
city.addOutgoingCity(graph.getCity(adjacent[m]-1), weights[m]);
graph.getCity(adjacent[m]-1).addIncomingCount();
}
}
} |
cabcd169-4b16-40dc-80c1-24c2df9c237a | 9 | private void updateCreature(Creature creature,
long elapsedTime)
{
// apply gravity
if (!creature.isFlying()) {
creature.setVelocityY(creature.getVelocityY() +
GRAVITY * elapsedTime);
}
// change x
float dx = creature.getVelocityX();
float oldX = creature.getX();
float newX = oldX + dx * elapsedTime;
Point tile =
getTileCollision(creature, newX, creature.getY());
if (tile == null) {
creature.setX(newX);
}
else {
// line up with the tile boundary
if (dx > 0) {
creature.setX(
TileMapRenderer.tilesToPixels(tile.x) -
creature.getWidth());
}
else if (dx < 0) {
creature.setX(
TileMapRenderer.tilesToPixels(tile.x + 1));
}
creature.collideHorizontal();
}
if (creature instanceof Player) {
checkPlayerCollision((Player)creature, false);
}
// change y
float dy = creature.getVelocityY();
float oldY = creature.getY();
float newY = oldY + dy * elapsedTime;
tile = getTileCollision(creature, creature.getX(), newY);
if (tile == null) {
creature.setY(newY);
}
else {
// line up with the tile boundary
if (dy > 0) {
creature.setY(
TileMapRenderer.tilesToPixels(tile.y) -
creature.getHeight());
}
else if (dy < 0) {
creature.setY(
TileMapRenderer.tilesToPixels(tile.y + 1));
}
creature.collideVertical();
}
if (creature instanceof Player) {
boolean canKill = (oldY < creature.getY());
checkPlayerCollision((Player)creature, canKill);
}
} |
607e612b-c133-485a-bd82-296c0d05cb42 | 3 | public void testFormatPrefixPlural3() {
try {
builder.appendPrefix(null, "");
fail();
} catch (IllegalArgumentException ex) {}
try {
builder.appendPrefix("", null);
fail();
} catch (IllegalArgumentException ex) {}
try {
builder.appendPrefix(null, null);
fail();
} catch (IllegalArgumentException ex) {}
} |
0927586d-e4a6-4c25-8e20-2e97c0b78e41 | 5 | private static int Chain(String number, HashMap<String, Integer> memoized) {
Integer savedValue = (Integer) memoized.get(number);
if (savedValue != null) {
// System.out.println(number + " -> " + savedValue + " (Memoized)");
return savedValue;
} else if ("1".equals(number) || "89".equals(number)) {
// System.out.println(number);
return Integer.parseInt(number);
} else {
// System.out.print(number + " -> ");
BigInteger newNumber = BigInteger.ZERO;
for (int i = 0; i < number.length(); i++) {
int digit = Integer.parseInt(number.substring(i, i + 1));
newNumber = newNumber.add(BigInteger.valueOf(digit * digit));
}
int returnValue = Chain(newNumber.toString(), memoized);
if (memoized.size() < _maxMemoizedSize) {
memoized.put(number, returnValue);
}
return returnValue;
}
} |
3e07fec3-9e31-4175-bc32-51de80ece678 | 9 | public static boolean isFullPattern(final String pattern) {
boolean full = true;
final Matcher m = Pattern.compile(GROUP).matcher(pattern);
if (m.find()) {
int level = 0;
final int l = pattern.length() - 1;
int i = 0;
while ((i < l) && full) {
final char c = pattern.charAt(i);
if (c == '(') {
if ((level == 0) && (i != 0)) {
full = false;
}
level++;
}
else if (c == ')') {
if ((level == 1) && (i != l)) {
full = false;
}
level--;
}
i++;
}
}
else {
full = false;
}
return full;
} |
1309efdd-3000-4a80-878d-4beeb423229f | 0 | @Test
public void getEdgeByVertices() {
Vertex a = new Vertex(0);
Vertex b = new Vertex(1);
Edge e = new Edge(a, b);
g.addVertex(a);
g.addVertex(b);
g.addEdge(a, b, 1);
assertTrue(g.getEdgeByVertices(a, b).equals(e));
} |
3bbccbc2-bb85-426e-a008-4793136ea7ec | 2 | public static void main(String[] args) {
//Instantiate an object of BufferedReader, called br.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//Instantiate an object of HashMap, called hm.
HashMap<String, Student> hm = new HashMap<String, Student>();
//Ask user how many students they want to enter. This will
//set the number of times that the data input questions will be asked.
try{ //I don't understand what this is.
System.out.println("How many students would you like to enter?");
int num = Integer.parseInt(br.readLine());
//use a for loop to:
//1.Print the questions and store the answers in scanner objects.
//2.Instantiate a new object of Student.
//3.Assign the local variables in the object.
//4.Store the object in an array.
for (int i = 0; i< num; i++){
System.out.println("What is your Social Security Number?");
String ssn = br.readLine();
System.out.println("What is your first name?");
String firstName = br.readLine();
System.out.println("What is your last name?");
String lastName = br.readLine();
System.out.println("Where do you go to school?");
String school = br.readLine();
System.out.println("What is your address?");
String address = br.readLine();
System.out.println("How old are you?");
int age = Integer.parseInt(br.readLine());
System.out.println("What grade are you in?");
int grade = Integer.parseInt(br.readLine());
System.out.println("What is your phone number?");
String phoneNumber = br.readLine();
System.out.println("What is your birthday?");
String birthday = br.readLine();
//Instantiate an object of Student class.
Student studentObject = new Student();
//populate the object with the values from scanner.
studentObject.setFirstName(firstName);
studentObject.setLastName(lastName);
studentObject.setSchool(school);
studentObject.setAddress(address);
studentObject.setAge(age);
studentObject.setGrade(grade);
studentObject.setPhoneNumber(phoneNumber);
studentObject.setBirthday(birthday);
studentObject.setSsn(ssn);
//store the object that contains all the student information in a HashMap by using the put method.
//it uses the ssn as a key value.
hm.put(ssn, studentObject);
}//end first loop that stores data into objects and hashmap
} catch (IOException ioe) {
ioe.printStackTrace();
System.out.println("IO error trying to read your name!");
System.exit(1);
}//this is part of exception handling. Apparently, I have to use this when I use BufferedReader,
//but Marco won't explain it to me yet, so I will just use Scanner below to take the input from the user.
//instantiate a new Scanner Object
Scanner scanner = new Scanner(System.in);
//ask the user which student they want.
System.out.println("Enter the SSN of the student whose information you would like.");
String studentSsn = scanner.nextLine();//scanner stores the ssn as the local String variable, studentSsn.
//Instantiate a new student object, s, which is equal to that hashmap value which corresponds
//to the key which is the local String variable, studentSsn.
Student s = hm.get(studentSsn);
//I call each of the properties that I want by calling the getter of each variable in the Student object, s.
System.out.println(s.getFirstName());
System.out.println(s.getLastName());
System.out.println(s.getSchool());
System.out.println(s.getAddress());
System.out.println(s.getPhoneNumber());
System.out.println(s.getBirthday());
System.out.println(s.getAge());
System.out.println(s.getGrade());
}//close main |
fff6b1fa-4dac-4197-ac71-f795c15c04ee | 4 | public static SeekableInput replaceInputStreamWithSeekableInput(InputStream in) {
if (in instanceof SeekableInput)
return (SeekableInput) in;
SeekableInput sin = null;
try {
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
/*
byte[] buf = new byte[1024];
while( true ) {
int read = in.read( buf, 0, buf.length );
if( read < 0 )
break;
out.write( buf, 0, read );
}
*/
while (true) {
int read = in.read();
if (read < 0)
break;
out.write(read);
}
in.close();
out.flush();
out.close();
byte[] data = out.toByteArray();
sin = new SeekableByteArrayInputStream(data);
}
catch (IOException ioe) {
logger.log(Level.FINE, "Problem getting debug string");
}
return sin;
} |
80c4e6ab-c40f-4cbd-82a5-27ff6fea3e2f | 5 | private static Vec2 generateRandomPos(Mob mob, double radius, Vec2 dir) {
// boolean hasBest = false;
// int xBest = 0, yBest = 0, zBest = 0;
// double best = -99999;
Random random = TurnSynchronizer.synchedRandom;
Vec2 pos = new Vec2();
for (int i = 0; i < 10; i++) {
// in a square for now...
pos.set(random.nextDouble() * 2 * radius - radius,
random.nextDouble() * 2 * radius - radius);
if (dir != null && pos.dot(dir) < 0)
continue;
pos.addSelf(mob.pos);
Tile tile = mob.level.getTile(mob.pos);
if (tile == null || !tile.canPass(mob))
continue;
return pos;
}
return null;
} |
25411a83-68cc-4d7e-b351-8adf34821cce | 0 | public Star(Animation anim) {
super(anim);
} |
329b2c01-e142-4d0a-863f-052bf89f5f1a | 6 | public static Stella_Object accessXmlElementSlotValue(XmlElement self, Symbol slotname, Stella_Object value, boolean setvalueP) {
if (slotname == Stella.SYM_STELLA_NAMESPACE_NAME) {
if (setvalueP) {
self.namespaceName = ((StringWrapper)(value)).wrapperValue;
}
else {
value = StringWrapper.wrapString(self.namespaceName);
}
}
else if (slotname == Stella.SYM_STELLA_NAMESPACE_URI) {
if (setvalueP) {
self.namespaceUri = ((StringWrapper)(value)).wrapperValue;
}
else {
value = StringWrapper.wrapString(self.namespaceUri);
}
}
else if (slotname == Stella.SYM_STELLA_ELEMENT_DICTIONARY) {
if (setvalueP) {
self.elementDictionary = ((KeyValueList)(value));
}
else {
value = self.elementDictionary;
}
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("`" + slotname + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
return (value);
} |
6651ae4d-6ca4-4859-9d99-321f14f8a7e4 | 2 | public void save(DataOutputStream out) throws IOException {
super.save(out);
for (int i = 0; i<4 ; i++) {
if (lines[i].isEmpty()){
out.writeUTF("");
} else {
out.writeUTF(lines[i]);
}
}
} |
8dec6ba9-250f-4631-b044-b86aea957759 | 0 | public static GeneralValidator isEqual() {
return EQUALS_VALIDATOR;
} |
13db7751-04c7-4095-bac7-4d8333ae3a03 | 0 | public String toCSV() {
return super.toCSV();
} |
c5212687-3c98-460c-bdd4-27d4e2271444 | 5 | private void executeSavedAction(char action){
try {
if (action == 'r') primaryService.movePlayer(this.shServiceClient, 'r');
else if (action == 'l') primaryService.movePlayer(this.shServiceClient, 'l');
else if (action == 'd') primaryService.movePlayer(this.shServiceClient, 'd');
else if (action == 'u') primaryService.movePlayer(this.shServiceClient, 'u');
logger.info("The action saved is now executed in the new primary server.");
}
catch (RemoteException e) {
String errorMsg= "RemoteException occured. The recovery manager could not reach the new primary in order to execute the action saved.";
logger.error(errorMsg);
throw new IllegalStateException(errorMsg, e);
}
} |
78426a90-0e94-47ca-bc3e-a5bcc2320d60 | 3 | private Station createStation() throws StorageReaderException {
String name = null;
try {
name = nextString();
int price = nextInt();
int[] income = new int[4];
for(int i = 0; i < income.length; i++) {
income[i] = nextInt();
}
int mortgage = nextInt();
if(!isEndOfBlock()) {
throw new EndOfBlockException(fileName);
}
return new Station(name, price, income, mortgage);
} catch(Exception e) {
throw new CreationException(name, "Station", e);
}
} |
01ea5cc2-13cd-4487-a293-41d9eb17f118 | 9 | public void Solve() {
int previousNumerator = 0;
int previousDenominator = 1;
double previousValue = 0;
double targetValue = 3 / 7.0;
for (int d = 2; d <= _max; d++) {
// System.out.println(d);
int upper = d / 2 + 1;
int lower = 1;
while (2 < upper - lower) {
int n = lower + (upper - lower) / 2;
double value = (double) n / (double) d;
if (value < targetValue) {
lower = n;
} else {
upper = n;
}
}
for (int n = lower - 1; n <= upper + 1; n++) {
if (n <= 0) {
continue;
} else if (d <= n) {
continue;
}
double value = (double) n / (double) d;
if (n % d != 0 && value < targetValue && previousValue < value) {
previousNumerator = n;
previousDenominator = d;
previousValue = value;
System.out.println("Updated for " + n + " / " + d + " = " + value);
}
}
}
System.out.println("Result=" + previousNumerator);
} |
31ef0959-a5d4-4c11-8919-a863765350ae | 6 | public int cdlEveningDojiStarLookback( double optInPenetration )
{
if( optInPenetration == (-4e+37) )
optInPenetration = 3.000000e-1;
else if( (optInPenetration < 0.000000e+0) || (optInPenetration > 3.000000e+37) )
return -1;
return ((( ((( (this.candleSettings[CandleSettingType.BodyDoji.ordinal()].avgPeriod) ) > ( (this.candleSettings[CandleSettingType.BodyLong.ordinal()].avgPeriod) )) ? ( (this.candleSettings[CandleSettingType.BodyDoji.ordinal()].avgPeriod) ) : ( (this.candleSettings[CandleSettingType.BodyLong.ordinal()].avgPeriod) )) ) > ( (this.candleSettings[CandleSettingType.BodyShort.ordinal()].avgPeriod) )) ? ( ((( (this.candleSettings[CandleSettingType.BodyDoji.ordinal()].avgPeriod) ) > ( (this.candleSettings[CandleSettingType.BodyLong.ordinal()].avgPeriod) )) ? ( (this.candleSettings[CandleSettingType.BodyDoji.ordinal()].avgPeriod) ) : ( (this.candleSettings[CandleSettingType.BodyLong.ordinal()].avgPeriod) )) ) : ( (this.candleSettings[CandleSettingType.BodyShort.ordinal()].avgPeriod) )) +
2;
} |
8c5bf1a7-14ee-4fbb-a3e9-fb214722872a | 6 | public static String escape(String string) {
char c;
String s = string.trim();
StringBuffer sb = new StringBuffer();
int len = s.length();
for (int i = 0; i < len; i += 1) {
c = s.charAt(i);
if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') {
sb.append('%');
sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16));
sb.append(Character.forDigit((char)(c & 0x0f), 16));
} else {
sb.append(c);
}
}
return sb.toString();
} |
b3037bc8-ece4-477d-822a-9c6af8f3e7de | 4 | public static void main(String[] args) {
// TODO Auto-generated method stub
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
List<File> files = new ArrayList<>();
files.add(new File("TestClass1.java"));
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(files);
CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits);
Iterable<? extends CompilationUnitTree> parseResult = null;
SourcePositions sourcePositions = null;
try {
JavacTask javacTask = (JavacTask) task;
sourcePositions = Trees.instance(javacTask).getSourcePositions();
parseResult = javacTask.parse();
} catch (IOException e) {
// Parsing failed
e.printStackTrace();
System.exit(0);
}
for (CompilationUnitTree compilationUnitTree : parseResult) {
ASTCrawler c = new ASTCrawler();
TreePath p = new TreePath(compilationUnitTree);
c.scan(p, null);
}
} |
bd24736e-8b15-4092-b400-c2ed6a60fff4 | 3 | public byte[] toRedisField()
{
byte[] toReturn = new byte[row.length + cf.length + cq.length + 2];
int i = 0;
for (byte b : row)
{
toReturn[i] = b;
i++;
}
toReturn[i] = Utils.RECORD_SEPARATOR;
i++;
for (byte b : cf)
{
toReturn[i] = b;
i++;
}
toReturn[i] = Utils.RECORD_SEPARATOR;
i++;
for (byte b : cq)
{
toReturn[i] = b;
i++;
}
return toReturn;
} |
04ed0de9-2509-4316-9707-7bc30135e4c6 | 1 | public VueRecherche() {
/* Background */
/*
* ImageIcon icon = new ImageIcon("img//gdeFond2.jpg"); JLabel img = new
* JLabel(icon); add(img);
*/
rech = new JTextField(15);
rech.setText("Saisir mots-clés...");
rech.setBackground(new Color(227, 231, 244));
rech.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ENTER) {
texteRech = rech.getText();
}
}
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
});
this.add(rech);
} |
40c79daa-a9df-4d01-b5a8-085f878e7ef8 | 2 | public static void loadConfig() {
// Audio
float musicVolume = new Float(getProperty("music", "1f"));
SoundStore.get().setMusicVolume(musicVolume);
SoundStore.get().setCurrentMusicVolume(musicVolume);
float sfxVolume = new Float(getProperty("sfx", "1f"));
SoundStore.get().setSoundVolume(sfxVolume);
// Video
boolean fullScreen = new Boolean(getProperty("fullscreen", "false"));
Camera.get().setFullscreen(fullScreen);
boolean vsync = new Boolean(getProperty("vsync", "false"));
Camera.get().setVSync(vsync);
// Keybinds
int binding;
for(Keybind keybind : Keybind.values()) {
try {
binding = new Integer(getProperty(keybind.name()));
} catch(NumberFormatException e) {
continue;
}
keybind.setKey(binding);
}
} |
c63f62b3-7fa5-4ef7-9c30-65d81d0bffb9 | 1 | @Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + baggageCurWeight;
result = prime * result + baggageMaxWeight;
result = prime * result
+ ((comfortType == null) ? 0 : comfortType.hashCode());
result = prime * result + passengerCurCount;
result = prime * result + passengerMaxCount;
return result;
} |
e3fcc618-8d8f-4805-9a92-9ad4e799582b | 0 | public void constructPizza() {
pizzaBuilder.createNewPizzaProduct();
pizzaBuilder.buildDough();
pizzaBuilder.buildSauce();
pizzaBuilder.buildTopping();
} |
f249533e-1686-4ed2-8ac8-4c14fe07db45 | 0 | public void setGradeLevel(String gradelevel) {
this.gradelevel = gradelevel;
} |
b3c5c9a5-b165-404a-b87e-0687d256e079 | 9 | public void setUserinfo(String p_userinfo) throws MalformedURIException
{
if (p_userinfo == null)
{
m_userinfo = null;
}
else
{
if (m_host == null)
{
throw new MalformedURIException(
"Userinfo cannot be set when host is null!");
}
// userinfo can contain alphanumerics, mark characters, escaped
// and ';',':','&','=','+','$',','
int index = 0;
int end = p_userinfo.length();
char testChar = '\0';
while (index < end)
{
testChar = p_userinfo.charAt(index);
if (testChar == '%')
{
if (index + 2 >= end ||!isHex(p_userinfo.charAt(index + 1))
||!isHex(p_userinfo.charAt(index + 2)))
{
throw new MalformedURIException(
"Userinfo contains invalid escape sequence!");
}
}
else if (!isUnreservedCharacter(testChar)
&& USERINFO_CHARACTERS.indexOf(testChar) == -1)
{
throw new MalformedURIException(
"Userinfo contains invalid character:" + testChar);
}
index++;
}
}
m_userinfo = p_userinfo;
} |
6f55e3a3-fcfe-45b9-882e-7c6d5b8213b2 | 5 | @Override
public double evaluate(final double z) {
if (z < x[0]) {
return y[0];
} else if (z > x[x.length - 1]) {
return y[y.length - 1];
}
for (int i = 0; i < x.length - 1; i++) {
if (z >= x[i] && z <= x[i + 1]) {
// // a*(x-b) + c
// final double a = (y[i + 1] - y[i]) / (x[i + 1] - x[i]);
// final double b = x[i];
// final double c = y[i];
// m*x + t
final double m = (y[i + 1] - y[i]) / (x[i + 1] - x[i]);
final double t = y[i] - m * x[i];
// assert (m * z + t == a * (z - b) + c);
return m * z + t;
}
}
return -1; // Wird nie aufgerufen.
} |
4fcf670d-c103-49cd-9543-6b437a28562f | 0 | public void newFrameAtRunTimeStack(int offset) {
runStack.newFrameAt(offset);
} |
cbbc1ff6-4102-403e-8d6a-e40a7585d7c9 | 3 | public String longestPalindrome(String s) {
for (int l = s.length(); l > 0; l--) {
for (int i = s.length() - l; i > -1; i--) {
if (isPalindorme(s, i, i + l - 1))
return s.substring(i, i + l);
}
}
return null;
} |
084cf8ae-4dbd-4741-9bfc-c50270a1cab4 | 6 | @EventHandler
public void EndermanWeakness(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.getEndermanConfig().getDouble("Enderman.Weakness.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getEndermanConfig().getBoolean("Enderman.Weakness.Enabled", true) && damager instanceof Enderman && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.WEAKNESS, plugin.getEndermanConfig().getInt("Enderman.Weakness.Time"), plugin.getEndermanConfig().getInt("Enderman.Weakness.Power")));
}
} |
803af463-f1ee-4182-916b-5ba13fe70d74 | 4 | @Override
public String toString() {
switch(this) { // "this" is one of the enumerated type values
case ACE:
return "Ace";
case JACK:
return "Jack";
case QUEEN:
return "Queen";
case KING:
return "King";
default:
int numericValue = 1 + ordinal();
return "" + numericValue;
}
} |
5ded8f15-cdf4-4ac1-917c-2f2ad4ae70ef | 0 | @Override
public String getDbname() {
return dbname;
} |
d3b48a7b-e0f1-4e85-82fe-65c143608bca | 2 | protected Markers readMarkers(String fileName) {
Markers markersSeqChange = Markers.readMarkers(fileName);
String label = Gpr.removeExt(Gpr.baseName(fileName));
// Convert 'SeqChange' markers to 'Custom' markers
Markers markers = new Markers();
for (Marker m : markersSeqChange) {
Custom custom = new Custom(m.getParent(), m.getStart(), m.getEnd(), m.getStrand(), m.getId(), label);
if (m instanceof VariantWithScore) custom.setScore(((VariantWithScore) m).getScore());
markers.add(custom);
}
// Number added
return markers;
} |
8e4b2112-3eaa-4080-9803-ba6fce729e41 | 7 | public boolean isEmptyCluster(Hashtable<Room,MapRoom> processed, int x, int y)
{
for(final Enumeration<MapRoom> e=processed.elements();e.hasMoreElements();)
{
final MapRoom room=e.nextElement();
if((((room.x>x-CLUSTERSIZE)&&(room.x<x+CLUSTERSIZE))
&&((room.y>y-CLUSTERSIZE)&&(room.y<y+CLUSTERSIZE)))
||((room.x==x)&&(room.y==y)))
return false;
}
return true;
} |
542385d2-9506-4eb8-9711-eb493b8a1390 | 3 | public int do300baudFFT (CircularDataBuffer circBuf,WaveData waveData,int start) {
// Get the data from the circular buffer
double samData[]=circBuf.extractDataDouble(start,26);
double datar[]=new double[FFT_64_SIZE];
// Run the data through a Blackman window
int a;
for (a=0;a<datar.length;a++) {
if ((a>=19)&&(a<45)) datar[a]=samData[a-19];
else datar[a]=0.0;
}
fft64.realForward(datar);
double spec[]=getSpectrum(datar);
int freq=getFFTFreq (spec,waveData.getSampleRate());
return freq;
} |
78334008-1e1e-4faa-81da-59514eabb201 | 8 | @Override
public int compareTo(PokerHandValue pokerHandValue) {
if(Value.equals(pokerHandValue.Value) && Rank.equals(pokerHandValue.Rank))
return 0;
if(Rank.compareTo(pokerHandValue.Rank) == 0 && Rank == PokerHandRank.Two_Pair)
return CompareTwoPair(pokerHandValue);
if(Rank.compareTo(pokerHandValue.Rank) == 0)
return new PlayingCard(Value, "").compareTo(new PlayingCard(pokerHandValue.Value, ""));
if(Rank.compareTo(pokerHandValue.Rank) > 0)
return 1;
if(Rank.compareTo(pokerHandValue.Rank) < 0)
return -1;
if(new PlayingCard(Value, "").compareTo(new PlayingCard(pokerHandValue.Value, "")) > 0)
return 1;
return -1;
} |
6664e51f-80f2-4926-ad47-2d5a19f512f3 | 6 | public static int dehexchar(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - ('A' - 10);
}
if (c >= 'a' && c <= 'f') {
return c - ('a' - 10);
}
return -1;
} |
24e1074c-90ee-4f5d-bef6-011ec37febc6 | 9 | private static void intArToByteAr() {
bAr[0] = (byte)'4';
//Bounds check ints in tableAr for byte conversion
for (int y = 0; y < tableAr.length; y++)
for (int x = 0; x < tableAr[y].length; x++)
if (tableAr[y][x] > 255) tableAr[y][x] = 255;
else if (tableAr[y][x] < 0) tableAr[y][x] = 0;
if (LedTable_Settings.snakedLeds) {
int cell = 1;
for (int y = 0; y < LedTable_Settings.ledY; y++) {
if (y % 2 == 0) {
for (int x = 0; x < LedTable_Settings.ledX; x++) {
bAr[cell++] = (byte)tableAr[y][x * 3];
bAr[cell++] = (byte)tableAr[y][x * 3 + 1];
bAr[cell++] = (byte)tableAr[y][x * 3 + 2];
}
} else {
for (int x = LedTable_Settings.ledX - 1; x >= 0; x--) {
bAr[cell++] = (byte)tableAr[y][x * 3];
bAr[cell++] = (byte)tableAr[y][x * 3 + 1];
bAr[cell++] = (byte)tableAr[y][x * 3 + 2];
}
}
}
}
} |
a7d7e289-5fb3-430e-8416-474138f6fb29 | 7 | protected static String getCurrentElement( XmlPullParser xpp )
{
StringBuffer el = new StringBuffer();
try
{
int eventType = xpp.getEventType();
String elname = xpp.getName();
while( eventType != XmlPullParser.END_DOCUMENT )
{
if( (eventType == XmlPullParser.START_TAG) || (eventType == XmlPullParser.TEXT) )
{
el.append( xpp.getText() );
}
else if( eventType == XmlPullParser.END_TAG )
{
String t = xpp.getText();
if( t.indexOf( "</" ) == 0 )
{
el.append( t );
}
if( xpp.getName().equals( elname ) )
{
break;
}
}
eventType = xpp.next();
}
}
catch( Exception e )
{
log.error( "OOXMLAdapter.getCurrentElement: " + e.toString() );
}
return el.toString();
} |
d675015a-bfb5-46a5-8401-ca6127c45a40 | 9 | static public void generateLevel(ru.mipt.cs.level_generator.Difficulty diff, double size) {
LvlGenerator.size = size;
int numberOfFields = GetConfigByDiff.numberOfFields(diff);
int numberOfFZones = GetConfigByDiff.numberOfFZones(diff);
int numberOfObs = GetConfigByDiff.numberOfObs(diff);
particleDefault = GetConfigByDiff.particle();
trajectory = LvlGenerator.getTrajectory();
int counterOfObs = numberOfObs;
for (int i = 0; i < (numberOfFields + numberOfObs); i++){
Point enter = trajectory.getPointAt(trajectory.length()*0.75*(i+1)/(numberOfFields+numberOfObs));
Orientation orientation = trajectory.getOrientationAt(trajectory.length()/1.9*(i+1)/numberOfFields);
double m = Math.random();
if ((i > 0) && (counterOfObs > 0) && (m < (i)/(numberOfFields+numberOfObs-2))) {
insertObs(diff, enter, orientation);
counterOfObs--;
}
else {
insertField(diff, enter, orientation);
}
trajectory = LvlGenerator.getTrajectory();
}
LinkedList<ForbiddenZone> fzlist = new LinkedList<ForbiddenZone>();
for (int i = 0; i < (numberOfFZones/2); i++){
//TODO use threads, resolve tied
Point normal = trajectory.getN(trajectory.getNumberAt(trajectory.length()*0.85*(i+1)/numberOfFZones));
Point current = trajectory.getPointAt(trajectory.length()*0.85*(i+1)/numberOfFZones);
double len = normal.length(); normal.setX(normal.getX()/len); normal.setY(normal.getY()/len);
System.out.println("Normal: "+ normal.getX() +' '+ normal.getY());
Random r = new Random();
double enraser = GetConfigByDiff.setRecAccuracy(diff)*(1+2*r.nextDouble());
//right-handed
int a = (int) Math.round((2+2*r.nextDouble())*GetConfigByDiff.setRecAccuracy(diff)/3);
int b = (int) Math.round((2+2*r.nextDouble())*GetConfigByDiff.setRecAccuracy(diff)/3);
ForbiddenZone fz = new ForbiddenZone((int)Math.round(current.getX()+enraser*normal.getX()+GetConfigByDiff.setRecAccuracy(diff)/4*(r.nextDouble()-0.5)),
(int)Math.round(current.getY()+enraser*normal.getY()),a,b);
fzlist.add(fz);
//left-handed
enraser = GetConfigByDiff.setRecAccuracy(diff)*(2+2*r.nextDouble());
enraser *= -1;
fz = new ForbiddenZone((int)Math.round(current.getX()+enraser*normal.getX()+GetConfigByDiff.setRecAccuracy(diff)/4*(r.nextDouble()-0.5)),
(int)Math.round(current.getY()+enraser*normal.getY()),a,b);
fzlist.add(fz);
}
int toAdd = numberOfFZones%2;
for (int i = 0; i < fzlist.size(); i++)
if (LvlGenerator.trajectory.liesToClose(fzlist.get(i), diff)) {
Rectangle.moveList.remove(fzlist.get(i)); fzlist.remove(i);
i--; toAdd++;
System.out.println("Removed!");
}
for (int i = 0; i < toAdd; i++) {
ForbiddenZone fz = new ForbiddenZone(0, 0, 0, 0);
System.out.println("added at toAdd "+i);
do {
LvlGenerator.shake(fz);
} while (trajectory.cross(fz));
}
new Destination (0.5*trajectory.get().getLast().getX()+0.5*trajectory.get().get(trajectory.get().size()-1).getX(),
0.5*trajectory.get().getLast().getY()+0.5*trajectory.get().get(trajectory.get().size()-1).getY(), diff);
} |
f261caad-26ec-4885-9413-e2267766e6bb | 4 | public static <T> List<List<T>> array_chunk(List<T> arr, int page) {
if (arr == null) return new ArrayList<List<T>>();
if (page < 1) return new ArrayList<List<T>>(); // hmm. GIGO.
List<List<T>> output = new ArrayList<List<T>>();
int count = 0;
while (arr.size() > count) {
int newCount = count + page;
if (newCount > arr.size()) newCount = arr.size();
List<T> newArr = arr.subList(count,newCount);
output.add((List<T>)newArr);
count = newCount;
}
/*if (count < arr.size()) {
output.add(arr.subList(count,arr.size() - 1));
}*/
return output;
} |
b3a37d83-13b9-4897-bcbb-5b7a646528f0 | 6 | public void insert(ListNode node, int index) {
ListNode currentNode = root;
ListNode beforeNode = root;
int currentIndex = 0;
if (!isEmpty() && index >= 0 && index <= size()) {
// iterate to index
while (currentNode != null && currentIndex != index) {
beforeNode = currentNode;
currentNode = currentNode.next;
currentIndex++;
}
// insert
if (index == 0) {
root = node;
node.next = currentNode;
} else {
beforeNode.next = node;
node.next = currentNode;
}
}
} |
7310efa5-dfaf-407e-9098-3722ab9876c1 | 6 | @Override
public void run() {
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(CE_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CE_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CE_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CE_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
initComponents();
//set frame position
setLocation(
(Toolkit.getDefaultToolkit().getScreenSize().width-getSize().width) / 2,
(Toolkit.getDefaultToolkit().getScreenSize().height-getSize().height) / 2
);
getRootPane().setDefaultButton(btn_login);
//read string from file and fill textfield
String [] Array = LoginData.readSQL ();
txf_host.setText(Array[0]);
txf_port.setText(Array[1]);
txf_database.setText(Array[2]);
txf_user.setText(Array[3]);
txf_pw.setText(Array[4]);
this.setVisible(true);
} |
da5e7d0c-720a-4db7-987b-c97b822660d1 | 5 | protected int addPacket(OggPacket packet, int offset) {
if(packet.isBeginningOfStream()) {
isBOS = true;
}
if(packet.isEndOfStream()) {
isEOS = true;
}
// Add on in 255 byte chunks
int size = packet.getData().length;
for(int i = numLVs; i< 255; i++) {
int remains = size - offset;
int toAdd = 255;
if(remains < 255) {
toAdd = remains;
}
lvs[i] = IOUtils.fromInt(toAdd);
tmpData.write(packet.getData(), offset, toAdd);
numLVs++;
offset += toAdd;
if(toAdd < 255) {
break;
}
}
return offset;
} |
9818ec64-be76-4d7a-bd52-cdba65238b90 | 6 | public boolean checkAntiDiagonal(){
// diagonal upper right to lower left (anti-diagonal)
for (int col = numColumns - 1; col >= 3; col--) {
for (int row = 0; row < numRows - 3; row++) {
int curr = gameGrid[col][row].getState();
if (curr > 0
&& curr == gameGrid[col - 1][row + 1].getState() //move column to the left
&& curr == gameGrid[col - 2][row + 2].getState() //and row down, checking
&& curr == gameGrid[col - 3][row + 3].getState()) //each state
{
winX = col;
winY = row;
game.setGameIsOver(true);
return true;
}
}
}
return false;
} |
76e9e90c-de45-4d6e-ae0c-e5ddada911fc | 8 | public List<Float> getFloatList(String path) {
List<?> list = getList(path);
if (list == null) {
return new ArrayList<Float>(0);
}
List<Float> result = new ArrayList<Float>();
for (Object object : list) {
if (object instanceof Float) {
result.add((Float) object);
} else if (object instanceof String) {
try {
result.add(Float.valueOf((String) object));
} catch (Exception ex) {
}
} else if (object instanceof Character) {
result.add((float) ((Character) object).charValue());
} else if (object instanceof Number) {
result.add(((Number) object).floatValue());
}
}
return result;
} |
9ec8c040-9f0d-4e45-a245-26616fb9dcf5 | 1 | public String llenaCatalogo(ArrayList<String> elementos) {
String opcion = "<option label='";
String opcion_ = "/>";
String res = "";
for (String elem : elementos) {
res += opcion + elem + "' " + "value='" + elem + "' " + opcion_ + "\n";
}
return res;
} |
6ae3e1c1-1538-42c8-b7db-257d58274bb9 | 8 | @Override
public void callOperationAsynchronously(final String operationName, final CallbackListener listener,
final int periodMs, final Object... arguments) {
final String serviceName = getName();
Thread thread = new Thread() {
public void run() {
try {
OrocosOperation operation = getOperation(operationName);
Any[] anyArguments = castOperationArguments(operation, arguments);
CAnyArgumentsHolder holder = new CAnyArgumentsHolder(anyArguments);
CSendHandle handler = getCService().sendOperation(operationName, anyArguments);
CSendStatus sendStatus = handler.collectIfDone(holder);
while(sendStatus == CSendStatus.CSendNotReady){
sendStatus = handler.collectIfDone(holder);
// System.out.println("SendStatus: " + sendStatus.value());
Thread.sleep(periodMs);
}
if(sendStatus == CSendStatus.CSendSuccess){
Object returnValue = AnyObjectCast.anyToObject(handler.ret());
listener.callback(serviceName, operationName, returnValue);
}else if(sendStatus == CSendStatus.CSendFailure){
listener.callback(serviceName, operationName, null);
logger.error("The asynchornous call to the operation '" + operationName + "' fails.");
}
} catch (CNoSuchNameException e) {
e.printStackTrace();
} catch (CWrongNumbArgException e) {
logger.error("The number of the arguments passed to the operation is wrong.");
e.printStackTrace();
} catch (CWrongTypeArgException e) {
logger.error("At least one of the arguments passed to the operation belong to a wrong type.");
e.printStackTrace();
} catch (CCallInterrupted e) {
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
thread.start();
} |
12f4a410-6803-4c90-9a2f-840c056ca983 | 0 | public String getInstallDate() {
return installdate;
} |
3021dd85-7b1f-41cd-9e1a-a9616dc94a3a | 4 | private static String dirString(DirKey dk){
if(dk==DirKey.Up){
return "up";
}
else if(dk==DirKey.Down){
return "down";
}
else if(dk==DirKey.Left){
return "left";
}
else if(dk==DirKey.Right){
return "right";
}
else{
return "else";
}
} |
7cc7925c-62a4-4b84-aa88-bf47b8d4e965 | 9 | private final void method4006(BufferedStream buffer, int i, byte b, int i_0_) {
anInt4337++;
if (i_0_ != 1) {
if ((i_0_ ^ 0xffffffff) != -3) {
if ((i_0_ ^ 0xffffffff) == -4) {
buffer.readByte();
} else if ((i_0_ ^ 0xffffffff) == -5) {
anInt4324 = buffer.readUnsignedByte();
} else if (i_0_ == 5) {
anInt4336 = buffer.readUnsignedByte();
} else if ((i_0_ ^ 0xffffffff) == -7) {
aBoolean4335 = true;
} else if (i_0_ == 7) {
aBoolean4325 = true;
}
} else {
anInt4334 = buffer.readUnsignedShort() + 1;
anInt4326 = buffer.readUnsignedShort() - -1;
}
} else {
anInt4330 = buffer.readUnsignedShort();
if (anInt4330 == 65535) {
anInt4330 = -1;
}
}
if (b != -2) {
method4007(102, (byte) 75, null);
}
} |
375bbf41-cab5-4c9b-bd52-a0a9fd5c48cf | 6 | public void updateEntity()
{
if (this.brewTime > 0)
{
--this.brewTime;
if (this.brewTime == 0)
{
this.brewPotions();
this.onInventoryChanged();
}
else if (!this.canBrew())
{
this.brewTime = 0;
this.onInventoryChanged();
}
else if (this.ingredientID != this.brewingItemStacks[3].itemID)
{
this.brewTime = 0;
this.onInventoryChanged();
}
}
else if (this.canBrew())
{
this.brewTime = 400;
this.ingredientID = this.brewingItemStacks[3].itemID;
}
int var1 = this.getFilledSlots();
if (var1 != this.filledSlots)
{
this.filledSlots = var1;
this.worldObj.setBlockMetadataWithNotify(this.xCoord, this.yCoord, this.zCoord, var1);
}
super.updateEntity();
} |
99e91775-b44c-4cf2-9229-7a35ab0d5b21 | 4 | public int moveByInt(int direction){
int moved = 0;
switch(direction){
case 0: moved=this.left();
break;
case 1: moved=this.right();
break;
case 2: moved=this.up();
break;
case 3: moved=this.down();
break;
}
return moved;
} |
0c0a12e8-a8d2-490c-b55e-3a49b279c3b8 | 8 | @Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof PieDataset)) {
return false;
}
PieDataset that = (PieDataset) obj;
int count = getItemCount();
if (that.getItemCount() != count) {
return false;
}
for (int i = 0; i < count; i++) {
Comparable k1 = getKey(i);
Comparable k2 = that.getKey(i);
if (!k1.equals(k2)) {
return false;
}
Number v1 = getValue(i);
Number v2 = that.getValue(i);
if (v1 == null) {
if (v2 != null) {
return false;
}
}
else {
if (!v1.equals(v2)) {
return false;
}
}
}
return true;
} |
5de22af2-bd8f-43c6-bbf2-3783294e5bf1 | 7 | private static void processKey(Object id, SelectionKey key, SelectorManager2 mgr) throws IOException, InterruptedException {
if(log.isLoggable(Level.FINEST))
log.finest(id+""+key.attachment()+"proccessing");
//This is code to try to avoid the CancelledKeyExceptions
if(!key.channel().isOpen() || !key.isValid())
return;
//if isAcceptable, than is a ServerSocketChannel
if(key.isAcceptable()) {
Helper.acceptSocket(id, key);
}
if(key.isConnectable())
Helper.connect(id, key);
if(key.isWritable()) {
Helper.write(id, key);
}
//The read MUST be after the write as a call to key.isWriteable is invalid if the
//read resulted in the far end closing the socket.
if(key.isReadable()) {
Helper.read(id, key, mgr);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.