method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
a4f1eca2-abef-4b48-a82a-5d5b673aabfb
| 7
|
public static int search(int[] A, int target) {
int len = A.length;
int low = 0;
int high = len - 1;
while (low <= high) {
int mid = (high + low) / 2;
int val = A[mid];
if (val == target) {
return mid;
}
if (A[mid] >= A[low]) {
if (A[mid] > target && target >= A[low]) {
high = mid - 1;
} else {
low = mid + 1;
}
} else {
if (A[mid] < target && target <= A[high]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
}
return -1;
}
|
885742ff-1905-46aa-964b-d96fe42f581c
| 0
|
public boolean isEspecial() {
return especial;
}
|
6d57479b-a19f-48f8-9b2c-d91b1d5def8d
| 0
|
public ObjectProperty getObjectProperty(OntModel model) {
return model.createObjectProperty(getUri());
}
|
6636cb24-0574-4712-9cb9-34411b10bae5
| 1
|
private Server(User user, Socket s, String name){
this.user = user;
this.s = s;
try {
addUser(s, name);
oin = new ObjectInputStream(s.getInputStream());
} catch (Exception e){
e.printStackTrace();
}
setDaemon(true);
setPriority(NORM_PRIORITY);
start();
}
|
af15d04f-74fe-4511-8bd6-5f53f9e50c86
| 2
|
public static void initLayout(){
/*Math and Layout below this line, pass at your own risk
----------------------------------------------------------*/
{
int rows[] = new int[34];
for(int x = 0; x < rows.length; x++){
rows[x] = (Height/rows.length)/2;
}
int columns[] = new int[60];
for(int x = 0; x < columns.length; x++){
columns[x] = (Width/columns.length)/2;
}
layout.rowHeights = rows;
layout.columnWidths = columns;
}
resetConstraints();
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 20;
c.insets = new Insets(0, 0, 0, 1);
mainPanel.add(playerNumbers, c);
resetConstraints();
c.gridx = 1;
c.gridy = 2;
c.gridheight = 20;
c.gridwidth = 17;
c.insets = new Insets(0, 0, 0, 1);
mainPanel.add(playerArea, c);
resetConstraints();
c.gridx = 0;
c.gridy = 0;
c.gridheight = 2;
c.gridwidth = 18;
c.insets = new Insets(0, 0, 0, 1);
mainPanel.add(graveyardLabel, c);
resetConstraints();
dayButtons.setLocation(c, 0, 22, 20, 12, 20, 22, 7, 12);
resetConstraints();
c.gridwidth = 9;
c.gridheight = 20;
c.gridy = 2;
c.gridx = 18;
mainPanel.add(roleList, c);
resetConstraints();
c.gridheight = 2;
c.gridwidth = 9;
c.gridx = 18;
c.gridy = 0;
mainPanel.add(roleListLabel, c);
resetConstraints();
c.gridwidth = 8;
c.gridheight = 2;
c.gridx = 27;
c.gridy = 0;
mainPanel.add(dayLabel, c);
resetConstraints();
c.gridwidth = 25;
c.gridheight = 22;
c.gridx = 35;
c.gridy = 0;
mainPanel.add(notesPane, c);
resetConstraints();
c.gridwidth = 5;
c.gridheight = 5;
c.gridx = 36;
c.gridy = 22;
mainPanel.add(save, c);
resetConstraints();
c.gridwidth = 5;
c.gridheight = 5;
c.gridx = 42;
c.gridy = 22;
mainPanel.add(load, c);
resetConstraints();
c.gridwidth = 5;
c.gridheight = 5;
c.gridx = 48;
c.gridy = 22;
mainPanel.add(whisper, c);
resetConstraints();
c.gridwidth = 5;
c.gridheight = 5;
c.gridx = 54;
c.gridy = 22;
mainPanel.add(update, c);
resetConstraints();
c.gridwidth = 5;
c.gridheight = 5;
c.gridx = 36;
c.gridy = 28;
mainPanel.add(saveAs, c);
resetConstraints();
c.gridwidth = 5;
c.gridheight = 5;
c.gridx = 42;
c.gridy = 28;
mainPanel.add(help, c);
resetConstraints();
c.gridwidth = 5;
c.gridheight = 5;
c.gridx = 48;
c.gridy = 28;
mainPanel.add(generalNotes, c);
resetConstraints();
c.gridwidth = 5;
c.gridheight = 5;
c.gridx = 54;
c.gridy = 28;
mainPanel.add(info, c);
}
|
4457b011-3741-4c91-ad8e-bfff6f594272
| 2
|
@Override
public int compareTo(Object arg0) {
if (!(arg0 instanceof TargetTransition))
throw new ClassCastException();
TargetTransition t0 = (TargetTransition) arg0;
int compareActions = this.action.compareTo(t0.action);
if (compareActions != 0)
return compareActions;
else
return this.invoke.compareTo(t0.invoke);
}
|
4dfbaa35-8db9-4310-b560-ae2c27cb483a
| 5
|
public CostReadings readReadings(JsonReader reader) throws IOException {
Number period = null;
Number cost = null;
Number energy = null;
String ts = null;
reader.beginObject();
while (reader.hasNext()) {
String key = reader.nextName();
if (key.equals("period")) {
period = reader.nextLong();
} else if (key.equals("energy")) {
energy = reader.nextDouble();
} else if (key.equals("cost")) {
cost = reader.nextDouble();
} else if (key.equals("ts")) {
ts = reader.nextString();
} else {
System.err.println("Building CostReadings: Unknown key: "+key);
reader.skipValue();
}
}
reader.endObject();
return new CostReadings(cost, energy, period, ts);
}
|
cb77ded8-a7ed-409a-9e60-ced6ae4a8629
| 8
|
static void initialization() {
if (initialized == false) {
for (int i = 0; i <= sizeOfMemInt; i++) {
if ((i < rootSize) || ((i >= (rootSize + FATSize)) && i < sizeOfMemInt)) {
setMem(i, 0);
}
if (i >= rootSize && i < (rootSize + FATSize)) {
setMem(i, 1);
if (i == rootSize) {
setMem(i, -3);
}
}
}
initialized = true;
}
}
|
ea26d8db-d790-49c4-90d6-547eee768028
| 5
|
public int filterRGB(int fx, int fy, int argb) {
fx -= x;
fy -= y;
if( fx < 0 || fy < 0 || fx >= w || fy >= h)
return argb;
int d = data[fx + w*fy];
return (d < 0) // first bit set -> opaque
? d
: argb;
}
|
2f9a3d72-684b-40da-82f5-6221bca1e932
| 5
|
@Override
public int compareTo(TLValue that) {
if(this.isNumber() && that.isNumber()) {
if(this.equals(that)) {
return 0;
}
else {
return this.asDouble().compareTo(that.asDouble());
}
}
else if(this.isString() && that.isString()) {
return this.asString().compareTo(that.asString());
}
else {
throw new RuntimeException("illegal expression: can't compare `" + this + "` to `" + that + "`");
}
}
|
a652cd5c-9156-4a01-b5b5-d937c7cbd570
| 2
|
public Hand getActiveHand() {
for (Hand hand : hands) {
if (hand.isActive()) {
return hand;
}
}
return null;
}
|
222001be-f326-41c4-b91b-b24c57a0dde3
| 4
|
public void addAgent(){
Random rand = new Random();
int x;
int y;
for(Integer i = 0;i < ((EnvironnementParticule)environment).nb_agent;i++){
//on les place dans un coin au hazard (attention boucle infini si + d'Agent que de case)
do{
x = rand.nextInt(environment.taille_envi);
y = rand.nextInt(environment.taille_envi);
}while(environment.grille[x][y] != null);
//on leur donne une force de mouvement au hazard (elles peuvents avoirs (0,0) ce qui fait qu'elle bouge pas)
int mx = rand.nextInt(2);
int my = rand.nextInt(2);
//et une direction a cette force au hazard
if(rand.nextBoolean())
mx = -mx;
if(rand.nextBoolean())
my = -my;
AgentParticule agent = new Particule(i.toString(),x, y,mx,my);
environment.grille[x][y] = agent;
agents.add(agent);
}
}
|
c05fc825-b11b-4b06-85d4-b032d97c51a0
| 8
|
public static void select(JoeTree tree, OutlineLayoutManager layout, int type) {
Node node = null;
Node youngestNode = null;
Node oldestNode = null;
switch(type) {
case UP:
youngestNode = tree.getYoungestInSelection();
node = youngestNode.prevSibling();
if (node == youngestNode) {return;}
break;
case DOWN:
oldestNode = tree.getOldestInSelection();
node = oldestNode.nextSibling();
if (node == oldestNode) {return;}
break;
case LEFT:
youngestNode = tree.getYoungestInSelection();
node = youngestNode.prevSibling();
if (node == youngestNode) {return;}
tree.removeNodeFromSelection(youngestNode);
break;
case RIGHT:
oldestNode = tree.getOldestInSelection();
node = oldestNode.nextSibling();
if (node == oldestNode) {return;}
tree.removeNodeFromSelection(oldestNode);
break;
default:
return;
}
tree.addNodeToSelection(node);
// Record the EditingNode and CursorPosition and ComponentFocus
tree.setEditingNode(node);
// Redraw and Set Focus
layout.draw(node,OutlineLayoutManager.ICON);
}
|
e4031842-3268-49e7-adde-448de8868f6b
| 7
|
public static void addTiles(Tile[][] tiles, int startX, int startY, String path, List<Tile> spawnPoints) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try {
InputStream is = classLoader.getResourceAsStream(path);
BufferedReader reader;
if(is == null) {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(path)), "ISO-8859-1"));
}else{
reader = new BufferedReader(new InputStreamReader(is));
}
//Read the width and height of the tileset
int w = Integer.parseInt(reader.readLine());
int h = Integer.parseInt(reader.readLine());
String data[][] = new String[h][w];//The position is mirrored in data[][] !!
String line;
int i = 0;
//Add all the data to an array
while ((line = reader.readLine()) != null) {
if(!line.substring(0, 2).equals("//")) {
data[i] = line.split(";");
i++;
}
}
//Iterate the array and add a tile for each position
for(int x = 0; x < data.length; x++) {
for(int y = 0; y < data[0].length; y++) {
Tile t = generateTile(y + startX, x + startY, data[x][y], spawnPoints); //The position is mirrored in data[][]
if(t != null) {
tiles[y + startX][x + startY] = t;
}
}
}
reader.close();
} catch (IOException exc) {
System.out.println("Could not find " + path);
}
}
|
a3a34b3a-1aeb-48cc-8648-ab9173bd2241
| 7
|
private static double[] discreteAverage (double[] values, PricingVector pricing,
double awareness, double sensitivity)
{
// Initialize the auxiliary variables.
double temp = 0;
double sum = 0;
double overDiff = 0, overDiffTemp = 0;
int start, end;
double newPrice;
int durationCheapest = 0;
// Finding the cheapest window in the day.
ArrayList<Integer> cheapest = pricing.getCheapest();
for (Integer index: cheapest) {
int startCheapest = pricing.getPricings(index).getStartMinute();
int endCheapest = pricing.getPricings(index).getEndMinute();
durationCheapest += endCheapest - startCheapest;
}
double cheapestPrice =
pricing.getPricings(pricing.getCheapest().get(0)).getCurrentPrice();
// Moving from all the available vectors residual percentages to the
// cheapest one.
for (int i = 0; i < pricing.getPricings().size(); i++) {
if (cheapest.contains(i) == false) {
sum = 0;
overDiff = 0;
start = pricing.getPricings(i).getStartMinute();
end = pricing.getPricings(i).getEndMinute();
newPrice = pricing.getPricings(i).getCurrentPrice();
for (int j = start; j <= end; j++) {
temp = cheapestPrice * values[j] / newPrice;
overDiffTemp = (values[j] - temp) * awareness * sensitivity;
overDiff += overDiffTemp;
values[j] -= overDiffTemp;
}
double additive = overDiff / durationCheapest;
for (Integer index: cheapest) {
int startCheapest = pricing.getPricings(index).getStartMinute();
int endCheapest = pricing.getPricings(index).getEndMinute();
for (int j = startCheapest; j <= endCheapest; j++)
values[j] += additive;
}
for (int j = 0; j < values.length; j++)
sum += values[j];
System.out.println("Summary after index " + i + ": " + sum);
}
}
return values;
}
|
531c1ec2-bff9-4aaf-aa74-66e7cfd02c69
| 2
|
public List<CreditProgram> getActivePrograms() {
//Создаем результирующий список
List<CreditProgram> resultList = new ArrayList<CreditProgram>();
try {
//Создаем запрос к БД
Statement statement = getConnection().createStatement();
ResultSet result = statement.executeQuery(activeQuery);
while (result.next()) {
resultList.add(fetchObject(result));
}
} catch (SQLException exc) {
JOptionPane.showMessageDialog(null, "Ошибка при создании запроса");
}
return resultList;
}
|
a650731f-fae9-421e-b81f-5f60392d0ec7
| 6
|
private void triangulate(int[] sides) {
boolean[] discard = new boolean[sides.length];
int index = 0;
for (int i = 0; i < sides.length - 2; i++) {
int[] tri = new int[3];
for (int j = 0; j < 3; j++) {
if (index < sides.length) {
if (!discard[index]) {
tri[j] = sides[index];
} else {
j--;
}
if (j == 1)
discard[index] = true;
if (j != 2)
index++;
} else {
index = 0;
j--;
}
}
indices.put(tri);
}
}
|
47d14930-1e80-41dd-b3bc-1801f793f486
| 7
|
public void readDirectory(File currentDir){
if(currentDir == null || currentDir.isHidden()){
return;
}
if(fileExtension == null){
fileExtension = "";
}
if (currentDir.isFile() && (currentDir.getName().endsWith(fileExtension))) {
readFile(currentDir);
}
if (currentDir.isDirectory()) {
File[] files = currentDir.listFiles();
for (int i = 0; i < files.length; i++) {
readDirectory(files[i]);
}
}
}
|
56209984-1d0b-4c50-8261-6ea0975bd5d8
| 9
|
private void drawData() {
worker.setAntiAliasing(gdef.antiAliasing);
worker.clip(im.xorigin, im.yorigin - gdef.height - 1, gdef.width, gdef.height + 2);
double[] x = xtr(dproc.getTimestamps());
double[] lastY = null;
double[] bottomY = null;
for (Map.Entry<PlotElement, Integer> entry : gdef.plotElements.entrySet())
{
PlotElement pe = entry.getKey();
int axis = entry.getValue();
AxisImageParameters aim = im.axisImageParams[axis];
double areazero = mapper.ytr(axis, (aim.yminval > 0.0) ? aim.yminval : (aim.ymaxval < 0.0) ? aim.ymaxval : 0.0);
// draw line, area and stack
if (pe instanceof SourcedPlotElement) {
SourcedPlotElement source = (SourcedPlotElement) pe;
double[] y = ytr(axis, source.getValues());
if (source instanceof Line) {
worker.drawPolyline(x, y, source.color, ((Line) source).stroke);
}
else if (Area.class.isAssignableFrom(source.getClass())) {
if(source.parent == null) {
worker.fillPolygon(x, areazero, y, source.color);
}
else {
worker.fillPolygon(x, lastY, y, source.color);
worker.drawPolyline(x, lastY, source.getParentColor(), new BasicStroke(0));
}
}
else if (source instanceof Stack) {
Stack stack = (Stack) source;
float width = stack.getParentLineWidth();
if (width >= 0F) {
// line
worker.drawPolyline(x, y, stack.color, new BasicStroke(width));
}
else {
// area
bottomY = floor(areazero, lastY);
worker.fillPolygon(x, bottomY, y, stack.color);
worker.drawPolyline(x, lastY, stack.getParentColor(), new BasicStroke(0));
}
}
else {
// should not be here
throw new IllegalStateException("Unknown plot source: " + source.getClass().getName());
}
lastY = y;
}
}
worker.reset();
worker.setAntiAliasing(false);
}
|
56906cbe-8965-46bf-85c4-b292c666f659
| 6
|
public void getList(int rep) {
String tempQuery = "";
if(rep == 0) {
tempQuery = DEFAULT_QUERY;
}
else if(rep == 1) {
tempQuery = "";
}
Statement stmt = null;
this.connect();
conn = this.getConnection();
try {
stmt = conn.createStatement();
}
catch (SQLException e) {
e.printStackTrace();
}
ResultSet rs;
try
{
rs = stmt.executeQuery(tempQuery);
try {
tableUtils.updateTableModelData((DefaultTableModel) listGoods.getModel(), rs, 3);
}
catch (Exception ex) {
Logger.getLogger(ViewMember.class.getName()).log(Level.SEVERE, null, ex);
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
this.disconnect();
}
try {
listGoods.setRowSelectionInterval(0, 0);
}
catch(Exception e) { }
}
|
81850977-3b1a-4765-97aa-4531b9f66f3f
| 3
|
protected void setPieceDims()
{
int wmax = -1;
int hmax = -1;
for (int i = 0; i < body.length; i++)
{
if (body[i].x > wmax)
wmax = body[i].x;
if (body[i].y > hmax)
hmax = body[i].y;
}
width = wmax + 1;
height = hmax + 1;
}
|
be52cf39-da37-49c9-a2e2-017135581ea6
| 6
|
public boolean transferOwnership(String regionName, String newOwner, World world) {
// World world = Bukkit.getServer().getWorld("world");
ProtectedRegion target = _plugin.WORLDGUARD.getGlobalRegionManager().get(world).getRegion(regionName);
String currentOwner = getOwnerName(regionName, world);
boolean ret;
if(!_plugin.getDBConnector().isForSale(regionName)) {
_plugin.getDBConnector().removeForSale(regionName, world);
return false;
}
if(currentOwner.equals("FAILED_MULTI"))
return false;
if(accounts.chargeMoney(newOwner,getRegionPrice(regionName, world))) {
DefaultDomain newOwners = new DefaultDomain();
DefaultDomain curOwner = target.getOwners();
newOwners.addPlayer(newOwner);
target.setOwners(newOwners);
if(!currentOwner.equals("PUBLIC_DOMAIN")) {
if(accounts.addMoney(currentOwner, getRegionPrice(regionName, world))) {
ret = true;
target.setFlag(DefaultFlag.PRICE, null);
} else {
accounts.addMoney(newOwner,getRegionPrice(regionName, world));
target.setOwners(curOwner);
_plugin.WORLDGUARD.getGlobalRegionManager().get(world).removeRegion(regionName);
_plugin.WORLDGUARD.getGlobalRegionManager().get(world).addRegion(target);
ret = false;
}
}
target.setFlag(DefaultFlag.PRICE, null);
_plugin.WORLDGUARD.getGlobalRegionManager().get(world).removeRegion(regionName);
_plugin.WORLDGUARD.getGlobalRegionManager().get(world).addRegion(target);
updateLockette(regionName, newOwner, world);
try {
_plugin.WORLDGUARD.getGlobalRegionManager().get(world).save();
} catch (Exception e) {
System.out.println(e);
}
ret = true;
return ret;
}
return false;
}
|
76c04228-b1b5-4e94-8c15-e4670383a750
| 5
|
@Override
public UserVo getUser(String email, String password) {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try{
con = dataSource.getConnection();
stmt = con.prepareStatement(
"select UNO, EMAIL, PWD, NAME, TEL"
+ " from SE_USERS"
+ " where EMAIL=? and PWD=?");
stmt.setString(1, email);
stmt.setString(2, password);
rs = stmt.executeQuery();
if (rs.next()) {
return new UserVo()
.setNo(rs.getInt("UNO"))
.setEmail(rs.getString("EMAIL"))
.setPassword(rs.getString("PWD"))
.setName(rs.getString("NAME"))
.setTel(rs.getString("TEL"));
} else {
throw new Exception("아이디와 암호가 일치하는 사용자가 없습니다.");
}
}catch(Throwable e){
throw new DaoException(e);
}finally{
try{rs.close();}catch(Throwable e){}
try{stmt.close();}catch(Throwable e){}
try{con.close();}catch(Throwable e){}
}
}
|
20a82ae8-12a3-47e5-b291-2f7fb18c5a50
| 0
|
public boolean isInitialized() {
return this.initialized;
}
|
a6bc0e8e-5c97-4c46-bd3d-226d984cae12
| 3
|
@Test
public void findsShortestPath3()
{
Tree<Vertex> vertices = new Tree<>(new VertexComparator());
Vertex v1 = new Vertex(0,0);
Vertex v2 = new Vertex(1,0);
Vertex v3 = new Vertex(1,1);
Vertex v4 = new Vertex(2,1);
Vertex v5 = new Vertex(2,2);
Vertex v6 = new Vertex(0,3);
vertices.add(v1);
vertices.add(v2);
vertices.add(v3);
vertices.add(v4);
vertices.add(v5);
vertices.add(v6);
v1.addAdjacent(v2);
v2.addAdjacent(v3);
v3.addAdjacent(v4);
v4.addAdjacent(v5);
v1.addAdjacent(v6);
v6.addAdjacent(v5);
TreeMap<Vertex, Vertex> paths = Dijkstra.getShortestPaths(v1, v5, vertices.toLinkedList());
assertTrue(paths.get(v5) == v4 && paths.get(v4) == v3 && paths.get(v3) == v2 && paths.get(v2) == v1);
}
|
909e7d84-446b-4748-90c9-e743f6209940
| 9
|
private boolean jj_scan_token(int kind) {
if (jj_scanpos == jj_lastpos) {
jj_la--;
if (jj_scanpos.next == null) {
jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken();
} else {
jj_lastpos = jj_scanpos = jj_scanpos.next;
}
} else {
jj_scanpos = jj_scanpos.next;
}
if (jj_rescan) {
int i = 0; Token tok = token;
while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; }
if (tok != null) jj_add_error_token(kind, i);
}
if (jj_scanpos.kind != kind) return true;
if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls;
return false;
}
|
6a6fdf32-209e-4eda-b5a2-d7966e429a9e
| 6
|
@Override
public void paintComponent(Graphics g){ //de paintComponent die alle Blokken in de blokken-HashMap op de juiste plaats zal painten
super.paintComponent(g);
int breedte = Constanten.BLOKGROOTTE;
int hoogte = Constanten.BLOKGROOTTE;
for(Positie pos : blokken.keySet()){
Image img = blokken.get(pos).getAfbeelding().getImage();
if(!forceerBlokGrootte){
breedte = img.getWidth(this);
hoogte = img.getHeight(this);
}
int x = pos.getX() * Constanten.BLOKGROOTTE + offsetX;
int y = (this.getHeight() - (pos.getY() * Constanten.BLOKGROOTTE + offsetY)) - Constanten.BLOKGROOTTE;
if(herhaalX) x = x % (this.getWidth() + Constanten.BLOKGROOTTE) + (x<0 ? this.getWidth() + Constanten.BLOKGROOTTE : 0) - Constanten.BLOKGROOTTE;
if(herhaalY) y = y % (this.getHeight() + Constanten.BLOKGROOTTE) + (y<0 ? this.getHeight() + Constanten.BLOKGROOTTE : 0) - Constanten.BLOKGROOTTE;
g.drawImage(img, x, y, breedte, hoogte, this);
}
}
|
eaa65c83-c2b1-45a7-84cd-5605361ac9bc
| 7
|
protected Color parseRGBColor(String str) {
if (RGB_COLOR.matcher(str).find())
return parseRGBA(str);
if (RGBA_COLOR.matcher(str).find())
return parseRGBA(str);
if (str.startsWith("0x")) {
try {
return new Color(Integer.valueOf(str.substring(2), 16));
}
catch (NumberFormatException e) {
out(ScriptEvent.FAILED, str + " cannot be parsed as color.");
return null;
}
}
if (str.startsWith("#")) {
try {
return new Color(Integer.valueOf(str.substring(1), 16));
}
catch (NumberFormatException e) {
out(ScriptEvent.FAILED, str + " cannot be parsed as color.");
return null;
}
}
Color c = parseRGBA(str);
if (c == null)
out(ScriptEvent.FAILED, str + " cannot be parsed as color.");
return c;
}
|
9a97be89-6cf7-4514-9b5f-72601e700802
| 0
|
public void executionFinished() {
executionFinished = true;
}
|
55e3adff-099d-47a4-84d5-04cf67ae903c
| 5
|
public String[] getImageLinks(String Make, String Model) {
String searchText = Make + " " + Model;
searchText = searchText.replaceAll(" ", "+");
String[] links = new String[1];
String key="AIzaSyDUmEpoEHSYB-pBKrM_slE2KmTyX_LJGwk";
String cx = "004334298273927197431:bennqbfbvec";
URL url;
try {
url = new URL(
"https://www.googleapis.com/customsearch/v1?key="+key+ "&cx="+ cx +"&q="+ searchText + "&searchType=image" + "&alt=json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br =
new BufferedReader(new InputStreamReader( (conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null)
{
for (int i = 0; i < 1; i++) {
if(output.contains("\"link\": \"")) {
links[i]=output.substring(output.indexOf("\"link\": \"")+
("\"link\": \"").length(), output.indexOf("\","));
System.out.println(links[i]); //Will print the google search links
}
}
}
conn.disconnect();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return links;
}
|
440f8684-52a8-4f87-91d6-8d8f86e540c1
| 3
|
public String getNewVariableWithLambdaProduction(Grammar grammar,
Set lambdaSet) {
String[] variables = grammar.getVariables();
for (int k = 0; k < variables.length; k++) {
if (!lambdaSet.contains(variables[k])
&& isVariableWithLambdaProduction(variables[k], grammar)) {
return variables[k];
}
}
return null;
}
|
69d0bca6-9ce4-4aed-a435-fbb3a821965e
| 4
|
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
switch(columnIndex){
case 0:
return list.get(rowIndex).getOutputSpEmployeeTargetPK().getSzYear();
case 1:
return list.get(rowIndex).getOutputSpEmployeeTargetPK().getSzMonth();
case 2:
return list.get(rowIndex).getIntWorkingDay();
case 3:
return list.get(rowIndex).getSzWorkPlaceId();
default:
return null;
}
}
|
e6f446f4-3eec-4045-bb9e-382e54180ba7
| 7
|
public ArrayList<String> cbProjetos() throws SQLException {
ArrayList<String> Projeto = new ArrayList<>();
Connection conexao = null;
PreparedStatement comando = null;
ResultSet resultado = null;
try {
conexao = BancoDadosUtil.getConnection();
comando = conexao.prepareStatement(SQL_SELECT_TODOS_PROJETOS);
/// comando.setString(1, codDepartamento);
resultado = comando.executeQuery();
Projeto.removeAll(Projeto);
while (resultado.next()) {
Projeto.add(resultado.getString("NOME"));
}
conexao.commit();
} catch (Exception e) {
if (conexao != null) {
conexao.rollback();
}
throw new RuntimeException(e);
} finally {
if (comando != null && !comando.isClosed()) {
comando.close();
}
if (conexao != null && !conexao.isClosed()) {
conexao.close();
}
}
return Projeto;
}
|
98434c9b-8441-4e41-a929-a0389bf4c3fc
| 9
|
@Override
public void build() {
if (eastLonBound <= westLonBound) {
throw new ExceptionInvalidParam("East bound <= West bound");
}
if (northLatBound <= southLatBound) {
throw new ExceptionInvalidParam("North bound <= South bound");
}
if (destWidth <= 0) {
throw new ExceptionInvalidParam("Destination width <= 0");
}
if (destHeight <= 0) {
throw new ExceptionInvalidParam("Destination height <= 0");
}
if (sourceModule == null) {
throw new ExceptionInvalidParam("Source module not defined");
}
if (destNoiseMap == null) {
throw new ExceptionInvalidParam("Destination noise map not defined");
}
// Resize the destination noise map so that it can store the new output
// values from the source model.
destNoiseMap.setSize(destWidth, destHeight);
// Create the plane model.
Sphere sphereModel = new Sphere();
sphereModel.setModule(sourceModule);
double lonExtent = eastLonBound - westLonBound;
double latExtent = northLatBound - southLatBound;
double xDelta = lonExtent / (double) destWidth;
double yDelta = latExtent / (double) destHeight;
double curLon = westLonBound;
double curLat = southLatBound;
// Fill every point in the noise map with the output values from the model.
ArrayPointer.NativeFloatPrim pDest = destNoiseMap.getSlabPtr(0);
for (int y = 0; y < destHeight; y++) {
curLon = westLonBound;
for (int x = 0; x < destWidth; x++) {
float curValue = (float) sphereModel.getValue(curLat, curLon);
pDest.floatAssignThenIncrementPosition(curValue);
curLon += xDelta;
}
curLat += yDelta;
if (callback != null) {
callback.callback(y);
}
}
}
|
d167441e-bd98-4def-b5f1-964380cadd19
| 6
|
public void printOut(){
File file=new File(name);
PrintWriter myout;
try{
myout=new PrintWriter(new FileOutputStream(file));
myout.println("<mapfile bitmap=\""+mygraph.getImageName()+"\" scale-feet-per-pixel=\""+mygraph.getScale()+"\">");
for(int i=0;i<mygraph.getCurr();i++){
myout.println("<location id=\""+mygraph.locations[i].getID()
+"\" name=\""+mygraph.locations[i].getName()
+"\" x=\""+(int)mygraph.locations[i].getPoint().getX()
+"\" y=\""+(int)mygraph.locations[i].getPoint().getY()+"\" />");
}
for(int i=0;i<mygraph.getCurr();i++){
for(int j=i;j<mygraph.getCurr();j++){
if(mygraph.adjacent[i][j]){
myout.println("<path idfrom=\""+i+"\" idto=\""+j+"\" type=\"undirected\">");
}
}
}
myout.println("</mapfile>");
if(myout!=null){
myout.close();
}
}
catch(FileNotFoundException e){
System.out.println("File "+file.getName()+" not found!");
}
}
|
181231f7-afe9-4dd0-8f72-c8a08aea948e
| 3
|
protected TreeNode<K, D> predecessor(TreeNode<K, D> node) {
if (!isNil(node.getLeftChild())) {
return getMaxNode(node.getLeftChild());
}
TreeNode<K, D> parent = node.getParent();
while (!isNil(parent) && node == parent.getLeftChild()) {
node = parent;
parent = node.getParent();
}
return parent;
}
|
c31759d0-1e29-40d4-a242-671d9302a0fc
| 1
|
public void addGraph(final Graph graph) {
if (graph == null) {
throw new IllegalArgumentException("Graph cannot be null");
}
graphs.add(graph);
}
|
a2fd8883-b7a6-46c5-bc1a-503a13d60db8
| 9
|
private BandCholesky decompose(AbstractBandMatrix A) {
if (n != A.numRows())
throw new IllegalArgumentException("n != A.numRows()");
if (upper && A.ku != kd)
throw new IllegalArgumentException("A.ku != kd");
if (!upper && A.kl != kd)
throw new IllegalArgumentException("A.kl != kd");
notspd = false;
intW info = new intW(0);
if (upper)
LAPACK.getInstance().dpbtrf(UpLo.Upper.netlib(), n, kd, A.getData(),
Matrices.ld(kd + 1), info);
else
LAPACK.getInstance().dpbtrf(UpLo.Lower.netlib(), n, kd, A.getData(),
Matrices.ld(kd + 1), info);
if (info.val > 0)
notspd = true;
else if (info.val < 0)
throw new IllegalArgumentException();
if (upper)
Cu.set(A);
else
Cl.set(A);
return this;
}
|
38212f8c-10a3-4cf5-aa43-15af0ac917cc
| 9
|
public static double swap(TailContainer<Plane> sol, double temperature) {
for (Plane pi : sol.getRecords()) {
for (Plane pj : sol.getRecords()) {
if (pi != pj){
for (int i = 0; i < pi.getSchedule().size(); i++) {
for (int j = 1; j < pj.getSchedule().size(); j++) {
// Are these two swapable at this point?
if (pi.compareTo(pj, i, j)) {
// Try swap them and validate the result
// to see how it goes.
ArrayList<Flight> li = new ArrayList<Flight>(pi.getSchedule().subList(0, i));
li.addAll(pj.getSchedule().subList(j, pj.getSchedule().size()));
ArrayList<Flight> lj = new ArrayList<Flight>(pj.getSchedule().subList(0, j));
lj.addAll(pi.getSchedule().subList(i, pi.getSchedule().size()));
// FIXME: is swap always a one-way operation?
// or is the algorithm actually doing them both?
if(validateSchedule(li) && validateSchedule(lj)){
// This swap was approved.
// Calculate cost. If i not better, randomly accept it
double cost = pi.getCost() + pj.getCost();
Plane piTemp = new Plane(pi, li);
Plane pjTemp = new Plane(pi, li);
double newCost = piTemp.getCost() + pjTemp.getCost();
// The temperature value depends on the
// progression of the algorithm.
Random r = new Random();
// Probability of accepting new_sol. p is directly
// proportional to the value of t and inversely proportional
// to the value of the ratio cost/new_cost, thus:
// new_cost < cost => p > 100%
double p = probability(temperature, cost, newCost);
if (p > r.nextDouble()){
// accept solution
System.out.println("New Solution with cost " + newCost + "§");
System.out.println("Probability: " + p);
pi.setSchedule(li);
pj.setSchedule(lj);
pi = piTemp;
pj = pjTemp;
cost = newCost;
return cost;
}
}
}
}
}
}
}
}
return -1.0;
}
|
fba7a0c7-7349-43d0-8599-100c3be0be5f
| 1
|
public void update(double percent) {
if (percent > 1) {
dispose();
return;
}
message.setText(loadingMessage + Math.round(percent * 100) + " %");
Stage st = (Stage) scene.getWindow();
st.setTitle("Loading..." + Math.floor(percent * 100));
}
|
b4e23d3b-e213-4b1b-80a2-5d19e151e62e
| 0
|
public ChatMessage(String authorId, String message) {
this.authorId = authorId;
this.message = message;
time = new Date();
}
|
541bed02-deb3-40f8-af49-ef12d5e49547
| 7
|
public void stopAllRunningModels() {
if (map.isEmpty())
return;
synchronized (map) {
for (ModelCanvas mc : map.values()) {
if (mc.getMdContainer() instanceof AtomContainer) {
if (((AtomContainer) mc.getMdContainer()).hasDNAScroller())
((AtomContainer) mc.getMdContainer()).stopDNAAnimation();
}
Model model = mc.getMdContainer().getModel();
model.haltScriptExecution();
if (model.getJob() != null) {
if (!model.getJob().isStopped()) {
if (model instanceof MDModel) {
((MDModel) model).stopImmediately();
}
else {
model.stop();
}
}
}
}
}
}
|
5a23ea1e-a34a-4e21-9005-2ebc6a071847
| 2
|
public double getDouble(String key) throws JSONException {
Object o = get(key);
try {
return o instanceof Number ?
((Number)o).doubleValue() :
Double.valueOf((String)o).doubleValue();
} catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key) +
"] is not a number.");
}
}
|
7d728246-9337-40e8-b9b6-1325d0b027b9
| 8
|
public void find(int mode, String searchby, Object keyfield, String keyword, int sort) {
String searchstring = searchby + "Search=" + convert(keyword) +
"&mode=" + MODES[mode] + "&type=lite" +
((sort == -1) ? "" : ("&sort=" + getSort(MODES[mode])[sort]));
// add the new keyword to the list
boolean cacheditem = false; int n = getCount(keyfield);
if (keyword.length() > 0) {
for (int i = n - 1; i >= 0; i--) {
String choicetext = getString(getItem(keyfield, i), "text");
if (keyword.equals(choicetext)) { cacheditem = true; break; }
}
if (!cacheditem) {
Object choice = create("choice");
setString(choice, "text", keyword);
add(keyfield, choice);
if (n > 8) { remove(getItem(keyfield, 0)); }
}
}
Object nProductInfo = getResponse(searchstring + "&page=1");
if (!isErrorMessage(nProductInfo)) {
try {
Object result = parse("result.xml");
Object nextresult = find(result, "nextresult");
putProperty(nextresult, "SearchString", searchstring);
loadList(nProductInfo, 1, find(result, "resultlist"), find(result, "total"), nextresult);
addPage(result);
} catch (Exception exc) { exc.printStackTrace(); }
}
}
|
6aaa0239-8192-4c2f-b197-fdadc3d9bc8b
| 8
|
public void debugDisplay(String val) {
if (isVisible()) {
__debug = true;
parentRepaint();
getFather().hideToolTip(__tooltip);
if (val != null && val.length() > 0) {
if (val.length() > 10) {
val = val.substring(0, 7) + "...";
}
OVNode n = getOutNode();
if (n != null && n.visible()) {
Point p = new Point(n.getLocation());
if (!n.getParent().equals(getFather())) {
p.x += n.getParent().getX();
p.y += n.getParent().getY();
}
__tooltip = getFather().showToolTip(val, p,
OrientationEnum.RIGHT);
}
}
if (__timer != null) {
__timer.cancel();
__timer.purge();
}
__timer = new Timer();
__timer.schedule(new TimerTask() {
@Override
public void run() {
__debug = false;
getFather().hideToolTip(__tooltip);
__tooltip = null;
parentRepaint();
}
}, 1000);
}
}
|
3f11ab0a-3d75-47a1-b124-691944904d53
| 4
|
public boolean accept(File f) {
if (f.isDirectory())
return true;
String fname = f.getName();
int lastSlash = fname.lastIndexOf(".");
if (lastSlash < 0)
return false;
String extension = fname.substring(lastSlash + 1);
if (extension != null) {
if (extension.equalsIgnoreCase("json")) {
return true;
} else {
return false;
}
}
return false;
}
|
6236a100-f5c8-421e-97e7-6c2617f3195d
| 4
|
@SuppressWarnings("unchecked")
private void tuesdayCheckActionPerformed(java.awt.event.ActionEvent evt) {
if(this.dayChecks[2].isSelected()) {
this.numSelected++;
if(this.firstSelection) {
stretch();
}
this.models[2] = new DefaultListModel<Object>();
this.tuesdayJobList.setModel(this.models[2]);
this.tuesdayScrollPane.setViewportView(this.tuesdayJobList);
this.tuesdayJobName.setColumns(20);
this.tuesdayLabel.setText("Job Name:");
this.tuesdayAddJob.setText("Add Job");
this.tuesdayAddJob.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
if(!Config.this.tuesdayJobName.getText().isEmpty()) {
Config.this.models[2].addElement(Config.this.tuesdayJobName.getText());
Config.this.tuesdayJobList.setModel(Config.this.models[2]);
Config.this.tuesdayJobName.setText("");
}
}
});
this.tuesdayDeleteJob.setText("Delete Job");
this.tuesdayDeleteJob.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
while(!Config.this.tuesdayJobList.isSelectionEmpty()) {
int n = Config.this.tuesdayJobList.getSelectedIndex();
Config.this.models[2].remove(n);
}
}
});
javax.swing.GroupLayout tuesdayTabLayout = new javax.swing.GroupLayout(this.tuesdayTab);
this.tuesdayTab.setLayout(tuesdayTabLayout);
tuesdayTabLayout.setHorizontalGroup(
tuesdayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(tuesdayTabLayout.createSequentialGroup()
.addContainerGap()
.addComponent(this.tuesdayScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(tuesdayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(tuesdayTabLayout.createSequentialGroup()
.addComponent(this.tuesdayLabel)
.addGroup(tuesdayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(tuesdayTabLayout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(this.tuesdayAddJob))
.addGroup(tuesdayTabLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(this.tuesdayJobName, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addComponent(this.tuesdayDeleteJob))
.addContainerGap(431, Short.MAX_VALUE))
);
tuesdayTabLayout.setVerticalGroup(
tuesdayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(tuesdayTabLayout.createSequentialGroup()
.addContainerGap()
.addGroup(tuesdayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(tuesdayTabLayout.createSequentialGroup()
.addGroup(tuesdayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(this.tuesdayJobName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(this.tuesdayLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(this.tuesdayAddJob)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(this.tuesdayDeleteJob))
.addComponent(this.tuesdayScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(25, Short.MAX_VALUE))
);
this.dayTabs.addTab("Tuesday", this.tuesdayTab);
} else {
this.numSelected--;
stretch();
this.dayTabs.remove(this.tuesdayTab);
}
}
|
eba8369c-4b8b-4d4f-b677-4df274d2f879
| 0
|
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
this.setVisible(false);
}//GEN-LAST:event_jButton1ActionPerformed
|
33f75a2a-3042-4ffd-8b58-c7414b204b97
| 9
|
private double[] refactorDistApart(double[] distApart, double threshold) {
for (int i = 0; i < window; i++) {
distApart[i] = threshold;
}
for (int i = distApart.length - window; i < distApart.length; i++) {
distApart[i] = threshold;
}
for (int i = 0; i < distApart.length; i++) {
// Find only the local minimum
if (distApart[i] < threshold) {
int startIndex = i;
double localMinimum = Double.POSITIVE_INFINITY;
int localMinimumIndex = i;
while (i < distApart.length - window && distApart[i] < threshold) {
if (distApart[i] < localMinimum) {
localMinimum = distApart[i];
localMinimumIndex = i;
}
i++;
}
for (int k = startIndex; k < i; k++) {
if (k != localMinimumIndex)
distApart[k] = threshold;
}
}
}
return distApart;
}
|
3033915e-8997-4913-872a-59d5e7eb840c
| 6
|
public static void openUserProfile(User user)
{
if(user == null)
return;
final Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if(desktop != null && desktop.isSupported(Desktop.Action.BROWSE))
try
{
if(user.getUsername().equalsIgnoreCase(""))
return;
desktop.browse(new URL("https://osu.ppy.sh/u/" + user.getUserID()).toURI());
}
catch(final Exception e)
{
e.printStackTrace();
}
}
|
f01cb5bc-d70b-4d3e-9b08-c2ecbb3a25c1
| 8
|
TupleNode parseTuple(SeekableStringReader sr)
{
//tuple = tuple_empty | tuple_one | tuple_more
//tuple_empty = '()' .
//tuple_one = '(' expr ',' <whitespace> ')' .
//tuple_more = '(' expr_list trailing_comma ')' .
// trailing_comma = '' | ',' .
sr.read(); // (
sr.skipWhitespace();
TupleNode tuple = new TupleNode();
if(sr.peek() == ')')
{
sr.read();
return tuple; // empty tuple
}
INode firstelement = parseExpr(sr);
if(sr.peek() == ',')
{
sr.read();
sr.skipWhitespace();
if(sr.read() == ')')
{
// tuple with just a single element
tuple.elements.add(firstelement);
return tuple;
}
sr.rewind(1); // undo the thing that wasn't a )
}
tuple.elements = parseExprList(sr);
tuple.elements.add(0, firstelement);
// handle trailing comma if present
sr.skipWhitespace();
if(!sr.hasMore())
throw new ParseException("missing ')'");
if(sr.peek() == ',')
sr.read();
if(!sr.hasMore())
throw new ParseException("missing ')'");
char closechar = sr.read();
if(closechar==',')
closechar = sr.read();
if(closechar!=')')
throw new ParseException("expected ')'");
return tuple;
}
|
1e103e48-f189-4691-8484-8395d7c48eac
| 2
|
public int compareTo(Piece other) {
if (this == other) {
return 0;
}
if (this.seen < other.seen) {
return -1;
} else {
return 1;
}
}
|
c89e6ad1-39c0-430a-8441-801d6883bbb5
| 2
|
@Override
public int uniqueWordsCount() {
int count = 0;
for(Map.Entry<String, Integer> entry : storage.entrySet()) {
if(entry.getValue() == 1) {
count ++;
}
}
return count;
}
|
7979c066-4ccf-469a-af1d-425d5d23db78
| 6
|
public void aimEnemy() {
int x = Math.abs(me.getX() - nearestEnemy.getX());
int y = Math.abs(me.getY() - nearestEnemy.getY());
double result = Math.toDegrees(Math.atan((double)y / (double)x));
if(nearestEnemy.getX() <= me.getX() && nearestEnemy.getY() <= me.getY()) {
result = 180 + result;
}
else if(nearestEnemy.getX() <= me.getX() && nearestEnemy.getY() >= me.getY()){
result = 180 - result;
}
else if(nearestEnemy.getX() >= me.getX() && nearestEnemy.getY() <= me.getY()){
result = 360 - result ;
}
result += 0.5;
targetRtation = (int)(me.getDirection() - result);
}
|
07182d68-6b74-460a-8c0c-4c7b4be2b97d
| 1
|
public void sendChat(String message) {
try {
byte[] sendBuffer = ("type:chat\nmsg:" + message + "\n").getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, ip, port);
sock.send(sendPacket);
} catch (Exception e) {
}
}
|
737754b6-1e2b-44d3-af01-9f5fb3fe3f16
| 5
|
@Override
public ByteBuffer getData() {
int dataOffset = 0; // TODO
ByteBuffer buffer = ByteBuffer.allocate(100); // TODO
if (name != null) {
buffer.putInt(dataOffset | 0x80000000);
int stringoffset = dataOffset;
ByteBuffer strbuf = ByteBuffer.allocate(name.length() * 2 + 2);
strbuf.order(ByteOrder.LITTLE_ENDIAN);
strbuf.putShort((short) name.length());
for (int i = 0; i < name.length(); i++) {
strbuf.putShort((short) name.charAt(i));
}
strbuf.position(0);
long oldpos = buffer.position();
buffer.position(dataOffset);
buffer.put(strbuf);
dataOffset += name.length() * 2 + 2;
if ((dataOffset % 4) != 0) {
dataOffset += 4 - (dataOffset % 4);
}
buffer.position((int) oldpos);
} else {
buffer.putInt(nameOrId);
}
if (directory != null) {
buffer.putInt(dataOffset | 0x80000000);
int oldpos = buffer.position();
buffer.position(dataOffset);
// todo int dirsize = directory.buildBuffer(buffer, virtualBaseOffset);
// dataOffset = dirsize;
buffer.position(oldpos);
} else if (data != null) {
buffer.putInt(dataOffset);
int oldpos = buffer.position();
buffer.position(dataOffset);
/* todo dataOffset = data.buildBuffer(buffer, virtualBaseOffset,
dataOffset);*/
buffer.position(oldpos);
} else {
throw new RuntimeException("Directory and Data are both null!");
}
return buffer;
}
|
c5bd2da1-68e3-4695-bbf2-1b1db8fdf87b
| 4
|
public void draw(Vector2f camera, Vector2f pos, PlayerState ps){
float tempX = pos.getX();
float tempY = pos.getY();
tempX = TileUtil.toIsoX(pos.getX(), pos.getY()) + camera.getX() - 32;
tempY = TileUtil.toIsoY(pos.getX(), pos.getY()) + camera.getY() - 57;
switch (ps){
case WALK_DOWN:
case WALK_LEFT:
case WALK_RIGHT:
case WALK_UP:
shadowWalk.draw(tempX, tempY);
break;
default:
shadowStand.draw(tempX, tempY);
break;
}
}
|
c4d93cf3-8214-4d18-b6d8-1cbd25d03763
| 2
|
public void doSearch() {
for (int i = 0; i < mThreadNum; i++) {
new Thread(new Runnable() {
@Override
public void run() {
while (true){
mListener.parseH5();
}
}
}).start();
}
}
|
b96321bb-06bf-4c5d-b35c-6ae675e819a2
| 6
|
@Override
public Map<TKey<?, ?>, List<Class<? extends Enum<?>>>> getRelationTargets(TKey<?, ?> key) {
return validRelations.get(key);
}
|
91de4a6a-8c23-4ce5-84a0-7500fba91d23
| 3
|
public int[] bubbleSort(int[] pZahlen) {
for (int i = 0; i < pZahlen.length; i++) {
for (int j = 0; j < pZahlen.length - 1; j++) {
if (pZahlen[j] > pZahlen[j + 1]) {
int lBuffer = pZahlen[j];
pZahlen[j] = pZahlen[j + 1];
pZahlen[j + 1] = lBuffer;
}
}
}
return pZahlen;
}
|
e7d586a3-672c-40af-ba1b-24da2b11c463
| 0
|
@Override
public void setLoggerName(String loggerName) {
this.loggerName = loggerName;
}
|
bcc44c7c-44c7-4557-a19e-e93e35f534a0
| 9
|
public void lineDetection() {
ArrayList<Integer> numbLigne = new ArrayList<Integer>();
int count = 0;
for(int i=0; i < tab.length; i++) {
count = 0;
for(int j=0; j < tab[0].length; j++) {
if(tab[i][j].getValue() != 0) {
count++;
}
if(count == 10) {
numbLigne.add(i);
}
}
}
if(numbLigne.size() > 0) {
for(int i=0; i < numbLigne.size(); i++) {
Integer ligne = numbLigne.get(i);
score+= (10 + (numbLigne.size()-1)*10);
for(int j=0; j < 10; j++) {
tab[ligne][j] = new Cellule(false, 0);
}
for(int u=ligne-1; u >= 0; u--) {
debug.out("Ligne n : " + u);
for(int v=0; v < 10; v++) {
tab[u+1][v] = tab[u][v];
}
}
}
}
}
|
1373ea58-5643-46c3-96e4-8966112017f8
| 4
|
public static SelectItem[] getSelectItems(List<?> entities, boolean selectOne) {
int size = selectOne ? entities.size() + 1 : entities.size();
SelectItem[] items = new SelectItem[size];
int i = 0;
if (selectOne) {
items[0] = new SelectItem("", "---");
i++;
}
for (Object x : entities) {
items[i++] = new SelectItem(x, x.toString());
}
return items;
}
|
20914b75-c744-495f-9ddb-c19e7f93e456
| 5
|
public void searchLogradouro() {
facesContext = FacesContext.getCurrentInstance();
requestContext = RequestContext.getCurrentInstance();
if (selectBtnSearchBairro == true && this.bairro.getCidade() != null) {
List<Logradouro> listLogradouro;
try {
logradouro.setLog_bairro_id(this.bairro);
listLogradouro = genericDAO.searchObject(Logradouro.class,"logradouro",
null, null,
new String[]{"log_bairro_id", "log_descricao"},
new Object[]{logradouro.getLog_bairro_id(), "%" + logradouro.getLog_descricao() + "%"});
selectBtnSearchLogradouro = true;
if (listLogradouro.isEmpty()) {
opcaoHeader = "cadastrar logradouro";
facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Logradouro não encontrado", "Cadastre-o para prosseguir!"));
requestContext.getCurrentInstance().execute("PF('cadastrarDialog').show();");
} else if (listLogradouro.size() == 1) {
facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Logradouro encontrado", "Prossiga o cadastro!"));
logradouro = listLogradouro.get(0);
} else {
facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Informe mais detalhes!", "Sua busca retornou muitos campos"));
}
} catch (Exception ex) {
Logger.getLogger(UnidadeMB.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Alterta!", "Verifique o Bairro primeiramente"));
}
}
|
faf11f00-de3a-4911-b009-06b4e1b71036
| 2
|
public int getAttackDamageBonus(Entity e) {
if (type == ToolType.axe) {
return (level + 1) * 2 + random.nextInt(4);
}
if (type == ToolType.sword) {
return (level + 1) * 3 + random.nextInt(2 + level * level * 2);
}
return 1;
}
|
b2df9a51-e96c-471c-b7b2-68f5f967b5cf
| 5
|
public static Moves getFightingMovesRound1(BotState state, int armiesForFighting) {
Moves out = new Moves();
List<Region> southAmericaBorderRegions = new ArrayList<>();
List<Region> australiaBorderRegions = new ArrayList<>();
SuperRegion australia = state.getVisibleMap().getSuperRegion(6);
SuperRegion southAmerica = state.getVisibleMap().getSuperRegion(2);
for (Region region : state.getVisibleMap().getOpponentBorderingRegions(state)) {
if (region.getSuperRegion().equals(australia)) {
australiaBorderRegions.add(region);
}
if (region.getSuperRegion().equals(southAmerica)) {
southAmericaBorderRegions.add(region);
}
}
if (australiaBorderRegions.size() > 0) {
PlaceArmiesMove placeArmiesMove = new PlaceArmiesMove(state.getMyPlayerName(),
australiaBorderRegions.get(0), armiesForFighting);
MovesPerformer.performDeployment(state, placeArmiesMove);
out.armyPlacementMoves.add(placeArmiesMove);
out.totalDeployment += armiesForFighting;
} else if (southAmericaBorderRegions.size() > 0) {
PlaceArmiesMove placeArmiesMove = new PlaceArmiesMove(state.getMyPlayerName(),
southAmericaBorderRegions.get(0), armiesForFighting);
MovesPerformer.performDeployment(state, placeArmiesMove);
out.armyPlacementMoves.add(placeArmiesMove);
out.totalDeployment += armiesForFighting;
} else {
out = FightingMovesChooser.getFightingMoves(state, armiesForFighting);
}
return out;
}
|
8d6c2b2f-ab43-4635-898c-837416aad626
| 4
|
@Override
public String toString()
{
if(ouder1 != null && ouder2 != null)
return this.ouder1.toString() + " & " + this.ouder2.toString();
else if(ouder1 != null)
return this.ouder1.toString();
else if (ouder2 != null)
return this.ouder2.toString();
else
return "Geen ouders bekend";
}
|
9318ad9a-1363-4ffc-af11-5ba29981225d
| 0
|
public UndoQueueEvent(Document doc, int type) {
setDocument(doc);
setType(type);
}
|
d2c0a7fb-c019-445f-8e05-4d6e37f5703b
| 3
|
public static void main(String[] args) throws InterruptedException {
ArrayList<Integer> list = new ArrayList<>();
ExecutorService executor = Executors.newCachedThreadPool();
Future<Integer> future;
for (int i = 1; i < 10; i++) {
future = executor.submit(new MyCallable(i));
try {
list.add(future.get());
} catch (ExecutionException ex) {
System.out.println(ex.getMessage());
}
}
executor.shutdown();
//this is ont necessary in this case .. but .. good practice :)
executor.awaitTermination(1, TimeUnit.DAYS);
for (int i = 0; i < list.size(); i++) {
//get returned values from call()
System.out.println("List Values " + i + " Value: " + list.get(i));
}
}
|
4368daec-2837-4fab-9bca-a900d4e3e360
| 8
|
public static boolean checkDataIntegrity(int gameVersion, byte[] data, int offset, int expectedNewOffset)
{
offset = 0;
try
{
offset += BLANK_MAX_LENGTH;
offset += DEFAULT_ODM_MAX_LENGTH;
if ((GameVersion.MM6 == gameVersion) || (GameVersion.MM7 == gameVersion))
{
offset += EDITOR_MAX_LENGTH_MM6;
}
else
{
offset += EDITOR_MAX_LENGTH_MM8;
offset += 1;
}
offset += SKY_BITMAP_MAX_LENGTH;
offset += GROUND_BITMAP_MAX_LENGTH;
offset += NUMBER_OF_TILE_SET_SELECTORS * TileSetSelector.getRecordSize();
if ((GameVersion.MM6 != gameVersion) && (GameVersion.MM7 != gameVersion))
{
offset += 4;
}
offset += MAP_HEIGHT * MAP_WIDTH;
offset += MAP_HEIGHT * MAP_WIDTH;
offset += MAP_HEIGHT * MAP_WIDTH;
if (GameVersion.MM6 != gameVersion)
{
int normalsCount = ByteConversions.getIntegerInByteArrayAtPosition(data, offset);
offset += 4;
offset += MAP_HEIGHT * MAP_WIDTH * 2 * 4;
offset += MAP_HEIGHT * MAP_WIDTH * 2 * 2;
offset += IntVertex.getRecordSize() * normalsCount;
}
offset = D3Object.computeDataSize(gameVersion, data, offset);
int spriteCount = ByteConversions.getIntegerInByteArrayAtPosition(data, offset);
offset += 4;
offset += spriteCount * Sprite.getRecordSize(gameVersion);
int unknownMapDataCount = ByteConversions.getIntegerInByteArrayAtPosition(data, offset);
offset += 4;
offset += unknownMapDataCount * 2 + (MAP_WIDTH * MAP_HEIGHT * 4);
int monsterCount = ByteConversions.getIntegerInByteArrayAtPosition(data, offset);
offset += 4;
offset += monsterCount * SpawnPoint.getRecordSize(gameVersion);
}
catch (ArrayIndexOutOfBoundsException exception)
{
new RuntimeException("Integrity check failed for game version=" + gameVersion + ".", exception).printStackTrace();
return false;
}
catch (DataSizeException exception)
{
new RuntimeException("Integrity check failed for game version=" + gameVersion + ".", exception).printStackTrace();
return false;
}
if (offset != expectedNewOffset)
{
new RuntimeException("Integrity check failed for game version=" + gameVersion + ": offset<" + offset + "> != expectedNewOffset<" + expectedNewOffset + ">").printStackTrace();
}
return (offset == expectedNewOffset);
}
|
f29144fa-685f-4d6a-8d04-4bf3d3cac556
| 9
|
public static void main(String[] args) {
int total = 0;
for (int i : primeSieve(1000000)) {
if (i < 10) {
continue;
}
if (isPrime(i)) {
boolean flag = true;
for (int j = 1; j < Integer.toString(i).length(); j++) {
if (!isPrime((int) Math.floor(i / Math.pow(10, j)))) {
flag = false;
break;
}
}
if (!flag) {
continue;
}
for (int j = Integer.toString(i).length(); j >= 1; j--) {
if (!isPrime((int) (i % Math.pow(10, j)))) {
flag = false;
break;
}
}
if (flag) {
total += i;
}
}
}
System.out.println(total);
}
|
22c4aeb2-1db7-4d2e-8200-113b2bc9e918
| 7
|
public void executeQuery(String supplierName) {
CachedRowSet coffees = null;
CachedRowSet suppliers = null;
JoinRowSet jrs = null;
try {
coffees = new CachedRowSetImpl();
coffees.setCommand("SELECT * FROM COFFEES");
coffees.execute(connection);
suppliers = new CachedRowSetImpl();
suppliers.setCommand("SELECT * FROM SUPPLIERS");
suppliers.execute(connection);
jrs = new JoinRowSetImpl();
jrs.addRowSet(coffees, "SUP_ID");
jrs.addRowSet(suppliers, "SUP_ID");
System.out.println("Coffees bought from " + supplierName + ": ");
while (jrs.next()) {
if (jrs.getString("SUP_NAME").equals(supplierName)) {
String coffeeName = jrs.getString(1);
System.out.println(" " + coffeeName);
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try{
if (jrs != null) { jrs.close(); }
if (suppliers != null) { suppliers.close(); }
if (coffees != null) { coffees.close(); }
}catch(SQLException ex){
ex.printStackTrace();
}
}
}
|
7953c9a4-d679-4a00-933e-2fe0a96e36fa
| 3
|
private void setDiceArray(FieldCircularList[] map) {
int index;
FieldCircularList[] diceArray;
for(int i = 0; i < map.length; i++) {
diceArray = new FieldCircularList[11];
for(int j = 0; j < diceArray.length; j++) {
index = i + 2 + j;
if(index >= map.length) {
index -= map.length;
}
diceArray[j] = map[index];
}
map[i].setDiceArray(diceArray);
}
}
|
1d52385c-9503-453f-ac0c-fb41f8446eaf
| 9
|
public String longestPalindrome(String s) {
// Start typing your Java solution below
// DO NOT write main() function
int maxi = 0;
int max = 0;
StringBuilder sb = new StringBuilder();
sb.append('\001');
for (int i = 0; i < s.length(); i++) {
sb.append(s.charAt(i));
sb.append('\001');
}
String ss = sb.toString();
int n = ss.length();
int[] res = new int[n];
int far = 0;
int index = 0;
for (int i = 1; i < n; i++) {
if (far > i) {
if (res[index * 2 - i] + i < far) {
res[i] = res[index * 2 - i];
continue;
}
}
int j = far + 1;
while (j < n && (i * 2 - j >= 0)
&& ss.charAt(j) == ss.charAt(i * 2 - j)) {
j++;
}
far = j - 1;
index = i;
res[i] = far - i;
if (max < res[i]) {
max = res[i];
maxi = i;
}
}
sb = new StringBuilder();
for (int i = maxi - max + 1; i <= maxi + max - 1; i += 2) {
sb.append(ss.charAt(i));
}
return sb.toString();
}
|
f26ce26e-d7e7-4b11-b219-7503eac95ce7
| 2
|
public int getDeathYear() {
return (death == null || death.getDate() == null) ? 0 : death.getDate().getYear();
}
|
c8059416-9ecb-427b-a6a1-9b914bb0781e
| 9
|
public void update(DeltaState deltaState) {
if (!this.getScene().getSystemPause() && this.getScene().getPlayState()) {
if (this.cantidadDeVidas <= 0) {
this.morir();
} else {
if (this.cantidadDeVidas < 7) {
intervaloDeAccion = 80;
}
this.getScene().bossMataBrosEnElCamino(this);
if (this.getScene().bossGolpeadoPorEsferaRodante(this)) {
this.cantidadDeVidas = cantidadDeVidas - 1;
Mob mob = this.getScene().esferaColisionadaConBoss(this);
mob.getScene().esferaExploto(mob);
// sonido explosion
Sound sonidoExplosion = new SoundBuilder().buildSound(this
.getClass().getClassLoader()
.getResourceAsStream("snowBallExplode.wav"));
sonidoExplosion.play();
Explosion explosion = new Explosion(mob.getX() - 15,
mob.getY() - 20);
mob.getScene().addComponent(explosion);
mob.destroy();
}
if (apareciendo) {
this.estado.update(deltaState);
if (this.getScene().tocoFondo(this)) {
this.setY(this.getDim().getHeight()
- this.getAppearance().getHeight());
this.getEstado().cambiarMovimiento(this);
apareciendo = false;
}
} else if (saltando) {
this.estado.update(deltaState);
this.direccion.moverBoss(this);
} else if (tiempoInactividad > 0) {
tiempoInactividad--;
} else {
this.comenzarAMoverse();
this.saltando = true;
}
}
}
}
|
8dc5b6c0-963d-485a-aa48-d6a1a0b24442
| 1
|
public static int gcd(int a, int b) {
if(b == 0) {
return a;
}
return gcd(b, a % b);
}
|
b09387de-d2c1-44a5-8fe3-3e68ce6e89bd
| 9
|
public static double[][] computeDistance(Artist[] artists,DatabaseConnector db){
int na=artists.length;
double[][] dist=new double[na][na];
double[][] var=new double[na][na];
String stringArtists="";
int p=0;
HashMap<String,Integer> artistMap=new HashMap<String,Integer>();
for(Artist a:artists){
if(p>0){stringArtists+=",";}
stringArtists+="\""+a.name+"\"";
artistMap.put(a.name, p);
p++;
}
String query="select t1.artist,t2.artist,t1.var+t2.var from artistcount t1 cross join artistcount t2\n";
query+="on t1.artist in ("+stringArtists+") and\n";
query+="t2.artist in ("+stringArtists+")\n";
query+="and t1.artist<t2.artist\n";
query+="order by t1.artist,t2.artist\n";
try {
ResultSet s=db.statement.executeQuery(query);
s.first();
for(int i=0;i<(na-1);i++){
for(int j=i+1;j<na;j++){
var[i][j]=s.getDouble(3);
var[j][i]=s.getDouble(3);
s.next();
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
query="select a1,a2,sum(g) as g,sum(l) as l,\n";
query+="sum(score1) as s1,sum(score2) as s2 from(\n";
query+="select t1.tag,t1.artist as a1,t2.artist as a2,\n";
query+="greatest(t1.count/t3.count,t2.count/t4.count) as g,\n";
query+="least(t1.count/t3.count,t2.count/t4.count) as l,\n";
query+="t1.count/t3.count as score1,\n";
query+="t2.count/t4.count as score2\n";
query+="from (select * from artisttags \n";
query+="where artist in ("+stringArtists+") and count>200\n";
query+=") as t1 join\n";
query+="(select * from artisttags where artist in ("+stringArtists+") and count>200) t2\n";
query+="on t1.tag=t2.tag and t1.artist<t2.artist\n";
query+="join artistcount t3 on t1.artist=t3.artist\n";
query+="join artistcount t4 on t2.artist=t4.artist) t\n";
query+="group by a1,a2\n";
;
try {
ResultSet s=db.statement.executeQuery(query);
s.first();
int i=0;
while(!s.isAfterLast()){
int a1=artistMap.get(s.getString(1));
int a2=artistMap.get(s.getString(2));
double x=s.getDouble(3)-s.getDouble(5)-s.getDouble(6);
double m=s.getDouble(4);
dist[a1][a2]=m/(2+x);
dist[a2][a1]=m/(2+x);
s.next();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=0;i<na;i++){
for(int j=0;j<na;j++){
dist[i][j]=1-dist[i][j];
}
}
return dist;
}
|
affb0764-5b75-4e08-84e6-acbf5d0410ec
| 7
|
public String build(List<Integer> list) {
for(Integer i : list) {
if (i > 0 && i <= 3) {
firstRow = buildRow(i, firstRow);
} else if (i > 3 && i <= 6) {
secondRow = buildRow(i-3, secondRow);
} else if (i > 6 && i <= 9) {
thirdRow = buildRow(i-6, thirdRow);
}
}
return firstRow + "\n---------\n"+ secondRow +"\n---------\n"+ thirdRow;
}
|
f2d78f17-565f-471c-a74c-7fd747260f3b
| 4
|
public ShopElement[] getShopListInfo(){
ShopElement[] finalList = new ShopElement[shopListArr.length];
//Since a SAX XML parser reads a file from the beginning to end,
//we need to sort the current shopList array in ascending order to read the XML file
//from the beginning.
if(isSorted) {
ShopElement[] tempList = new ShopElement[shopListArr.length];
//Sort the shopList in ascending order
String[] ascendingArray = Sort.sortArray((String[]) shopListArr.clone());
tempList = gasSAXManager.getShopListInfo(ascendingArray);
//After getting the information, it changes back the ascending array
//to the original shopList order. The original shopList array may
//have been sorted based on the shops' property value(price or distance).
for (int i=0; i< shopListArr.length; i++)
for (int j=0; j< ascendingArray.length; j++)
if (shopListArr[i].endsWith(ascendingArray[j])){
finalList[i] = tempList[j];
break;
}
}else{
finalList = gasSAXManager.getShopListInfo((String[]) shopListArr.clone());
}
return finalList;
}
|
d8f64ee0-f707-4075-b1a7-1597d666747b
| 8
|
public Job createJob(Element eElement) {
Job job = new Job(eElement.getAttribute("name"),eElement.getAttribute("description"));
if(eElement.hasChildNodes()){
NodeList list = eElement.getChildNodes();
for(int i = 0; i < list.getLength(); i++){
Node nNode = list.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE){
Element child = (Element) nNode;
if(child.getNodeName().equals("job")){
Job childjob = createJob(child);
job.addChild(childjob);
}
else if(child.getNodeName().equals("task")){
Task task = new Task(child.getAttribute("name"), child.getAttribute("description"), child.getAttribute("state"));
NodeList intervals = child.getChildNodes();
for(int j = 0; j < intervals.getLength(); j++){
Node interval = intervals.item(j);
if (interval.getNodeType() == Node.ELEMENT_NODE){
Element intvl = (Element) interval;
Interval newInterval = new Interval(intvl.getAttribute("start"),intvl.getAttribute("end"));
task.getIntervals().add(newInterval);
}
}
job.addChild(task);
}
else if(child.getNodeName().equals("action")){
Action action = new Action(child.getAttribute("name"), child.getAttribute("description"), child.getAttribute("state"));
job.addChild(action);
}
}
}
}
return job;
}
|
48617601-f99f-4e72-ad0e-dec06ff73f7b
| 5
|
public UncheckedBinding outbound(UncheckedBinding outBinding) {
UncheckedBinding inBinding = outBinding;
if (outBinding == null)
return null;
if (outBinding.getObj() == null) {
inBinding = new Binding<Timestamp>(Timestamp.class, null);
}
if (Time.class == outBinding.getType()) {
return inBinding;
}
if (outBinding.getType().equals(DateTime.class)) {
inBinding = new Binding<Timestamp>(Timestamp.class,
((DateTime) outBinding.getObj()).toTimestamp());
}
if (Date.class.isAssignableFrom(outBinding.getType())) {
inBinding = new Binding<Timestamp>(Timestamp.class, new Timestamp(
((Date) outBinding.getObj()).getTime()));
}
return inBinding;
}
|
b5476de8-fdb9-4a66-9b77-863470727a79
| 8
|
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
this.inputCounter -= delta;
Input input = gc.getInput();
mouse.x = input.getMouseX(); mouse.y = input.getMouseY();
boolean click = input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON);
if (inputCounter<0) {
//Deplacements
this.etatEditor = GestionClavier.gererClavier(input, coordCarte, etatEditor, map, sbg);
//Selection du block
switch (etatEditor) {
case EDITOR :
effetsCarteME.selection(mouse, click, map, coordCarte, selec);
break;
case BLOCKS :
etatEditor = listeBlocksME.selection(mouse, click, effetsCarteME, etatEditor, selec);
break;
case OBJETS :
etatEditor = listeObjetsME.selection(mouse, click, effetsCarteME, etatEditor, selec);
break;
}
//TODO Bof comme maj des coords ...
if (coordCarte.x > tailleMap.x || coordCarte.y < -tailleMap.x)
coordCarte.x = MathPerso.mod(coordCarte.x, tailleMap.x);
if (coordCarte.y > tailleMap.y || coordCarte.y < -tailleMap.y)
coordCarte.y = MathPerso.mod(coordCarte.y, tailleMap.y);
inputCounter = 70;
}
}
|
3e751c8a-7d28-449f-81be-5af753aa5419
| 2
|
public void start() {
conversation.start();
while (true) {
Message msg = conversation.getMessage();
ui.addMessage(msg);
if (playSound()) {
GoogleVoice v = voices.get(msg.bot);
v.read(msg.msg);
}
System.out.println(msg.bot + "> " + msg.msg);
}
}
|
cbc0f5e6-cad4-4b94-9ba8-ec47382ae27a
| 0
|
public double getMean(){
return mean;
}
|
d0a12870-8f38-4760-b764-be1111aa4d9a
| 5
|
@Override
public void print() throws AnimalException {
System.out.println("\tInformatii animal:");
if (this.getNumeAnimal() == null)
throw new AnimalException("Animal's name is invalid!");
if (this.getOrigine() == null)
throw new AnimalException("Country's name is invalid!");
if (numeRezervatie == null)
throw new AnimalException("Rezervation's name is invalid!");
System.out.println("Nume: " + this.getNumeAnimal());
String alivee = "";
if (isAlive() == true)
alivee = "da";
else
alivee = "nu";
System.out.println("Traieste: " + alivee);
System.out.println("Origine: " + this.getOrigine());
if (ifpet() == false)
System.out.println("Acest animal poate fi gasit in rezervatia "
+ getNumeRezervatie());
}
|
e0dc24ba-3df1-4446-a2e4-4246844f42ab
| 5
|
@Override
public void setMode(EditorMode mode) {
if (mode == EditorMode.DEBUG) {
interpreter_.setDebug(true);
} else {
interpreter_.setDebug(false);
}
this.mode_ = mode;
for (String s : settings_.keySet()) {
for (Setting stg : settings_.get(s)) {
stg.setMode(getMode());
}
}
if (mode_ != EditorMode.NODE && mode_ != EditorMode.DEBUG) {
setVisible(false);
} else {
setVisible(true);
}
repaint();
}
|
be68691d-038e-4111-940a-f4a08c8c64b7
| 7
|
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || !(obj instanceof Person))
return false;
Person other = (Person)obj;
if(other.getId() != getId() ||
!Helper.compareObjects(this.getVorname(), other.getVorname()) ||
!Helper.compareObjects(this.getNachname(), other.getNachname()) ||
!Helper.compareObjects(this.getAdresse(), other.getAdresse()))
{
return false;
}
return true;
}
|
f93ff760-8890-4ac5-9f03-c480a18cc60a
| 0
|
public String concatenate(String one, String two){
return one + two;
}
|
06a8f85d-16c1-4e1a-9d17-8f4cb610588d
| 6
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Utilisateur other = (Utilisateur) obj;
if (nom == null) {
if (other.nom != null)
return false;
} else if (!nom.equals(other.nom)) {
return false;
}
return true;
}
|
4f8f377b-1ab5-4483-9135-ab041c7317b4
| 6
|
public static void save(String filename, double[] input) {
// assumes 44,100 samples per second
// use 16-bit audio, mono, signed PCM, little Endian
AudioFormat format = new AudioFormat(SAMPLE_RATE, 16, 1, true, false);
byte[] data = new byte[2 * input.length];
for (int i = 0; i < input.length; i++) {
int temp = (short) (input[i] * MAX_16_BIT);
data[2*i + 0] = (byte) temp;
data[2*i + 1] = (byte) (temp >> 8);
}
// now save the file
try {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
AudioInputStream ais = new AudioInputStream(bais, format, input.length);
if (filename.endsWith(".wav") || filename.endsWith(".WAV")) {
AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File(filename));
}
else if (filename.endsWith(".au") || filename.endsWith(".AU")) {
AudioSystem.write(ais, AudioFileFormat.Type.AU, new File(filename));
}
else {
throw new RuntimeException("File format not supported: " + filename);
}
}
catch (Exception e) {
System.out.println(e);
System.exit(1);
}
}
|
36d80b70-d18c-47a5-a912-710f0fa4afdc
| 8
|
@Override
public Datagram onReceive(Datagram datagram) {
RemoteObjectReference remoteObjectReference;
RegistryMessage registryMessage;
if (datagram.type.equals(Datagram.DatagramType.DATAGRAM_BIND)) {
registryMessage = (RegistryMessage) datagram.body;
String name = (String) registryMessage.args.get(0);
remoteObjectReference = (RemoteObjectReference) registryMessage.args.get(1);
if (nameMapping.containsKey(name)) {
registryMessage.exception = new Exception("Name is already used in this registry server.");
}
else {
nameMapping.put(name, remoteObjectReference);
}
}
else if (datagram.type.equals(Datagram.DatagramType.DATAGRAM_REBIND)) {
registryMessage = (RegistryMessage) datagram.body;
String name = (String) registryMessage.args.get(0);
remoteObjectReference = (RemoteObjectReference) registryMessage.args.get(1);
nameMapping.put(name, remoteObjectReference);
}
else if (datagram.type.equals(Datagram.DatagramType.DATAGRAM_LOOKUP)) {
registryMessage = (RegistryMessage) datagram.body;
String name = (String) registryMessage.args.get(0);
if (nameMapping.containsKey(name)) {
registryMessage.remoteObjectReference = nameMapping.get(name);
}
else {
registryMessage.exception = new Exception("There is no remote object registered on this server.");
}
}
else if (datagram.type.equals(Datagram.DatagramType.DATAGRAM_UNBIND)) {
registryMessage = (RegistryMessage) datagram.body;
String name = (String) registryMessage.args.get(0);
if (nameMapping.containsKey(name)) {
nameMapping.remove(name);
}
else {
registryMessage.exception = new Exception("There is no remote object registered on this server.");
}
}
else if (datagram.type.equals(Datagram.DatagramType.DATAGRAM_GET_NAMES)) {
registryMessage = (RegistryMessage) datagram.body;
String[] names = new String[nameMapping.keySet().size()];
nameMapping.keySet().toArray(names);
registryMessage.names = names;
}
else {
registryMessage = new RegistryMessage(new Exception("Illegal datagram type in dispatcher."));
}
return new Datagram(datagram.type, datagram.srcIpAddr, datagram.srcInPort, registryMessage);
}
|
b4a724d0-1619-476d-9057-65b918d71b0a
| 7
|
private void constraint_31B() throws IOException {
for (int k = 1; k <= NUM_VARS; k++) {
for (int m = 1; m <= SQUARE_SIZE; m += 3) {
for (int n = 1; n <= SQUARE_SIZE; n += 3) {
int p = 0;
// place box row by row into a an array to create one big
// row
String[] temp = new String[9];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
temp[p] = (m + i) + "" + (n + j) + "" + k;
p++;
}
}
// now the box is placed into an array of strings
// we are going to use the same algorithm from above
// to find the combination as if the box was a row
for (int j = 0; j <= temp.length; j++) {
int ptr = 1;
for (int i = j; i < temp.length - 1; i++) {
out.append("-" + temp[j] + " ");
out.append("-" + temp[j + ptr] + " 0\n");
ptr++;
}
}
}
}
}
}
|
023b0a37-e431-4a35-8bd8-86744fada705
| 6
|
public void ordenarListaRequerimientos(GrafoTabla Grafico){
ArrayList <Requerimiento> ListaAuxiliar = new ArrayList();
ArrayList <Double> ListaAuxiliarDouble = new ArrayList();
int nodo_aux = 0;
double distancia_ref;
double distancia;
ArrayList <Integer> añadido = new ArrayList();
int posicion = nodo_aux;
//distancia = Grafico.getDistancia(nodo_aux, this.getListaRequerimientos().get(0).getNodoInicial().getPosicion());
distancia = Grafico.getDistancia(nodo_aux, this.getListaRequerimientos(0).getNodoInicial().getPosicion());
for(int j=0;j<this.getListaRequerimientosSize();j++){
for(int i=0;i<this.getListaRequerimientosSize();i++){
if(!añadido.contains(this.getListaRequerimientos(i).getNodoInicial().getPosicion())){
distancia_ref = Grafico.getDistancia(nodo_aux, this.getListaRequerimientos(i).getNodoInicial().getPosicion());
if(distancia_ref<=distancia){
distancia = distancia_ref;
posicion = i;
}
}
}
añadido.add(this.ListaRequerimientos.get(posicion).getNodoInicial().getPosicion());
ListaAuxiliar.add(this.ListaRequerimientos.get(posicion));
ListaAuxiliarDouble.add(this.getDistanciaRequerimientos(posicion));
nodo_aux = this.ListaRequerimientos.get(posicion).getNodoDestino().getPosicion();
for(int k=0;k<this.getListaRequerimientosSize();k++){
if(!añadido.contains(this.getListaRequerimientos(k).getNodoInicial().getPosicion())){
distancia = Grafico.getDistancia(nodo_aux, this.getListaRequerimientos(k).getNodoInicial().getPosicion());
break;
}
}
}
this.ListaRequerimientos = ListaAuxiliar;
this.ListaDistanciaRequerimientos = ListaAuxiliarDouble;
}
|
a8ff7971-097e-46cb-a685-8f95cf0b8348
| 4
|
@Override
public Tile getTile(Tile source, Direction dir) {
int x = source.getX();
int y = source.getY();
switch(dir) {
case NORTH:
y--;
break;
case SOUTH:
y++;
break;
case EAST:
x++;
break;
case WEST:
x--;
break;
}
return tiles[x][y];
}
|
f9b8d7df-e485-46a0-9e08-7bebe36916f8
| 8
|
public static void assertEquals(String message, Object expected, Object actual)
{
if (!assertionsEnabled)
{
return;
}
// If one but not both of the objects are null, fail.
String failureMessagePostfix = ": Expected <"+expected+"> but had <"+actual+">.";
if ((expected == null && actual != null) || (expected != null && actual == null))
{
throw new Error(message + failureMessagePostfix);
}
// If both are non-null, check for equality.
else if (expected != null && actual != null)
{
if (!expected.equals(actual))
{
throw new Error(message + failureMessagePostfix);
}
}
}
|
1718c7b9-89d9-4f3c-8d8e-b8ad0d8beff6
| 1
|
public void setProperty(String key, Object value)
{
if (properties == null)
{
properties = new HashMap<String, Object>();
}
properties.put(key, value);
}
|
cda3e09b-2418-4f72-8962-17aaf8a127c9
| 3
|
@Override
public void delete(Key key)
{
int i = hash(key);
if (st[i].contains(key)) // Note: More efficient using than
// contains(key) as
// duplicate calculation of hash(key) not
// involved
N--;
st[i].delete(key);
if (M > INIT_CAPACITY && N <= 2 * M)
resize(M / 2);
}
|
66276f08-2dd7-49ce-a691-0170950b4ef0
| 9
|
public static NaturalSetCollection intersect(NaturalSetCollection a, NaturalSetCollection b) throws NaturalSetException{
NaturalSetCollection intersect = null;
if(b.domain.equals(a.domain)){
intersect = new NaturalSetCollection(b.domain);
ArrayList<NaturalSet> first = b.elements, second = a.elements;
int firstPosition = 0, secondPosition = 0;
int firstEnd = first.size() - 1, secondEnd = second.size() - 1;
while(firstPosition < firstEnd && secondPosition < secondEnd) {
int order = first.get(firstPosition).compareTo(second.get(secondPosition));
if(order == 0){
intersect.elements.add(first.get(firstPosition));
firstPosition++;
secondPosition++;
} else if (order > 0) {
secondPosition++;
} else {
firstPosition++;
}
}
if(firstPosition != firstEnd){
first = a.elements;
second = b.elements;
secondPosition = firstPosition;
firstPosition = secondEnd;
secondEnd = firstEnd;
firstEnd = firstPosition;
}
NaturalSet last = first.get(firstEnd);
NaturalSet current = second.get(secondPosition);
int order = current.compareTo(last);
while(secondPosition <= secondEnd && order <= 0){
if(order == 0){ intersect.elements.add(current); }
secondPosition++;
}
} else {
throw new NaturalSetException("NaturalSetCollections have to be defined over the same Domain to intersect");
}
return intersect;
}
|
fb19aab2-8271-4251-b8aa-6a746bf4a1a1
| 5
|
public void body()
{
initializeResultsFile(); // create new files for statistics
createGridlet(NUM_GRIDLETS); // create gridlets
// send a reminder to itself at time init_time, with a message to
// submit Gridlets.
super.send(super.get_id(), GridSimTags.SCHEDULE_NOW + init_time * 10,
GridSimTags.GRIDLET_SUBMIT);
/*****
// Uncomment this if you want more info on the progress of the sims
System.out.println(super.get_name() +
": initial SUBMIT_GRIDLET event will be at clock: " +
init_time + ". Current clock: " + GridSim.clock());
******/
// a loop that keeps waiting for incoming events
while (Sim_system.running())
{
Sim_event ev = new Sim_event();
super.sim_get_next(ev); // get the next event in the incoming queue
// exit the loop if we get a signal of end of simulation
if (ev.get_tag() == GridSimTags.END_OF_SIMULATION)
{
System.out.println("============== " + super.get_name() +
". Ending simulation...");
break;
}
// for other events or activities
switch (ev.get_tag())
{
// submit a gridlet
case GridSimTags.GRIDLET_SUBMIT: //SUBMIT_GRIDLET:
/***
// Uncomment this if you want more info on the progress
System.out.println(super.get_name() +
": received an SUBMIT_GRIDLET event. Clock: " + GridSim.clock());
****/
processGridletSubmission(ev); // process the received event
break;
// Receive a gridlet back from the resource
case GridSimTags.GRIDLET_RETURN:
/*****
// Uncomment this if you want more info on the progress
System.out.println(super.get_name() +
": received an GRIDLET_RETURN event. Clock: " + GridSim.clock());
****/
processGridletReturn(ev);
break;
// A gridlet has failed because a packet was dropped
case GridSimTags.FNB_GRIDLET_FAILED_BECAUSE_PACKET_DROPPED:
processGridletPacketDropping(ev);
break;
default:
System.out.println(super.get_name() +
": Received an unknown event: " + ev.get_tag());
break;
} // switch (ev.get_tag())
ev = null;
}// while (Sim_system.running())
// remove I/O entities created during construction of this entity
super.terminateIOEntities();
// print the statistics regarding to this experiment
printStatistics();
}// body()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.