method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
cdef8458-18a1-4e52-a89b-4fd37905c1c0
| 7
|
public List<Square> getClickableSurround(int i, int j) {
List<Square> squares = new ArrayList<Square>();
for (int x = i - 1; x <= i + 1; x++) {
for (int y = j - 1; y <= j + 1; y++) {
if (positionExists(x, y) || (x == i && y == j)) continue;
Square s = board[x][y];
if (!s.isFlagged() && !s.isRevealed()) squares.add(s);
}
}
return squares;
}
|
5ddd63fc-4e2a-430a-b0b9-3fd82f01f440
| 0
|
public void setIdLogEnt(int idLogEnt) {
this.idLogEnt = idLogEnt;
}
|
9d733155-9238-4df8-8912-bbbdfd9e533f
| 8
|
@Override
public boolean onCommand(CommandSender sender, Command command, String sabel, String[] args) {
if (Utils.commandCheck(sender, command, "sub")) {
Player player = (Player) sender;
if (args.length == 0) {
// /power - displays power help
// /power list - displays all powers (elements), with green and
// red indicator (showing what you have)
// /power current - displays current powers, how much mana they
// do/use
// /power info <power> - learn info about a power
// /power select <power> - learn a power (element) - drains
// anima to 0 and resets max to default
// not to be confused with the elemental attacks!!!!!!!!!!!!!
switch (args.length) {
case 0:
// show help
break;
case 1:
// list & current
break;
case 2:
// info & select
break;
}
} else if (args.length == 1) {
if (!Maleficus.getInstance().getSubMap().containsKey(args[0].toLowerCase())) {
player.sendMessage(" §6[§fUh oh!§6]§f The subElement §a" + args[0] + " §fdoesn't exist!");
return true;
}
SubElements p = Maleficus.getInstance().getSubMap().get(args[0].toLowerCase());
if(MPlayer.hasEnoughSubAnima(player, MPlayer.getSubLevel(player) * 100)) {
p.run(player);
return true;
} else {
player.sendMessage(" §6[§fUh oh!§6]§f You need §a" + ((MPlayer.getSubLevel(player) * 100) - MPlayer.getSubAnima(player)) + " §fmore SubAnima to use that!");
}
}
return true;
}
return false;
}
|
1f1b7c1a-4ea3-4169-99e2-1c85f859c23d
| 8
|
public synchronized void create_tables()
{
Connection c = null;
try
{
clearSoftState();
c = connectionPool.getConnection();
Statement s = c.createStatement();
s.executeQuery("show tables");
for( String t : CREATE_TABLES )
{
try {
s.execute(t);
} catch( Exception e ) {
// e.printStackTrace();
logger.warning(e.toString());
logger.warning(t);
}
}
s.close();
/**
* Create roles
*/
PreparedStatement stmt = null;
for( UserRole role : UserRole.values() ) {
stmt = c.prepareStatement("INSERT INTO roles (role) VALUES ('" + role.getTag() + "')");
stmt.executeUpdate();
stmt.close();
}
} catch( SQLException e ) {
e.printStackTrace();
} finally {
try{
c.close();
} catch( SQLException e ) {}
}
try {
createAccount("admin", "", UserRole.ADMIN);
logger.info("Created admin account with blank password -- change the password!");
} catch( DuplicateAccountException e ) {
logger.info("Admin account already exists, skipped creation");
} catch( IOException e ) {
e.printStackTrace();
logger.warning(e.toString());
}
for( String cat : DEFAULT_CATEGORIES ) {
addCategory(cat);
}
}
|
c5840d9c-55a1-424f-9196-c7740c91cdca
| 1
|
public void mousePressed(MouseEvent event) {
Transition t = getDrawer().transitionAtPoint(event.getPoint());
if (t != null) {
controller.transitionCollapse(t.getFromState(), t.getToState());
}
}
|
af8e0c17-a647-413b-b6c1-382bfc2772aa
| 3
|
private ArrayList<Card> returnPairSetup()
{
ArrayList<Card> setup = new ArrayList<>();
if (compareCardFigures(0, 1))
{
setup.add(cards.get(0));
setup.add(cards.get(1));
}
else if (compareCardFigures(1, 2))
{
setup.add(cards.get(1));
setup.add(cards.get(2));
}
else if ( compareCardFigures(2, 3))
{
setup.add(cards.get(2));
setup.add(cards.get(3));
}
return setup;
}
|
c6acf1a5-0f74-4362-b60b-fe0cbd5be78b
| 3
|
public boolean isAlive() {
if (this.getWorld() == null)
return false;
if(!this.getWorld().liesWithinBoundaries(this))
return false;
if (this.getCurrentHitPoints() == 0)
return false;
return true;
}
|
75b3ed2f-cf5c-45bd-bc64-92a300c4d5cb
| 4
|
@Override
public List<Object> getAll(int gameID){
try {
db.start();
DBCollection collection = db.getDB().getCollection("moves");
XStream xStream = new XStream();
DBCursor cursor = collection.find();
if (cursor == null)
return null;
List<Object> commands = new ArrayList<Object>();
while(cursor.hasNext()) {
DBObject obj = cursor.next();
String xml = (String)obj.get(Integer.toString(gameID));
if (xml != null)
commands.add((Object) xStream.fromXML(xml));
}
db.stop(true);
return commands;
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
|
29b09764-abb3-4c31-8c3e-1161a67bbe7e
| 7
|
@Override
public List<String> onTabComplete(CommandSender sender, org.bukkit.command.Command cmd, String label, String[] args) {
if(!cmd.getName().equals(cmdName) || args.length > 1) {
return null;
}
List<String> results = new LinkedList<>();
boolean ignoreArg = false;
if(args.length == 0) {
ignoreArg = true;
}
for(Command command : commands.values()) {
if(command.hasPermission(sender) && (ignoreArg || command.getName().startsWith(args[0]))) {
results.add(command.getName());
}
}
return results;
}
|
e6411271-461e-4889-8018-da52716dbe78
| 5
|
private boolean pointCollides(double x, double y){
for (Building b : model.getBuildings()){
Rectangle rect = (Rectangle) b.getShape();
if (x <= rect.getX()+rect.getWidth() && x >= rect.getX()
&& y <= rect.getY()+rect.getHeight() && y >= rect.getY()){
return true;
}
}
return false;
}
|
34dd15dc-176c-4747-862b-200d7679f78f
| 7
|
public static int getOrder(Enemy enemy){
//命令
int order = 0 ;
//boss坦克在数组中的位置
int boss_y = Game.BOSS_TANK_X * Constant.WIDTH_HEIGHT ;
int boss_x = Game.BOSS_TANK_Y * Constant.WIDTH_HEIGHT ;
//敌人位置
int x = enemy.getLocation_x() ;
int y = enemy.getLocation_y() ;
//
String[] mapArray = enemy.getMainFrame().mapArray;
if( enemy.getLocation_y() < boss_y && ifCanWalkInThisDirection(Tank.direction_down, x, y, mapArray)){
//if( ifCanWalkInThisDirection(Tank.direction_down, x, y, mapArray) == true){
order = Tank.direction_down ;
//}else{
//order = 4 ;
//}
//System.out.println("******向下走******");
}else if(enemy.getLocation_x() < boss_x && ifCanWalkInThisDirection(Tank.direction_right, x, y, mapArray) == true){
//System.out.println("******向右走******");
order = Tank.direction_right ;
}else if(enemy.getLocation_x() > boss_x && ifCanWalkInThisDirection(Tank.direction_left, x, y, mapArray) == true){
//System.out.println("******向左走******");
order = Tank.direction_left ;
}else{
//当前方向行走
if( ifCanWalkInThisDirection(enemy.getDirection(), x, y, mapArray) == true){
//System.out.println("******向本方向继续走完******");
order = enemy.getDirection() ;
}else{
order = (int)(Math.random() * 100) % 4 ;
}
}
return order ;
}
|
aee764e8-0089-4545-986f-036592f94348
| 5
|
public void saveParamDiffsData(int cGeneration, Hypothesis h)
{
int hIndex = 0;
int[] diffs = new int[targetValues.length];
for (int i = 0; i < targetValues.length; i++)
{
//Convert each block of five bits to an integer value
String binStr = "";
for (int j = 0; j < 7; j++)
{
binStr += h.bitstring[hIndex] + "";
hIndex++;
}
int cVal = Integer.parseInt(binStr, 2); //2 for binary
//Calculate how much the hypothesis fitness value
//differs from the target value.
int diff = Math.abs(cVal - targetValues[i]);
double perc = (double)100 - (double)diff / (double)128 * (double)100;
//Add a small random diff to fitness for testing purpose
if (rndFitness)
{
double rndDiff = Math.random() * 10 - 5;
perc += rndDiff;
if (perc < 0) perc = 0;
if (perc >= 100) perc = 100;
}
diffs[i] = (int)perc;
}
saveToGnuplot(cGeneration, diffs);
}
|
a9f0b1f9-8e91-4904-b3bf-30bb177f6430
| 0
|
@Test
public void testMyComparer()
{
assertTrue(true);
}
|
419ec8e6-5831-4636-9cc4-e99246d13336
| 5
|
public String leerOpcion() throws IOException, SQLException, ParseException {
String input = bf.readLine();
if(input.equals("1")){
agregarInsumo();
}else if(input.equals("2")){
consumirInsumo();
}else if(input.equals("3")){
buscarInsumo();
}else if(input.equals("4")){
agregarCantidadInsumo();
}else if(input.equals("5")){
System.exit(0);
}
return input;
}
|
421991a6-9ccd-4b63-a553-7c142954198a
| 9
|
private OSXApplicationProxy() {
try {
final File file = new File("/System/Library/Java");
if(file.exists()) {
ClassLoader scl = ClassLoader.getSystemClassLoader();
Class<?> clc = scl.getClass();
if(URLClassLoader.class.isAssignableFrom(clc)) {
Method addUrl = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] {URL.class});
addUrl.setAccessible(true);
addUrl.invoke(scl, new Object[] {file.toURI().toURL()});
}
}
Class<?> appClass = Class.forName("com.apple.eawt.Application");
application = appClass.getMethod("getApplication", new Class[0]).invoke(null, new Object[0]);
applicationListenerClass = Class.forName("com.apple.eawt.ApplicationListener");
} catch (ClassNotFoundException e) {
application = null;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
|
00d6068b-15a1-49a3-932c-28b154a5ec41
| 6
|
public void run() {
log.logDebug( "MockAgent.Worker started");
ISemiSpaceTuple t=null;
String cargo;
while(isRunning) {
t = blackboard.read(template, 1000); // leave up to a second
System.out.println("MockAgent read "+t+" "+isRunning);
if (t == null) {
synchronized(synchObject) {
try {
synchObject.wait(1000);
} catch (Exception e) {}
}
}
if (isRunning && t != null) {
log.logDebug("MockAgent GOT"+ t.getJSON());
if (containsData(t)) {
cargo = (String)t.get(ITupleFields.CARGO);
tracer.trace(0, cargo);
System.out.println(cargo);
}
t = null;
}
}
}
|
5376bc61-58a3-4bb3-a5ce-f3ca142f9a2e
| 6
|
public static String maximumNonDuplicateSubstring(String str)
{
Set<Character> encountered = new HashSet<Character>();
int i = 0,
firstCharacterIndex = 0,
count = 0,
largestCharacterIndex = 0,
largestCount = -1;
while (i <= str.length())
{
if (i == str.length())
{
System.out.println("Yes");
if (count > largestCount)
{
largestCount = count;
largestCharacterIndex = firstCharacterIndex;
}
break;
}
System.out.print(i);
if (encountered.contains(str.charAt(i)))
{
System.out.println();
System.out.println(encountered.contains(str.charAt(i)) + " " + encountered);
if (count > largestCount)
{
largestCount = count;
largestCharacterIndex = firstCharacterIndex;
}
encountered.clear();
encountered.add(str.charAt(i));
if (i + 1 == str.length())
{
}
System.out.println("First chr: " + firstCharacterIndex);
i = firstCharacterIndex;
firstCharacterIndex += 1;
}
else
{
encountered.add(str.charAt(i));
count++;
}
i++;
}
System.out.println(largestCount);
return str.substring(largestCharacterIndex, largestCharacterIndex + largestCount);
}
|
0b78e7bf-d5ae-4f01-b974-600ee0981da2
| 5
|
public boolean mouseInRegion(int x1, int x2, int y1, int y2) {
if (getScale() != 1) {
x2 = (int) ((x2 - x1) * getScale());
x1 *= getScale();
x2 += x1;
y2 = (int) ((y2 - y1) * getScale());
y1 *= getScale();
y2 += y1;
x1 += Main.scaledX;
x2 += Main.scaledX;
y1 += Main.scaledY;
y2 += Main.scaledY;
}
if (mouseX >= x1 && mouseX <= x2 && mouseY >= y1 && mouseY <= y2) {
return true;
}
return false;
}
|
8eba8484-d669-4f20-a6b4-52938ba9522c
| 8
|
@EventHandler
public void onEntityDeath(EntityDeathEvent e) {
Player player = e.getEntity().getKiller();
if (!(e.getEntity() instanceof Player)) {
e.getDrops().clear();
e.getEntity().getEquipment().setBootsDropChance(0);
e.getEntity().getEquipment().setHelmetDropChance(0);
e.getEntity().getEquipment().setChestplateDropChance(0);
e.getEntity().getEquipment().setLeggingsDropChance(0);
e.setDroppedExp(0);
}
Random intel = new Random();
Random dex = new Random();
Random str = new Random();
Random vit = new Random();
Random chance = new Random();
Random type = new Random();
if (e.getEntity().getCustomName() != null) {
if (e.getEntity().getCustomName().contains("Novice")) {
int probOne = chance.nextInt(30);
player.sendMessage("You got a " + probOne);
if (probOne == 0) {
player.sendMessage("You should be getting a drop");
if (e.getEntity().getCustomName().contains("Warrior")) {
int intelligence = intel.nextInt(6) + 1;
int dexterity = dex.nextInt(9) + 1;
int strength = str.nextInt(20) + 11;
int vitality = vit.nextInt(10) + 1;
int kind = type.nextInt(4);
if (kind == 0) {
ItemStack drop = createItem("Weak Warrior Helmet",
Material.LEATHER_HELMET, ChatColor.AQUA
+ "Int: " + intelligence,
ChatColor.GREEN + "Dex: " + dexterity,
ChatColor.RED + "Str: " + strength,
ChatColor.LIGHT_PURPLE + "Vit: " + vitality);
e.getEntity()
.getWorld()
.dropItemNaturally(
e.getEntity().getLocation(), drop);
} else if (kind == 1) {
ItemStack drop1 = createItem(
"Weak Warrior Chestplate",
Material.LEATHER_CHESTPLATE, ChatColor.AQUA
+ "Int: " + intelligence,
ChatColor.GREEN + "Dex: " + dexterity,
ChatColor.RED + "Str: " + strength,
ChatColor.LIGHT_PURPLE + "Vit: " + vitality);
e.getEntity()
.getWorld()
.dropItemNaturally(
e.getEntity().getLocation(), drop1);
} else if (kind == 2) {
ItemStack drop2 = createItem(
"Weak Warrior Leggings",
Material.LEATHER_LEGGINGS, ChatColor.AQUA
+ "Int: " + intelligence,
ChatColor.GREEN + "Dex: " + dexterity,
ChatColor.RED + "Str: " + strength,
ChatColor.LIGHT_PURPLE + "Vit: " + vitality);
e.getEntity()
.getWorld()
.dropItemNaturally(
e.getEntity().getLocation(), drop2);
} else {
ItemStack drop3 = createItem("Weak Warrior Boots",
Material.LEATHER_BOOTS, ChatColor.AQUA
+ "Int: " + intelligence,
ChatColor.GREEN + "Dex: " + dexterity,
ChatColor.RED + "Str: " + strength,
ChatColor.LIGHT_PURPLE + "Vit: " + vitality);
e.getEntity()
.getWorld()
.dropItemNaturally(
e.getEntity().getLocation(), drop3);
}
// int dex str vit
}
}
}
}
}
|
4261ecf8-db52-4876-b785-e8ddedf376f4
| 2
|
protected void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
HttpSession session = req.getSession(true);
int uid = (int)((User)session.getAttribute("currentSessionUser")).getId();
//HashMap<Product,Integer> cart = (HashMap<Product,Integer>)session.getAttribute("cart");
try {
//cart =
Integer quantity = Integer.parseInt(req.getParameter("quantity"));
if (quantity <= 0) {
// Errors if quantity is less than 0
throw new NumberFormatException();
}
int price = Integer.parseInt(req.getParameter("price"));
long id = Long.parseLong(req.getParameter("id"));
// Don't care about anything else, just need name and price;
Product p = new Product(req.getParameter("name"), "0", 0, price);
p.setId(id);
OrderDAO.insert(uid, (int)id, quantity, price);
/*if (cart == null) { // If there's nothing in the cart, make a new cart
cart = new HashMap<Product,Integer>();
}
if (cart.get(p) != null) {
// if a product is already in the cart, just add the quantity of the old and the new
cart.put(p, cart.get(p) + quantity);
} else {
// else just put in a new Product, Quantity mapping
cart.put(p, quantity);
}
// Put the cart in the session
session.setAttribute("cart", cart);*/
res.sendRedirect("products");
} catch (NumberFormatException | SQLException e) {
req.getRequestDispatcher("WEB-INF/productOrderError.jsp").forward(req, res);
}
}
|
fe7ca35f-3f4b-4db7-838c-f7eece0475c3
| 0
|
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
|
abef86bf-25af-42e9-8947-39121d5356f2
| 6
|
private boolean isTwoPair(ArrayList<Card> player) {
ArrayList<Integer> sortedHand=new ArrayList<Integer>();
sortedHand=sortHand(player);
int pair1Counter=0;
int pair2Counter=0;
int pair1Int=100;
int pair2Int=100;
for(int i=0;i<player.size()-1;i++) {
if(sortedHand.get(i)==sortedHand.get(i+1)){
if(sortedHand.get(i)==pair1Int || sortedHand.get(i)==pair2Int){
return false;
}
else if(pair1Counter==1){
pair2Counter++;
pair2Int=sortedHand.get(i);
}
else{
pair1Counter++;
pair1Int=sortedHand.get(i);
}
}
}
return(pair1Counter==1 && pair2Counter>=1);
}
|
a27196b5-9411-4077-ac08-540d4ed13a19
| 6
|
public void givePin() {
if(dead || flyingType || crashed) {
return;
}
if (pinned)
{
pinned = false;
setHappiness(Happiness.AVERAGE);
return;
}
if(!pinned) {
if(sleeping) wakeup();
staycount = 0;
staying = false;
setToFood(false);
toSukkiri = false;
setToShit(false);
shitting = false;
birth = false;
angry = false;
furifuri = false;
setEating(false);
peropero = false;
sukkiri = false;
scare = false;
setEatingShit(false);
nobinobi = false;
setHappiness(Happiness.VERY_SAD);
pinned = true;
return;
}
return;
}
|
1dd2f966-3d6f-4d7b-856a-586a03563e75
| 4
|
public String getCurTime(){
Date d = new Date ();
String date_str="";
if(d.getHours()<10)
date_str="0";
date_str+=d.getHours()+":";
if(d.getMinutes()<10)
date_str+="0";
date_str+=d.getMinutes()+":";
if(d.getSeconds()<10)
date_str+="0";
date_str+=d.getSeconds()+":";
int n = (int) d.getTime() % 1000;
date_str+=(n<0 ? n+1000 : n);
return date_str;
}
|
b23f46ae-15fa-40be-8080-e48937c78399
| 0
|
private void setFrameVer(){
modificar.setVisible(true);
modificar.setTitle("Ver Producto");
modificar.setSize(500, 300);
}
|
de460608-b7df-45cb-8de0-b3fd291ee09e
| 7
|
@Override
public void runClient(GameEntity entity, float delta) {
if(physics != null) {
Vector3 position = physics.getPosition();
decal.setPosition(position.x + offset.x, position.y + offset.y, position.z + offset.z);
if(up != null && rot != null) {
decal.setRotation(rot, up);
} else {
decal.setRotationZ(physics.getAngle()*MathUtils.radDeg);
}
ShaderManager.getInstance().getDecalBatch().add(decal);
if(follow) {
float diff = 180*MathUtils.degRad - physics.getAngle();
if(diff != 0 && Math.abs(xOffset) <= 10f) {
xOffset += diff*0.1f;
} else if(diff == 0) {
xOffset *= 0.9;
}
camera.position.set(position.x-xOffset, position.y - dist, 5f);
camera.lookAt(position.x, position.y + dist, 0);
camera.update();
light.position.set(position.x, position.y, position.z);
}
}
}
|
ad172c80-3e14-41d6-8557-6e223eb4b41e
| 3
|
protected void writeAttributes(GrowableConstantPool constantPool,
DataOutputStream output) throws IOException {
int count = getKnownAttributeCount();
if (unknownAttributes != null)
count += unknownAttributes.size();
output.writeShort(count);
writeKnownAttributes(constantPool, output);
if (unknownAttributes != null) {
Iterator i = unknownAttributes.entrySet().iterator();
while (i.hasNext()) {
Map.Entry e = (Map.Entry) i.next();
String name = (String) e.getKey();
byte[] data = (byte[]) e.getValue();
output.writeShort(constantPool.putUTF8(name));
output.writeInt(data.length);
output.write(data);
}
}
}
|
f9f78e27-76e0-47e3-83bf-3ee505bca173
| 6
|
public static void addConj (String conj) {
switch (conjState) {
case -1:
days[dayNum].conj[days[dayNum].conjNum].conj[0] = conj;
System.out.print("Yo Form: ");
conjState++;
break;
case 0:
days[dayNum].conj[days[dayNum].conjNum].conj[1] = conj;
System.out.print("Tú Form: ");
conjState++;
break;
case 1:
days[dayNum].conj[days[dayNum].conjNum].conj[2] = conj;
System.out.print("Él Form: ");
conjState++;
break;
case 2:
days[dayNum].conj[days[dayNum].conjNum].conj[3] = conj;
System.out.print("Nos Form: ");
conjState++;
break;
case 3:
days[dayNum].conj[days[dayNum].conjNum].conj[4] = conj;
System.out.print("Ellos Form: ");
conjState++;
break;
case 4:
days[dayNum].conj[days[dayNum].conjNum].conj[5] = conj;
System.out.print("Infinitive: ");
conjState = -1;
days[dayNum].conjNum++;
break;
default:
System.out.println("Error Occured: InputManager.conjState is" +
" out of bounds.");
System.out.print("Infinitive Form: ");
conjState = -1;
break;
}
output();
}
|
47800516-f97c-45ff-ae63-652e0c5258a4
| 8
|
public void debuffRecovery(){
recovery++;
if (cc == EARTH && recovery >= 80){
entombed = false;
jolly = true;
recovery = 0;
}
else if (cc == WATER && recovery >= 60){
slowed = false;
jolly = true;
recovery = 0;
}
else if (cc == WIND && recovery >= 40){
knockedback = false;
jolly = true;
recovery = 0;
}
else if(cc == FIRE && recovery >= 20){
stunned = false;
jolly = true;
recovery = 0;
}
}
|
f1360b11-9e28-4f65-9e35-7c870be54d5c
| 0
|
public int getWidth() {
return width;
}
|
2350bf9a-1722-48be-a3d9-3584f244bd1d
| 6
|
public BigDecimal weightedMean_as_BigDecimal() {
if (!weightsSupplied) {
System.out.println("weightedMean_as_BigDecimal: no weights supplied - unweighted mean returned");
return this.mean_as_BigDecimal();
} else {
boolean holdW = Stat.weightingOptionS;
if (weightingReset) {
if (weightingOptionI) {
Stat.weightingOptionS = true;
} else {
Stat.weightingOptionS = false;
}
}
BigDecimal mean = BigDecimal.ZERO;
switch (type) {
case 1:
case 12:
BigDecimal[] bd = this.getArray_as_BigDecimal();
BigDecimal[] wwb = amWeights.getArray_as_BigDecimal();
mean = Stat.mean(bd, wwb);
bd = null;
wwb = null;
break;
case 14:
throw new IllegalArgumentException("Complex cannot be converted to BigDecimal");
default:
throw new IllegalArgumentException("This type number, " + type + ", should not be possible here!!!!");
}
Stat.weightingOptionS = holdW;
return mean;
}
}
|
6f9bad3b-3de7-4a87-9953-5e945a717a51
| 9
|
@Test
public void testCastingToVoid() {
assertNull(ValueType.VOID.cast(null));
try {
ValueType.VOID.cast(false);
fail();
} catch(ClassCastException e) {
// empty block
}
try {
ValueType.VOID.cast((byte) 1);
fail();
} catch(ClassCastException e) {
// empty block
}
try {
ValueType.VOID.cast('a');
fail();
} catch(ClassCastException e) {
// empty block
}
try {
ValueType.VOID.cast(1.0);
fail();
} catch(ClassCastException e) {
// empty block
}
try {
ValueType.VOID.cast(1.0f);
fail();
} catch(ClassCastException e) {
// empty block
}
try {
ValueType.VOID.cast(1);
fail();
} catch(ClassCastException e) {
// empty block
}
try {
ValueType.VOID.cast(1L);
fail();
} catch(ClassCastException e) {
// empty block
}
try {
ValueType.VOID.cast((short) 1);
fail();
} catch(ClassCastException e) {
// empty block
}
try {
ValueType.VOID.cast(new Object());
fail();
} catch(ClassCastException e) {
// empty block
}
}
|
5fd30f5b-8cca-4559-a287-775e635d3dca
| 0
|
public void stopLiveWindowMode() {}
|
119465f3-6a1c-40b6-8d57-7990964f0fe0
| 5
|
@Override
public void mouseClicked(MouseEvent e) {
// Double-click event.
if (e.getClickCount() >= 2) {
// Prevent the user from taking another screenshot while cropping.
if (cropWindow != null && !cropWindow.canSave())
return;
// Get the configuration data.
Configuration config = Configuration.loadConfiguration();
// Take a screenshot of the entire screen.
Screenshot.takeScreenShot();
// Did they enable the cropping feature?
if (config.getProperty("enableAutoCropping").equals("true")) {
String cropMessage = "Would you like to crop this image?";
int doCrop = JOptionPane.showConfirmDialog(null, cropMessage, "SwiftSnap", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
if (doCrop == JOptionPane.YES_OPTION) {
// Open a window for the user to select the dimensions.
cropWindow = new CropWindow();
return;
}
}
// Save the screenshot.
Screenshot.save();
}
}
|
0ec2cc5a-7aa5-4ac1-b8e5-a9c48365d7cb
| 3
|
public boolean equals(Object obj) {
if (obj == null)
return false;
if (obj instanceof Name)
return name.equals(((Name) obj).getName());
return obj instanceof String && name.equals(obj);
}
|
83793c05-2ddc-4264-98a1-1804e9c42699
| 1
|
public static void main(String args[]) {
Enumeration days;
Vector dayNames = new Vector();
dayNames.add("Sunday");
dayNames.add("Monday");
dayNames.add("Tuesday");
dayNames.add("Wednesday");
dayNames.add("Thursday");
dayNames.add("Friday");
dayNames.add("Saturday");
days = dayNames.elements();
while (days.hasMoreElements()){
System.out.println(days.nextElement());
}
}
|
0c425359-7566-498d-862a-f773794fbaad
| 4
|
public static BigInteger calculateRepresentationNumber(Cell[] currentBoard){
BigInteger out = BigInteger.ZERO;
Cell actualCell;
int ibase = Piece.values().length + 2;
BigInteger base = BigInteger.valueOf(ibase);
for(int i=0; i < currentBoard.length;i++){
actualCell = currentBoard[i];
if (actualCell == Cell.DEFAULT_EMPTY_CELL){
//Do nothing. Empty cells value is zero.
}else{
if(actualCell == Cell.DEFAULT_TAKEN_CELL){
//Calculate the new hashcode.
out = out.add(base.pow(i));
}
else{
if (actualCell instanceof PieceCell){
PieceCell pieceCell = (PieceCell) actualCell;
Piece piece = pieceCell.getPiece();
//Calculate the new hashcode.
out = out.add(BigInteger.valueOf(piece.ordinal() +2).multiply(base.pow(i)));
}
}
}
}
return out;
}
|
a49f10ec-4998-48e3-a7a3-21863004f594
| 4
|
public MethodVisitor visitMethod(final int access, final String name,
final String desc, final String signature, final String[] exceptions) {
checkState();
checkAccess(access, Opcodes.ACC_PUBLIC + Opcodes.ACC_PRIVATE
+ Opcodes.ACC_PROTECTED + Opcodes.ACC_STATIC
+ Opcodes.ACC_FINAL + Opcodes.ACC_SYNCHRONIZED
+ Opcodes.ACC_BRIDGE + Opcodes.ACC_VARARGS + Opcodes.ACC_NATIVE
+ Opcodes.ACC_ABSTRACT + Opcodes.ACC_STRICT
+ Opcodes.ACC_SYNTHETIC + Opcodes.ACC_DEPRECATED + 0x40000); // ClassWriter.ACC_SYNTHETIC_ATTRIBUTE
CheckMethodAdapter.checkMethodIdentifier(version, name, "method name");
CheckMethodAdapter.checkMethodDesc(desc);
if (signature != null) {
CheckMethodAdapter.checkMethodSignature(signature);
}
if (exceptions != null) {
for (int i = 0; i < exceptions.length; ++i) {
CheckMethodAdapter.checkInternalName(exceptions[i],
"exception name at index " + i);
}
}
CheckMethodAdapter cma;
if (checkDataFlow) {
cma = new CheckMethodAdapter(access, name, desc, cv.visitMethod(
access, name, desc, signature, exceptions), labels);
} else {
cma = new CheckMethodAdapter(cv.visitMethod(access, name, desc,
signature, exceptions), labels);
}
cma.version = version;
return cma;
}
|
4f2a828c-579f-4347-b646-ea49a043bc8b
| 6
|
private void method46(int i, Stream stream) {
while(stream.bitPosition + 21 < i * 8) {
int k = stream.readBits(14);
if(k == 16383)
break;
if(npcArray[k] == null)
npcArray[k] = new NPC();
NPC npc = npcArray[k];
npcIndices[npcCount++] = k;
npc.anInt1537 = loopCycle;
int l = stream.readBits(5);
if(l > 15)
l -= 32;
int i1 = stream.readBits(5);
if(i1 > 15)
i1 -= 32;
int j1 = stream.readBits(1);
npc.desc = EntityDef.forID(stream.readBits(18));
int k1 = stream.readBits(1);
if(k1 == 1)
anIntArray894[anInt893++] = k;
npc.anInt1540 = npc.desc.aByte68;
npc.anInt1504 = npc.desc.anInt79;
npc.anInt1554 = npc.desc.walkAnim;
npc.anInt1555 = npc.desc.anInt58;
npc.anInt1556 = npc.desc.anInt83;
npc.anInt1557 = npc.desc.anInt55;
npc.anInt1511 = npc.desc.standAnim;
npc.setPos(myPlayer.smallX[0] + i1, myPlayer.smallY[0] + l, j1 == 1);
}
stream.finishBitAccess();
}
|
50ad9fce-e539-4daa-ac30-60edd7a42b49
| 1
|
public void setPosition(Position currentpos) {
this.CurrentPosition = currentpos;
if (!this.trail.contains(currentpos)) {
trail.add(currentpos);
PlayerTrail.add(currentpos);
}
}
|
a17ac14f-815a-40b3-8b33-5577d5424d09
| 2
|
public GameResult getGameStatus() {
if (getMafiaCount() == 0) return GameResult.VillagerWins;
else if (getVillagerCount() <= getMafiaCount()) return GameResult.MafiaWins;
return GameResult.GameStable;
}
|
91905753-9de1-4990-bf63-7687fb865dfe
| 9
|
@Override
public int onTrailerFound(COSDictionary trailer, int ordering) {
if (ordering == 0) {
rootID = trailer.getReference(COSName.ROOT);
infoID = trailer.getReference(COSName.INFO);
documentIsEncrypted = trailer.containsKey(COSName.ENCRYPT);
COSArray Ids = trailer.getArray(COSName.ID, null);
if (((Ids == null) || (Ids.size()!=2)) && documentIsEncrypted)
throw new EParseError("Missing (required) file identifier for encrypted document");
if (Ids != null) {
if (Ids.size() != 2) {
if (documentIsEncrypted)
throw new EParseError("Invalid document ID array size (should be 2)");
context.softAssertSyntaxComliance(false, "Invalid document ID array size (should be 2)");
Ids = null;
} else {
if ((Ids.get(0) instanceof COSString) && (Ids.get(1) instanceof COSString)) {
documentId[0] = ((COSString)Ids.get(0)).getBinaryValue();
documentId[1] = ((COSString)Ids.get(1)).getBinaryValue();
} else context.softAssertSyntaxComliance(false, "Invalid document ID");
}
} // Ids != null
}
return ParsingEvent.CONTINUE;
}
|
9c5385c9-edae-403b-ae30-2c25cfc34bbf
| 8
|
public void actionPerformed(ActionEvent event)
{
String actionCommand = event.getActionCommand();
if (actionCommand.equals("BROWSE")) {
int returnVal = browse.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
fileLoc.setText(browse.getSelectedFile().getPath());
searchButton.setEnabled(true);
}
}
if (actionCommand.equals("SEARCH")) {
Thread newThread = new Thread(new Runnable() {
public void run() {
manager.folderLocation(fileLoc.getText());
if (fileLoc.getText().equals("")) {
errorHasOccured("Please enter a directory.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
int checkError = manager.searchFolder();
if (checkError == 0) {
errorHasOccured("The location - " + fileLoc.getText() + " has caused an error, please try again.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (folderData!=null) {
content.remove(folderData);
folderData = null;
}
folderData = generateTable();
content.add(folderData);
totalLabel.setText(SortOperations.sizeParser(manager.totalSize()) + " in total.");
totalLabel.setVisible(true);
}
});
searchProcess = new JProgressBar(0, 10);
searchProcess.setStringPainted(true);
searchProcess.setValue(0);
searchProcess.setLocation(30, 480);
content.add(searchProcess);
searchProcess.setVisible(true);
newThread.run();
}
if (actionCommand.equals("EXIT")) {
System.exit(0);
}
if (actionCommand.equals("ABOUT")) {
String aboutText = "Download File Manager Alpha v0.1\nAuthor: Anthony Baker\nContact: abake40@gmail.com";
errorHasOccured(aboutText, "About", JOptionPane.INFORMATION_MESSAGE);
}
}
|
84a4d9df-976d-4d1c-b838-8d96d053af80
| 7
|
protected String startSetToString() {
StringBuffer FString = new StringBuffer();
boolean didPrint;
if (m_starting == null) {
return getStartSet();
}
for (int i = 0; i < m_starting.length; i++) {
didPrint = false;
if ((m_hasClass == false) ||
(m_hasClass == true && i != m_classIndex)) {
FString.append((m_starting[i] + 1));
didPrint = true;
}
if (i == (m_starting.length - 1)) {
FString.append("");
}
else {
if (didPrint) {
FString.append(",");
}
}
}
return FString.toString();
}
|
a70c631e-67cd-48f7-83a8-126b2902590c
| 9
|
public boolean skipPast(String to) throws JSONException {
boolean b;
char c;
int i;
int j;
int offset = 0;
int length = to.length();
char[] circle = new char[length];
/*
* First fill the circle buffer with as many characters as are in the to
* string. If we reach an early end, bail.
*/
for (i = 0; i < length; i += 1) {
c = next();
if (c == 0) {
return false;
}
circle[i] = c;
}
/* We will loop, possibly for all of the remaining characters. */
for (;;) {
j = offset;
b = true;
/* Compare the circle buffer with the to string. */
for (i = 0; i < length; i += 1) {
if (circle[j] != to.charAt(i)) {
b = false;
break;
}
j += 1;
if (j >= length) {
j -= length;
}
}
/* If we exit the loop with b intact, then victory is ours. */
if (b) {
return true;
}
/* Get the next character. If there isn't one, then defeat is ours. */
c = next();
if (c == 0) {
return false;
}
/*
* Shove the character in the circle buffer and advance the circle
* offset. The offset is mod n.
*/
circle[offset] = c;
offset += 1;
if (offset >= length) {
offset -= length;
}
}
}
|
9abdbf06-8904-4bee-b730-58c9e4de4c03
| 9
|
public void actionPerformed(ActionEvent event)
{
if(event.getActionCommand().equals("Add"))
{
String name = userField.getText().trim();
if (name.equals("") || name.equals("Enter User Name"))
JOptionPane.showMessageDialog(null, "Invalid User Name");
else
{
String key = randomKeyGenerator();
while(isDuplicateKey(key))
key = randomKeyGenerator();
listModel.addElement(key + " " + accessOption[accessBox.getSelectedIndex()].substring(0,1)
+ " " + name);
saveSecurityFile();
userField.setText("");
}
}
else if(event.getActionCommand().equals("Delete") && userList.getSelectedIndex() > -1)
{
String user = userList.getSelectedValue();
if(user.substring(7,8).equals("A") && administrators == 1)
JOptionPane.showMessageDialog(null,"ERROR: Must Maintain At Least One Administrator Account");
else
{
listModel.removeElementAt(userList.getSelectedIndex());
if(user.substring(7,8).equals("A"))
administrators--;
saveSecurityFile();
}
}
}
|
768c23d1-5367-4bc1-8e64-2de13b4ff44a
| 8
|
private Peer getMostUpdatedPeer() {
int newestVersion = handle.getVersion();
Peer mostUpdatedPeer = null;
for (Map.Entry<Integer, Peer> entry : peersTable.entrySet()) {
Integer id = entry.getKey();
Peer peer = entry.getValue();
log.addLogEntry("Checking connectivity with Peer " + id);
int peerVersion = peer.getVersion();
boolean isPeerReachable = false;
if (peerVersion == -1) {// not reachable
log.addLogEntry("Peer " + id + "could not be reached");
for (int i = 1; i <= 5; i++) {
log.addLogEntry(i + " try to connect");
peerVersion = peer.getVersion();
if (peerVersion != -1) {
isPeerReachable = true;
log.addLogEntry("Peer is back alive");
break;
}
}
if (!isPeerReachable) {
log.addLogEntry("Check if this bot is Online");
if (isInternetReachable()) {
peersTable.remove(id);
log.addLogEntry("bot is online, remove unresponsive peer");
continue;
} else {
mostUpdatedPeer = null;
break;
}
}
} else {
log.addLogEntry("Peer " + id + " connected with version "
+ peerVersion);
if (newestVersion < peerVersion
&& handle.getVersion() < peerVersion) {
mostUpdatedPeer = peer;
newestVersion = peerVersion;
}
}
}
return mostUpdatedPeer;
}
|
ac3abe79-f4eb-4e98-b711-6992628ceae8
| 4
|
double getDefence(Match match, Team team) {
int countMatches = 0;
int[] goals = new int[deep];
Match currentMatch = getPrevMatch(team, match);
for (int i = 0; i < deep && currentMatch != null; i++, currentMatch = getPrevMatch(
team, currentMatch), countMatches++) {
goals[i] = currentMatch.score.total
- getScoreForTeam(currentMatch, team);
countMatches++;
}
if (countMatches < deep)
return -1;
double res = 0;
for (int i = 0; i < goals.length; i++) {
res += goals[i];
}
return res / (deep);
}
|
dc2a0d4b-3c0b-45de-ad61-c67a5a4b5087
| 7
|
public static int checkRequirements(MapleCharacter player, int itemId) {
int cat = getItemType(itemId);
if (cat > 1000) {
return 1;
} else if (MapleItemInformationProvider.getInstance().getSlotMax(itemId) < 1) {
return 2;
} else {
int taocount = player.getMaxStatItems() * 200;
if (cat > 100) {
taocount *= 2;
}
if (!player.hasAllStatMax()){
return 3;
} else if (!player.haveSight(taocount)) {
return 4;
} else if (!checkEtcItems(player, cat)) {
return 5;
} else if (player.getBossPoints() < (taocount * 1000)) {
return 6;
} else {
return 7;
}
}
}
|
809d0208-3a71-4294-8eeb-2edbca3212af
| 4
|
public void run(){
do{
int randy = (int)(Math.random()*100);
if(((randy%2)==0) & (actual>0) ){ // Consumidor
lleno.esperar();
mutex.esperar();
// zona critica
cont++;
actual--;
System.out.println(nombreHilo+"elimina buffer["+actual+"]="+buffer[actual]);
buffer[actual] = -1;
// fin de la zona critica
mutex.señal();
vacio.señal();
try{
Thread.currentThread().sleep((int) (Math.random()*100));
}
catch (InterruptedException e) {
}
}
else{//productor
vacio.esperar();
mutex.esperar();
// Zona critica
cont++;
buffer[actual]=randy;
System.out.println(nombreHilo+"añade buffer["+actual+"]="+buffer[actual]);
actual++;
// fin zona critica
mutex.señal();
lleno.señal();
try {
Thread.currentThread().sleep((int) (Math.random() * 100));
}
catch (InterruptedException e) {
}
}
}
while(cont<10);
}
|
522aef42-8e25-4a7e-aabb-b2d320d37f9f
| 9
|
public HashMap<String, String> getParsedRequest(BufferedReader inFromUser) throws SocketTimeoutException,
IOException {
resultMap = new HashMap<String, String>();
parametersMap = new HashMap<String, String>();
String line = inFromUser.readLine();
// if end of the stream has been reached notify process thread
if (line == null) {
httRequest.isTerminatedByClient = true;
return null;
}
requestsHeaderPrinter.append(line + "\n");
// Get first line
String[] splitedLine = line.split(" ");
if (splitedLine.length != 3) {
return null;
}
resultMap.put(METHOD, splitedLine[0]);
if (splitedLine[1].contains("?")) { // Check for URL params
int q = splitedLine[1].indexOf("?");
String dir = splitedLine[1].substring(0, q);
String params = splitedLine[1].substring(q + 1, splitedLine[1].length());
resultMap.put(LOCATION, dir);
addToPramsMap(params);
} else {
resultMap.put(LOCATION, splitedLine[1]);
}
resultMap.put(PROTOCOL, splitedLine[2]);
// Get all Headers
while ((line = inFromUser.readLine()) != null && !line.isEmpty()) {
splitedLine = line.split(": ");
if (splitedLine.length != 2) {
return null;
}
requestsHeaderPrinter.append(line + "\n");
resultMap.put(splitedLine[0].toLowerCase(), splitedLine[1].toLowerCase());
}
// If POST request get params from request body
if (resultMap.get(METHOD).equals(HttpRequestHandler.HTTP_METHOD_POST)
&& resultMap.containsKey(HttpHeaders.HEADER_CONTENT_LENGTH.toLowerCase())) {
StringBuilder bodyString = new StringBuilder();
int len = Integer.parseInt(resultMap.get(HttpHeaders.HEADER_CONTENT_LENGTH.toLowerCase()));
for (int i = 0; i < len; i++) {
bodyString.append((char) inFromUser.read());
}
addToPramsMap(bodyString.toString());
}
return resultMap;
}
|
9f342b3a-96c9-4b3c-9659-6664a379cd8a
| 4
|
final void method500ms() {
long timeMillis = System.currentTimeMillis();
while (true) {
if (System.currentTimeMillis() > timeMillis + 500)
return;
for (int i = 0; i < 10_000; i++) {
// busy wait
if (i == 10_000)
break;
}
}
}
|
3a806c00-9ea6-4ad3-9429-65c7d86bdf00
| 5
|
public void run(){
while(!finished && !failed){ // бесконечный цикл
chooseNextNode(); // обхода вершин
visitNextNode(); // и оставление феромонов в них
writePheromon(); // запоминает, куда должен оставить феромоны
if(finished){
alive = false;
while(true){
try{
sleep(1);
}
catch (InterruptedException e){}
}
}
}
}
|
6936c514-1efb-41de-8005-d31d648230ea
| 3
|
private Integer addResults(MyRecursiveTask task1, MyRecursiveTask task2) {
int value;
try {
value = task1.get().intValue() + task2.get().intValue();
} catch (InterruptedException e) {
e.printStackTrace();
value = 0;
} catch (ExecutionException e) {
e.printStackTrace();
value = 0;
}
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
return value;
}
|
194e73f8-9ba1-4154-b8d7-91cd9e9f71c7
| 6
|
public ListNode reverseKGroup(ListNode head, int k) {
ListNode header = new ListNode(0);
header.next = head;
ListNode[] nodes = new ListNode[k];
int count = 0;
ListNode pre = header;
ListNode p = head;
while (p!=null){
while(p!=null && count<k){
nodes[count] = p;
p = p.next;
count++;
}
if (p!=null || count==k){
ListNode temp = nodes[k-1].next;
for (int i = k-1; i >= 0; i--) {
pre.next = nodes[i];
pre = pre.next;
}
pre.next = temp;
}
else{
pre.next = nodes[0];
}
count = 0;
}
return header.next;
}
|
984a6745-e90d-4a81-8e2d-b662d41e3a5d
| 1
|
@Override
public void removeClientConnectListener(ConnectOnServerListener listener) {
if (clientConnectListenerList != null) {
clientConnectListenerList.remove(ConnectOnServerListener.class, listener);
}
}
|
7c83f651-d0d4-4d64-a486-7ea999a552c1
| 4
|
private static Body fullyConnectBody( int boxWidth, int boxHeight, Body body ) {
for( int heightIdx = 0; heightIdx < boxHeight; heightIdx++ )
for( int widthIdx = 0; widthIdx < boxWidth; widthIdx++ )
{
if( widthIdx < boxWidth -1 )
body.connectShape( body.geometry[heightIdx*boxWidth+widthIdx],
body.geometry[heightIdx*boxWidth+widthIdx+1] );
if( heightIdx < boxHeight-1 )
body.connectShape( body.geometry[heightIdx*boxWidth+widthIdx],
body.geometry[(heightIdx+1)*boxWidth+widthIdx] );
}
return body;
}
|
5d125513-ec35-45e1-a968-94249baf0a6c
| 3
|
protected void paintComponent (Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
Rectangle rect;
for (int i = 0; i < circles.size(); i++) {
rect = circles.elementAt(i);
g2d.setStroke(new BasicStroke(3.0f));
g2d.setColor(Color.black);
g2d.drawString(nodeList.get(i).getType() + ": " + nodeList.get(i).getTitle(),
rect.x + 10, rect.y + 40);
g2d.setColor(Color.blue);
if (nodeList.get(i).getType().equals("Claim")) {
g2d.drawRoundRect(rect.x, rect.y, rect.width, rect.height, 20, 20);
} else if (nodeList.get(i).getType().equals("Response to Bipolar")){
g2d.drawOval(rect.x, rect.y, rect.width, rect.height);
}
}
}
|
919a5dc7-0fdc-48fd-9376-340758692ea4
| 4
|
public wordsDocument(String phrase) {
String text = onlyText(phrase);
String[] temp = text.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\)", "").replaceAll("\\(", "").split(" ");
for (String current : temp) {
current = current.replaceAll("[\n,.?!:\";'']", "");
if (current.contains("'") && !(current.substring(0, 1).equals("'"))) {
current = current.replace("'", "");
}
totalWords.add(current);
}
while (totalWords.contains("")) {
totalWords.remove("");
}
}
|
7ec97f8b-f20d-488d-933b-549976f021f2
| 6
|
public LoginWindow() {
super(500,190);
getContentPane().setLayout(null);
usernameLabel = new JLabel();
usernameField = new JTextField(25);
passwordLabel = new JLabel();
passwordField = new JPasswordField(25);
loginButton = new JButton(NavalBattle.getLocalizationManager().getString("login_login"));
JButton registerButton = new JButton(NavalBattle.getLocalizationManager().getString("login_register"));
JButton offlineButton = new JButton(NavalBattle.getLocalizationManager().getString("login_offline"));
JLabel lblVersion = new JLabel(Constants.NAVALBATTLE_VERSION_TITLE);
usernameLabel.setText(NavalBattle.getLocalizationManager().getString("login_username"));
passwordLabel.setText(NavalBattle.getLocalizationManager().getString("login_password"));
passwordLabel.setToolTipText(NavalBattle.getLocalizationManager().getString("login_roketgamer_tooltip"));
passwordField.setToolTipText(NavalBattle.getLocalizationManager().getString("login_roketgamer_tooltip"));
usernameLabel.setBounds(295,8,78,30);
usernameField.setBounds(365,8,113,30);
passwordLabel.setBounds(295,39,78,30);
passwordField.setBounds(365,39,113,30);
loginButton.setBounds(400,81,78,30);
registerButton.setBounds(400, 113, 78, 30);
offlineButton.setBounds(315, 81, 78, 30);
lblVersion.setBounds(7, 139, 193, 14);
getContentPane().add(usernameLabel);
getContentPane().add(usernameField);
getContentPane().add(passwordLabel);
getContentPane().add(passwordField);
getContentPane().add(loginButton);
getContentPane().add(lblVersion);
getContentPane().add(registerButton);
getContentPane().add(offlineButton);
loginButton.setFocusable(false);
registerButton.setFocusable(false);
offlineButton.setFocusable(false);
passwordField.addKeyListener(Constants.keys);
usernameField.addKeyListener(Constants.keys);
usernameField.setText(NavalBattleIO.getAttribute("lastGoodUserName"));
announcementButton = new JButton(NavalBattle.getLocalizationManager().getString("login_announcement"));
announcementButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
announcementButton.setFocusable(false);
announcementButton.setBounds(34, 68, 117, 30);
getContentPane().add(announcementButton);
updateButton = new JButton(NavalBattle.getLocalizationManager().getString("login_update"));
updateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
updateButton.setFocusable(false);
updateButton.setBounds(34, 27, 117, 30);
getContentPane().add(updateButton);
lblCheckingForUpdate = new JLabel(NavalBattle.getLocalizationManager().getString("login_checking"));
lblCheckingForUpdate.setBounds(34, 55, 153, 14);
getContentPane().add(lblCheckingForUpdate);
passwordField.addFocusListener(new Focus(this));
usernameField.addFocusListener(new Focus(this));
updateButton.setVisible(false);
announcementButton.setVisible(false);
Thread t = new Thread(new Runnable() {
public void run() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
lblCheckingForUpdate.setVisible(true);
}
});
try {
Thread.sleep(3500);
} catch(Exception e) { }
try {
while(!NavalBattle.getBroadcastService().hasChecked()) { }
} catch(Exception e) { }
SwingUtilities.invokeLater(new Runnable() {
public void run() {
lblCheckingForUpdate.setVisible(false);
}
});
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
updateButton.setVisible(NavalBattle.getBroadcastService().needsUpdate());
announcementButton.setVisible(NavalBattle.getBroadcastService().hasAnnouncement());
} catch(Exception e) {
NavalBattle.getDebugWindow().printWarning("Error while setting BroadcastService button(s) visible.");
}
}
});
repaint();
}
});
t.start();
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(updateButton.isVisible()) {
int dialogResult = JOptionPane.showConfirmDialog (null, NavalBattle.getLocalizationManager().getString("login_update_alert"), "NavalBattle",JOptionPane.YES_NO_OPTION);
if (dialogResult != JOptionPane.YES_OPTION) {
return;
}
}
login();
}
});
offlineButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
NavalBattle.getWindowHandler().getToasterManager().showToaster(new ImageIcon(getClass().getResource("/com/roketgamer/res/logo_100px.png")), NavalBattle.getLocalizationManager().getString("toast_offline_mode"));
NavalBattle.getDebugWindow().printInfo("Opening in offline mode");
NavalBattle.getDebugWindow().printWarning("RoketGamer disabled");
NavalBattle.getGameState().setOffline(true);
nextWindow("LoggingInWindow");
donewithMe();
}
});
registerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
NavalBattle.getDebugWindow().printInfo("Opening register page");
URLUtils.openURL(NavalBattle.getRoketGamer().getServerLocation() + "/register.php?game=1&name=NavalBattle");
}
});
updateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
nextWindow("UpdateWindow");
}
});
announcementButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
nextWindow("BroadcastWindow");
}
});
}
|
921a44c4-8df9-4300-91fb-ad099f5b488e
| 2
|
public void cambiarPesoNodo(long target, int peso) {
for (int i = 0; i < connections.getLength(); i++) {
Connection connection = connections.get(i);
if (connection.getTarget()==target) {
connection.setPrecio(peso);
difusion(XmlToolkit.crearCambioPeso(this.id,target,peso));
}
}
}
|
6d68e322-2f8e-4d94-87c4-383fd8c5919c
| 1
|
public static boolean propertyEqualsAsString(PropertyContainer container, String key, String test_value) {
if (container != null) {
return container.propertyEquals(key, test_value);
} else {
throw new IllegalArgumentException("Provided PropertyContainer was null.");
}
}
|
502eb219-c048-4cce-be0c-c7ff872249e6
| 8
|
private void editRackProperties(){
RackPropertiesDialog dlg = new RackPropertiesDialog(this.r.getRackProperties(),this, "Edit Rack Properties", "table goes here...");
if (dlg.getExitWithOK()){
String propName = "rows";
String str = "";
try {
this.r.getRackProperties().setRows(Integer.parseInt(dlg.getProperty(propName).trim()));
propName = "cols";
this.r.getRackProperties().setCols(Integer.parseInt(dlg.getProperty(propName).trim()));
propName = "scale";
this.r.getRackProperties().setScale(Double.parseDouble(dlg.getProperty(propName).trim()));
propName = "imagesPath";
str = dlg.getProperty(propName).trim();
if (new File(str).exists()) {
this.r.getRackProperties().setImagesPath(str);
} else {
throw new FileNotFoundException("The directory '" + str + "' does not exist.");
}
propName = "modulesPath";
str = dlg.getProperty(propName).trim();
if (new File(str).exists()) {
this.r.getRackProperties().setModulesPath(str);
} else {
throw new FileNotFoundException("The directory '" + str + "' does not exist.");
}
propName = "rackImageFilename";
str = dlg.getProperty(propName).trim();
if (new File(this.r.getRackProperties().getImagesPath() + "/" + str).exists()) {
this.r.getRackProperties().setRackImageFilename(str);
} else {
throw new FileNotFoundException("The file '" + this.r.getRackProperties().getImagesPath() + "/" + str + "' does not exist.");
}
propName = "rackHP";
this.r.getRackProperties().setRackHP(Integer.parseInt(dlg.getProperty(propName).trim()));
this.r.save();
JOptionPane.showMessageDialog(this, "Changes will take effect the next time the rack is loaded.", "Rack Properties Saved",JOptionPane.PLAIN_MESSAGE);
} catch (FileNotFoundException e){
JOptionPane.showMessageDialog(frame, e.getMessage() + " Changes to rack properties not saved.", "Problem Saving Rack Properties",JOptionPane.ERROR_MESSAGE);
} catch (NullPointerException e){
JOptionPane.showMessageDialog(frame, "Property '" + propName + "' not found. Changes to rack properties not saved.", "Problem Saving Rack Properties",JOptionPane.ERROR_MESSAGE);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(frame, "Property '" + propName + "' is not in the correct format. Changes to rack properties not saved.", "Problem Saving Rack Properties",JOptionPane.ERROR_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Problem saving rack property '" + propName + ".' Changes to rack properties not saved.\n\nError details:.\n" + e, "Problem Saving Rack Properties",JOptionPane.ERROR_MESSAGE);
}
}
dlg.dispose();
}
|
4795d3a0-acbf-4128-a6b1-3291e301c822
| 9
|
protected void FillBuff() throws java.io.IOException
{
if (maxNextCharInd == available)
{
if (available == bufsize)
{
if (tokenBegin > 2048)
{
bufpos = maxNextCharInd = 0;
available = tokenBegin;
}
else if (tokenBegin < 0)
bufpos = maxNextCharInd = 0;
else
ExpandBuff(false);
}
else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
}
int i;
try {
if ((i = inputStream.read(buffer, maxNextCharInd,
available - maxNextCharInd)) == -1)
{
inputStream.close();
throw new java.io.IOException();
}
else
maxNextCharInd += i;
return;
}
catch(java.io.IOException e) {
--bufpos;
backup(0);
if (tokenBegin == -1)
tokenBegin = bufpos;
throw e;
}
}
|
629533f6-aab2-48ec-a3a8-b45f26bf8d76
| 5
|
public int computeLCS(int i, int j)
{
if ((i == 0) || (j == 0))
return 0;
if (length[i][j] > 0)
return length[i][j];
if (seq1[i] == seq2[j]) {
length[i][j] = computeLCS(i-1, j-1) + 1;
indices[i][j] = I * (i-1) + j-1;
} else if (computeLCS(i-1, j) >= computeLCS(i, j-1)) {
length[i][j] = length[i-1][j];
indices[i][j] = -(I * (i-1) + j);
} else {
length[i][j] = length[i][j-1];
indices[i][j] = -(I * (i) + j-1);
}
return (length[i][j]);
}
|
3405f2b7-38e7-4911-a886-029946b7d9af
| 9
|
@Override
public boolean equals(Object o) {
if (!(o instanceof Container)) return false;
Container container = (Container) o;
if (UUID != null ? !UUID.equals(container.UUID) :
container.UUID != null)
return false;
if (id != null ? !id.equals(container.id) :
container.id != null)
return false;
if (links != null ? !links.equals(container.links) :
container.links != null)
return false;
if (name != null ? !name.equals(container.name) :
container.name != null)
return false;
return true;
}
|
7ee1657f-b8a8-4064-9642-03fbfa962455
| 5
|
private String randomCard(int i) {
String card; // String carte a retourner
// Affecte la string carte au cas par cas en fonction de la valeur de l'entier.
switch (i) {
case 0:
card = "chevalier";
break;
case 1:
card = "monopole";
break;
case 2:
card = "route";
break;
case 3:
card = "decouverte";
break;
case 4:
card = "victoire";
break;
default:
return "null";
}
return card; // Retourne la string ressource.
}
|
bcd9ccf7-abdc-43eb-be15-f65a883f30b1
| 8
|
public void beginContact(Contact c) {
Fixture fa = c.getFixtureA();
Fixture fb = c.getFixtureB();
if(fa.getUserData() != null && fa.getUserData().equals("foot")) {
numFootContacts++;
}
if(fb.getUserData() != null && fb.getUserData().equals("foot")) {
numFootContacts++;
}
if(fa.getUserData() != null && fa.getUserData().equals("crystal")) {
// remove crystal
bodiesToRemove.add(fa.getBody());
}
if(fb.getUserData() != null && fb.getUserData().equals("crystal")) {
bodiesToRemove.add(fb.getBody());
}
}
|
36cccdb9-36c5-48a2-9014-84ed2eb72d12
| 2
|
public static HsvImage convertToHsv(RgbImage rgb) {
HsvImage hsv = new HsvImage(rgb.getWidth(), rgb.getHeight());
for (int x = 0; x < rgb.getWidth(); x++) {
for (int y = 0; y < rgb.getHeight(); y++) {
HsvPixel px = convertPixel(rgb, x, y);
hsv.setPixel(x, y, HUE, px.hue);
hsv.setPixel(x, y, SATURATION, px.saturation);
hsv.setPixel(x, y, VALUE, px.value);
}
}
return hsv;
}
|
2bb70e13-476c-4478-8ba4-ab6a298d67ed
| 1
|
@Override
public boolean startVideoProcessing(File videoFile) {
if (!videoFile.exists())
return false;
processThread = createProcessThread(videoFile, this.mediator);
// Start
processThread.start();
return true;
}
|
3cc97116-5fa6-4efb-a236-fbff7020c27e
| 7
|
public static void htmlDescribeInstances(String title, String head, NamedDescription relation, org.powerloom.PrintableStringWriter stream, boolean ruleP) {
{ Cons instances = edu.isi.powerloom.PLI.getConceptInstances(relation, null, null).consify();
Cons assertedinstances = Logic.ASSERTION_INFERENCE.levellizedAllClassInstances(relation.surrogateValueInverse);
Cons directinstances = edu.isi.powerloom.PLI.getDirectConceptInstances(relation, null, null).consify();
int nInstances = instances.length();
OntosaurusUtil.htmlWriteHeaderWithTable(stream, title, head);
if (instances == Stella.NIL) {
{
stream.print("<I>");
stream.print("None");
stream.println("</I>");
}
}
else {
{
stream.print(nInstances + (((nInstances == 1) ? " instance; " : " instances; ")) + directinstances.length() + " direct (");
OntosaurusUtil.htmlEmitImage(stream, "icons/small-circ-filled.gif", "x", 11, 11, "BOTTOM", 0);
stream.println(")");
{
stream.print("<DL>");
instances = instances.sort(Native.find_java_method("edu.isi.powerloom.logic.Logic", "logicFormLessP", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Stella_Object")}));
{ Stella_Object instance = null;
Cons iter000 = instances;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
instance = iter000.value;
{
stream.print("<DT>");
OntosaurusUtil.htmlEmitImage(stream, (directinstances.memberP(instance) ? "icons/small-circ-filled.gif" : "icons/small-circ-open.gif"), (directinstances.memberP(instance) ? "x" : "o"), 11, 11, "BOTTOM", 0);
stream.print(" ");
if (assertedinstances.memberP(instance)) {
OntosaurusUtil.pprintObject(instance, stream);
}
else {
{
stream.print("<I>");
OntosaurusUtil.pprintObject(instance, stream);
stream.print("</I>");
}
}
stream.println("</DT>");
}
}
}
stream.println("</DL>");
}
}
}
if (ruleP) {
stream.println("<HR SIZE=2>");
}
return;
}
}
|
19b1917a-cfaa-475a-95e8-93935834d742
| 6
|
PluginClassLoader(final ClassLoader parent, String main, final File file) throws InvalidPluginException, MalformedURLException {
super(new URL[] {file.toURI().toURL()}, parent);
try {
Class<?> jarClass;
try {
jarClass = Class.forName(main, true, this);
} catch (ClassNotFoundException ex) {
throw new InvalidPluginException("Cannot find main class `" + main + "'", ex);
}
Class<? extends DragonPlugin> pluginClass;
try {
pluginClass = jarClass.asSubclass(DragonPlugin.class);
} catch (ClassCastException ex) {
throw new InvalidPluginException("main class `" + main + "' does not extend DragonAddon", ex);
}
plugin = pluginClass.newInstance();
} catch (IllegalAccessException ex) {
throw new InvalidPluginException("No public constructor", ex);
} catch (InstantiationException ex) {
throw new InvalidPluginException("Abnormal plugin type", ex);
}
}
|
048038b5-5914-4a15-8dc3-48988ebc558a
| 0
|
public WhereIterable(Iterable<T> source, Predicate<T> predicate)
{
this._predicate = predicate;
this._source = source;
}
|
c8f1393f-81cf-4237-b6cd-2a24227a9f90
| 5
|
public static String[] format(String[] text)
{
int max = 0;
int n = 0;
StringBuilder sb;
for(int i = 0; i < text.length; i++)
{
if(text[i].length() > max)
max = text[i].length();
}
for(int i = 0; i < text.length; i++)
{
sb = new StringBuilder();
if(text[i].length() < max)
{
n = max - text[i].length();
for(int j = 0; j < n; j++)
{
sb.append(" ");
}
sb.append(text[i]);
text[i] = sb.toString();
}
}
return text;
}
|
101ac87e-472e-46f8-a157-0bd13f214af8
| 5
|
public static boolean compareBufferedImages(BufferedImage bufferedImage1, BufferedImage bufferedImage2) {
if (bufferedImage1.getWidth() == bufferedImage2.getWidth() && bufferedImage1.getHeight() == bufferedImage2.getHeight()) {
for (int x = 0; x < bufferedImage1.getWidth(); x++) {
for (int y = 0; y < bufferedImage1.getHeight(); y++) {
if (bufferedImage1.getRGB(x, y) != bufferedImage2.getRGB(x, y))
return false;
}
}
} else {
return false;
}
return true;
}
|
0a407b52-0c60-4bfb-b1a8-c34cc888ecf5
| 2
|
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
Point p = (Point) obj;
return properties == null ? p.properties == null : properties.equals(p.properties);
}
|
2d477b49-b5d5-4b22-af1d-c9639541bed5
| 3
|
public void setZonesCount(int xCount, int yCount) {
if(xCount > 64 || yCount > 46) {
try {
game.myControle.writeToDebugFile("Could not load that many zones. Maximum 1024*1024!");
} catch (IOException e) {
System.out.println("Error setting zones in class Mapper. Zones count too high!");
}
}
}
|
fe760738-032e-49fa-9697-5e0f17fddf3a
| 2
|
public void cargarArchivo(){
try
{
FileInputStream fileIn = new FileInputStream("configurations.txt");
ObjectInputStream in = new ObjectInputStream(fileIn);
ArrayList<Configuracion> confi;
confi = (ArrayList<Configuracion>) in.readObject();
if(confi!=null){
configuraciones = confi;
}
in.close();
fileIn.close();
}catch( IOException | ClassNotFoundException i)
{
i.printStackTrace();
}
}
|
80211266-cc72-4848-b21f-4bf6c0f14ba1
| 8
|
@EventHandler
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) {
if (HyperPVP.isCycling()) {
event.setCancelled(true);
}
if (!HyperPVP.hasMatchBeenAnnounced()) {
event.setCancelled(true);
return;
}
for (Region region : HyperPVP.getMap().getRegions(RegionType.TEAM)) {
if (region.hasLocation(event.getBlockClicked().getLocation())) {
event.getPlayer().sendMessage(ChatColor.RED + "You can't empty a bucket on a spawn!");
event.setCancelled(true);
return;
}
}
if (HyperPVP.getMap().getType() == GameType.DTC || HyperPVP.getMap().getType() == GameType.RTC) {
for (Region region : HyperPVP.getMap().getRegions(RegionType.DTC)) {
if (region.hasLocation(event.getBlockClicked().getLocation())) {
event.getPlayer().sendMessage("You can't empty a bucket on a core!");
event.setCancelled(true);
}
}
}
}
|
5ce9e268-11e0-40e3-b9eb-296240481541
| 8
|
private void updateResiduesComputedMenu(String group3List, int[] group3Counts, boolean popup) {
if (group3List == null || group3Counts == null)
return;
JMenu menu = popup ? residuesComputedMenu2 : residuesComputedMenu1;
if (menu == null)
return;
for (int i = 0; i < menu.getItemCount(); i++) {
proteinGroup.remove(menu.getItem(i));
}
menu.removeAll();
for (int i = 1, n = JmolConstants.GROUPID_AMINO_MAX; i < n; ++i) {
final String residueName = JmolConstants.predefinedGroup3Names[i];
if (group3List.indexOf("p>" + residueName) != -1) {
int m = group3Counts[group3List.indexOf(residueName) / 6];
JMenuItem mi = new JRadioButtonMenuItem(residueName + " (" + m + ")");
mi.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
jmolContainer.jmol.viewer.runScriptImmediatelyWithoutThread("select " + residueName);
}
}
});
menu.add(mi);
proteinGroup.add(mi);
}
}
}
|
4caec596-8f1e-4227-addb-91eaf0635533
| 0
|
public void testByteIntConvert() {
int expect = 8;
byte[] bytes = ByteUtils.intToByteArray(expect);
int i = ByteUtils.byteArrayToInt(bytes);
assertEquals(expect, i);
expect = -8;
bytes = ByteUtils.intToByteArray(expect);
i = ByteUtils.byteArrayToInt(bytes);
assertEquals(expect, i);
expect = -255;
bytes = ByteUtils.intToByteArray(expect);
i = ByteUtils.byteArrayToInt(bytes);
assertEquals(expect, i);
expect = 255;
bytes = ByteUtils.intToByteArray(expect);
i = ByteUtils.byteArrayToInt(bytes);
assertEquals(expect, i);
expect = 128;
bytes = ByteUtils.intToByteArray(expect);
i = ByteUtils.byteArrayToInt(bytes);
assertEquals(expect, i);
expect = -128;
bytes = ByteUtils.intToByteArray(expect);
i = ByteUtils.byteArrayToInt(bytes);
assertEquals(expect, i);
expect = -0xffffffff;
bytes = ByteUtils.intToByteArray(expect);
i = ByteUtils.byteArrayToInt(bytes);
assertEquals(expect, i);
expect = 0xffffffff;
bytes = ByteUtils.intToByteArray(expect);
i = ByteUtils.byteArrayToInt(bytes);
assertEquals(expect, i);
expect = -1;
bytes = ByteUtils.intToByteArray(expect);
i = ByteUtils.byteArrayToInt(bytes);
assertEquals(expect, i);
expect = 0;
bytes = ByteUtils.intToByteArray(expect);
i = ByteUtils.byteArrayToInt(bytes);
assertEquals(expect, i);
}
|
f10dc676-b548-4736-ab13-09d906d9f07a
| 1
|
@Override
public boolean hasNext() {
if (first == null)
return false;
return !(current == null);
}
|
00685a9f-5ea5-4903-90e9-fa2dc427bd7a
| 0
|
public Tile[][] getTiles() {
return this.map;
}
|
6c661387-623e-472f-acaf-68ddb69d28eb
| 3
|
public GestionarProducto(){
try{
//obtenemos el driver de para mysql
Class.forName("org.gjt.mm.mysql.Driver");
//obtenemos la conexión
connection = DriverManager.getConnection(url,login,password);
}
catch(SQLException e){
System.out.println(e);
}catch(ClassNotFoundException e){
System.out.println(e);
}catch(Exception e){
System.out.println(e);
}
}
|
a0a579fe-3856-4f2f-89d5-f2b4a52d3d8b
| 8
|
@Override
public void destroyTarget() throws Exception {
Object arr[] = {this, target};
double rate = 3;// Math.random(); // generate random success
if (target.isRunning()) {
if (!target.isHidden()) {
// if rate bigger than success rate it will destroy
if (rate > War.SUCCESS_RATE) {
for (WarEventListener l : allListeners) {
l.RemovedLauncherFromUI(target.getLauncherId());
}
for (WarEventListener l : allListeners) {
l.AddMessageToGui("Destruction of launcher " + target.getLauncherId()
+ " was sucess!");
}
target.stopLauncher();
logTargetDestroyed();
WarDBConnection.updateLauncherStatus(target.getLauncherId().toString(), "Destroy");
} else {
for (WarEventListener l : allListeners) {
l.AddMessageToGui("Destruction of launcher " + target.getLauncherId() + " was failed");
}
throw new Exception("Destruction of launcher " + target.getLauncherId() + " was failed");
}
} else {
for (WarEventListener l : allListeners) {
l.AddMessageToGui("Destruction of launcher " + target.getLauncherId()
+ " was failed - Launcher is hidden!");
}
throw new Exception("Destruction of launcher " + target.getLauncherId()
+ " was failed - Launcher is hidden!");
}
} else {
for (WarEventListener l : allListeners) {
l.AddMessageToGui("Destruction of launcher " + target.getLauncherId()
+ " was failed - Launcher is not running!");
}
throw new Exception("Destruction of launcher " + target.getLauncherId()
+ " was failed - Launcher is not running!");
}
}
|
0ba88729-15f1-45e2-951d-1b43eb771abb
| 4
|
private static char[] getQualityColumn (Alignment layoutMap, int index) {
List<Read> reads = new ArrayList<Read>();
for (Read lay : layoutMap.values()) {
if (lay.getOffset() <= index && index < lay.getOffset() + lay.getLength()) {
reads.add(lay);
}
}
char[] column = new char[reads.size()];
for (int i = 0; i < reads.size(); i++) {
Read read = reads.get(i);
char c = read.quality.get(index - read.getOffset());
column[i] = c;
}
return column;
}
|
d1c0e851-8e4f-4fec-9451-661a3b1f44b1
| 3
|
@SuppressWarnings("unchecked")
@Get
public ExeReport login() {
String login = (String) getRequest().getAttributes().get("login");
String password = (String) getRequest().getAttributes().get("password");
EntityManager em = emf.createEntityManager();
List<Account> targets = null;
String queryString = "select obj from Account as obj ";
Query query = em.createQuery(queryString);
targets = query.getResultList();
for (Account item : targets) {
if (item.getLogin().equals(login)
&& item.getPassword().equals(password)) {
return ExeReportHelper.getValideAccount(String.valueOf(item
.getUserId()));
}
}
return ExeReportHelper.getUnvalideAccount();
}
|
ffda388d-35e4-43d4-839d-46101f424eb7
| 3
|
public static Utilisateur activerCompte(String url) throws RuntimeException {
CourrielActivation c = CourrielActivationRepo.get().deLUrl(url);
if (c == null)
return null;
EntityTransaction transaction = UtilisateurRepo.get().transaction();
try {
transaction.begin();
c.getUtilisateur().setCompteActive(true);
CourrielActivationRepo.get().supprimer(c);
UtilisateurRepo.get().mettreAJour(c.getUtilisateur());
transaction.commit();
return c.getUtilisateur();
}
catch (RuntimeException e) {
if (transaction.isActive())
transaction.rollback();
throw e;
}
}
|
e266a0e1-af23-4677-b958-97b9fbc5e22e
| 4
|
public static void main(String[] args) {
InetAddress ip = null;
Socket clientSocket = null;
try {
ip = InetAddress.getByName("localhost");
clientSocket = new Socket (ip, 1801);
// поток для передачи векторов серверу
BufferedWriter out = new BufferedWriter(new OutputStreamWriter (clientSocket.getOutputStream()));
// выходной файл, куда записываются результаты
// BufferedWriter out2 = new BufferedWriter(new OutputStreamWriter ( new FileOutputStream(args[1])));
BufferedWriter out2 = new BufferedWriter(new OutputStreamWriter ( new FileOutputStream("C:\\users\\netcracker\\2.txt")));
// поток для получения вектора от сервера
BufferedReader in = new BufferedReader(new InputStreamReader (clientSocket.getInputStream()));
// входной вектор
InputStreamReader in2 = new InputStreamReader(new FileInputStream ("C:\\users\\netcracker\\1.txt"));
while (true) {
System.out.println("Read two vectors...");
Vector v1 = Vectors.readVector(in2); // первый вектор
if (v1.getLength() == 0) {
break;
}
Vector v2 = Vectors.readVector(in2); // второй вектор
System.out.println("size"+v1.getLength()+" "+ v1.toString());
System.out.println("size"+v1.getLength()+" "+v2.toString());
// передаем два вектора серверу
System.out.println("Send vectors to server...");
Vectors.writeVector(v1, out);
Vectors.writeVector(v2, out);
// ждем от вектора ответ
System.out.println("Wait vector from server...");
// считываем вектор
Vector v = Vectors.readVector(in);
System.out.println(v.toString());
// записываем вектов в файл
System.out.println("Write vector to file...");
Vectors.writeVector(v, out2);
out2.flush();
}
in2.close();
in.close();
out2.close();
out.close();
clientSocket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
|
ed59eceb-5bb7-485a-9b61-d014ffff0918
| 7
|
public byte[] getBlock(int address, int blockSize) {
int offset = 0;
for (int i = 0; i < offsetBits; i++) {
offset |= address & (1 << i);
}
address >>= offsetBits;
int index = 0;
for (int i = 0; i < indexBits; i++) {
index |= address & (1 << i);
}
address >>= indexBits;
int tag = 0;
for (int i = 0; i < tagBits; i++) {
tag |= address & (1 << i);
}
int blockNumber = (address / blockSize) * blockSize;
byte[] block = new byte[blockSize];
for (int i = 0; i < cacheMemory[index].length; i++) {
if (cacheMemory[index][i].valid && cacheMemory[index][i].tag == tag) {
int j = 0;
for (int k = 0; k < blockNumber; k++) {
block[j++] = cacheMemory[index][i].data[k];
}
}
}
return block;
}
|
a43f1a77-d3e9-4af2-aad6-5282ba344e15
| 2
|
public List<Integer> getClientIds() {
synchronized(CONNECTION_LOCK) {
List<Integer> clientIds = new ArrayList<Integer>();
for(Integer clientId: clients.keySet()) {
if(clients.get(clientId) != null)
clientIds.add(clientId);
}
return clientIds;
}
}
|
b37783f9-d969-42cb-87a1-acde5e0c260d
| 0
|
public int getInitialWidth() {
return initialWidth;
}
|
36cb3249-7a1f-4fc0-adea-89aff4b50319
| 6
|
public boolean sendCommand(String p_command) {
int indexInit = p_command.indexOf(".");
if (indexInit < 0) {
return false;
}
String deviceName = p_command.substring(0, indexInit);
String command = p_command.substring(indexInit + 1);
if (deviceName.equals(this.name) && command.equalsIgnoreCase("GETPOS")) {
writeOut("GETPOS X=" + position.getX() +
" Y=" + position.getY() +
" DIR=" + Math.toDegrees(position.getT()));
} else if (deviceName.equals(platform.getName())) {
platform.sendCommand(command);
return true;
} else {
for (Device sensor : sensors) {
if (deviceName.equals(sensor.getName())){
sensor.sendCommand(command);
return true;
}
}
}
return false;
}
|
f53cc457-91fa-44c3-a724-0c6f3e67d47b
| 1
|
public boolean getBoolean( String name ){
XAttribute attribute = getAttribute( name );
if( attribute == null )
throw new XException( "no attribute known with name: " + name );
return attribute.getBoolean();
}
|
09a1f099-6a3a-436a-8664-439c8c881392
| 1
|
public void visit_putstatic_nowb(final Instruction inst) {
final Type type = ((MemberRef) inst.operand()).nameAndType().type();
stackHeight -= type.stackHeight();
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
}
|
40d6c59d-684c-4b57-acad-15ffffb622b0
| 9
|
@EventHandler(priority = EventPriority.LOW)
public void InventoryClick(InventoryClickEvent event)
{
if(!event.isCancelled())
{
HumanEntity ent = event.getWhoClicked();
if(ent instanceof Player)
{
Inventory inv = event.getInventory();
if(inv instanceof AnvilInventory)
{
InventoryView view = event.getView();
int rawSlot = event.getRawSlot();
if(rawSlot == view.convertSlot(rawSlot))
{
if(rawSlot == 2)
{
ItemStack item = event.getCurrentItem();
if(item != null && item.getAmount() != 1
&& plugin.getConfigs("GlitchPatch.AnvilEnchant.Enable").equals("true"))
{
item.setAmount(1);
if (plugin.getConfigs("Settings.Display.PatchAlert").equals("true"))
gp.patched("AnvilEnchant", ((Player) ent).getPlayer(), true);
}
}
}
}
}
}
}
|
11c7200f-1aa4-4174-ba35-a358d33d3429
| 4
|
private void writeOutputMatrices() throws Exception {
/* First read the original matrix dimensions */
BipartiteGraphInfo graphInfo = getGraphInfo();
int numLeft = graphInfo.getNumLeft();
int numRight = graphInfo.getNumRight();
VertexIdTranslate vertexIdTranslate =
VertexIdTranslate.fromFile(new File(ChiFilenames.getVertexTranslateDefFile(baseFilename, numShards)));
/* Output left */
String leftFileName = baseFilename + "_U.mm";
BufferedWriter wr = new BufferedWriter(new FileWriter(leftFileName));
wr.write("%%MatrixMarket matrix array real general\n");
wr.write(this.D + " " + numLeft + "\n");
for(int j=0; j < numLeft; j++) {
int vertexId = vertexIdTranslate.forward(j); // Translate to internal vertex id
for(int i=0; i < D; i++) {
wr.write(vertexValueMatrix.getValue(vertexId, i) + "\n");
}
}
wr.close();
/* Output right */
String rightFileName = baseFilename + "_V.mm";
wr = new BufferedWriter(new FileWriter(rightFileName));
wr.write("%%MatrixMarket matrix array real general\n");
wr.write(this.D + " " + numRight + "\n");
for(int j=0; j < numRight; j++) {
int vertexId = vertexIdTranslate.forward(numLeft + j); // Translate to internal vertex id
for(int i=0; i < D; i++) {
wr.write(vertexValueMatrix.getValue(vertexId, i) + "\n");
}
}
wr.close();
logger.info("Latent factor matrices saved: " + baseFilename + "_U.mm" + ", " + baseFilename + "_V.mm");
}
|
b2a6d1a7-5da7-4831-8156-c8d59c8f5d39
| 5
|
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final StreamRolledBack other = (StreamRolledBack) obj;
if (!Objects.equals(this.streamName, other.streamName)) {
return false;
}
if (!Objects.equals(this.lastEventId, other.lastEventId)) {
return false;
}
return true;
}
|
a1214cc0-6cb3-4fbb-9fc4-8ef1d6404c40
| 6
|
public static String[] readSavedUsernames(File technicPath) {
byte[] mcHash = null;
String mcPass = "";
String mcUser = "";
String[] loginData = new String[2];
String[] dummyArray = { "", "", "" };
try {
File lastLogin = technicPath;
if (!lastLogin.exists()) {
return dummyArray;
}
Cipher cipher = getCipher(2, "passwordfile");
DataInputStream dis;
if (cipher != null) {
dis = new DataInputStream(new CipherInputStream(new FileInputStream(lastLogin), cipher));
} else {
dis = new DataInputStream(new FileInputStream(lastLogin));
}
try {
while (true) {
int version = dis.readInt();
String key = dis.readUTF();
String user = dis.readUTF();
boolean isHash = dis.readBoolean();
if (isHash) {
byte[] hash = new byte[32];
dis.read(hash);
mcHash = hash;
} else {
String pass = dis.readUTF();
mcPass = pass;
}
mcUser = user;
}
} catch (EOFException e) { }
loginData[0] = mcUser;
loginData[1] = mcPass;
dis.close();
return loginData;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
|
5c4edc74-d2d9-4bcb-b544-fb616dc98135
| 7
|
private static void initMacApplicationInstance() {
if(!isRunningOnMac()) return;
//if we already have initialized these then just return
if(macAdapterClass != null && macAppListenerInterface !=null &&
macAppEventClass != null && macAdapterInstance != null) {
return;
}
//Get the classes
try {
macAdapterClass = Class.forName("com.apple.eawt.Application");
macAppListenerInterface = Class.forName("com.apple.eawt.ApplicationListener");
macAppEventClass = Class.forName("com.apple.eawt.ApplicationEvent");
} catch (ClassNotFoundException classNotFound) {
// One (or more) of the Apple extension classes is missing.
macAdapterClass = null;
macAppListenerInterface = null;
macAppEventClass = null;
}
try {
//
// Object macAdapterInstance = Application.getApplication();
//
Method getSingletonMethod = macAdapterClass.getMethod("getApplication");
macAdapterInstance = getSingletonMethod.invoke(null);
} catch (Exception dynEx) {
dynEx.printStackTrace();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.