method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
7efc6db8-23e2-487b-a173-28bed27d99ec
| 9
|
private static void keyAction(String actionString) {
if (controlsActive) {
if (actionString.equals("Fire")) {
session.player.setFiring(true);
} else if (actionString.equals("SpaceReleased")) {
session.player.setFiring(false);
} else if (actionString.equals("Left")) {
session.player.setDirection(-1);
} else if (actionString.equals("Right")) {
session.player.setDirection(1);
} else if (actionString.equals("ArrowKeyReleased")) {
session.player.setDirection(0);
} else if (actionString.equals("Toggle_Pause")) {
paused = !paused;
} else if (actionString.equals("KillAll")) {
for (Map.Entry<Integer, Enemy> e : session.enemies.entrySet()) {
Enemy selected = (Enemy) e.getValue();
selected.deactivate();
}
}
}
}
|
ee14a8af-1a45-42b6-a351-05a5cfc3d3f5
| 6
|
public int Edit_Data(ProfileInfo DataObj) {
//System.out.println("ProfileDAO.Edit_Data()");
int res = 0;
ProfileInfo profileObj = null;
String sql = "UPDATE profile SET Profile_Name=?, Video_Width=?, Video_Height=?, Video_FPS=?, Video_Bitrate=?, Video_Preset=?, Audio_Codec=?, Audio_Bitrate=?, Audio_SampleRate=? where Profile_Name=?";
try {
profileObj = (ProfileInfo)DataObj;
con = getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setString(1, profileObj.getProfileName());
pstmt.setString(2, profileObj.getVideoWidth());
pstmt.setString(3, profileObj.getVideoHeight());
pstmt.setString(4, profileObj.getVideoFPS());
pstmt.setString(5, profileObj.getVideoBitrate());
pstmt.setString(6, profileObj.getVideoPreset());
pstmt.setString(7, profileObj.getAudioCodec());
pstmt.setString(8, profileObj.getAudioBitrate());
pstmt.setString(9, profileObj.getAudioSamplerate());
pstmt.setString(10, profileObj.getProfileName());
res = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
if (con != null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
return res;
}
|
177ed502-d7ea-4964-aa75-a6724a2a2cb7
| 3
|
@Override
public void put( ByteBuffer out, Object v )
{
if (v == null)
{
out.put( Compress.NULL );
}
else
{
out.put( Compress.NOT_NULL );
try
{
for (int i = 0; i < fields.length; i++)
{
reflects[i].put( out, fields[i].get( v ) );
}
}
catch (Exception e)
{
throw new RuntimeException( e );
}
}
}
|
ab094fc9-1079-49d3-af81-02f66014c6d0
| 4
|
public static void rectangle(double x, double y, double halfWidth, double halfHeight) {
if (halfWidth < 0) {
throw new IllegalArgumentException("half width must be nonnegative");
}
if (halfHeight < 0) {
throw new IllegalArgumentException("half height must be nonnegative");
}
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2 * halfWidth);
double hs = factorY(2 * halfHeight);
if (ws <= 1 && hs <= 1) {
pixel(x, y);
} else {
offscreen.draw(new Rectangle2D.Double(xs - ws / 2, ys - hs / 2, ws, hs));
}
draw();
}
|
8e94855c-62dd-4356-bc70-1b24ffd8a07a
| 0
|
@Override
public void addServerStopListener(ServerStopListener listener) {
serverStopListenerList.add(ServerStopListener.class, listener);
}
|
cd3cbeac-3a23-4731-9f86-dfd9e712eb91
| 1
|
private String generateFinalKey(String in) {
String seckey = in.trim();
String acc = seckey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
MessageDigest sh1;
try {
sh1 = MessageDigest.getInstance("SHA1");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
return Base64.encodeBytes(sh1.digest(acc.getBytes()));
}
|
ecd768c4-e529-439e-8b15-400d3ccffd29
| 5
|
public Boolean asBooleanObj()
{
try {
if (isNull()) {
return null;
} else if (isBoolean()) {
return (Boolean) value;
}
String check = asString();
if (check == null) {
return null;
} else if (isTrue(check)) {
return Boolean.TRUE;
} else {
return Boolean.FALSE;
}
} catch (Exception e) {
throw new SwingObjectRunException( e, ErrorSeverity.SEVERE, FrameFactory.class);
}
}
|
40f16736-0a17-41f4-81da-c636dcfab1a0
| 6
|
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof XYZ)) {
return false;
}
XYZ other = (XYZ) obj;
if (x != other.x) {
return false;
}
if (y != other.y) {
return false;
}
if (z != other.z) {
return false;
}
return true;
}
|
ffa7c037-96ab-4cf6-8358-95b57517fe80
| 6
|
public static void writeValue( Object thing, OutputStream os ) throws IOException {
if( thing instanceof byte[] ) {
writeByteString( (byte[])thing, os );
} else if( thing instanceof Number ) {
writeNumberCompact( (Number)thing, os );
} else if( Boolean.TRUE.equals(thing) ) {
os.write(BE_TRUE);
} else if( Boolean.FALSE.equals(thing) ) {
os.write(BE_FALSE);
} else if( Default.INSTANCE.equals(thing) ) {
os.write(SE_DEFAULT);
} else if( thing instanceof SHA1ObjectReference ) {
writeSha1ObjectReference( (SHA1ObjectReference)thing, os );
} else {
throw new UnsupportedOperationException("Don't know how to encode "+thing.getClass());
}
}
|
30ac25ea-ea54-4c43-8a66-5304c10b2904
| 4
|
public void setGehRichtung(String richtungsbefehl)
{
if(richtungsbefehl.contains("nord"))
{
_gegangeneRichtung = "nord";
}
else if(richtungsbefehl.contains("ost"))
{
_gegangeneRichtung = "ost";
}
else if(richtungsbefehl.contains("süd"))
{
_gegangeneRichtung = "süd";
}
else if(richtungsbefehl.contains("west"))
{
_gegangeneRichtung = "west";
}
}
|
5823d5cf-e323-4948-8ddb-4ea7e11cd7a1
| 4
|
private int decodeResponse(String challenge, String string) {
if (string.length() > 100) {
return 0;
}
int[] shuzi = new int[] { 1, 2, 5, 10, 50 };
String chongfu = "";
HashMap<String, Integer> key = new HashMap<String, Integer>();
int count = 0;
for (int i = 0; i < challenge.length(); i++) {
String item = challenge.charAt(i) + "";
if (chongfu.contains(item) == true) {
continue;
} else {
int value = shuzi[count % 5];
chongfu += item;
count++;
key.put(item, value);
}
}
int res = 0;
for (int j = 0; j < string.length(); j++) {
res += key.get(string.charAt(j) + "");
}
res = res - decodeRandBase(challenge);
return res;
}
|
5711bdd4-5c1c-4156-84bd-969466756781
| 1
|
public boolean matches( Class<?> clazz )
{
return Modifier.isFinal( clazz.getModifiers() );
}
|
3f38801e-e77a-4794-8df5-6b915c28686b
| 3
|
public void addEdge( Vertex<T> v1, Vertex<T> v2 ) {
v1Pos = getVerticesIndexFor( v1 );
v2Pos = getVerticesIndexFor( v2 );
if ( v1Pos == -1 || v2Pos == -1 ) {
throw new IllegalArgumentException( "vertex not found" );
}
// avoid adding duplicate edges
if ( this.adjMatrix[v1Pos][v2Pos] == 0 ) {
this.adjMatrix[v1Pos][v2Pos] = 1;
this.numberOfEdges++;
}
else {
throw new IllegalArgumentException( "duplicate edge "
+ v1 + " " + v2 );
}
}
|
db44f91f-f222-4a5c-af29-c8e6a5686fa9
| 2
|
public boolean setNbCoupMax(int nvNbCoupMax){
if(nvNbCoupMax >= MIN_NB_COUPS && nvNbCoupMax <= MAX_NB_COUPS){
Integer coupMax = nvNbCoupMax;
propriete.setProperty("nb_coups", coupMax.toString());
return true;
}
else{
return false;
}
}
|
17d1afdc-71a0-40a0-bd48-34624885e5df
| 8
|
public void execute(MapleClient c, MessageCallback mc, String[] splitted) throws Exception {
if (splitted[0].equalsIgnoreCase("removeeqrow")) {
int lol = 4;
if (splitted.length == 2) {
lol = (Integer.parseInt(splitted[1]) * 4);
}
for (int i = 0; i < lol + 1; i++) {
IItem tempItem = c.getPlayer().getInventory(MapleInventoryType.EQUIP).getItem((byte) i);
if (tempItem == null) {
continue;
}
MapleInventoryManipulator.removeFromSlot1337(c, MapleInventoryType.EQUIP, (byte) i, tempItem.getQuantity(), false, true);
}
mc.dropMessage("should be done");
} else if (splitted[0].equalsIgnoreCase("removecashrow")) {
int lol = 4;
if (splitted.length == 2) {
lol = (Integer.parseInt(splitted[1]) * 4);
}
for (int i = 0; i < lol + 1; i++) {
IItem tempItem = c.getPlayer().getInventory(MapleInventoryType.CASH).getItem((byte) i);
if (tempItem == null) {
continue;
}
MapleInventoryManipulator.removeFromSlot1337(c, MapleInventoryType.CASH, (byte) i, tempItem.getQuantity(), false, true);
}
mc.dropMessage("should be done");
}
}
|
08efbba6-77a8-4606-b7e5-d69935925933
| 5
|
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
// Override OpenCms Environment with Base OpenCms Zip Url
if (this.getBaseOpenCmsZipUrl() != null) {
this.setOpenCmsEnvironmentZipFile(this.getBaseOpenCmsZipUrl());
}
// Execute OpenCms init
super.execute();
try {
this.getLog().info("Starting environment builder mojo...");
this.getLog().info(
"Base Zip File: "
+ this.getBaseOpenCmsZipUrl()
+ ", Output Zip File: "
+ this.getOutputOpenCmsZipFile()
+ ", Modules to Import: "
+ Arrays.toString(this.getModuleImportFiles()
.toArray(new String[0])));
// Execute shell
File scriptFile = new File(this.getTargetDirectory()
.getAbsolutePath() + DEPLOY_SCRIPT_FILE_NAME);
// Delete script file if it already exists
if (scriptFile.exists()) {
scriptFile.delete();
}
this.getLog()
.info("Starting script creation: "
+ scriptFile.getAbsolutePath());
// Only continue if script file is not null
if (scriptFile != null) {
// Write to file
FileWriter fw = new FileWriter(scriptFile.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
// Get contents
String fileContents = this.generateInstallScriptContents();
// Write to file
bw.write(fileContents);
// Close file writer
bw.close();
}
this.getLog().info("End of script creation...");
// Get execution command list
List<String> commandList = this
.getExecutableCommandList(scriptFile);
this.getLog().info(
"Running commands: "
+ Arrays.toString(commandList
.toArray(new String[0])));
// Run script
this.executeScript(commandList);
this.getLog().info("Deploy complete...");
// Check that output file is created
if (this.getOutputOpenCmsZipFile() != null) {
this.getLog().info("Creating Zip file ...");
// Zip up directory
ZipFile zipFile = new ZipFile(this.getOutputOpenCmsZipFile());
// Initiate Zip Parameters which define various properties such
// as compression method, etc.
ZipParameters parameters = new ZipParameters();
// set compression method to store compression
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
// Set the compression level
parameters
.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
// Exclue root folder
parameters.setIncludeRootFolder(false);
zipFile.addFolder(this.getTargetDirectory(), parameters);
this.getLog().info(
"Zip file created: "
+ zipFile.getFile().getAbsolutePath());
}
} catch (Exception ec) {
this.getLog().error(
"Error running OpenCms environment builder mojo", ec);
// Throw Mojo Execution Exception
MojoExecutionException mojoException = new MojoExecutionException(
"Error executing OpenCms environment builder mojo");
mojoException.initCause(ec);
throw mojoException;
}
}
|
c1bcab43-d674-4a99-b67f-6e3fec0e85b3
| 3
|
public void go_up(){
if( this.direction != Tank.direction_up)
this.direction = Tank.direction_up ;
else{
if(this.location_y - this.speed >= 0 && ifCanWalkInThisDirection())
{
this.location_y -= this.speed ;
ifGetProps();
}
}
}
|
a8371cb5-7822-4f7a-84be-442dd42c6c3f
| 5
|
protected BufferedImageWithFlipBits scale( Getter<BufferedImage> populator, int width, int height ) throws ResourceNotFound {
assert width != 0;
assert height != 0;
BufferedImage original = getOriginal(populator);
ensureMetadataInitialized(original);
final int dx0, dy0, dx1, dy1;
if( width < 0 ) { dx0 = -width ; dx1 = 0; } else { dx0 = 0; dx1 = width ; }
if( height < 0 ) { dy0 = -height; dy1 = 0; } else { dy0 = 0; dy1 = height; }
BufferedImageWithFlipBits b = new BufferedImageWithFlipBits(width, height, isCompletelyOpaque ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D)b.getGraphics();
// Interpolate only when scaling down
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
(b.getWidth() < original.getWidth() && b.getHeight() < original.getHeight()) ?
RenderingHints.VALUE_INTERPOLATION_BICUBIC :
RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
g.drawImage( original, dx0, dy0, dx1, dy1, 0, 0, original.getWidth(), original.getHeight(), null);
return b;
}
|
da425da0-4001-471e-9707-df0d93cbbbad
| 3
|
public static void rotate90CCW(int[][] image) {
if(image.length != image[0].length) {
throw new IllegalArgumentException("The matrix must be square.");
}
double n = image.length;
int f = (int)Math.floor(n/2);
int c = (int)Math.ceil(n/2);
// rotate 4 "pixels" of the image at a time
for(int x = 0; x < f; x++) {
for(int y = 0; y < c; y++) {
int temp = image[x][y];
image[x][y] = image[y][image.length-1-x];
image[y][image.length-1-x] = image[image.length-1-x][image.length-1-y];
image[image.length-1-x][image.length-1-y] = image[image.length-1-y][x];
image[image.length-1-y][x] = temp;
}
}
}
|
ab735eb9-1890-4d81-ae06-8007e9695ec9
| 0
|
public void setSsn(String ssn) {
this.ssn = ssn;
setDirty();
}
|
a58e7572-60d7-44d6-881b-0acb4fb94194
| 0
|
public DaedricWarAxe() {
this.name = Constants.DAEDRIC_WAR_AXE;
this.attackScore = 15;
this.attackSpeed = 18;
this.money = 1800;
}
|
0ab6dba8-9cb7-4d80-b356-2945e617ccdc
| 8
|
public PrimitiveOperator combineRightNLeftOnMin(PrimitiveOperator other) {
boolean[] newTruthTable = new boolean[8];
newTruthTable[0] = truthTable[((other.truthTable[0]) ? 2 : 0) | 0]; //000
newTruthTable[1] = truthTable[((other.truthTable[2]) ? 2 : 0) | 1]; //001
newTruthTable[2] = truthTable[((other.truthTable[1]) ? 2 : 0) | 0]; //010
newTruthTable[3] = truthTable[((other.truthTable[3]) ? 2 : 0) | 1]; //011
newTruthTable[4] = truthTable[((other.truthTable[0]) ? 2 : 0) | 4]; //100
newTruthTable[5] = truthTable[((other.truthTable[2]) ? 2 : 0) | 5]; //101
newTruthTable[6] = truthTable[((other.truthTable[1]) ? 2 : 0) | 4]; //110
newTruthTable[7] = truthTable[((other.truthTable[3]) ? 2 : 0) | 5]; //111
return new PrimitiveOperator(newTruthTable);
}
|
b8671266-1468-473a-bd23-bdec4213707c
| 0
|
@Test
public void edgeReturnsCorrectVerticesWhenFlipped() {
Vertex v = new Vertex(0);
Vertex u = new Vertex(0);
Edge e = new Edge(v, u);
e.flip();
assertEquals(e.getStart(), u);
assertEquals(e.getEnd(), v);
}
|
1d3a4fe4-2d1e-4512-af84-e0a3ce57b155
| 9
|
private void initialize() {
// Used for saving on pressing Ctrl-Enter and cancelling on escape
KeyAdapter keyAdapter = new KeyAdapter() {
@Override
public void keyPressed(KeyEvent ev) {
if ((ev.getKeyCode() == KeyEvent.VK_ENTER) && ((ev.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0)) {
saveEntry();
} else if (ev.getKeyCode() == KeyEvent.VK_ESCAPE) {
frame.setVisible(false);
frame.dispose();
}
}
};
frame = new JFrame();
frame.addKeyListener(keyAdapter);
frame.setBounds(100, 100, 450, 300);
if (width != 0 && height != 0) {
frame.setBounds(x, y, width, height);
} else {
x = 100; y = 100; width = 450; height = 300;
}
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.getContentPane().setLayout(new FormLayout(new ColumnSpec[] {
FormFactory.RELATED_GAP_COLSPEC,
FormFactory.DEFAULT_COLSPEC,
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("default:grow"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("default:grow"),
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,},
new RowSpec[] {
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
RowSpec.decode("default:grow"),
FormFactory.RELATED_GAP_ROWSPEC,
RowSpec.decode("default:grow"),
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.LINE_GAP_ROWSPEC,}));
JLabel lblWord = new JLabel(Localization.getInstance().get("wordColumnName"));
lblWord.setHorizontalAlignment(SwingConstants.RIGHT);
frame.getContentPane().add(lblWord, "2, 2, right, default");
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentMoved(ComponentEvent ev) {
x = frame.getX();
y = frame.getY();
}
@Override
public void componentResized(ComponentEvent ev) {
width = frame.getWidth();
height = frame.getHeight();
}
});
wordTextField = new JTextField();
frame.getContentPane().add(wordTextField, "4, 2, 3, 1, fill, default");
wordTextField.setColumns(10);
wordTextField.addKeyListener(keyAdapter);
JLabel lblDefinition = new JLabel(Localization.getInstance().get("definitionColumnName"));
lblDefinition.setHorizontalAlignment(SwingConstants.RIGHT);
frame.getContentPane().add(lblDefinition, "2, 4");
JScrollPane defScrollPane = new JScrollPane();
frame.getContentPane().add(defScrollPane, "4, 4, 3, 1, fill, fill");
defTextArea = new JTextArea();
defScrollPane.setViewportView(defTextArea);
defTextArea.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_TAB) {
if (e.getModifiers() > 0) {
wordTextField.grabFocus();
} else {
notesTextArea.grabFocus();
}
e.consume();
}
}
});
defTextArea.addKeyListener(keyAdapter);
JLabel lblNotes = new JLabel(Localization.getInstance().get("notesColumnName"));
lblNotes.setHorizontalAlignment(SwingConstants.RIGHT);
frame.getContentPane().add(lblNotes, "2, 6");
JScrollPane notesScrollPane = new JScrollPane();
frame.getContentPane().add(notesScrollPane, "4, 6, 3, 1, fill, fill");
notesTextArea = new JTextArea();
notesScrollPane.setViewportView(notesTextArea);
notesTextArea.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_TAB) {
if (e.getModifiers() > 0) {
defTextArea.grabFocus();
} else {
catTextField.grabFocus();
}
e.consume();
}
}
});
notesTextArea.addKeyListener(keyAdapter);
JLabel lblCategory = new JLabel(Localization.getInstance().get("categoryColumnName"));
lblCategory.setHorizontalAlignment(SwingConstants.RIGHT);
frame.getContentPane().add(lblCategory, "2, 8, right, default");
catTextField = new JTextField();
frame.getContentPane().add(catTextField, "4, 8, 3, 1, fill, default");
catTextField.setColumns(10);
catTextField.addKeyListener(keyAdapter);
JLabel lblTags = new JLabel(Localization.getInstance().get("tagsColumnName"));
lblTags.setHorizontalAlignment(SwingConstants.RIGHT);
frame.getContentPane().add(lblTags, "2, 10, right, default");
tagsTextField = new JTextField();
frame.getContentPane().add(tagsTextField, "4, 10, 3, 1, fill, default");
tagsTextField.setColumns(10);
tagsTextField.addKeyListener(keyAdapter);
btnSave = new JButton(Localization.getInstance().get("menuItemFileSave"));
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveEntry();
}
});
frame.getContentPane().add(btnSave, "4, 12");
btnCancel = new JButton(Localization.getInstance().get("cancel"));
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// TODO Maybe ask for saving?
frame.setVisible(false);
frame.dispose();
}
});
frame.getContentPane().add(btnCancel, "6, 12");
}
|
8e5dc264-ea82-4f53-994e-70f34c0380f1
| 4
|
public boolean updateScheduleRequest(Sport sport) {
String request = null;
switch(sport) {
case NBA: case NHL:
request = "http://api.sportsdatallc.org/" + sport.getName() + "-" + access_level + sport.getVersion() + "/games/" + season + "/" + season2 + "/schedule.xml?api_key=" + sport.getKey();
Element element = send(request);
try {
Node node = null;
NodeList gameNodes = element.getElementsByTagName("game");
for (int i=0;i<gameNodes.getLength();i++) {
NamedNodeMap nodeMapGameAttributes = gameNodes.item(i).getAttributes();
node = nodeMapGameAttributes.getNamedItem("id");
String sched_id = node.getNodeValue();
node = nodeMapGameAttributes.getNamedItem("home_team");
String sched_home_team_id = node.getNodeValue();
node = nodeMapGameAttributes.getNamedItem("away_team");
String sched_away_team_id = node.getNodeValue();
// status : closed, inprogress, scheduled, postponed
node = nodeMapGameAttributes.getNamedItem("status");
boolean isFinish = node.getNodeValue().equals("closed");
node = nodeMapGameAttributes.getNamedItem("scheduled");
Date sched_date = this.toJavaDate(node.getNodeValue());
ScheduleTeamModel schedule = new ScheduleTeamModel(sport,sched_id,sched_date,isFinish,sched_home_team_id,sched_away_team_id);
DataStore.storeSchedule(schedule);
}
} catch (Exception e) {
System.out.println("@ erreur lors du parcours du fichier xml dans getScheduleRequest()");
return false;
}
break;
// à compléter si besoin
default:
break;
}
return true;
}
|
65c1b4c7-7306-479d-8828-1b6efdca9078
| 6
|
public void addCreatureToWorld(final int creatureType, final Grid g) {
Thread creatureWatcher = new Thread(new Runnable() {
@Override
public void run() {
Random ra = new Random();
if (creatureType == SIMPLE_AGENT) {
while (g.getSimpleCreaturesAmount() < nSimpleCreaturesInWorld) {
// Manage the amount of simple creatures in the
// world.if less remove. if more add
addCreature(
g,
new Point(ra.nextInt(Grid.BOUND_MAX_X - 20), ra
.nextInt(Grid.BOUND_MAX_Y - 20)), g
.getBounds(), creatureType);
}
while (g.getSimpleCreaturesAmount() > nSimpleCreaturesInWorld) {
g.removeSimpleCreature();
}
IntelCreature.CREATURE_MEMORY = nSimpleCreaturesInWorld
+ nIntelCreaturesInWorld;
} else if (creatureType == INTEL_AGENT) {
while (g.getIntelCreaturesAmount() < nIntelCreaturesInWorld) {
// Manage the amount of intelligent creatures in the
// world. if less remove. if more add
addCreature(
g,
new Point(ra.nextInt(Grid.BOUND_MAX_X - 20), ra
.nextInt(Grid.BOUND_MAX_Y - 20)), g
.getBounds(), creatureType);
}
while (g.getIntelCreaturesAmount() > nIntelCreaturesInWorld) {
g.removeIntelCreature();
}
}
}
});
creatureWatcher.start();
}
|
39d234c5-fbcc-4cc8-83c6-140e1b0581bf
| 0
|
public Integer getMemory() {
return this.memory;
}
|
ea4f7af8-83f8-42dd-afee-2230edf29ffa
| 2
|
public List<Trip> getTripsByUser(User user) throws UserNotLoggedInException {
List<Trip> tripList = new ArrayList<Trip>();
User loggedUser = getLoggedUser();
if (loggedUser != null) {
if (user.isFriendWith(loggedUser)) {
tripList = getTripList(user);
}
return tripList;
} else {
throw new UserNotLoggedInException();
}
}
|
1134486f-1f6f-421e-93e8-ac0db1a73737
| 3
|
@SuppressWarnings ( {
"unused", "resource"
} )
@Test
public void testWriteJournalLarge () throws Exception {
if ( this.socketAddress == null ) {
return;
}
try ( AFUNIXSocket sock = connectToServer() ) {
System.err.println("Client running");
InputStream is = sock.getInputStream();
AFUNIXOutputStream os = sock.getOutputStream();
Path tmpFile = Files.createTempFile(Paths.get("/dev/shm/"), "journal", ".tmp");
FileChannel open = FileChannel.open(tmpFile, StandardOpenOption.READ, StandardOpenOption.WRITE);
try ( FileOutputStream fos = new FileOutputStream(tmpFile.toFile());
FileInputStream fis = new FileInputStream(tmpFile.toFile()) ) {
DataOutputStream dos = new DataOutputStream(fos);
dos.write("PRIORITY=2\n".getBytes("UTF-8"));
dos.write("MESSAGE=TEST2\n".getBytes("UTF-8"));
dos.write("TEST2\n".getBytes("UTF-8"));
int len = 68000;
writeLongLE(dos, len - 1);
byte data[] = new byte[len];
for ( int i = 0; i < len; i++ ) {
data[ i ] = (byte) ( ( i % 26 ) + 'A' );
}
data[ len - 1 ] = '\n';
dos.write(data);
fos.flush();
os.sendfd(fis.getFD());
}
finally {
Files.deleteIfExists(tmpFile);
}
System.err.println("Wrote from client");
}
catch ( Exception e ) {
e.printStackTrace();
}
}
|
d12190ca-5b7e-4dc7-a975-d8edbdd7d94f
| 6
|
public boolean exist(char[][] board, String word) {
if (word.length() == 0) {
return true;
}
int row = board.length;
if (row == 0) {
return false;
}
int col = board[0].length;
boolean[][] visited = new boolean[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (word.charAt(0) == board[i][j]) {
if (helper(board, word, 0, row, col, i, j, visited)) {
return true;
}
}
}
}
return false;
}
|
a7d1bcc6-0c10-459c-9d06-2d745dd2d600
| 3
|
private int brute(T[] a)
{
int inversions = 0;
for (int i = 1; i < a.length; i++)
for (int j = i - 1; j >= 0; j--)
if (SortHelper.less(a[i], a[j]))
inversions++;
return inversions;
}
|
97104670-543e-4ac3-8dd7-32f77f3cd47a
| 9
|
@Override
public ByteBuffer get(String path) throws IOException {
if (path.startsWith("/crc")) {
return fs.getCrcTable();
} else if (path.startsWith("/title")) {
return fs.getFile(0, 1);
} else if (path.startsWith("/config")) {
return fs.getFile(0, 2);
} else if (path.startsWith("/interface")) {
return fs.getFile(0, 3);
} else if (path.startsWith("/media")) {
return fs.getFile(0, 4);
} else if (path.startsWith("/versionlist")) {
return fs.getFile(0, 5);
} else if (path.startsWith("/textures")) {
return fs.getFile(0, 6);
} else if (path.startsWith("/wordenc")) {
return fs.getFile(0, 7);
} else if (path.startsWith("/sounds")) {
return fs.getFile(0, 8);
}
return null;
}
|
2eb3fe66-7af5-4cec-9340-f17b2965eeb7
| 6
|
public void draw(Graphics g, double mx, double my) {
g.setColor(Color.BLACK);
if(held && mx < 90.0) {
g.drawString("Angle: "+calcAngle(mx,my), (int)(x+10.0), 440);
g.drawLine((int)mx, (int)my, (int)x, 400);
double tempAngle = calcAngle(mx, my);
double tx = x;
double ty = 400.0;
// Check if the power is greater than 50, and if so, cap it
if (Math.sqrt(((mx-90.0)*(mx-90.0))+((my-400.0)*(my-400.0))) > 50) {
mx = 90.0 - Math.sin(Math.toRadians(90.0-tempAngle))*50.0;
my = 400.0 + Math.cos(Math.toRadians(90.0-tempAngle))*50.0;
}
double temp_vx = ((x-mx)/1.5);
double temp_vy = ((my-400.0)/1.5);
g.setColor(Color.GRAY);
// Draw trajectory if trajectory flag is set
if (showTrajectory) {
while(ty<450) {
g.fillOval((int)(tx-3),(int)(ty-3),6,6);
for(int i=0; i<2; i++) {
tx+=temp_vx;
ty-=temp_vy;
temp_vy+=-1.0;
}
}
}
}
}
|
c47ce4c8-efcf-412a-ae14-639a0c8ffcc0
| 0
|
public long getPacketDelay() {
return _packetDelay;
}
|
4acbecd9-622b-4896-9a36-ef2f5b9a8d54
| 3
|
private static String formatToLength(String base, int length) {
if (base == null) {
throw new NullPointerException();
}
String ret = "";
for (int i = base.length(); i <= length; i++) {
ret += " ";
}
ret += base;
if (base.length() - 1 > length) {
ret = base.substring(0, length - 1) + "..";
}
return ret;
}
|
d216690d-85f7-4c65-ae59-11384dbe8d1f
| 0
|
public Insertar() {
initComponents();
}
|
533bbd03-f672-491a-b187-dba4bca26010
| 6
|
public void detectLang() {
if (loadProfile()) return;
for (String filename: arglist) {
BufferedReader is = null;
try {
is = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "utf-8"));
Detector detector = detectorFactory.create(getDouble("alpha", DEFAULT_ALPHA));
if (hasOpt("--debug")) detector.setVerbose();
detector.append(is);
System.out.println(filename + ":" + detector.getProbabilities());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is!=null) is.close();
} catch (IOException e) {}
}
}
}
|
73e7679d-7e40-4a09-97f6-5aa05279c747
| 2
|
public void visitIntInsn(final int opcode, final int operand) {
mv.visitIntInsn(opcode, operand);
if (constructor && opcode != NEWARRAY) {
pushValue(OTHER);
}
}
|
ab4a0946-66c9-4798-af6b-a470c069b039
| 0
|
public void setCipherData(CipherDataType value) {
this.cipherData = value;
}
|
b6a8e106-8b5a-4be1-9e30-65228a843346
| 7
|
public Field(int dimension, int[] fieldSize, int countInRowForWin) throws NotImplementedException {
this.dimension = dimension;
this.countInRowForWin = countInRowForWin;
switch (dimension) {
case 2:
d2Field = new int[fieldSize[0]][fieldSize[1]];
for (int i = 0; i < fieldSize[0]; i++) {
for (int j = 0; j < fieldSize[1]; j++) {
d2Field[i][j] = -1;
}
}
break;
case 3:
d3Field = new int[fieldSize[0]][fieldSize[1]][fieldSize[2]];
for (int i = 0; i < fieldSize[0]; i++) {
for (int j = 0; j < fieldSize[1]; j++) {
for (int z = 0; z < fieldSize[2]; z++) {
d3Field[i][j][z] = -1;
}
}
}
break;
default:
throw new NotImplementedException();
}
}
|
279729eb-3606-48c8-b894-ed549a4cbc2e
| 4
|
private void sendRPC()
{
OpCode code = receivedRPC.getRPCOpcode();
if (code.equals(OpCode.PING_REQUEST))
{
handlePingRequest(receivedRPC);
}
else if (code.equals(OpCode.FIND_NODE_REQUEST))
{
handleFindNodeRequest(receivedRPC);
}
else if (code.equals(OpCode.FIND_VALUE_REQUEST))
{
handleFindValueRequest(receivedRPC);
}
else if (code.equals(OpCode.STORE_REQUEST))
{
handleStoreRequest(receivedRPC);
}
else
{
System.err.println("ServerManager : Unknown message type");
}
messageDispatcher.removeSessionHandler(sid);//unregister from the message dispatcher
}
|
ff4436e9-75e4-4706-ae8a-059058dec1cd
| 8
|
@Override
public void run()
{
try {
gate.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
isAtWork = true;
if(theBusiness.timer.getTimeOfDay() >= arrivalTime)
{
System.out.println(theBusiness.timer.getCurrentTime() + " " + getIdentity(name) + " " + "has arrived at work at " + theBusiness.timer.getThisCurrentTime(arrivalTime) + ".");
}
theBusiness.holdTeamLeadManagerMeeting(this);
while(theBusiness.timer.getTimeOfDay() < morningMeeting)
{
this.yield();
}
attendMorningMeeting();
while(theBusiness.timer.getTimeOfDay() < startLunchTime)
{
this.yield();
}
takeLunch((int)lunchTime);
while(theBusiness.timer.getTimeOfDay() < afternoonMeeting)
{
this.yield();
}
attendAfternoonMeeting();
while(theBusiness.timer.getTimeOfDay() < 4800)
{
this.yield();
}
theBusiness.arriveForFinalMeeting(this);
theBusiness.holdFinalMeeting(this);
// after all of the days business is done, wait until 5 to clock out
while(theBusiness.timer.getTimeOfDay() < departTime)
{
this.yield();
}
System.out.println(theBusiness.timer.getCurrentTime() + " " + getIdentity(name) + " " + "has left work for the day" + ".");
isAtWork = false;
if(theBusiness.timer.getTimeOfDay() >= departTime){
return;
}
}
|
3aff790a-5d2c-41b9-88a0-211e85f52033
| 2
|
@Override
public void actionPerformed(ActionEvent e) {
int confirmation = JOptionPane.showConfirmDialog(null, "Are you sure to delete card?", "Confirmation", JOptionPane.YES_NO_OPTION);
if (confirmation == JOptionPane.YES_OPTION) {
try {
Connection conn;
Statement stat;
conn = DriverManager.getConnection(Utils.DB_URL);
stat = conn.createStatement();
stat.execute("DELETE FROM word WHERE id = "+ EditCard.getSelectedCardId() +"");
reloadWordsTable();
motherLangTextField.setText("");
translationTextField.setText("");
statusLbl.setText("Status: Card was successfuly deleted!");
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
|
395da3e3-9f3f-4bd2-af05-a54a52f3a129
| 2
|
public RepositoryHandler(String repositoryURL, String repositoryUsername, String repositoryPassword, int repositoryType) {
this.repositoryUsername = repositoryUsername;
this.repositoryPasword = repositoryPassword;
this.repositoryType = repositoryType;
this.repositoryURL = repositoryURL;
SessionFactory sessionFactory = SessionFactoryImpl.newInstance();
Map<String, String> parameter = new HashMap<String, String>();
parameter.put(SessionParameter.USER, repositoryUsername);
parameter.put(SessionParameter.PASSWORD, repositoryPasword);
if (repositoryType == REP_TYPE_ALFRESCO) {
parameter.put(SessionParameter.OBJECT_FACTORY_CLASS,
"org.alfresco.cmis.client.impl.AlfrescoObjectFactoryImpl");
}
parameter.put(SessionParameter.ATOMPUB_URL, repositoryURL);
parameter.put(SessionParameter.BINDING_TYPE,
BindingType.ATOMPUB.value());
System.out.println("Accessing ATOMPUB_URL: "
+ parameter.get(SessionParameter.ATOMPUB_URL) + " userid: "
+ parameter.get(SessionParameter.USER) + " password: "
+ parameter.get(SessionParameter.PASSWORD));
List<Repository> repositories = new ArrayList<Repository>();
repositories = sessionFactory.getRepositories(parameter);
for (Repository r : repositories) {
System.out.println("-- Found repository: " + r.getName());
}
Repository repository = repositories.get(0);
parameter.put(SessionParameter.REPOSITORY_ID, repository.getId());
session = sessionFactory.createSession(parameter);
System.out.println("-- Connected to repository: "
+ repository.getName() + ", with id: " + repository.getId());
//get workflow engines
// ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
}
|
1e3e6e7d-f536-40aa-ba8b-0298388a49d6
| 5
|
public static void ex15(){
System.out.println("Taula de qualificacions del alumnes: ");
System.out.println("Alumne\tConeptes (60%)\tProcediments (30%)\tActitud (10%)\tFinal");
int c=0, p=0, a=0;
float f=0;
DecimalFormat df=new DecimalFormat("0.00");
for(int i=0; i<25; i++){
c=(int)(Math.random()*11);
p=(int)(Math.random()*11);
a=(int)(Math.random()*11);
f=(float)(((float)c*0.6)+((float)p*0.3)+((float)a*0.1));
char l=' ';
if(f>=9){
l='E';
}else if(f>=7){
l='N';
}else if(f>=6){
l='B';
}else if(f>=5){
l='S';
}else{
l='I';
}
System.out.println((i+1)+"\t"+c+"\t\t"+p+"\t\t\t"+a+"\t\t"+df.format(f)+" => "+l);
}
}
|
f671f41b-502b-4e7f-8d63-f438a9ba9251
| 2
|
public double standardDeviation_of_ComplexRealParts() {
boolean hold = Stat.nFactorOptionS;
if (nFactorReset) {
if (nFactorOptionI) {
Stat.nFactorOptionS = true;
} else {
Stat.nFactorOptionS = false;
}
}
double[] re = this.array_as_real_part_of_Complex();
double standardDeviation = Stat.standardDeviation(re);
Stat.nFactorOptionS = hold;
return standardDeviation;
}
|
d7197588-2ebe-4d93-811e-ecbe4b51b2de
| 6
|
public void learnUnlabeledData(FrameSet unlabeledData,
String partitionStyle, int partitionOption,
double convergenceThreshold, double alpha){
double previousDistance = Double.MAX_VALUE;
this.alpha = alpha;
boolean converged = false;
List<FrameSet> batches;
while(!converged){
System.out.println("Refining codebook...");
batches = unlabeledData.partition(partitionStyle, partitionOption);
// To show progress...
int nbBatches = batches.size();
double lastPercentage = -1;
int batchesDone = 0;
long startTime = System.nanoTime();
for(FrameSet batch : batches){
double percentage=Math.floor((double)batchesDone/nbBatches*100);
if(percentage != lastPercentage){
System.out.println("Progress: " + percentage + "%");
lastPercentage = percentage;
if(percentage == 1.0){
long endTime = System.nanoTime();
System.out.println("Expected time to finish: " +
((startTime- endTime)/10000000) + "seconds");
}
}
Array2DRowRealMatrix activationForBatch = l1RegularizedLassoSolve(batch);
improveWithLeastSquaresSolve(batch, activationForBatch);
batchesDone++;
}
System.out.println("Activating unlabeled data...");
FrameSet activations = activate(unlabeledData);
System.out.println("Calculating reconstruction error...");
double currentDistance = getAverageRegularizedReconstructionError(
unlabeledData, activations);
System.out.println("Current error = " + currentDistance);
if(currentDistance > previousDistance){
System.out.println("DISTANCE INCREASED! Running again.");
previousDistance = currentDistance;
}else if(previousDistance - currentDistance < convergenceThreshold){
converged = true;
}else{
System.out.println("We made a step of "
+ (previousDistance - currentDistance)
+ ", which does not meet convergence criteria. "
+ "Running again.");
previousDistance = currentDistance;
}
}
}
|
c916453a-c12f-4589-9d02-096c9c801f8e
| 6
|
private void checkCollisions() {
// Collision between ball and left paddle
if (paddles[0].collide(ball)) {
if (ball.getXSpeed() < 0) {
changeBallTrajectory(true);
}
}
// Collision between ball and right paddle
if (paddles[1].collide(ball)) {
if (ball.getXSpeed() > 0) {
changeBallTrajectory(false);
}
}
// Collision between ball and the top or bottom of the window
if(!(ball.getY() > ball.getHeight() / 2 && ball.getY() < WINDOW_DIMENSIONS[1] - ball.getHeight() / 2)) {
ball.setYSpeed(- ball.getYSpeed());
}
}
|
c2421f6e-3f4d-406e-867e-3674fdf1d06f
| 4
|
@Test
public void testWrongUser() throws Exception{
AccessControlServer server = new AccessControlServer(1935);
server.start();
SpotStub spot = new SpotStub("139",1935);
spot.start();
SpotStub security = new SpotStub("security",1935);
security.start();
sleep(100);
security.resetAnswer();
security.setReListen();
spot.setWrong();
sleep(100);
String ans = "";
int x = 0;
while(x != -1 && x<=50){ //if no response is received in 10 seconds, test is deemed failed.
x++;
ans = security.getAnswer();
sleep(100);
if(ans != ""){
if(ans.equals("wrong")){
x = -1;
}
else{
spot.setWrong();
sleep(100);
security.resetAnswer();
security.setReListen();
}
}
}
assertEquals("wrong",ans);
}
|
480bdb36-98de-499f-a65d-57a5a55711d7
| 5
|
public RC4(final byte[] seed)
{
if (seed.length < 1) { throw new IllegalArgumentException("RC4 Key too short (minimum: 1 byte)"); }
if (seed.length > 256) { throw new IllegalArgumentException("RC4 Key too long (maximum: 256 bytes)"); }
for (int i = 0; i < 256; i++)
{
this.s[i] = i;
}
for (int i = 0; i < 256; i++)
{
this.b = (this.b + this.s[i] + (seed[i % seed.length]) & 0xFF) % 256;
this.swap(this.b, i);
}
this.b = 0;
for (int i = 0; i < RC4.SKIP_BYTES; i++)
{
this.getByte();
}
}
|
cd4276ca-8823-41b1-abcd-8cc492618323
| 1
|
public List findByProperty(String propertyName, Object value) {
log.debug("finding Problem instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from Problem as model where model."
+ propertyName + "= ?";
Query queryObject = getSession().createQuery(queryString);
queryObject.setParameter(0, value);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}
|
503f0619-139d-46f1-90bf-455869cdf92e
| 4
|
public void updateList() {
for (int i=0;i<parent.window.nbSongsInList;i++) {
if (parent.tracksManager.tracksList.size()>i+listOffset)
{
Track thisTrack = parent.tracksManager.tracksList.get(i+listOffset);
if (thisTrack.getId()==parent.tracksManager.currentTrack) getSpecificCell("edit", i).setValue("");
else getSpecificCell("edit", i).setValue("edit");
getSpecificCell("edit", i).setActive(thisTrack.getId()==parent.tracksManager.currentTrack);
getSpecificCell("match", i).setActive(thisTrack.matches[parent.tracksManager.currentTrack().getId()]!=0);
if (thisTrack.matches[parent.tracksManager.currentTrack().getId()]==2)
getSpecificCell("match", i).setValue("SUPER");
else getSpecificCell("match", i).setValue("match");
getSpecificCell("listAuthor", i).setValue(thisTrack.author);
getSpecificCell("listTitle", i).setValue(thisTrack.title);
getSpecificCell("listPart", i).setValue(String.valueOf(thisTrack.part));
getSpecificCell("listBpm", i).setValue(String.valueOf(thisTrack.bpm));
getSpecificCell("listKeyFr", i).setValue(String.valueOf(thisTrack.keyFr));
getSpecificCell("listFrPerBpm", i).setValue(String.valueOf(thisTrack.frPerBpm));
getSpecificCell("listTempoForRef", i).setValue(String.valueOf(thisTrack.tempoForRef));
getSpecificCell("listRefFr", i).setValue(String.valueOf(thisTrack.refFr));
getSpecificCell("listKeyNotes", i).setValue(thisTrack.keyNotes);
}
else
{
getSpecificCell("edit", i).setValue("");
getSpecificCell("edit", i).setActive(false);
getSpecificCell("match", i).setActive(false);
getSpecificCell("listAuthor", i).setValue("");
getSpecificCell("listTitle", i).setValue("");
getSpecificCell("listPart", i).setValue("");
getSpecificCell("listBpm", i).setValue("");
getSpecificCell("listKeyFr", i).setValue("");
getSpecificCell("listFrPerBpm", i).setValue("");
getSpecificCell("listTempoForRef", i).setValue("");
getSpecificCell("listRefFr", i).setValue("");
getSpecificCell("listKeyNotes", i).setValue("");
}
}
}
|
03b5e402-a25d-4080-9d4b-c6b71a0978ca
| 0
|
public void setUserInput(int[] n)
{
userInput = n;
}
|
b08e6d66-cf36-44f2-a95a-52917feaec6c
| 9
|
@Override
public ArrayList<Chromosome<T>> update()
{
if(chromoPool.size() % (settings.getInt("GAmkIII.popDivision") * 2) != 0)
{
throw new RuntimeException("Gene pool size (" + chromoPool.size() + ") is not dividable by " + (settings.getInt("GAmkIII.popDivision") * 2));
}
ArrayList<Chromosome<T>> newChromoList = new ArrayList<Chromosome<T>>();
double totalFitness = 0;
for(Chromosome<T> chromosome : chromoPool)
{
totalFitness += chromosome.getFitness();
}
avgFitness = totalFitness/chromoPool.size();
for(int i = chromoPool.size() / settings.getInt("GAmkIII.popDivision"); i > 0; i -= 2)
{
Chromosome<T> c1 = pickChromosome(chromoPool);
Chromosome<T> c2 = pickChromosome(chromoPool);
if(Math.random() <= crossOverRate)
{
if(c1.getLength() != c2.getLength())
{
throw new RuntimeException("Chromosome lengths do not match, can not crossover");
}
int crossOverPoint = (int) Math.floor(Math.random() * c1.getLength());
c1.crossOver(crossOverPoint, c2);
}
for(int j = 1; j <= settings.getInt("GAmkIII.popDivision"); j++)
{
newChromoList.add(c1);
newChromoList.add(c2);
}
}
chromoPool.clear();
for(Chromosome<T> chromosome : newChromoList)
{
for(int i = 0; i <= chromosome.getLength() - 1; i++)
{
if(Math.random() <= mutationRate)
{
chromosome.mutate(i);
}
}
}
return newChromoList;
}
|
a39464d1-65a7-4b36-9533-5aae51c58a75
| 1
|
@Override
public V get(K key) {
int i = findEntry(key);
if (i < 0)
return null;
return bucket[i].getValue();
}
|
0b972e8e-b24d-4004-ab69-61cb0f8cdb61
| 8
|
public VoidValue visitDefine(DefineComponent c) {
addLeadingComments(c);
String name = c.getName();
SourceLocation location = c.getSourceLocation();
Annotation annotation = makeAnnotation(c);
if (name == DefineComponent.START) {
if (!si.isIgnored(c)) {
Pattern body = c.getBody();
ChildType ct = si.getChildType(body);
if (ct.contains(ChildType.ELEMENT))
schema.addRoot(body.accept(particleBuilder),
location,
annotation);
}
}
else {
Pattern body = si.getBody(c);
if (body != null) {
ChildType ct = si.getChildType(body);
if (ct.contains(ChildType.ELEMENT)) {
guide.setGroupEnableAbstractElement(name,
getGroupEnableAbstractElements(c, groupEnableAbstractElements));
schema.defineGroup(name,
body.accept(particleBuilder),
location,
annotation);
}
else if (ct.contains(ChildType.DATA) && !ct.contains(ChildType.TEXT))
schema.defineSimpleType(name,
body.accept(simpleTypeBuilder),
location,
annotation);
if (ct.contains(ChildType.ATTRIBUTE))
schema.defineAttributeGroup(name,
body.accept(attributeUseBuilder),
location,
annotation);
}
}
addTrailingComments(c);
return VoidValue.VOID;
}
|
16b21def-ce36-4a04-be98-35903dcfc112
| 3
|
public ReleaseType getLatestType() {
this.waitForThread();
if (this.versionType != null) {
for (ReleaseType type : ReleaseType.values()) {
if (this.versionType.equals(type.name().toLowerCase())) {
return type;
}
}
}
return null;
}
|
f68807cc-a4ec-449a-b165-f90458537196
| 8
|
private String getHelp(String ind) {
boolean found = false;
String help = "";
try {
int index = Integer.parseInt(ind);
for(Command leaf : currentMenu.getCommands()) {
if(leaf.getIndex() == index) {
help = "[" + leaf.getDesc() + "] " + leaf.getHelp();
found = true;
}
}
for(CmdMenu node : currentMenu.getSubMenues()) {
if((node.getIndex() == index) && (!found)) {
help = "[" + node.getDesc() + "] " + node.getHelp();
found = true;
}
}
if(index == 0) {
help = "[" + currentMenu.getDesc() + "] " + currentMenu.getHelp();
found = true;
}
if(!found) {
help = "Ungueltige Eingabe.";
}
}
catch(Exception e) {
help = "Ungueltige Eingabe.";
}
return help;
}
|
e3bbc6e8-7708-438d-884f-3a9d76f6e1c6
| 7
|
@Override
public String generate(TreeLogger logger, GeneratorContext context,
String typeName) throws UnableToCompleteException {
TypeOracle typeOracle = context.getTypeOracle();
JClassType type = typeOracle.findType(typeName);
if (type.isAbstract() && type.isInterface() == null) {
logger.log(Type.ERROR,
"Target type should either be an interface or a non-abstract class");
throw new UnableToCompleteException();
}
/*
* Class name depends on the used properties -> must evaluate the type
* before we know whether to generate a new class. Most of the effort
* does currently go to the evaluation, so we might as well keep the
* design simple by directly producing the class body at the same time
* instead of first populating a data model and then using that data
* model to produce the source only when needed.
*/
StringSourceWriter sourceWriter = new StringSourceWriter();
Set<String> usedSelectionProperties = writeMethods(
logger.branch(Type.DEBUG, "Processing methods in " + typeName),
context, type, sourceWriter);
// Properties in deterministic order
ArrayList<String> sortedProperties = new ArrayList<String>(
usedSelectionProperties);
Collections.sort(sortedProperties);
StringBuilder prefixes = new StringBuilder("Impl");
for (String propertyName : sortedProperties) {
try {
SelectionProperty property = context.getPropertyOracle()
.getSelectionProperty(logger, propertyName);
if (property.getPossibleValues().size() > 1) {
/*
* Separating with not 100% safe as a_b + c and a + b_c
* would both give a_b_c, but the collision risk is quite
* minimal. AbstractClientBundleGenerator seems to use the
* same strategy in generateSimpleSourceName.
*/
prefixes.append('_').append(property.getCurrentValue());
}
} catch (BadPropertyValueException e) {
logger.log(Type.ERROR, "Could not recheck property", e);
throw new UnableToCompleteException();
}
}
String packageName = type.getPackage().getName();
String className = type.getSimpleSourceName() + prefixes.toString();
PrintWriter writer = context.tryCreate(logger, packageName, className);
if (writer != null) {
ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(
packageName, className);
logger.log(Type.DEBUG,
"Assembling " + factory.getCreatedClassName());
if (type.isInterface() != null) {
factory.addImplementedInterface(type.getQualifiedSourceName());
} else {
factory.setSuperclass(type.getQualifiedSourceName());
}
SourceWriter realSourceWriter = factory.createSourceWriter(context,
writer);
realSourceWriter.print(sourceWriter.toString());
realSourceWriter.commit(logger);
}
String createdClassName = packageName + "." + className;
return createdClassName;
}
|
8907c1fc-7d23-43d1-a8a6-885605c18363
| 7
|
public void updatePtgs()
{
if( expression == null ) // happens upon init
{
return;
}
byte[] rkdata = getData();
int offset = 15 + cch; // the start of the parsed expression
int sz = offset;
int sz2 = rkdata.length - (offset + cce);
cce = 0;
// add up the size of the expressions
for( int i = 0; i < expression.size(); i++ )
{
Ptg ptg = (Ptg) expression.elementAt( i );
cce += ptg.getLength();
}
sz += cce;
sz += sz2;
byte[] updated = new byte[sz];
System.arraycopy( rkdata, 0, updated, 0, offset );
byte[] cbytes = ByteTools.shortToLEBytes( cce );
updated[4] = cbytes[0];
updated[5] = cbytes[1];
// 20090317 KSC: added handling for PtgArrays
boolean hasArray = false;
byte[] arraybytes = new byte[0];
for( int i = 0; i < expression.size(); i++ )
{
Ptg ptg = (Ptg) expression.elementAt( i );
byte[] b;
// 20090317 KSC: added handling for PtgArrays
if( ptg instanceof PtgArray )
{
PtgArray pa = (PtgArray) ptg;
b = pa.getPreRecord();
arraybytes = ByteTools.append( pa.getPostRecord(), arraybytes );
hasArray = true;
}
else
{
b = ptg.getRecord();
}
try
{
System.arraycopy( b, 0, updated, offset, b.length/*20071206 KSC: Not necessarily the same ptg.getLength()*/ );
}
catch( Exception e )
{
log.warn( "setting ExternalSheetValue in Name rec: value: " + ptg.getOpcode() + ": " + e );
}
offset = offset + ptg.getLength();
}
// 20090317 KSC: added handling for PtgArrays
if( hasArray )
{
updated = ByteTools.append( arraybytes, updated );
}
// add the rest if any
if( sz2 > 0 )
{
System.arraycopy( rkdata, (rkdata.length - sz2), updated, offset, sz2 );
}
setData( updated );
}
|
e37fdce8-8920-41ac-be37-d87d5b8ad47a
| 5
|
private void pop(char c) throws JSONException {
if (this.top <= 0) {
throw new JSONException("Nesting error.");
}
char m = this.stack[this.top - 1] == null ? 'a' : 'k';
if (m != c) {
throw new JSONException("Nesting error.");
}
this.top -= 1;
this.mode = this.top == 0
? 'd'
: this.stack[this.top - 1] == null
? 'a'
: 'k';
}
|
43c22906-211b-4db3-b851-1a57e3f416ae
| 4
|
@Override
public void appendTo(Appendable out) {
try {
boolean needComma = false;
out.append('{');
for (Map.Entry<String, Object> entry : mMap.entrySet()) {
if (needComma) {
out.append(',');
} else {
needComma = true;
}
out.append(Json.quote(entry.getKey()));
out.append(':');
Object v = entry.getValue();
if (v instanceof JsonCollection) {
((JsonCollection) v).appendTo(out);
} else {
out.append(Json.toString(v));
}
}
out.append('}');
} catch (IOException exception) {
Log.error(exception);
}
}
|
3fcb2552-8951-40f0-830a-9906f5d65584
| 6
|
private SplayNode<K> search(K data) {
if (data == getRoot().data) {
return this.root;
} else {
SplayNode<K> padre = null;
SplayNode<K> hijo = this.root;
while ((hijo != null) && (hijo.data != data)) {
if ((Integer)data < (Integer)hijo.data) {
padre = hijo;
hijo = hijo.left;
}else{
padre = hijo;
hijo = hijo.right;
}
}
if (hijo == null) {
SplayNode<K> aux = gotGrandPa(padre);
if (padre != this.root) {
Splay(aux, padre);
}
}else{
Splay(padre, hijo);
}
}
return this.root;
}
|
355148b7-9ddd-4345-bd91-513d17300b0f
| 4
|
private MenuItem prompt() throws IOException
{
int option;
while (true) {
display();
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String line = input.readLine();
try {
option = Integer.parseInt(line);
if (option >= 0 && option < this.menuItems.size()) {
return this.menuItems.get(option);
}
} catch (NumberFormatException e) {
}
System.err.println(line + " ist keine gueltige Option\n");
}
}
|
887fb299-b9c6-44a4-894a-73a130cfbdba
| 2
|
public boolean noticeUser(String user, String msg) {
boolean success = true;
String[] msgSplit = msg.split("\n");
for(int i=0;i<msgSplit.length;i++){
if(!sendln("NOTICE " + user + " :" + msgSplit[i]) ) {
success = false;
}
}
return success;
}
|
1c73599f-626a-4332-8aee-7e7eef203f51
| 8
|
protected void applyShadow(BufferedImage image) {
int dstWidth = image.getWidth();
int dstHeight = image.getHeight();
int left = (this.shadowSize - 1) >> 1;
int right = this.shadowSize - left;
int xStart = left;
int xStop = dstWidth - right;
int yStart = left;
int yStop = dstHeight - right;
int shadowRgb = this.shadowColor.getRGB() & 0x00FFFFFF;
int[] aHistory = new int[this.shadowSize];
int historyIdx = 0;
int aSum;
int[] dataBuffer = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
int lastPixelOffset = right * dstWidth;
float sumDivider = this.shadowOpacity / this.shadowSize;
// horizontal pass
for (int y = 0, bufferOffset = 0; y < dstHeight; y++, bufferOffset = y * dstWidth) {
aSum = 0;
historyIdx = 0;
for (int x = 0; x < this.shadowSize; x++, bufferOffset++) {
int a = dataBuffer[bufferOffset] >>> 24;
aHistory[x] = a;
aSum += a;
}
bufferOffset -= right;
for (int x = xStart; x < xStop; x++, bufferOffset++) {
int a = (int) (aSum * sumDivider);
dataBuffer[bufferOffset] = a << 24 | shadowRgb;
// substract the oldest pixel from the sum
aSum -= aHistory[historyIdx];
// get the lastest pixel
a = dataBuffer[bufferOffset + right] >>> 24;
aHistory[historyIdx] = a;
aSum += a;
if (++historyIdx >= this.shadowSize) {
historyIdx -= this.shadowSize;
}
}
}
// vertical pass
for (int x = 0, bufferOffset = 0; x < dstWidth; x++, bufferOffset = x) {
aSum = 0;
historyIdx = 0;
for (int y = 0; y < this.shadowSize; y++,
bufferOffset += dstWidth) {
int a = dataBuffer[bufferOffset] >>> 24;
aHistory[y] = a;
aSum += a;
}
bufferOffset -= lastPixelOffset;
for (int y = yStart; y < yStop; y++, bufferOffset += dstWidth) {
int a = (int) (aSum * sumDivider);
dataBuffer[bufferOffset] = a << 24 | shadowRgb;
// substract the oldest pixel from the sum
aSum -= aHistory[historyIdx];
// get the lastest pixel
a = dataBuffer[bufferOffset + lastPixelOffset] >>> 24;
aHistory[historyIdx] = a;
aSum += a;
if (++historyIdx >= this.shadowSize) {
historyIdx -= this.shadowSize;
}
}
}
}
|
9a0802dc-2b78-4b66-b182-cd3b7ee49514
| 9
|
public void refreshFields(){
this.removeAll();
GridBagConstraints pCon = new GridBagConstraints();
traceBox = new SubPanel(getTopLevelContainer());
intBox = new SubPanel(getTopLevelContainer());
deriveBox = new SubPanel(getTopLevelContainer());
GridBagConstraints bCon = new GridBagConstraints();
bCon.fill = GridBagConstraints.BOTH;
bCon.gridx = 0;
bCon.gridy = 0;
bCon.gridheight = 1;
bCon.gridwidth = 10;
bCon.weightx = 1;
bCon.weighty = 1;
this.add(traceBox, bCon);
bCon.gridy = 1;
this.add(intBox, bCon);
bCon.gridy = 2;
this.add(deriveBox, bCon);
JPanel colorBox = new JPanel() {
/**
*
*/
private static final long serialVersionUID = 1L;
public void paint(Graphics g) {
g.setColor(color);
g.fillRect(0, 0, 30,30);
}
};
colorBox.setPreferredSize(new Dimension(30,30));
pCon.gridx = 0;
pCon.gridy = 0;
pCon.gridheight = 1;
pCon.gridwidth = 1;
pCon.ipadx = 3;
pCon.ipady = 3;
traceBox.add(colorBox, pCon);
indVar = new OCLabel(func.getIndependentVar().getName() + ":", 1, 1, 1, 0, traceBox, mainApp);
pt2Trace = new OCTextField(getTopLevelContainer(), true, 9, 1, 1, 2, 0, traceBox, mainApp) {
public void associatedAction() {
tracePt();
}
};
trace = new OCButton("Trace", 1, 1, 3, 0, traceBox, mainApp){
public void associatedAction() throws ParseException, ValueNotStoredException, EvalException {
pt2Trace.primaryAction();
}
};
depVar = new OCLabel(func.getDependentVar().getName() + ":", 1, 1, 4, 0, traceBox, mainApp);
tracePtVal = new OCTextField(getTopLevelContainer(), false, 9, 1, 1, 5, 0, traceBox, mainApp);
if(func.getGraphType() == 1){
start = new OCLabel("start:", 1, 1, 0, 0, intBox, mainApp);
startInt = new OCTextField(getTopLevelContainer(), true, 4, 1, 1, 1, 0, intBox, mainApp){
public void associatedAction(){
}
};
end = new OCLabel("end:", 1, 1, 2, 0, intBox, mainApp);
endInt = new OCTextField(getTopLevelContainer(), true, 4, 1, 1, 3, 0, intBox, mainApp){
public void associatedAction(){
}
};
integrate = new OCButton("Integrate", 1, 1, 4, 0, intBox, mainApp){
public void associatedAction() throws ParseException, ValueNotStoredException, EvalException{
startInt.primaryAction();
endInt.primaryAction();
integrate();
}
};
intApprox = new OCLabel("Int:", 1, 1, 5, 0, intBox, mainApp);
intVal = new OCTextField(getTopLevelContainer(), false, 9, 1, 1, 6, 0, intBox, mainApp);
indVar = new OCLabel(func.getIndependentVar().getName() + ":", 1, 1, 0, 0, deriveBox, mainApp);
indVarVal = new OCTextField(getTopLevelContainer(), true, 4, 1, 1, 1, 0, deriveBox, mainApp){
public void associatedAction(){
try {
derive();
} catch (EvalException e) {
// TODO Auto-generated catch block
;
} catch (ParseException e) {
// TODO Auto-generated catch block
;
}
}
};
derive = new OCButton("Derive", 1, 1, 2, 0, deriveBox, mainApp){
public void associatedAction() throws ParseException, ValueNotStoredException, EvalException{
indVarVal.primaryAction();
}
};
slopeApprox = new OCLabel("Slope:", 1, 1, 3, 0, deriveBox, mainApp);
slopeVal = new OCTextField(getTopLevelContainer(), false, 9, 1, 1, 4, 0, deriveBox, mainApp);
if(func.isTakingIntegral()){
startInt.getField().setText("" + func.getStartIntegral());
endInt.getField().setText("" + func.getEndIntegral());
integrate();
}
if(func.isDeriving()){
indVarVal.getField().setText("" + func.getDerivative());
try {
derive();
} catch (EvalException e) {
// TODO Auto-generated catch block
;
} catch (ParseException e) {
// TODO Auto-generated catch block
;
}
}
if(func.isTracingPt()){
pt2Trace.getField().setText("" + func.getTraceVal());
tracePt();
}
}
else if(func.getGraphType() == 2){
//spacer = new OCLabel("Integrate", 1, 1, 5, 0, deriveBox, mainApp);
}
else{
;//do nothing, will add when more graph types supported
}
this.revalidate();
this.repaint();
}
|
76a10ba7-583a-477a-a787-a2b5677b1efe
| 1
|
public <T> void put( CapabilityName<T> name, T capability ){
if( capability == null ){
capabilities.remove( name );
}
else{
capabilities.put( name, capability );
}
}
|
f6897a9b-40db-4f3b-ade8-c1b2be12678c
| 9
|
private void updateComponents(boolean inserted) {
Map<Class, Object> map = new HashMap<Class, Object>();
for (Element i : elementFlow) {
content = (AbstractDocument.LeafElement) i;
enum3 = content.getAttributeNames();
synchronized (enum3) {
while (enum3.hasMoreElements()) {
name = enum3.nextElement();
attr = content.getAttribute(name);
if (name.toString().equals("component")) {
if (attr instanceof Engine) {
engineRespond((Engine) attr, inserted);
map.put(attr.getClass(), attr);
}
else if (attr instanceof ModelCommunicator) {
communicatorRespond((ModelCommunicator) attr, inserted);
}
else if (attr instanceof PageApplet) {
appletRespond((PageApplet) attr, inserted);
}
}
}
}
}
if (!map.isEmpty() && page != null) {
for (Class c : map.keySet()) {
indexifyEngines(c);
}
}
}
|
b9019f48-cfd3-4bf4-a5a5-e59356a502c7
| 4
|
static private int jjMoveStringLiteralDfa5_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(3, old0);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(4, active0);
return 5;
}
switch(curChar)
{
case 99:
if ((active0 & 0x4000L) != 0L)
return jjStartNfaWithStates_0(5, 14, 16);
break;
default :
break;
}
return jjStartNfa_0(4, active0);
}
|
0e689624-a9cf-4177-951b-dc1b74700dcf
| 0
|
public String getAddressType() {
return addressType.get();
}
|
31442987-a7bb-4284-84d1-56c89338d0ee
| 6
|
public static Description instantiateExternalVariables(Description self, KeyValueMap bindings) {
if (!(bindings.emptyP())) {
{ Object old$Evaluationmode$000 = Logic.$EVALUATIONMODE$.get();
Object old$Queryiterator$000 = Logic.$QUERYITERATOR$.get();
try {
Native.setSpecial(Logic.$EVALUATIONMODE$, Logic.KWD_DESCRIPTION);
Native.setSpecial(Logic.$QUERYITERATOR$, null);
{ Description description = Description.newDescription();
{ Stella_Object var = null;
Stella_Object binding = null;
DictionaryIterator iter000 = ((DictionaryIterator)(bindings.allocateIterator()));
while (iter000.nextP()) {
var = iter000.key;
binding = iter000.value;
bindings.insertAt(var, Logic.evaluateTerm(binding));
}
}
description.ioVariables = self.ioVariables.copy();
{ PatternVariable var = null;
Vector vector000 = self.ioVariables;
int index000 = 0;
int length000 = vector000.length();
for (;index000 < length000; index000 = index000 + 1) {
var = ((PatternVariable)((vector000.theArray)[index000]));
bindings.insertAt(var, var);
}
}
{ PatternVariable var = null;
Vector vector001 = ((Vector)(KeyValueList.dynamicSlotValue(self.dynamicSlots, Logic.SYM_LOGIC_EXTERNAL_VARIABLES, null)));
int index001 = 0;
int length001 = vector001.length();
for (;index001 < length001; index001 = index001 + 1) {
var = ((PatternVariable)((vector001.theArray)[index001]));
if (bindings.lookup(var) == null) {
bindings.insertAt(var, var);
}
}
}
{ PatternVariable var = null;
Vector vector002 = self.internalVariables;
int index002 = 0;
int length002 = vector002.length();
for (;index002 < length002; index002 = index002 + 1) {
var = ((PatternVariable)((vector002.theArray)[index002]));
bindings.insertAt(var, var);
}
}
description.proposition = Proposition.inheritProposition(self.proposition, bindings);
return (Description.finishBuildingDescription(description, true, Logic.KWD_TOP_LEVEL));
}
} finally {
Logic.$QUERYITERATOR$.set(old$Queryiterator$000);
Logic.$EVALUATIONMODE$.set(old$Evaluationmode$000);
}
}
}
return (self);
}
|
3c2bed70-204d-4a7a-ab6d-fa80bed99c08
| 1
|
public String tcp2String(Packet packet) {
TCPPacket tcpPacket = (TCPPacket) packet; //Creates a tcpPacket out of the received packet
EthernetPacket ethernetPacket = (EthernetPacket) packet.datalink;
//Creates a ethernet packet to get the ether layer stuff
methodData += src_macInEnglish = ethernetPacket.getSourceAddress(); //Gets the src_mac
methodData += dst_macInEnglish = ethernetPacket.getDestinationAddress(); //Gets the dst_mac
methodData += src_TCPPort = tcpPacket.src_port; //Retrieves the source Port
methodData += sourcePortTCP = String.valueOf(src_TCPPort); //Creates a Src_port string
methodData += dst_TCPPort = tcpPacket.dst_port; //Retrieves the Destination Port
methodData += destinationPortTCP = String.valueOf(dst_TCPPort); //Creates a String for the dst_tcpPort
protocol = tcpPacket.protocol; //Holds the protocol Name
methodData += protocolName = "TCP"; //Make the protocol name TCP
for(int i = 0; i < tcpPacket.data.length; i++) {
data += String.valueOf((char) tcpPacket.data[i]);
}
methodData += data;
methodData += src_ip = tcpPacket.src_ip; //Retrieves the src Ip address
methodData += srcIPString = src_ip.toString();
methodData += dst_ip = tcpPacket.dst_ip; //Retrieves the dst IP address
methodData += dstIPString = dst_ip.toString(); //Creates a string with dst_ip
return methodData;
}
|
4d2d6d1a-70e2-4bf1-9052-601d9139a063
| 6
|
final void da(int i, int i_636_, int i_637_, int[] is) {
float f = ((((Class101_Sub1) ((SoftwareToolkit) this).aClass101_Sub1_7492)
.aFloat5681)
+ ((((Class101_Sub1) ((SoftwareToolkit) this).aClass101_Sub1_7492)
.aFloat5662) * (float) i
+ (((Class101_Sub1) ((SoftwareToolkit) this).aClass101_Sub1_7492)
.aFloat5680) * (float) i_636_
+ (((Class101_Sub1) ((SoftwareToolkit) this).aClass101_Sub1_7492)
.aFloat5664) * (float) i_637_));
if (f < (float) ((SoftwareToolkit) this).anInt7482
|| f > (float) ((SoftwareToolkit) this).anInt7494)
is[0] = is[1] = is[2] = -1;
else {
int i_638_
= (int) ((float) ((SoftwareToolkit) this).anInt7491
* (((Class101_Sub1)
((SoftwareToolkit) this).aClass101_Sub1_7492).aFloat5686
+ ((((Class101_Sub1)
((SoftwareToolkit) this).aClass101_Sub1_7492)
.aFloat5672) * (float) i
+ (((Class101_Sub1)
((SoftwareToolkit) this).aClass101_Sub1_7492)
.aFloat5673) * (float) i_636_
+ (((Class101_Sub1)
((SoftwareToolkit) this).aClass101_Sub1_7492)
.aFloat5669) * (float) i_637_))
/ f);
int i_639_
= (int) ((float) ((SoftwareToolkit) this).anInt7497
* (((Class101_Sub1)
((SoftwareToolkit) this).aClass101_Sub1_7492).aFloat5685
+ ((((Class101_Sub1)
((SoftwareToolkit) this).aClass101_Sub1_7492)
.aFloat5655) * (float) i
+ (((Class101_Sub1)
((SoftwareToolkit) this).aClass101_Sub1_7492)
.aFloat5678) * (float) i_636_
+ (((Class101_Sub1)
((SoftwareToolkit) this).aClass101_Sub1_7492)
.aFloat5666) * (float) i_637_))
/ f);
if (i_638_ >= ((SoftwareToolkit) this).anInt7509
&& i_638_ <= ((SoftwareToolkit) this).anInt7508
&& i_639_ >= ((SoftwareToolkit) this).anInt7490
&& i_639_ <= ((SoftwareToolkit) this).anInt7506) {
is[0] = i_638_ - ((SoftwareToolkit) this).anInt7509;
is[1] = i_639_ - ((SoftwareToolkit) this).anInt7490;
is[2] = (int) f;
} else
is[0] = is[1] = is[2] = -1;
}
}
|
a9066bf2-580c-4da5-8a3c-877b28fd39ce
| 6
|
@Override
public void addDevice(Device device) {
Connection conn = null;
PreparedStatement st = null;
try {
conn = OracleDAOFactory.createConnection();
st = conn.prepareStatement(INSERT_DEVICE);
int id_prev = device.getIdPrev();
if (id_prev == -1) {
st.setNull(1, Types.INTEGER);
} else {
st.setInt(1, id_prev);
}
st.setInt(2, device.getIdComponent());
st.setString(3, device.getTitle());
st.executeUpdate();
} catch (SQLException e) {
throw new ShopException("Can't add device to database", e);
} finally {
try {
if (st != null) {
st.close();
}
} catch (SQLException e) {
throw new ShopException(CANT_CLOSE_STATEMENT, e);
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
throw new ShopException(CANT_CLOSE_CONNECTION, e);
}
}
}
|
5f364825-fa40-483f-8764-be1e82203aad
| 5
|
private PairNode<T> compareAndLink(PairNode<T> first, PairNode<T> second) {
if (second == null) {
return first;
}
if (compare(second.element, first.element) < 0) {
second.prev = first.prev;
first.prev = second;
first.nextSibling = second.leftChild;
if (first.nextSibling != null) {
first.nextSibling.prev = first;
}
second.leftChild = first;
return second;
} else {
second.prev = first;
first.nextSibling = second.nextSibling;
if (first.nextSibling != null) {
first.nextSibling.prev = first;
}
second.nextSibling = first.leftChild;
if (second.nextSibling != null) {
second.nextSibling.prev = second;
}
first.leftChild = second;
return first;
}
}
|
dfa386c5-9a7d-4812-9733-ebb9c811d2b9
| 7
|
public boolean inside(int ax,int ay,int aw,int ah,int bx,int by,int bw,int bh) {
return ((ax > bx && ax < bx+bw) && (ay > by && ay < by + bh) &&
(ax + aw > bx && ax + aw < bx + bw) && (ay+ah > by && ay+ah < by+bh));
}
|
6417496c-3258-4c68-80fe-648673e7be61
| 0
|
public void setIssueNo(String value) {
this.issueNo = value;
}
|
dea70034-63c3-4e36-bf8c-b09e77f78afb
| 7
|
@Override
public boolean equals(Object obj)
{
if(this == obj)
return true;
// this ensures that they both belong to the same switch
if(!super.equals(obj))
return false;
if(!(obj instanceof VirtualPort))
return false;
// same physical port
VirtualPort that = (VirtualPort) obj;
PhysicalPort thisPhyPort = this.getPhysicalPort();
PhysicalPort thatPhyPort = that.getPhysicalPort();
return thisPhyPort == null && thatPhyPort == null ||
thisPhyPort != null && thatPhyPort != null && thisPhyPort.equals(thatPhyPort);
}
|
e701ee04-d09c-43e3-a142-1444c375bfb3
| 0
|
public ModUserLoginEvent(Player player) {
this.player = player;
}
|
1b5db228-1380-4cef-9783-dc283d3ab60f
| 6
|
public ArrayList<Node> generateER(int n,double p){
int linkCounter = 0;
int v = 1;
int w = -1;
double r;
long start = System.currentTimeMillis();
Random gen = new Random();
ArrayList<Node> nodes = new ArrayList<Node>();
Link link;
for(int i=0;i<n;i++)
{
Node newnode = new Node(i);
nodes.add(newnode);
}
while(v<n)
{
r = gen.nextDouble();
w = w + 1 + (int)Math.floor( Math.log(1d-r) / Math.log(1d-p)) ;
while( (w >= v) && (v<n))
{
w = w - v;
v++;
}
if(v < n)
{
link = new Link(nodes.get(w));
nodes.get(v).addLink(link);
link = new Link(nodes.get(v));
nodes.get(w).addLink(link);
linkCounter++;
}
}
if(verb)
{
System.out.println("Generated ER with N = " + nodes.size() + " and L = " + linkCounter + " in " + (System.currentTimeMillis()-start) + " ms.");
}
return nodes;
}
|
26552793-164f-457c-b68a-3c864e0f2f71
| 4
|
boolean exactlyEqual(DsDef def) {
return dsName.equals(def.dsName) && dsType.equals(def.dsType) &&
heartbeat == def.heartbeat && Util.equal(minValue, def.minValue) &&
Util.equal(maxValue, def.maxValue);
}
|
be893d29-4cde-47f3-a730-b8be07965d63
| 8
|
public static int countNeighbours(boolean [][] world, int col, int row){
int total = 0;
total = getCell(world, col-1, row-1) ? total + 1 : total;
total = getCell(world, col , row-1) ? total + 1 : total;
total = getCell(world, col+1, row-1) ? total + 1 : total;
total = getCell(world, col-1, row ) ? total + 1 : total;
total = getCell(world, col+1, row ) ? total + 1 : total;
total = getCell(world, col-1, row+1) ? total + 1 : total;
total = getCell(world, col , row+1) ? total + 1 : total;
total = getCell(world, col+1, row+1) ? total + 1 : total;
return total;
}
|
d62ce794-3495-45fc-b588-813318214ff8
| 5
|
public static void printMatrix(Object[][] M) {
// Calculation of the length of each column
int[] maxLength = new int[M[0].length];
for (int j = 0; j < M[0].length; j++) {
maxLength[j] = M[0][j].toString().length();
for (int i = 1; i < M.length; i++)
maxLength[j] = Math.max(M[i][j].toString().length(), maxLength[j]);
maxLength[j] += 3;
}
// Display
String line, word;
for (int i = 0; i < M.length; i++) {
line = "";
for (int j = 0; j < M[i].length; j++) {
word = M[i][j].toString();
while (word.length() < maxLength[j])
word += " ";
line += word;
}
System.out.println(line);
}
}
|
88d05b14-e592-460c-81eb-9eacabb991e5
| 8
|
private final void checkoutBand() {
final NoYesPlugin plugin = new NoYesPlugin("Local repository "
+ this.repoRoot.getFilename() + " does not exist",
Main.formatMaxLength(this.repoRoot, null, "The directory ",
" does not exist or is no git-repository.\n")
+ "It can take a while to create it. Continue?",
this.io.getGUI(), false, "");
this.io.handleGUIPlugin(plugin);
this.start = System.currentTimeMillis();
if (!plugin.get()) {
return;
}
this.io.startProgress("Initializing repo", -1);
this.repoRoot.getParent().toFile().mkdirs();
try {
Git.init().setDirectory(this.repoRoot.toFile()).call();
} catch (final GitAPIException e) {
this.io.handleException(ExceptionHandle.CONTINUE, e);
return;
}
try {
final Git gitSession = Git.open(this.repoRoot.toFile());
final StoredConfig config = gitSession.getRepository().getConfig();
config.setString("remote", "origin", "url",
VersionControl.DEFAULT_GIT_URL_HTTPS);
config.setString("branch", this.BRANCH.value(), "remote",
this.BRANCH.value());
config.setString("branch", this.BRANCH.value(), "merge",
"+refs/heads/" + this.BRANCH.value());
config.save();
final ObjectId remoteHead = getRemoteHead(gitSession);
final DiffCommand diffCommand = gitSession.diff();
final List<DiffEntry> diffs;
// set head
gitSession.reset().setMode(ResetType.SOFT)
.setRef(remoteHead.getName()).call();
diffCommand.setCached(true);
diffCommand.setShowNameAndStatusOnly(true);
diffs = diffCommand.call();
this.io.startProgress("checking out", diffs.size());
for (final DiffEntry diff : diffs) {
if (diff.getChangeType() != ChangeType.DELETE) {
this.io.setProgressTitle("checking out ...");
this.io.updateProgress(1);
continue;
}
final String file0 = diff.getOldPath();
final String file;
if (file0.startsWith("enc")) {
file = file0.substring(4) + ".abc";
encrypt(file0, file, false);
} else {
file = file0;
}
this.io.setProgressTitle("checking out " + file);
// unstage to make checkout working
gitSession.reset().setRef(remoteHead.getName()).addPath(file)
.call();
final CheckoutCommand checkout = gitSession.checkout().addPath(
file);
final boolean existing = this.repoRoot.resolve(file).exists();
if (existing) {
final String old = this.repoRoot.resolve(file)
.createBackup("_old");
if (old == null) {
this.io.printError("failed to checkout " + old, true);
this.io.updateProgress(1);
continue;
}
this.io.printError(
String.format("%-40s renamed to %s\n", file, old),
true);
}
checkout.call();
this.io.updateProgress(1);
}
this.io.endProgress("Checkout done");
} catch (final GitAPIException | IOException | InterruptedException e) {
this.repoRoot.resolve(".git").delete();
this.io.handleException(ExceptionHandle.CONTINUE, e);
return;
}
}
|
5a7bbf7d-e120-43b3-bc1f-59a0434eb4cc
| 2
|
public void setKilpienergia(double energia){
if (-50 <= energia && energia <= 100){
this.kilpienergia = energia;
}
}
|
b7f1409e-cc21-4c7f-8be7-1a15bfa29de1
| 4
|
public void setup(Plugin p) {
this.p = p;
if(!p.getDataFolder().exists()) p.getDataFolder().mkdir();
cfile = new File(p.getDataFolder(), "ezPermissions.yml");
if(!cfile.exists()) {
try { cfile.createNewFile(); }
catch (Exception e) { e.printStackTrace(); }
}
config = YamlConfiguration.loadConfiguration(cfile);
if(!config.contains("groups")) config.createSection("groups");
setupGroups();
}
|
a4e4b9a2-6b3a-4597-8dca-4d679c1f76dc
| 5
|
public Database()
{
if (Misc.is(Constants.DatabaseType, new String[] { "sqlite", "h2", "h2sql", "h2db" })) {
this.driver = "org.h2.Driver";
this.dsn = ("jdbc:h2:" + Constants.Plugin_Directory + File.separator + Constants.SQLDatabase + ";AUTO_RECONNECT=TRUE");
this.username = "sa";
this.password = "sa";
} else if (Constants.DatabaseType.equalsIgnoreCase("mysql")) {
this.driver = "com.mysql.jdbc.Driver";
this.dsn = ("jdbc:mysql://" + Constants.SQLHostname + ":" + Constants.SQLPort + "/" + Constants.SQLDatabase);
this.username = Constants.SQLUsername;
this.password = Constants.SQLPassword;
}
try
{
Class.forName(this.driver).newInstance(); } catch (Exception e) {
System.out.println("[iConomy] Driver error: " + e);
}
if ((Misc.is(Constants.DatabaseType, new String[] { "sqlite", "h2", "h2sql", "h2db" })) &&
(this.h2pool == null))
this.h2pool = JdbcConnectionPool.create(this.dsn, this.username, this.password);
}
|
964760d2-d581-4b59-b821-d25afb2c0688
| 7
|
@EventHandler(priority=EventPriority.HIGH, ignoreCancelled=true)
public void onBreak(BlockBreakEvent event)
{
if(!event.getBlock().getWorld().getName().equals(p.getWorld())) return;
Player player = event.getPlayer();
Location loc = event.getBlock().getLocation();
Chunk c = loc.getChunk();
String chunk = c.getX()+","+c.getZ();
if(p.getChunkManager().canBuild(player, chunk))
{
int localX = loc.getBlockX() - (16*c.getX());
int localZ = loc.getBlockZ() - (16*c.getZ());
if(((localX > (p.getOffset()-1) && localX < 16-p.getOffset()) && (localZ > (p.getOffset()-1) && localZ < 16-p.getOffset())) || player.hasPermission("plots.override"))
{
// Only do not cancel in this state
// Other cases are always cancelled
return;
}
}
player.sendMessage(RED+"You cannot build here");
event.setCancelled(true);
}
|
dc79dcf1-9828-4a24-a356-1af8962bda9f
| 9
|
private void dispatchHotkeys(GameContainer c) throws SlickException {
Input input = c.getInput();
if (input.isMousePressed(Input.MOUSE_LEFT_BUTTON)) {
bodies.insert(new Body(input.getMouseX() * scale, input.getMouseY() * scale, 0, 0, 1e19, 1e4));
}
if (input.isKeyPressed(Input.KEY_R)) {
initializeTree();
c.reinit();
}
if (input.isKeyPressed(Input.KEY_D)) {
BarnesHutTree.drawQuads = !BarnesHutTree.drawQuads;
}
if (input.isKeyPressed(Input.KEY_P) || input.isKeyPressed(Input.KEY_PAUSE)) {
running = !running;
}
if (input.isKeyPressed(Input.KEY_ADD)) {
++Body.speedFactor;
} else if (input.isKeyPressed(Input.KEY_SUBTRACT)) {
--Body.speedFactor;
} else if (input.isKeyPressed(Input.KEY_0) || input.isKeyPressed(Input.KEY_NUMPAD0)) {
Body.speedFactor = 0;
}
}
|
564160ea-61fd-4f26-9deb-b4f494e60a3b
| 6
|
@EventHandler
public void WolfMiningFatigue(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getWolfConfig().getDouble("Wolf.MiningFatigue.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getWolfConfig().getBoolean("Wolf.MiningFatigue.Enabled", true) && damager instanceof Wolf && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_DIGGING, plugin.getWolfConfig().getInt("Wolf.MiningFatigue.Time"), plugin.getWolfConfig().getInt("Wolf.MiningFatigue.Power")));
}
}
|
fde25fd1-c8c9-4fa9-9526-5444ad592b3f
| 7
|
*/
public void spaceVertical(FastVector nodes) {
// update undo stack
if (m_bNeedsUndoAction) {
addUndoAction(new spaceVerticalAction(nodes));
}
int nMinY = -1;
int nMaxY = -1;
for (int iNode = 0; iNode < nodes.size(); iNode++) {
int nY = getPositionY((Integer) nodes.elementAt(iNode));
if (nY < nMinY || iNode == 0) {
nMinY = nY;
}
if (nY > nMaxY || iNode == 0) {
nMaxY = nY;
}
}
for (int iNode = 0; iNode < nodes.size(); iNode++) {
int nNode = (Integer) nodes.elementAt(iNode);
m_nPositionY.setElementAt((int) (nMinY + iNode * (nMaxY - nMinY) / (nodes.size() - 1.0)), nNode);
}
}
|
2dde16b7-5fef-44a5-874f-b785c94530ce
| 8
|
private RubiksCube doRotate(Rotation aDirection, Face aFace, int offset,
int tlCubieIdx, int trCubieIdx, int brCubieIdx, int blCubieIdx,
int topCubieIdx, int rightCubieIdx, int bottomCubieIdx, int leftCubieIdx) {
// cube's are immutable so we need to return a new cube state.
byte[] toReturn = new byte[20];
// initialize the return array to this cube's state.
for (int i = 0; i < this.state.length; i+=1) {
toReturn[i] = this.state[i];
}
// The offsets are used to switch the orientation of the corner cubies.
// The values of the offsets are determined by the face that is being rotated.
int offsetOne = 0;
int offsetTwo = 0;
if (offset == 0) { // Front/Rear faces
offsetOne= 0;
offsetTwo = 0;
} else if (offset == 1) { // Left/Right faces
offsetOne= 1;
offsetTwo = 2;
} else if (offset == 2) { // Top/Bottom faces
offsetOne = 2;
offsetTwo = 1;
}
// Calculate the orientations of the corner cubies
int tlOrien = state[tlCubieIdx] % 3;
int trOrien = state[trCubieIdx] % 3;
int brOrien = state[brCubieIdx] % 3;
int blOrien = state[blCubieIdx] % 3;
// Calculate the orientations of the edge cubies.
int topOrien = state[topCubieIdx] % 2;
int rightOrien = state[rightCubieIdx] % 2;
int bottomOrien = state[bottomCubieIdx] % 2;
int leftOrien = state[leftCubieIdx] % 2;
// If this is a left or right face than we have to switch the orientation of the edge cubies.
if (aFace == Face.LEFT || aFace == Face.RIGHT) {
topOrien = (topOrien + 1) % 2;
bottomOrien = (bottomOrien + 1) % 2;
leftOrien = (leftOrien + 1) % 2;
rightOrien = (rightOrien + 1) % 2;
}
if (aDirection == Rotation.CLOCKWISE) {
// Rotate the corner cubies
toReturn[tlCubieIdx] = (byte) ((aFace.top_right * 3) + ((tlOrien + offsetOne) % 3));
toReturn[trCubieIdx] = (byte) ((aFace.bottom_right * 3) + ((trOrien + offsetTwo) % 3));
toReturn[brCubieIdx] = (byte) ((aFace.bottom_left * 3) + ((brOrien + offsetOne) % 3));
toReturn[blCubieIdx] = (byte) ((aFace.top_left * 3) + ((blOrien + offsetTwo) % 3));
// Rotate the edge cubies
toReturn[topCubieIdx] = (byte) ((aFace.right -8) * 2 + topOrien);
toReturn[rightCubieIdx] = (byte) ((aFace.bottom-8) * 2 + rightOrien);
toReturn[bottomCubieIdx] = (byte) ((aFace.left-8) * 2 + bottomOrien);
toReturn[leftCubieIdx] = (byte) ((aFace.top-8) * 2 + leftOrien);
} else if (aDirection == Rotation.COUNTER_CLOCKWISE) {
// Rotate the corner cubies
toReturn[tlCubieIdx] = (byte) ((aFace.bottom_left * 3) + ((tlOrien + offsetOne) % 3));
toReturn[trCubieIdx] = (byte) ((aFace.top_left * 3) + ((trOrien + offsetTwo) % 3));
toReturn[brCubieIdx] = (byte) ((aFace.top_right * 3) + ((brOrien + offsetOne) % 3));
toReturn[blCubieIdx] = (byte) ((aFace.bottom_right * 3) + ((blOrien + offsetTwo) % 3));
// Rotate the edge cubies
toReturn[topCubieIdx] = (byte) ((aFace.left-8) * 2 + topOrien);
toReturn[rightCubieIdx] = (byte) ((aFace.top-8) * 2 + rightOrien);
toReturn[bottomCubieIdx] = (byte) ((aFace.right-8) * 2 + bottomOrien);
toReturn[leftCubieIdx] = (byte) ((aFace.bottom-8) * 2 + leftOrien);
}
return new RubiksCube(toReturn);
}
|
8e69b575-c9f2-4063-a38e-04b89d47908b
| 7
|
public static void main(String[] args) throws IOException {
SSPPBuildManager manager = new SSPPBuildManager();
if (args.length != 3) {
LOG.info("Usage: java SSPPBuildManager CIUrl tempFolder formalBuildFolder");
System.exit(0);
} else {
CI_URL = args[0];
CI_ZIP_URL = CI_URL + "*zip*/archive.zip";
String buildNumber = manager.getBuildNumberFromWeb();
LOG.info("Last Successful build: " + buildNumber);
manager.setBuildNumber(buildNumber);
manager.quit();
String downloadFolder = args[1];
File tempFolder = new File(downloadFolder);
if (tempFolder.exists()) {
FileUtils.deleteDirectory(tempFolder);
tempFolder.mkdirs();
}
manager.setDownloadRootFolderPath(downloadFolder);
String formalBuildFolderDir = args[2];
File formalBuildFolder = new File(formalBuildFolderDir);
if (!formalBuildFolder.exists() || !formalBuildFolder.isDirectory() || !formalBuildFolder.canWrite()) {
LOG.info("The path doesn't exist or is not a writable directory: " + formalBuildFolderDir);
System.exit(0);
}
manager.setFormalBuildFolder(formalBuildFolderDir);
File targetFolder = new File(manager.getFormalBuildFolder() + File.separator + manager.getBuildNumber());
if (targetFolder.exists()) {
LOG.info("The build has been created before: " + targetFolder.getAbsolutePath() + ". Do nothing ...");
System.exit(0);
}
}
LOG.info("Downloading build from " + CI_URL);
if (manager.downloadBuild()) {
manager.decompressZip();
manager.removeUselessFolder();
LOG.info("Build is ready in " + manager.getFormalBuildFolder() + File.separator + manager.getBuildNumber());
}
}
|
310720bb-6d81-4f27-b298-c708a9f2eaa5
| 7
|
public static void testValidity(Object o) throws JSONException {
if (o != null) {
if (o instanceof Double) {
if (((Double)o).isInfinite() || ((Double)o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
} else if (o instanceof Float) {
if (((Float)o).isInfinite() || ((Float)o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
}
}
}
|
3e15d7f2-86da-4e7c-b9f2-db735a65faf4
| 8
|
@Override
public void remove(Integer[] ids) throws DaoException
{
if ((ids == null) || (ids.length < 1))
{
return ;
}
PooledConnection connection = null;
PreparedStatement pStatement = null;
try
{
connection = (PooledConnection) cp.takeConnection();
StringBuffer query = new StringBuffer(NewsDaoStatement.deleteNews.getStatement());
int lastId = ids[ids.length - 1];
for (int id : ids)
{
query.append(id);
if (lastId == id)
{
query.append(")");
}
else
{
query.append(",");
}
}
pStatement = connection.prepareStatement(query.toString());
return;
// return (pStatement.executeUpdate() > 0 ? true : false);
}
catch (NoConnectionException | ConnectionSQLException e)
{
log.error("Can't take connection from ConnectionPool", e);
throw new DaoException("Can't take connection from ConnectionPool", e);
}
catch (SQLException e)
{
log.error("Error in SQL statement " + NewsDaoStatement.deleteNews.getStatement(), e);
throw new DaoException("Error in SQL statement " + NewsDaoStatement.deleteNews.getStatement(), e);
}
finally
{
if (null != connection)
{
try
{
this.closeStatement(pStatement);
cp.releaseConnection(connection);
}
catch (ConnectionSQLException e)
{
log.error("Can't release connection back", e);
throw new DaoException("Can't release connection back", e);
}
}
}
}
|
0949816f-8e39-4a09-8c72-c11b347ad6dc
| 1
|
private static String FormatInt(String value) {
if (value.length() == 1) {
return "0" + value;
} else {
return value;
}
}
|
52a86ec5-6280-44f5-89a5-c14def6b3b96
| 9
|
private java.util.ArrayList<Element> findImplementations(String base){
java.util.ArrayList<Element> elements = new java.util.ArrayList<Element>();
NodeList Schemas = getSchema();
for (int i=0; i<Schemas.getLength(); i++ ) {
Node node = Schemas.item(i);
String typeName = DOM.getAttributeValue(node, "name");
String nodeName = stripNameSpace(node.getNodeName().toLowerCase());
if (nodeName.equals("complextype")){
boolean isAbstract = DOM.getAttributeValue(node, "abstract").equalsIgnoreCase("true");
if (!isAbstract){
NodeList complexTypes = node.getChildNodes();
for (Node complexNode : DOM.getNodes(complexTypes)){
String complexType = stripNameSpace(complexNode.getNodeName());
if (complexType.equalsIgnoreCase("simpleContent") || complexType.equalsIgnoreCase("complexContent")) {
NodeList childNodes = complexNode.getChildNodes();
for (Node childNode : DOM.getNodes(childNodes)){
if (stripNameSpace(childNode.getNodeName()).equalsIgnoreCase("extension")){
if (DOM.getAttributeValue(childNode, "base").equals(base)){
System.out.println("\t" + typeName);
elements.add(new Element(node));
}
}
}
}
}
}
}
}
return elements;
}
|
4395560b-343e-4e4f-9520-7bf3d732c535
| 9
|
int[] mergeObjects(List<Detection> detections, ArrayList<Detection>[][] grid, HashMap<String, Double> sizeInformation) {
long startTime = System.nanoTime();
int num_groups = 0, num_excess = 0;
double ra_cell_size = sizeInformation.get("ra_cell_size");
double dec_cell_size = sizeInformation.get("dec_cell_size");
int i = 0;
for (Detection det : detections) {
if (det.groupId != null) {
continue;
}
i++;
if ((i % 50000) == 0)
LOG.info("{} in {} seconds", i, (System.nanoTime() - startTime) / 1000000000);
num_groups += 1;
int ra = det.gridX;
int dec = det.gridY;
det.groupId = det.detectionId;
double ra_radius = det.w_ra / 2;
double dec_radius = det.w_dec / 2;
int ra_cells = (int) Math.round(Math.ceil(ra_radius / ra_cell_size));
int dec_cells = (int) Math.round(Math.ceil(dec_radius / dec_cell_size));
int dec_min = Math.max(0, dec - dec_cells);
int dec_max = Math.min(dec_groups - 1, dec + dec_cells);
for (int ra_inc = -ra_cells; ra_inc <= ra_cells; ra_inc++) {
int ora = ((ra + ra_inc + ra_groups) % ra_groups + ra_groups) % ra_groups;
for (int odec = dec_min; odec <= dec_max; odec++) {
for (Detection other : grid[ora][odec]) {
if (det.shouldMatch(other)) {
assert (other.shouldMatch(det));
if (other.groupId != null) {
if (other.compareTo(det) >= 1) {
num_excess += 1;
}
} else {
other.groupId = det.detectionId;
}
}
}
}
}
}
long readTime = (System.nanoTime() - startTime) / 1000000000;
LOG.info("Merged {} detections in {} seconds", i, readTime);
return new int[]{num_groups, num_excess};
}
|
ddcc4bf9-bdd5-436f-bfff-44debd96fe96
| 2
|
@Before
public void setUp() throws Exception {
File f = new File(tmpFilename);
if (f.exists())
if (!f.delete())
throw new IOException("Can't delete cache file for testing\n");
f = null;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.