method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
be509018-7ccf-4b83-acd8-76044d4159c3 | 0 | public Integer getIdObservacion() {
return idObservacion;
} |
a7f9b0a9-ff10-48b8-bde0-bf86c81ee727 | 3 | public String printAST()
{
StringBuilder ret = new StringBuilder();
switch(rhs.size()){
case 1:
if(rhs.get(0) instanceof DeclList){
ret.append(((DeclList)rhs.get(0)).printAST());
}else{
ret.append(((FuncList)rhs.get(0)).printAST());
}
break;
case 2:
ret.append(((DeclList)rhs.get(0)).printAST());
ret.append(((FuncList)rhs.get(1)).printAST());
break;
}
return ret.toString();
} |
5a0b2c74-ae42-49fc-8c4b-e13afacba16d | 1 | @Override
public Item next() {
if (!hasNext())
throw new java.util.NoSuchElementException();
Item x = current.item;
current = current.next;
return x;
} |
7f845fdc-bd85-4c56-95ce-64c739f31b09 | 5 | @SuppressWarnings("unchecked")
private Collection<Object[]> getParameterArrays4_3() throws Exception {
Object[][] methodCalls = new Object[][]{new Object[]{"getTestClass"}};
Class<?> cl = invokeMethodChain(this, methodCalls);
Method[] methods = cl.getMethods();
Method parametersMethod = null;
for (Method method : methods) {
boolean providesParameters = method
.isAnnotationPresent(Parameters.class);
if (!providesParameters) {
continue;
}
if (parametersMethod != null) {
throw new Exception(
"Only one method should be annotated with @Labels");
}
parametersMethod = method;
}
if (parametersMethod == null) {
throw new Exception("No @Parameters method found");
}
return (Collection<Object[]>) parametersMethod.invoke(null);
} |
36c81d65-fef4-4efa-b37b-d17942bd0b64 | 4 | @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) {
if (plugin.config.BLOCK_WATER_DESTROY_LIST.contains(event.getBlockClicked().getType())){
event.setCancelled(true);
} else if (plugin.frozenPlayers.contains(event.getPlayer().getName())) {
//If player is frozen, place frozen block
plugin.newFrozen(event.getBlockClicked().getRelative(event.getBlockFace()));
} else if (plugin.config.FREEZE_LAVA && event.getBucket() == Material.LAVA_BUCKET) {
//If we always freeze lava, freeze it regardless of previous statements
plugin.newFrozen(event.getBlockClicked().getRelative(event.getBlockFace()));
} //Implied 'else flow'
} |
89f96d59-7ee1-4178-97c0-5abc8f179226 | 7 | public static String clean(String s) {
String ns = "";
for (int i=0;i<s.length();i++) {
char c = s.charAt(i);
if (c>=47&&c<=57 || c==45 || c==43 || c==42 || c==95) {
ns += c;
}
}
return ns;
} |
e1ab5126-0e9e-4f97-8a0e-5afb050c58ab | 2 | public double getDouble(String key) throws JSONException {
Object object = this.get(key);
try {
return object instanceof Number
? ((Number)object).doubleValue()
: Double.parseDouble((String)object);
} catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key) +
"] is not a number.");
}
} |
f9755582-ee45-4b6c-98d6-193d59553773 | 1 | public String toString(){
return color ? "o":"x";
} |
807f87aa-fad0-4651-8b76-abeb0967ed33 | 9 | void updateFramebufferSize() {
// Useful shortcuts.
int fbWidth = rfb.framebufferWidth;
int fbHeight = rfb.framebufferHeight;
// Calculate scaling factor for auto scaling.
if (maxWidth > 0 && maxHeight > 0) {
int f1 = maxWidth * 100 / fbWidth;
int f2 = maxHeight * 100 / fbHeight;
scalingFactor = Math.min(f1, f2);
if (scalingFactor > 100)
scalingFactor = 100;
System.out.println("Scaling desktop at " + scalingFactor + "%");
}
// Update scaled framebuffer geometry.
scaledWidth = (fbWidth * scalingFactor + 50) / 100;
scaledHeight = (fbHeight * scalingFactor + 50) / 100;
// Create new off-screen image either if it does not exist, or if
// its geometry should be changed. It's not necessary to replace
// existing image if only pixel format should be changed.
if (memImage == null) {
memImage = viewer.vncContainer.createImage(fbWidth, fbHeight);
memGraphics = memImage.getGraphics();
} else if (memImage.getWidth(null) != fbWidth
|| memImage.getHeight(null) != fbHeight) {
synchronized (memImage) {
memImage = viewer.vncContainer.createImage(fbWidth, fbHeight);
memGraphics = memImage.getGraphics();
}
}
// Images with raw pixels should be re-allocated on every change
// of geometry or pixel format.
if (bytesPixel == 1) {
pixels24 = null;
pixels8 = new byte[fbWidth * fbHeight];
pixelsSource = new MemoryImageSource(fbWidth, fbHeight, cm8,
pixels8, 0, fbWidth);
zrleTilePixels24 = null;
zrleTilePixels8 = new byte[64 * 64];
} else {
pixels8 = null;
pixels24 = new int[fbWidth * fbHeight];
pixelsSource = new MemoryImageSource(fbWidth, fbHeight, cm24,
pixels24, 0, fbWidth);
zrleTilePixels8 = null;
zrleTilePixels24 = new int[64 * 64];
}
pixelsSource.setAnimated(true);
rawPixelsImage = Toolkit.getDefaultToolkit().createImage(pixelsSource);
// Update the size of desktop containers.
if (viewer.inSeparateFrame) {
if (viewer.desktopScrollPane != null)
resizeDesktopFrame();
} else {
setSize(scaledWidth, scaledHeight);
}
viewer.moveFocusToDesktop();
} |
5e1e8395-d50b-4244-adf3-9509a91043b3 | 2 | @Override
public boolean equals(Object o) {
if ( !this.getClass().equals(o.getClass()) ) {
return false;
}
Key other = (Key)o;
if ( this.key == other.key ) {
return true;
} else {
return false;
}
} |
712c45ed-f7ad-440c-9ae8-cdde27b6f672 | 5 | public SubjectVo detail(int no) throws Throwable {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = dataSource.getConnection();
stmt = con.prepareStatement(
"select SNO, TITLE, DEST from SE_SUBJS"
+ " where SNO=?");
stmt.setInt(1, no);
rs = stmt.executeQuery();
if (rs.next()) {
return new SubjectVo()
.setNo(rs.getInt("SNO"))
.setTitle(rs.getString("TITLE"))
.setDescription(rs.getString("DEST"));
} else {
throw new Exception("해당 과목을 찾을 수 없습니다.");
}
} catch (Throwable e) {
throw e;
} finally {
try {rs.close();} catch (Throwable e2) {}
try {stmt.close();} catch (Throwable e2) {}
try {con.close();} catch (Throwable e2) {}
}
} |
21cad1ca-e2bf-43ff-8316-0d4f904239ff | 1 | private String getDeleteVerified( String variable ) {
StringBuilder sb = new StringBuilder();
if ( variable.equalsIgnoreCase( table.getDomName() ) ) {
sb.append( "\n" + TAB + TAB + TAB + "readRecord = " + toJavaCase( variable ) + "Dao.read( ");
sb.append( param + " );\n" );
sb.append( TAB + TAB + TAB + getNullEquals( "readRecord" ) );
}
else {
sb.append( "\n" + TAB + TAB + TAB + "readRecord" + countDelete + " = " + toJavaCase( variable ));
sb.append( "Dao.read( map );\n");
sb.append( TAB + TAB + TAB + getNullEquals( "readRecord" + countDelete ) );
countDelete++;
}
return sb.toString();
} |
795dd548-5402-44b0-a968-dc6d4949405f | 8 | public static void main(String[] args) {
RockPaperScissors myRPSgame = new RockPaperScissors();
String choice;
boolean keepOnPlaying=false;
if(args.length==0){
keepOnPlaying=true;
System.out.println("Play a game? Choose an option:");
}
Scanner in = new Scanner(System.in);
do{
choice="";
if(args.length>0) choice=args[0];
else{
System.out.println("0)quit \n1)Player vs Computer \n2)Computer_1 vs Computer_2");
choice=in.nextLine(); // using Strings makes it easier to extend the range of valid answers.
}
if(choice.equals("0") ) {
keepOnPlaying=false;
System.out.println("Bye for this time!\n");
}
else if(choice.equals("1") ){
if(args.length>1) myRPSgame.playPvC(args[1]);
else {
myRPSgame.playPvC();
System.out.println("===================\nPlay another round? Choose an option:");
}
}
else if(choice.equals("2") ){
myRPSgame.playCvC();
if(args.length==0) System.out.println("===================\nPlay another round? Choose an option:");
}
else {
System.out.println("\nYou chose " + choice +" which is not an option.");
System.out.println("It's good to think outside the box,");
System.out.println("but in this case, you must choose 0, 1 or 2 .");
}
}while(keepOnPlaying);
in.close();
}//main |
d983b4c7-6423-49ae-9f28-9a81ac6dfeb4 | 9 | private List<Mapper> estimateMappers() {
List<Mapper> newMapperList = new ArrayList<Mapper>();
if(isSplitSizeChanged || isMapperConfChanged) {
MapperEstimator mapperEstimator = new MapperEstimator(finishedConf, newConf);
//split size is changed
if(isSplitSizeChanged) {
List<Long> splitsSizeList = InputSplitCalculator.getSplitsLength(newConf);
Map<Integer, Mapper> cacheNewMapper = new HashMap<Integer, Mapper>();
for(int i = 0; i < splitsSizeList.size(); i++) {
Long cSplitSize = splitsSizeList.get(i);
int cSplitMB = (int) (cSplitSize / (1024 * 1024)) ; //HDFS_BYTES_READ
if(!cacheNewMapper.containsKey(cSplitMB)) {
Mapper newMapper = mapperEstimator.estimateNewMapper(job.getMapperList(), cSplitSize);
newMapperList.add(newMapper);
cacheNewMapper.put(cSplitMB, newMapper);
}
else
newMapperList.add(cacheNewMapper.get(cSplitMB)); //Note: multiple references of newMapper
}
}
//do not need to consider split size
else if(isMapperConfChanged) {
for(int i = 0; i < job.getMapperList().size(); i++) {
Mapper newMapper = mapperEstimator.estimateNewMapper(job.getMapperList().get(i));
newMapperList.add(newMapper);
}
}
//none mapper configuration changed
else
for(Mapper mapper : job.getMapperList())
newMapperList.add(mapper);
}
//none mapper configuration changed
else {
for(Mapper mapper : job.getMapperList())
newMapperList.add(mapper);
}
return newMapperList;
} |
0d327b28-1e27-4562-bdc3-a38be6a7751b | 2 | private TreeNodePageWrapper getNodeOfPage (TreeNodePageWrapper parentNode, AbstractPage page) {
TreeNodePageWrapper childNode = null;
for (@SuppressWarnings("unchecked")
Enumeration<TreeNodePageWrapper> children = parentNode.children(); children.hasMoreElements();) {
childNode = children.nextElement();
if (page.equals(childNode.page))
return childNode;
}
return null;
} |
3eb97f53-9715-4832-8585-639516bdaa4c | 1 | private void writeComment() {
if ( comment == null ) {
sb.append( "" );
}
else
sb.append( comment );
} |
3273442c-2dfb-450d-bb06-808d86b204df | 1 | @Test
public void validateBudgetObjectAndThrowExceptionIfNull() {
try {
calculateBudgetBreakdown.calculateBreakdown(null, budgetBreakdown);
fail("Budget Object Is Null.");
} catch(Exception e) {
assertEquals("Budget is null.", e.getMessage());
}
} |
8afed8dc-da1c-4e58-81de-13f8e5176b42 | 2 | @Override
public Iterable<Key> keys()
{
LinkedList<Key> list = new LinkedList<Key>();
for (int i = 0; i < M; i++)
if (keys[i] != null)
list.add(keys[i]);
return list;
} |
5eec5044-6cce-45a1-bbdd-a1b2141627aa | 6 | @Override
public void use(Mob source, World world) {
int dir = source.dir;
Vector2i pos = Vector2d.toVector2i(source.getPos());
Vector2i targeted;
//TODO: fix this shit.
if (dir == Mob.dirUp) {
targeted = new Vector2i(pos.getX() >> 4, (pos.getY() >> 4) - 1);
} else if (dir == Mob.dirRight) {
targeted = new Vector2i((pos.getX() >> 4) + 1, pos.getY() >> 4);
} else if (dir == Mob.dirDown) {
targeted = new Vector2i(pos.getX() >> 4, ((pos.getY()) >> 4) + 1);
} else if (dir == Mob.dirLeft) {
targeted = new Vector2i((pos.getX() >> 4) - 1, pos.getY() >> 4);
} else {
targeted = new Vector2i(-1, -1);
}
if(world.getTile(targeted.getX(), targeted.getY()).id == Tile.holeId && source instanceof Player) {
source.setActiveItem(null);
world.setTile(Tile.dirtId, targeted.getX(), targeted.getY());
}
} |
6834d7bf-9831-4fe9-9adc-da3496bc47dd | 3 | private static boolean deleteDirectory(File path)
{
if (path.exists())
{
File[] files = path.listFiles();
for (int i = 0; i < files.length; i++)
if (files[i].isDirectory())
deleteDirectory(files[i]);
else
files[i].delete();
}
return (path.delete());
} |
c274f536-98e1-41a3-9fa2-a9f2be65602a | 5 | @Override
public Buildable create(Object name, Object value) {
if (name.equals("forecast_end")) {
Date d = Conversions.convert(value, Date.class);
fc_end = new GregorianCalendar();
fc_end.setTime(d);
} else if (name.equals("forecast_days")) {
fc = (Integer) value;
if (fc < 1) {
throw new IllegalArgumentException("forecast_days < 1");
}
} else if (name.equals("first_year")) {
first_year = (Integer) value;
} else if (name.equals("last_year")) {
last_year = (Integer) value;
} else {
return super.create(name, value);
}
return LEAF;
} |
96784bf6-b26e-440b-bef4-72315ba26877 | 8 | static int FMInitTable() {
int s, t;
double rate;
int i, j;
double pom;
/* allocate total level table plus+minus section */
TL_TABLE = new int[2 * TL_MAX];
/* make total level table */
for (t = 0; t < TL_MAX; t++) {
if (t >= PG_CUT_OFF) {
rate = 0; /* under cut off area */
} else {
rate = ((1 << TL_BITS) - 1) / Math.pow(10, EG_STEP * t / 20); /* dB -> voltage */
}
TL_TABLE[t] = (int) rate;
TL_TABLE[TL_MAX + t] = -TL_TABLE[t];
/* Log(LOG_INF,"TotalLevel(%3d) = %x\n",t,TL_TABLE[t]);*/
}
/* make sinwave table (total level offet) */
for (s = 1; s <= SIN_ENT / 4; s++) {
pom = Math.sin(2.0 * Math.PI * s / SIN_ENT); /* sin */
pom = 20 * Math.log10(1 / pom); /* -> decibel */
j = (int) (pom / EG_STEP); /* TL_TABLE steps */
/* cut off check */
if (j > PG_CUT_OFF) {
j = PG_CUT_OFF;
}
/* degree 0 - 90 , degree 180 - 90 : plus section */
SIN_TABLE[s] = SIN_TABLE[SIN_ENT / 2 - s] = new IntSubArray(TL_TABLE, j);
/* degree 180 - 270 , degree 360 - 270 : minus section */
SIN_TABLE[SIN_ENT / 2 + s] = SIN_TABLE[SIN_ENT - s] = new IntSubArray(TL_TABLE, TL_MAX + j);
/* Log(LOG_INF,"sin(%3d) = %f:%f db\n",s,pom,(double)j * EG_STEP); */
}
/* degree 0 = degree 180 = off */
SIN_TABLE[0] = SIN_TABLE[SIN_ENT / 2] = new IntSubArray(TL_TABLE, PG_CUT_OFF);
/* envelope counter -> envelope output table */
for (i = 0; i < EG_ENT; i++) {
/* ATTACK curve */
/* !!!!! preliminary !!!!! */
pom = Math.pow(((double) (EG_ENT - 1 - i) / EG_ENT), 8) * EG_ENT;
/* if( pom >= EG_ENT ) pom = EG_ENT-1; */
ENV_CURVE[i] = (int) pom;
/* DECAY ,RELEASE curve */
ENV_CURVE[(EG_DST >> ENV_BITS) + i] = i;
/*TODO*///#if FM_SEG_SUPPORT
/*TODO*/// /* DECAY UPSIDE (SSG ENV) */
/*TODO*/// ENV_CURVE[(EG_UST>>ENV_BITS)+i]= EG_ENT-1-i;
/*TODO*///#endif
}
/* off */
ENV_CURVE[EG_OFF >> ENV_BITS] = EG_ENT - 1;
/* decay to reattack envelope converttable */
j = EG_ENT - 1;
for (i = 0; i < EG_ENT; i++) {
while (j != 0 && (ENV_CURVE[j] < i)) {
j--;
}
DRAR_TABLE[i] = j << ENV_BITS;
/* Log(LOG_INF,"DR %06X = %06X,AR=%06X\n",i,DRAR_TABLE[i],ENV_CURVE[DRAR_TABLE[i]>>ENV_BITS] ); */
}
return 1;
} |
a946c711-0609-463c-b589-c5928ff506f6 | 5 | public void stopOpenCmsProcess(String targetDirectory) {
// Check to see if a process is specified in the pid.txt file
this.getLogger().info(
"Checking to see if OpenCms Process is currently running");
try {
String currentlyRunningPid = this.readPidFromFile(targetDirectory);
if (!StringUtils.isEmpty(currentlyRunningPid)) {
// Process is running
this.getLogger().info(
"OpenCms Process is running, attempting to stop. PID: "
+ currentlyRunningPid);
// Handle Windows
if (OSValidator.isWindows()) {
// Try to kill task
Runtime.getRuntime().exec(
"taskkill /F /PID " + currentlyRunningPid);
this.getLogger().info("OpenCms Process killed (windows)");
} else if (OSValidator.isUnix()) {
// Linux
// Try to kill task
Runtime.getRuntime().exec("kill -9 " + currentlyRunningPid);
this.getLogger().info("OpenCms Process killed (linux)");
} else if (OSValidator.isMac()) {
// Mac
// Try to kill task
Runtime.getRuntime().exec("kill -9 " + currentlyRunningPid);
this.getLogger().info("OpenCms Process killed (linux)");
}
// clear out pid
this.writePidToFile("", targetDirectory);
} else {
this.getLogger().info("No OpenCms Processes Running");
}
} catch (IOException e) {
this.getLogger().error("Error stopping OpenCms Process", e);
}
} |
7b1e1cf7-dc3b-4247-9653-86e218e04c6a | 8 | private StringBuilder constructOutputsInit()
{
StringBuilder outputsInit = new StringBuilder();
HashSet<String> outputVars = new HashSet<String>();
outputsInit.append("\t/* Initialize output variables*/\n");
for(int i = 0; i < states.length; i++)
for(int j = 0; j < states[i].length; j++)
{
String[] actions = states[i][j].getActions();
if(actions != null)
{
for(int k = 0; k < actions.length; k++)
{
/* get the first token of the action string*/
String regex = "([\\+\\-\\*/&%\\|\\^]|[<>]+=)|([=])|([\\+\\-]+)";
if(actions[k].contains("=") || actions[k].contains("+") || actions[k].contains("-"))
{
String outputVar = actions[k].split(regex)[0].trim();
if(!outputVars.contains(outputVar))
{
outputVars.add(outputVar);
outputsInit.append("\t" + outputVar + " = 0;\n");
}
}
}
}
}
return outputsInit;
} |
222f0829-5730-424f-be12-f0dfacd883cd | 3 | public void moveMatchedFiles(){
File folderToMove = new File(folderForTheRestOfRaw);
for(String name:filesNamesFromFolderWithJPG){
if(fileAndItsNameinRawFolder.containsKey(name)){
try {
Files.move(fileAndItsNameinRawFolder.get(name).toPath(),
folderToMove.toPath().resolve(fileAndItsNameinRawFolder.get(name).getName()),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} |
34a66732-14f7-4208-bc56-7e21bf3d5084 | 3 | private void collectSaveables(Component component, List<Saveable> saveables) {
if (component instanceof Container) {
Container container = (Container) component;
int count = container.getComponentCount();
for (int i = 0; i < count; i++) {
collectSaveables(container.getComponent(i), saveables);
}
}
if (component instanceof Saveable) {
saveables.add((Saveable) component);
}
} |
3c4a374d-bbc4-4260-92c5-fac7f8e78968 | 4 | public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int score = Integer.parseInt(in.next());
if (score > 85) {
System.out.println("A");
} else if (score > 75) {
System.out.println("B");
} else if (score > 65) {
System.out.println("C");
} else if (score > 55) {
System.out.println("D");
} else {
System.out.println("F");
}
} |
4ce167c0-5575-4b9f-b552-aaa09ea14dab | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Computer))
return false;
Computer other = (Computer) obj;
if (model == null) {
if (other.model != null)
return false;
} else if (!model.equals(other.model))
return false;
if (storage == null) {
if (other.storage != null)
return false;
} else if (!storage.equals(other.storage))
return false;
return true;
} |
7c27ec6b-34d4-40fb-9aa3-4686e270d052 | 6 | public Texture(String fileName) {
try {
BufferedImage image = ImageIO.read(new File(TEXTURE_FOLDER + fileName));
int[] flippedPixels = image.getRGB(0, 0, image.getWidth(), image.getHeight(), null, 0, image.getWidth());
int[] pixels = new int[flippedPixels.length];
// Flip the image vertically
for(int i = 0; i < image.getWidth(); i++)
for(int j = 0; j < image.getHeight(); j++)
pixels[i + j * image.getWidth()] = flippedPixels[i + (image.getHeight() - j - 1) * image.getWidth()];
ByteBuffer data = BufferUtils.createByteBuffer(image.getHeight() * image.getWidth() * 4);
boolean hasAlpha = image.getColorModel().hasAlpha();
// Put each pixel in a Byte Buffer
for(int y = 0; y < image.getHeight(); y++) {
for(int x = 0; x < image.getWidth(); x++) {
int pixel = pixels[y * image.getWidth() + x];
byte alphaByte = hasAlpha ? (byte)((pixel >> 24) & 0xFF) : (byte)(0xFF);
data.put((byte)((pixel >> 16) & 0xFF));
data.put((byte)((pixel >> 8) & 0xFF));
data.put((byte)((pixel) & 0xFF));
data.put(alphaByte);
}
}
data.flip();
textureId = glGenTextures();
width = image.getWidth();
height = image.getHeight();
glBindTexture(GL_TEXTURE_2D, textureId);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
} catch(IOException e) {
e.printStackTrace();
System.exit(1);
}
} |
627ff26e-f518-478d-b12d-746be272e3ab | 6 | public static int toggleDoor(){
int i, j, k;
int count = 0;
boolean s2, s;
Map<Integer, Boolean> map = new HashMap<Integer, Boolean>();
s = true;
for (k = 1; k <= 100; k++){
map.put(k, s); //save all NO. of doors and status in map
}
for (i = 2; i <= 100; i++){
for (j = i; j <= 100; j++){
if (j%i==0){
s2 = ! map.get(j);//change the toggles when touch the NO. of door
map.put(j, s2);//change the status in map
}
}
}
for (Map.Entry<Integer, Boolean> m : map.entrySet()){
if (m.getValue() == true){
System.out.println(m.getKey() + " " + m.getValue());
count += 1;
}
}
return count;
} |
186dbd66-f3f9-4a25-baad-942854c520d7 | 6 | public void writeCellWithComputationsToFilesForVisualization(
String fullFileName,
int maxMeas,
int minMeas,
int mcc,
int net,
int area,
long cellid,
int n,
double d,
double r) {
List<OpenCellIdCell> cells = parseCells(fullFileName, maxMeas, minMeas, r);
for(OpenCellIdCell cell : cells) {
if(cell.getMcc() == mcc && cell.getNet() == net && cell.getArea() == area && cell.getCell() == cellid) {
System.out.println("Measurements: "+cell.getMeasurements().size());
for(Measurement m : cell.getMeasurements()) {
System.out.println(m.getCoordinates());
}
// Computation compDist = Generate.computation(cell, n, d, false);
// System.out.println("vectorAngle dist: "+compDist.getHeuristicCell2().getVectorAngle());
Computation compRSS = Generate.computation(cell, cell.getMeasurements().size(), d, true);
// System.out.println("vectorAngle rss: "+compRSS.getHeuristicCell2().getVectorAngle());
// Point2D.Double averagedCellTowerPos = Process.averagedCellTowerPosition(cell.getMeasurements());
// DefaultCell averagedCell = new DefaultCell(averagedCellTowerPos, 120.0);
// double errorDist = Generate.sphericalError(cell, compDist.getHeuristicCell1());
double errorRSS = Generate.sphericalError(cell, compRSS.getHeuristicCell1());
System.out.println("\n"+errorRSS);
// double errorAver = Generate.sphericalError(cell, averagedCell);
// String newFileNameFirst = JSONFile.filePathDesktop;
// newFileNameFirst += cell.getMcc()+"-"+cell.getNet()+"-"+cell.getArea()+"-"+cell.getCell();
//
// String newFileNameDist = newFileNameFirst + "_distance"+"_"+r+JSONFile.fileFormat;
// String newFileNameRSS = newFileNameFirst + "_RSS"+"_"+r+JSONFile.fileFormat;
// String newFileNameAver = newFileNameFirst + "_averaged"+"_"+r+JSONFile.fileFormat;
// JSONFile jsonFile = new JSONFile(JSONFile.filePathDesktop+cell.getMcc()+"-"+cell.getNet()+"-"+cell.getArea()+"-"+cell.getCell()+JSONFile.fileFormat);
// jsonFile.writeResultForMap(cell, compDist.getHeuristicCell1(), compDist.getHeuristicCell2(), errorDist);
// jsonFile = new JSONFile(newFileNameRSS);
// jsonFile.writeResultForMap(cell, compRSS.getHeuristicCell1(), compRSS.getHeuristicCell2(), errorRSS);
//
// jsonFile = new JSONFile(newFileNameAver);
// jsonFile.writeResultForMap(cell, averagedCell, null, errorAver);
System.out.println("Done writin cells to files");
return;
}
}
} |
48954d67-b3e6-472e-962f-717e54f5f39e | 9 | public static double[] getOptimalParams(int day,XYSeriesCollection dataset, String fileName, int lineNumber,double[] Prices) throws FileNotFoundException, IOException
{
double[] answer=new double[2];
int testStartDay=day-20;
double tempResult=0;
for(int longPeriod=10;longPeriod<80;longPeriod++)
{
for(int shortPeriod=1;shortPeriod<longPeriod;shortPeriod++)
{
double shares=0;
double money=100;
double Result=0;
for(int testday=testStartDay;testday<day;testday++)
{
double longAve =0;
double shortAve =0;
for(int i=testStartDay-longPeriod;i<testStartDay;i++){longAve=longAve+Prices[i];}
for(int i=testStartDay-shortPeriod;i<testStartDay;i++){shortAve=shortAve+Prices[i];}
longAve=longAve/longPeriod;
shortAve=shortAve/shortPeriod;
double currentValue=Prices[testday];
double dif=longAve-shortAve;
double currentDifNeeded=(0.5/100)*currentValue;
double TradePercent=0.2;
if( Math.abs(dif)<Math.abs(currentDifNeeded)){
if(dif>0){
shares=shares + ((money*TradePercent)-(money*TradePercent*0.002))/currentValue;
money = money - money*TradePercent ;
}
if(dif<0){
money = money + shares*TradePercent*currentValue -(shares*TradePercent*currentValue*0.002);
shares=shares-shares*TradePercent ;
}
}
}
Result=money+shares*Prices[day];
if(Result>tempResult)
{
tempResult=Result;
answer[0]=shortPeriod;
answer[1]=longPeriod;
}
}
}
// System.out.println(answer[0]+" "+answer[1]);
return answer;
} |
27d32dd1-6aa2-4fa6-a353-7d2b35f78cd8 | 4 | public static void main(String args[]) {
try {
MulticastSocket ms = new MulticastSocket();
ms.setTimeToLive(1);
InetAddress ia = InetAddress.getByName("experiment.mcast.net");
while (true) {
int ch;
String s = new String();
do {
ch = System.in.read();
if (ch != '\n') {
s = s + (char) ch;
}
} while (ch != '\n');
System.out.println("Sending message: " + s);
byte[] buf = s.getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length, ia,
4099);
ms.send(dp);
}
} catch (IOException e) {
System.out.println("Exception:" + e);
}
} |
90867659-f21a-4b46-98b8-baa40b06d641 | 1 | @Override
public void removeClientDisconnectListener(DisconnectOnServerListener listener) {
if (clientDisconnectListenerList != null) {
clientDisconnectListenerList.remove(DisconnectOnServerListener.class, listener);
}
} |
9aba9259-e457-4f71-bb10-8a6454ffce2b | 3 | public Direction getFacing() {
return (isMoving() || isCancelingMove() || isRecoveringFromCanceledMove() ? moveDirection : facingDirection);
} |
ec10e475-4c06-49f7-a80c-50cee66dde96 | 4 | public int getXSquares() {
boolean test = false;
if (test || m_test) {
System.out.println("GameBoardGraphics :: getXSquares() BEGIN");
}
if (test || m_test) {
System.out.println("GameBoardGraphics :: getXSquares() END");
}
return X_SQUARES;
} |
deaf23e4-d510-4567-ad21-434dd6885538 | 5 | public boolean mapActionPath(Request request){
String actionPath = getActionpathListenPattern();
String regExpActionPath = actionPath;
String requestPath = request.getPath();
List<String> varNames = new ArrayList<String>();
List<String> varValue = new ArrayList<String>();
// 1. Path: /test/[var1]/test2/[var2]/
// 2. Request: /test/value1/test2/value2/
// 3. Aus dem Path var1 und var2 extrahieren
// 4. Aus dem Request value1 und value2 extrahieren und den vars zuweisen
Matcher matcher;
matcher = Pattern.compile("(/\\[\\w+\\]/)").matcher(actionPath);
// Parse Names of Variables from the ActionPath
while(matcher.find()){
//System.out.printf( "%s an Postion [%d,%d]%n",
// matcher.group(), matcher.start(),
// matcher.end() );
varNames.add(actionPath.substring((matcher.start()+2), (matcher.end()-2)));
String regExpGroup = matcher.group();
regExpGroup = regExpGroup.replaceAll("\\[", "\\\\[");
regExpGroup = regExpGroup.replaceAll("\\]", "\\\\]");
//System.out.println(regExpGroup);
regExpActionPath = regExpActionPath.replaceAll(regExpGroup, "/(\\\\w+)/");
//System.out.println(regExpActionPath);
}
if(requestPath.matches(regExpActionPath)){
// Parse Variable Values
matcher = Pattern.compile(regExpActionPath).matcher(requestPath);
if(matcher.matches()){
if((matcher.groupCount()) != varNames.size()){
return false;
}
for(int i=0; i<matcher.groupCount();i++){
request.setParameter(varNames.get(i), matcher.group(i+1));
System.out.println("Find vars:"+varNames.get(i)+"="+matcher.group(i+1));
}
}
System.out.println(regExpActionPath);
System.out.println(requestPath);
return true;
}
return false;
} |
b98c2131-a513-44ee-a7de-deef8cd9bb07 | 4 | public PointGame getDownNeighbor() {
int x0 = x;
int y0 = y;
while (y0 < MAXY) {
// check if x=3 and y=2, we cannot go down.
if (x0==3 && y0==2) {
break;
}
y0++;
if (Board.validPoints.contains(new PointGame(x0,y0))) {
return new PointGame(x0,y0);
}
}
return null;
} |
79bc2f1b-64b6-4563-8426-93dd6eaad71a | 6 | public void engineSetSeed(byte[] seed) {
// compute the total number of random bytes required to setup adaptee
int materialLength = 0;
materialLength += 16; // key material size
materialLength++; // index size
byte[] material = new byte[materialLength];
// use as much as possible bytes from the seed
int materialOffset = 0;
int materialLeft = material.length;
if (seed.length > 0) { // copy some bytes into key and update indices
int lenToCopy = Math.min(materialLength, seed.length);
System.arraycopy(seed, 0, material, 0, lenToCopy);
materialOffset += lenToCopy;
materialLeft -= lenToCopy;
}
if (materialOffset > 0) { // generate the rest
while (true) {
try {
prng.nextBytes(material, materialOffset, materialLeft);
break;
} catch (IllegalStateException x) { // should not happen
throw new InternalError(MSG + String.valueOf(x));
} catch (LimitReachedException x) {
if (DEBUG) {
debug(MSG + String.valueOf(x));
debug(RETRY);
}
}
}
}
// setup the underlying adaptee instance
HashMap attributes = new HashMap();
// use AES cipher with 128-bit block size
attributes.put(UMacGenerator.CIPHER, Registry.AES_CIPHER);
// specify the key
byte[] key = new byte[16];
System.arraycopy(material, 0, key, 0, 16);
attributes.put(IBlockCipher.KEY_MATERIAL, key);
// use a 1-byte index
attributes.put(UMacGenerator.INDEX, new Integer(material[16] & 0xFF));
adaptee.init(attributes);
} |
741e13b7-854f-49ec-a15f-4e625cf6286f | 0 | public int getNumberOfImages()
{
return numberOfImages;
} |
c0ac9c2b-ab6b-4338-bfd0-93941b3d3398 | 9 | private int update() {
int n = getWritableFieldsCount();
String fields = "";
String separator = "";
Object[] valuesObj = new Object[n];
int i =0;
String clause = "";
String delimiter = "";
for(BeanTableMapping mapping: tableFields)
{
if(!mapping.isAutoincrement() && mapping.isWritable())
{
try {
fields += separator+mapping.getTableName()+"."+mapping.getTableFieldName()+"=?";
separator = ",";
Method getter = new PropertyDescriptor(mapping.getBeanFieldName(), mapping.getHoldingClass()).getReadMethod();
valuesObj[i] = getter.invoke(beanObj);
i += 1;
} catch (Exception ex) {
Logger.getLogger(GenericCrud.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
for(BeanTableMapping mapping: tableFields)
{
if(mapping.isPk())
{
clause = delimiter+mapping.getTableName()+"."+mapping.getTableFieldName()+"=?";
delimiter = "AND";
try {
Method getter = new PropertyDescriptor(mapping.getBeanFieldName(), mapping.getHoldingClass()).getReadMethod();
valuesObj[i] = getter.invoke(beanObj);
i +=1;
} catch (Exception ex) {
Logger.getLogger(GenericCrud.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
int nup = 0;
if(!clause.isEmpty())
{
String SQL1 = "UPDATE "+fromQuery+" SET "+ fields + " WHERE "+clause;
//System.out.println("UPDATE: "+SQL1);
for(Object o: valuesObj)
{
//System.out.println("\t o="+o);
}
database.preparedUpdate(SQL1,valuesObj);
}
return nup;
} |
f0f8682a-e467-4e01-821f-db248f315355 | 2 | public static boolean deleteSystem(String name) {
if(listSystems.containsKey(name)) {
System system = listSystems.get(name);
if(system.getUnits().isEmpty()) {
listSystems.remove(name);
return true;
}
}
return false;
} |
de12c8c8-95ca-4d98-8516-fd8f539126c5 | 7 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null)
return false;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
invoker=mob;
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> begin(s) to blink!"):L("^S<S-NAME> cast(s) a spell at <T-NAMESELF>.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
if(target.location()==mob.location())
if((mob.phyStats().level()+(2*getXLEVELLevel(mob)))>5)
success=beneficialAffect(mob,target,asLevel,(mob.phyStats().level()+(2*getXLEVELLevel(mob)))-4)!=null;
else
success=beneficialAffect(mob,target,asLevel,mob.phyStats().level()+(2*getXLEVELLevel(mob)))!=null;
}
}
else
return beneficialWordsFizzle(mob,target,L("<S-NAME> cast(s) a spell to <T-NAMESELF>, but the magic fizzles."));
// return whether it worked
return success;
} |
f54d7631-44f8-4f24-a277-d7c98f27c4e7 | 5 | public static boolean checkMenuKeys(String keys)
{
for(byte j=0;j<ControlKeys.getKeys();++j)
{
if((keys.charAt(j) == '1' && !ControlKeys.isKeyPressed(j)) || (keys.charAt(j) == '0' && ControlKeys.isKeyPressed(j)))
return false;
}
return true;
} |
4eee4958-4115-4642-95c5-2c62c665f866 | 3 | public void push(int action, IIntervalsTimeDomain domain) {
switch (action) {
case ADD:
actionStack.add(new AddAction(domain));
break;
case REMOVE:
actionStack.add(new RemoveAction(domain));
break;
case MASK:
actionStack.add(new MaskAction(domain));
break;
}
} |
1fe83132-74f0-43aa-a925-3cc4ece9d5d6 | 4 | private static String replace(String original, String find, String replace) {
if (original == null) return original;
if (find == null) return original;
if (replace == null) replace = "";
int found = original.indexOf(find);
while (found != -1) {
original = original.substring(0,found) + replace + original.substring(found + find.length());
found += replace.length();
found = original.indexOf(find, found);
}
return original;
} |
8080b00f-8636-444c-8d9b-7cde0683c292 | 6 | @Override
public boolean equals( Object other )
{
if ( other instanceof Table )
{
Table t = (Table)other;
if ( t.versions.equals(versions)&&t.rows.size()==rows.size() )
{
for ( int i=0;i<rows.size();i++ )
{
Row r1 = rows.get( i );
Row r2 = t.rows.get( i );
if ( r1.equals(r2) )
return false;
}
return true;
}
}
else if ( other instanceof Fragment )
{
// the fragment might already be IN the table
return this.contains( (Fragment)other );
}
return false;
} |
8da074a2-50f7-4ca1-8c6c-ca9ba755ce48 | 8 | @Override
public void actionPerformed(ActionEvent e) {
JMenuItem it = (JMenuItem) e.getSource();
if (it.getText().equals("Quitter")) {
System.exit(0);
} else {
if (it.getText().equals("Pause") && _players != null) {
for (int i = 0; i < _players.length; i++) {
_players[i].getTetrisCore().pause();
}
} else {
if (it.getText().equals("Lancer partie 1 joueur")) {
if (_players == null) {
createGame(1);
} else {
// shutDownGame();
//createGame(1);
}
} else {
if (it.getText().equals("Lancer partie 2 joueurs")) {
if (_players == null) {
createGame(2);
} else {
// shutDownGame();
//createGame(2);
}
}
}
}
}
} |
081a7e0e-a328-4c26-9073-6d69e5391d3c | 6 | private void move(int x, int y) {
if(!selected) {
selectedColumn += x;
selectedRow += y;
selectedColumn = getColumnPosition(selectedColumn);
Column column = getColumn(selectedColumn);
selectedRow = column.getRowPosition(selectedRow);
} else {
Column column = getColumn(selectedColumn);
if(column instanceof HeroColumn) {
HeroColumn heroCol = (HeroColumn)column;
if(x > 0) {
heroCol.nextHero();
} else if(x < 0) {
heroCol.previousHero();
}
if(heroCol.getName().equals("HeroColumn1")) {
player1Hero = heroCol.getSelectedHero();
} else if(heroCol.getName().equals("HeroColumn2")) {
player2Hero = heroCol.getSelectedHero();
}
}
}
} |
be9c0d02-94a9-485c-a2bf-acc8d88d16e9 | 8 | @Override
/**
* When attribute changed we need to change our LSDB and neighborList and
* and send to everyone a new LSP to keep them up to date.
*/
public void attrChanged(Interface iface, String attr) {
if (attr.equals("metric")) {
for (Entry<IPAddress, LinkState> ls : neighborList.entrySet()) {
if (ls.getValue().routerInterface.equals(iface)) {
neighborList.put(ls.getKey(), new LinkState(ls.getValue().routerId, (Integer) iface.getAttribute("metric"), ls.getValue().routerInterface));
}
}
}
if (attr.equals("state")) {
IPAddress keyToRemove = null;
for (Entry<IPAddress, LinkState> ls : neighborList.entrySet()) {
if (ls.getValue().routerInterface.equals(iface)) {
if (iface.isActive()) {
neighborList.put(ls.getKey(), new LinkState(ls.getValue().routerId, (Integer) iface.getAttribute("metric"), ls.getValue().routerInterface));
} else {
keyToRemove = ls.getKey();
}
}
}
if (keyToRemove != null) {
neighborList.remove(keyToRemove);
}
}
} |
237431ff-e861-4611-9470-e809a9a6b376 | 1 | public void cycle(long n) {
for (long i = 1; i <= n; i++){
result = result * i;
}
System.out.println(result);
//return result;
} |
f34c090b-65f3-4f83-b5c8-2f111fcbdf0d | 8 | public static boolean createTradingStrategy(String name, String username,
ArrayList<String> ruleList) {
initialise();
UserAccount user = UserAccountController.returnAccount(username);
// Check rules are all valid
boolean validStrategy = validStrategy(name, ruleList);
// Check ts name is unique
boolean uniqueName = true;
for (TradingStrategy ts : strategyList) {
if (ts.getName().equals(name)
&& (ts.getUserAccount() == user || ts.getUserAccount() == null)) {
uniqueName = false;
}
}
if (validStrategy && uniqueName) {
strategyList.add(new TradingStrategy(name, user, ruleList));
return true;
} else if (!validStrategy) {
System.out.println("Strategy is invalid for " + name);
} else if (!uniqueName) {
System.out.println("Name " + name + " is already in use.");
}
return false;
} |
8f9b6aff-ac57-4f6d-9e7d-0e36590b35e2 | 6 | public PongWindow() {
super();
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception ex) {
ex.printStackTrace();
}
this.width = 800;
this.height = 600;
if (ISMAXIMIZED) {
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
this.width = Math.max(dimension.width, dimension.height);
this.height = this.width / 16 * 10;
this.setUndecorated(true);
this.setExtendedState(Frame.MAXIMIZED_BOTH);
} else {
this.setPreferredSize(new Dimension(width, height));
this.setResizable(false);
}
this.setSize(this.width, this.height);
this.setTitle(TITLE);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.pack();
this.getRootPane().setDefaultButton(null);
this.requestFocusInWindow();
super.setBackground(Color.BLACK);
try {
Image image = ImageIO.read(ClassLoader.getSystemResource("pong.gif"));
super.setIconImage(image);
} catch (IOException ex) {
Logger.getLogger(this.getName()).log(Level.SEVERE, null, ex);
}
try {
Font font = Font.createFont(Font.TRUETYPE_FONT, ClassLoader.getSystemResourceAsStream("TexasLED.TTF"));
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);
} catch (Exception e) {
System.err.println(e.getMessage());
}
// Add the new code before showing the window.
canvas = new MyCanvas();
this.setVisible(true);
// Salir si presiona ESC
addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == (char)27)
if (JOptionPane.showConfirmDialog(null, "En verdad desea salir del juego?", "Salir",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
exit();
}
});
Container c = getContentPane();
c.setLayout(new BorderLayout(0, 0));
c.setBackground(Color.BLACK);
c.add(canvas);
timer = new Timer(50, this);
timer.start();
} |
bb842b08-22f6-4c09-a323-21321222e03b | 2 | private static int biggestLength(ArrayList<String> string) {
int biggerLength = string.get(0).length();
for(int i = 1; i < string.size(); i++) {
if(string.get(i).length() > biggerLength) {
biggerLength = string.get(i).length();
}
}
return biggerLength;
} |
8e0471eb-59e3-4a18-8029-9e93090dba53 | 3 | private boolean isPositionOutOfFrame(LifePosition lifePosition) {
return lifePosition.getPosition()[0] < 0 || lifePosition.getPosition()[1] < 0
|| lifePosition.getPosition()[0] >(frame.height()-1) || lifePosition.getPosition()[1] > (frame.width()-1);
} |
2fa69bd8-b1b5-4490-b10a-1166de57cf1f | 1 | public int hashCode() {
return (username != null ? username.hashCode() : 0);
} |
12120af5-17db-4d3d-8629-edd4085aed98 | 6 | @Override
public void run()
{
while (this.active)
{
try
{
if (players.isEmpty())
{
Thread.sleep(50L);
}
else
{
MapObjectPlayer p = players.pop();
try
{
URL url = new URL("http://s3.amazonaws.com/MinecraftSkins/" + p.getName() + ".png");
BufferedImage img = ImageIO.read(url);
BufferedImage pimg = new BufferedImage(20, 20, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = pimg.createGraphics();
g2d.setColor(Color.black);
g2d.fillRect(0, 0, 20, 20);
g2d.drawImage(img, 2, 2, 18, 18, 8, 8, 16, 16, null);
g2d.dispose();
img.flush();
p.setMarker(pimg);
Thread.sleep(20L);
}
catch (MalformedURLException e2)
{
}
catch (IOException e)
{
}
}
}
catch (InterruptedException e)
{
}
}
if (!this.active)
{
dispose();
}
} |
fc89c0b9-9e61-4bad-a047-109ae2a7c221 | 9 | public Object execute(List<Object> args) {
if (args.isEmpty()) {
throw new IllegalStateException("at least one argument expected in function EQUALS");
}
else if (args.size() == 1) {
return true;
}
else {
Object prev = args.get(0);
for (Object arg: args) {
if (prev == null && arg != null) {
return false;
}
if (prev != null && arg == null) {
return false;
}
if (prev != null && ! (prev.equals(arg))) {
return false;
}
}
return true;
}
} |
19d6e10d-bb73-48ee-b124-82734f2a5976 | 5 | @Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (!(obj instanceof Version))
{
return false;
}
Version other = (Version) obj;
if (major != other.major)
{
return false;
}
if (minor != other.minor)
{
return false;
}
return true;
} |
20025e89-bef4-4a7e-a095-be11311afc88 | 5 | public CheckResultMessage check16(int day) {
int r1 = get(33, 5);
int c1 = get(34, 5);
int r2 = get(36, 5);
int c2 = get(37, 5);
BigDecimal b = new BigDecimal(0);
if (checkVersion(file).equals("2003")) {
try {
in = new FileInputStream(file);
hWorkbook = new HSSFWorkbook(in);
b = getValue(r2 + 1 + day, c2 + 19, 9).add(
getValue(r2 + 1 + day, c2 + 21, 9)).add(
getValue(r2 + 1 + day, c2 + 23, 9));
if (0 != getValue(r1 + 3, c1 + 1 + day, 8).compareTo(b)) {
return error("支付机构汇总报表<" + fileName + ">系统未减少银行已减少未达账项余额:"
+ day + "日错误");
}
} catch (Exception e) {
}
} else {
try {
in = new FileInputStream(file);
xWorkbook = new XSSFWorkbook(in);
b = getValue1(r2 + 1 + day, c2 + 19, 9).add(
getValue1(r2 + 1 + day, c2 + 21, 9)).add(
getValue1(r2 + 1 + day, c2 + 23, 9));
if (0 != getValue1(r1 + 3, c1 + 1 + day, 8).compareTo(b)) {
return error("支付机构汇总报表<" + fileName + ">系统未减少银行已减少未达账项余额:"
+ day + "日错误");
}
} catch (Exception e) {
}
}
return pass("支付机构汇总报表<" + fileName + ">系统未减少银行已减少未达账项余额:" + day + "日正确");
} |
5bdf3101-4d33-45b4-9cf1-6b9ce0b8ac09 | 8 | public static void DoTurn(PlanetWars pw) {
// long endingTime = System.currentTimeMillis() + 5;
int testIndex = 0;
Planet source = null;
Planet dest = null;
MyNode root = new MyNode(new SimulatedPlanetWars(pw));
ArrayList<MyNode> beam = new ArrayList<MyNode>(3);
beam.add(root);
// for (MyNode node : root.getSons())
// System.out.println("I'm a node of " + node);
source = root.getSource();
dest = root.getDest();
//While there is still some time, we go through the tree of possibilities
while(testIndex < 10){
for (int i = 0; i<beam.size();++i){ // Cannot do (MyNode node : beam) because beam is modified with time going on
MyNode node = beam.get(i);
node.createSons();
if (!node.isLeave()){
beam.remove(i); //When it has been treated, we take it off the list only if it not a leave (prevent thus an empty bem array)
}
// System.out.println("Beam size 1 : " + beam.size());
for (MyNode son : node.getSons()){
son.conditionnalAdd(3,beam);
}
}
++ testIndex;
}
// Choosing the maximum value
int max = beam.get(0).getValue();
int index = 0;
for (int i = 1;i<beam.size();++i){
MyNode node = beam.get(i);
if (node.getValue()>max) {
index = i;
max = node.getValue();
}
}
// Choosing destination and source from the maximum value of D found in the beam array+
source = beam.get(index).getSource();
dest = beam.get(index).getDest();
// (3) Attack!
if (source != null && dest != null) {
pw.IssueOrder(source, dest);
}
} |
39efce97-7d8e-4cfd-848d-026e2844af8b | 9 | @Override
public void run() {
//Thread.setPriority(4);
try {
BufferedReader in = new BufferedReader( new InputStreamReader( client.getInputStream() ));
String message = "";
while (message != null) {
message = in.readLine().trim();
//first we check for known commands, if nothing matches it must be a message
//+ to be broadcast
if (message.equals("DISCONNECT") || message == null ) {
shutdown("DISCONNECT");
} else if (message.equals("")) {
//blank lines are ignored
} else if (message.equals("HEARTBEAT") ) {
sendMsg("HEARTBEAT");
} else if (message.equals("GETLIST")) {
//send a list of all connected users
sendMsg(super.getUserList());
} else {
//pass to all other connections
super.broadcast("<" +user + "> " + message);
}
//It's possible that a user could flood the server with messages,
//+ sleeping for a bit between loops could help slow this down.
Thread.yield();
Thread.sleep(1);
}
//we assume that all exceptions mean that the connection is no longer valid.
} catch (NullPointerException e) {
shutdown();
} catch (InterruptedException e) {
shutdown();
} catch (IOException e) {
shutdown();
}
} |
cd0c149e-348e-45f3-9e2b-7fdcb4b65b0e | 5 | private int ret10BitCode (int in,boolean errorBitsAllowed) {
int a,b,dif,errorMax;
// Make copy of what is going into the error corrector
unCorrectedInput=in;
if (errorBitsAllowed==true) errorMax=1;
else errorMax=0;
for (a=0;a<VALIDWORDS.length;a++){
dif=0;
for (b=0;b<BITVALUES.length;b++) {
if ((in&BITVALUES[b])!=(VALIDWORDS[a]&BITVALUES[b])) dif++;
}
if (dif<=errorMax) return a;
}
return -1;
} |
21985138-b59d-4eea-ba0c-2458bd14a307 | 7 | public static void makeCompactGrid(Container parent, int rows, int cols, int initialX, int initialY, int xPad, int yPad) {
SpringLayout layout;
try {
layout = (SpringLayout) parent.getLayout();
}
catch (ClassCastException exc) {
System.err.println("The first argument to makeCompactGrid must use SpringLayout.");
return;
}
// Align all cells in each column and make them the same width.
Spring x = Spring.constant(initialX);
for (int c = 0; c < cols; c++) {
Spring width = Spring.constant(0);
for (int r = 0; r < rows; r++) {
width = Spring.max(width, getConstraintsForCell(r, c, parent, cols).getWidth());
}
for (int r = 0; r < rows; r++) {
SpringLayout.Constraints constraints = getConstraintsForCell(r, c, parent, cols);
constraints.setX(x);
constraints.setWidth(width);
}
x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad)));
}
// Align all cells in each row and make them the same height.
Spring y = Spring.constant(initialY);
for (int r = 0; r < rows; r++) {
Spring height = Spring.constant(0);
for (int c = 0; c < cols; c++) {
height = Spring.max(height, getConstraintsForCell(r, c, parent, cols).getHeight());
}
for (int c = 0; c < cols; c++) {
SpringLayout.Constraints constraints = getConstraintsForCell(r, c, parent, cols);
constraints.setY(y);
constraints.setHeight(height);
}
y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad)));
}
// Set the parent's size.
SpringLayout.Constraints pCons = layout.getConstraints(parent);
pCons.setConstraint(SpringLayout.SOUTH, y);
pCons.setConstraint(SpringLayout.EAST, x);
} |
036b951c-19b9-4515-8734-50520f8df3be | 0 | protected void setI(int i)
{
tempI = i;
} |
4ddbc10a-ca13-46b6-9edc-1b269259e10a | 9 | public void testSimpleToken() throws Exception {
XmlPullParser xpp = factory.newPullParser();
assertEquals(true, xpp.getFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES));
// check setInput semantics
assertEquals(XmlPullParser.START_DOCUMENT, xpp.getEventType());
try {
xpp.nextToken();
fail("exception was expected of nextToken() if no input was set on parser");
} catch(XmlPullParserException ex) {}
xpp.setInput(null);
assertEquals(XmlPullParser.START_DOCUMENT, xpp.getEventType());
try {
xpp.nextToken();
fail("exception was expected of next() if no input was set on parser");
} catch(XmlPullParserException ex) {}
xpp.setInput(null); //reset parser
// attempt to set roundtrip
try {
xpp.setFeature(FEATURE_XML_ROUNDTRIP, true);
} catch(Exception ex) {
}
// did we succeeded?
boolean roundtripSupported = xpp.getFeature(FEATURE_XML_ROUNDTRIP);
// check the simplest possible XML document - just one root element
for(int i = 1; i <= 2; ++i) {
xpp.setInput(new StringReader(i == 1 ? "<foo/>" : "<foo></foo>"));
boolean empty = (i == 1);
checkParserStateNs(xpp, 0, XmlPullParser.START_DOCUMENT, null, 0, null, null, null, false, -1);
xpp.nextToken();
checkParserStateNs(xpp, 1, XmlPullParser.START_TAG, null, 0, "", "foo", null, empty, 0);
if(roundtripSupported) {
if(empty) {
// System.out.println("tag='"+xpp.getText()+"'");
// String foo ="<foo/>";
// String foo2 = xpp.getText();
// System.out.println(foo.equals(foo2));
assertEquals("empty tag roundtrip",
printable("<foo/>"),
printable(xpp.getText()));
} else {
assertEquals("start tag roundtrip",
printable("<foo>"),
printable(xpp.getText()));
}
}
xpp.nextToken();
checkParserStateNs(xpp, 1, XmlPullParser.END_TAG, null, 0, "", "foo", null, false, -1);
if(roundtripSupported) {
if(empty) {
assertEquals("empty tag roundtrip",
printable("<foo/>"),
printable(xpp.getText()));
} else {
assertEquals("end tag roundtrip",
printable("</foo>"),
printable(xpp.getText()));
}
}
xpp.nextToken();
checkParserStateNs(xpp, 0, XmlPullParser.END_DOCUMENT, null, 0, null, null, null, false, -1);
}
} |
1dd9f107-6b40-4bb0-8ac5-1733914c25b5 | 5 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final People other = (People) obj;
if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) {
return false;
}
return true;
} |
99c033bc-51da-4bb9-9ab8-9c8ba315a738 | 7 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// Retrieving the form POST data
//int account_number = Integer.parseInt(request.getParameter("account_number"));
//int total_purchaseCost= Integer.parseInt(request.getParameter("total_purchaseCost"));
String name = request.getParameter("account_holder_name");
long routing_number = Long.parseLong(request.getParameter("routing_number"));
long acc_number = Long.parseLong(request.getParameter("account_number"));
double total_cost = Double.parseDouble(request.getParameter("total_cost"));
double new_balance;
String error_message="";
boolean success_flag = true; // This flag is used to check if transaction is a success or not
HttpSession session = request.getSession();
//double ticket_cost = (Integer)session.getAttribute("total_cost");
//int confirmed_number_of_seats = (Integer)session.getAttribute("confirmed_number_of_seats");
String username = (String)session.getAttribute("username");
//int flight_id = Integer.parseInt((String)session.getAttribute("flight_number"));
int plane_number = Integer.parseInt((String)session.getAttribute("plane_number"));
int booking_id;
System.out.println("Total Ticket cost: "+ total_cost);
Transactions t = new Transactions();
try {
if(t.validateBankDetails(acc_number, routing_number, total_cost)){ // validated
// check if routing number is valid one or not
if(t.getRouting_number() != routing_number){
error_message = error_message + "Routing Number is Wrong <br/>";
success_flag = false;
}
// check if there is enough balance to buy a ticket
if(t.getBalance() < total_cost){
error_message = error_message + "Insufficient Balance <br/>";
success_flag = false;
}
// If the flag is true it means that there were no errors in routing no and balance
// hence add the booking details to the booking history
// and update the balance in the accounts table
if(success_flag){
//error_message = null;
error_message = "success";
List<ShoppingCart> sc = (List<ShoppingCart>) session.getAttribute("cart");
System.out.println(sc.size());
try {
Bookings b = new Bookings();
for (Iterator<ShoppingCart> iter = sc.iterator(); iter.hasNext(); ) {
ShoppingCart element = iter.next();
int flight_id= Integer.parseInt(element.getFlight_id());
int confirmed_number_of_seats = element.getNumberOfTickets();
//int account_number = 100001;
//int user_id= (int) session.getAttribute("user_id");
//System.out.println("user_id(int)(bookinghistory serlvet)"+user_id);
int ticket_cost= element.getTotal_cost();
//b.update_bookings(booking_id, flight_id, numberOfTickets, account_number, user_id, ticket_cost);
booking_id = b.addingBookingDetails(confirmed_number_of_seats, acc_number, username, ticket_cost);
b.addEntriesInBookingFlightsTable(booking_id, flight_id);
}
}
catch (SQLException e) {
e.printStackTrace();
}
session.removeAttribute("cart");
// Addding Booking Details
//Bookings b = new Bookings();
//booking_id = b.addingBookingDetails(confirmed_number_of_seats, acc_number, username, total_cost);
//b.addEntriesInBookingFlightsTable(booking_id, flight_id);
System.out.println("old balance: "+ t.getBalance());
//updating the balance in the accounts
new_balance = t.getBalance() - total_cost;
System.out.println("Updated Balance = " + new_balance);
t.updateBalance(new_balance,t.getAccount_number());
}
}else{ // not validated
error_message = "The Account Number entered is not valid! Please try again.";
}
System.out.println("Status Message: " +error_message);
response.getWriter().write(error_message);
//request.setAttribute("error_message", error_message);
//RequestDispatcher rd = request.getRequestDispatcher("transactionConfirmation.jsp") ;
//rd.include(request, response);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
82694714-d058-4f96-a59f-f03918d00761 | 2 | public void endOfTime() {
Iterator it = timeOut.keySet().iterator();
while(it.hasNext()) {
String nick = (String) it.next();
if(this.getDiffDate(nick) / 1000 >= timeToDeco) {
this.connectHandler.disconnect(nick);
timeOut.remove(nick);
}
}
} |
08047f58-0d09-4a54-930c-4b2fb3b71d73 | 9 | private static DataSet[][][] aggregateTraces(String[] nodeClasses,
String[] approaches, String[] metrics) {
DataSet[][][] allData = new DataSet[nodeClasses.length][approaches.length][metrics.length];
for(int i = 0; i < nodeClasses.length; i++) {
// VirtuaTraces
String[] virtuaTracesBaseDirs = {
"/media/embs/Data/VirtuaSimulationVirtuaVNMPs/"
};
for(int a = 0; a < virtuaTracesBaseDirs.length; a++) {
File baseDir = new File(virtuaTracesBaseDirs[a]);
DataSet[] metricsData = new DataSet[metrics.length];
for(int x = 0; x < metricsData.length; x++) {
metricsData[x] = new DataSet();
}
for(int j = 0; j < 30; j++) {
VirtuaSimulatorTraceReader reader = new VirtuaSimulatorTraceReader();
reader.readTrace(baseDir.getAbsolutePath() + "/vnmp_" + nodeClasses[i]
+ "_" + j + "_simulation.txt");
for(int k = 0; k < metrics.length; k++) {
metricsData[k].addValue((Double) reader.get(metrics[k]));
}
}
allData[i][a] = metricsData;
}
// ViNETraces
String[] approachesNames = { "HRA", ".greedy", ".dvine" };
for(int a = 1; a < approachesNames.length; a++) {
String approach = approachesNames[a];
File baseDir = new File("/media/embs/Data/vine-yard-virtua-vnmps/" +
nodeClasses[i]);
DataSet[] metricsData = new DataSet[metrics.length];
for(int x = 0; x < metricsData.length; x++) {
metricsData[x] = new DataSet();
}
for(int j = 0; j < 30; j++) {
ViNEYardTraceReader reader = new ViNEYardTraceReader();
String s = baseDir.getAbsolutePath() + "/vnmp_" + nodeClasses[i] + "_"
+ j + "/";
reader.readTrace(s + "MySimINFOCOM2009" + approach + ".out",
s + "time" + approach + ".out");
reader.readMappings(s + "sub.txt", s + "requests",
s + "mappings" + approach + ".out");
for(int k = 0; k < metrics.length; k++) {
metricsData[k].addValue((Double) reader.get(metrics[k]));
}
}
allData[i][a] = metricsData;
}
}
return allData;
} |
896c013e-d2d5-4775-9eda-c1ae968a32e0 | 4 | public static void arc(double x, double y, double r, double angle1, double angle2) {
if (r < 0) throw new RuntimeException("arc radius can't be negative");
while (angle2 < angle1) angle2 += 360;
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*r);
double hs = factorY(2*r);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Arc2D.Double(xs - ws/2, ys - hs/2, ws, hs, angle1, angle2 - angle1, Arc2D.OPEN));
draw();
} |
21a30859-d35a-4614-a1ee-2c185d046daf | 8 | private void process () {
IndexFile ixfl = null;
try {
File srcf = new File(srcPath);
if (!srcf.exists()) {
System.out.println ("File " + srcPath + " does not exist.");
return;
}
else if (srcf.isDirectory()) {
System.out.println ("File " + srcPath + " is a directory.");
return;
}
System.out.println ("Processing file " + srcPath);
Stylesheet ssht;
if (stylesheet != null) {
File ssf = new File(stylesheet);
if (!ssf.exists()) {
System.out.println ("Stylesheet file " + stylesheet + " does not exist.");
return;
}
else if (ssf.isDirectory ()) {
System.out.println ("File " + stylesheet + " is a directory.");
return;
}
ssht = new Stylesheet (stylesheet, destPath);
}
else {
ssht = new Stylesheet (destPath);
}
ssht.copyToOutput();
ixfl = new IndexFile
(new File (destPath), title);
XMLDumpFile srcFile = new XMLDumpFile
(new File(srcPath), new File(destPath), ixfl);
srcFile.processFile ();
}
catch (Exception e) {
e.printStackTrace ();
return;
}
finally {
if (ixfl != null) {
try {
ixfl.close();
}
catch (Exception ee) {}
}
}
System.out.println ("Completed conversion to directory " + destPath);
} |
c31f8adf-85ed-4003-9bfd-5ae6e945447d | 1 | private static final void loadImage(InputStream in, int length, String name, List<StdImage> images) throws IOException {
byte[] data = new byte[length];
StreamUtils.readFully(in, data);
StdImage img = StdImage.loadImage(data);
if (img != null) {
track(name, img);
images.add(img);
}
} |
1edb890a-a0b1-4d6c-9179-a673d793d27c | 4 | public boolean commit() throws LoginException {
if (succeeded == false) {
return false;
} else {
// add a Principal (authenticated identity)
// to the Subject
// assume the user we authenticated is the SamplePrincipal
userPrincipal = new SamplePrincipal(username);
if (!subject.getPrincipals().contains(userPrincipal))
subject.getPrincipals().add(userPrincipal);
if (debug) {
System.out.println("\t\t[SampleLoginModule] " +
"added SamplePrincipal to Subject with user "+ userPrincipal.getName() );
}
// in any case, clean out state
username = null;
for (int i = 0; i < password.length; i++)
password[i] = ' ';
password = null;
commitSucceeded = true;
return true;
}
} |
83f640cf-866b-4517-b9ea-d134573aeebf | 7 | public void writeWorld()
{
voted = false;
try {
// System.out.println("World sent s");
ByteBuffer toSend = ByteBuffer.allocate(9600004);
//out.write(Server.ENTIREWORLD);
//out.flush();
toSend.putInt(handle.earth.ground.w);
toSend.putInt(handle.earth.ground.h);
toSend.putInt((int)handle.earth.x);
toSend.putInt((int)handle.earth.y);
toSend.putInt(handle.mapRotation);
toSend.putInt(handle.gameMode);
//System.out.println(handle.earth.ground.w+" x "+handle.earth.ground.h);
for (int i = 0; i < handle.team1.size(); i ++)
{
toSend.putInt(handle.team1.get(i));
}
toSend.putInt(-1);
for (int i = 0; i < handle.team2.size(); i ++)
{
toSend.putInt(handle.team2.get(i));
}
toSend.putInt(-1);
ByteBuffer[] chunks = new ByteBuffer[handle.earth.ground.w/100];
for (int t = 0; t < handle.earth.ground.w; t+=100)
{
chunks[t/100] = ByteBuffer.allocate(900000);
for (int i = t; i < t+100; i ++)
{
chunks[t/100].put(handle.earth.ground.cellData[i]);
//System.out.println(i);
}
}
for (Entity e:handle.earth.entityList)
{
System.out.println(e.getClass().getName());
e.cerealize(toSend);
toSend.putInt(e.MYID);
}
toSend.put(Byte.MIN_VALUE);
toSend.put(Byte.MIN_VALUE);
out.addMesssage(toSend, Server.ENTIREWORLD);
//Server.writeByteBuffer(toSend,out);
for (int t = 0; t < chunks.length; t+=1)
{
//Server.writeByteBuffer(chunks[t],out);
out.addMesssage(chunks[t], Server.CHUNK);
}
// System.out.println("World sent");
} catch (Exception ex) {
ex.printStackTrace();
killMe();
}
} |
15e4a74e-b285-420f-8d82-89bede09d677 | 4 | public void startRun(int numSteps)
{
if (numSteps == 0)
{
this.numSteps = 1;
infinite = true;
}
else
{
this.numSteps += numSteps;
}
try{
if (!threadRun && Thread.currentThread().isAlive())
{
new Thread(this).start();
}
}
catch (IllegalThreadStateException e)
{
infinite = false;
System.out.println("InterruptedException");
}
} |
1a2079f1-f1e8-4429-9a89-f1458d1c5548 | 4 | public boolean checkProjectileToShipCollisions(Projectile p, Ship s){
if(p.getPos().getX()>(s.getPos().getX()-(s.getSize().getWidth()/2)))
if(p.getPos().getX()<(s.getPos().getX()+(s.getSize().getWidth()/2)))
if(p.getPos().getY()>(s.getPos().getY()-(s.getSize().getHeight()/2)))
if(p.getPos().getY()<(s.getPos().getY()+(s.getSize().getHeight()/2)))
return true;
return false;
} |
97eeee45-adfa-4848-b164-2492902d137a | 1 | public static synchronized ResponseParserFactory getInstance() {
if (instance == null) {
instance = new ResponseParserFactory();
}
return instance;
} |
90fcbcc5-23e9-4955-b86e-5b4eae623187 | 4 | public void fillDeclarables(Collection used) {
if (usedAnalyzers != null)
used.addAll(usedAnalyzers);
if (innerAnalyzers != null) {
Enumeration enum_ = innerAnalyzers.elements();
while (enum_.hasMoreElements()) {
ClassAnalyzer classAna = (ClassAnalyzer) enum_.nextElement();
if (classAna.getParent() == this)
classAna.fillDeclarables(used);
}
}
} |
28d6b278-735a-44c4-b19d-b00b2538bd7b | 6 | private double medianOfFive(ArrayList<double[]> puntos, int axis, int start){
if(puntos.get(start)[axis]>puntos.get(start+1)[axis])
swap(puntos, start,start+1);
if(puntos.get(start+2)[axis]>puntos.get(start+3)[axis])
swap(puntos,start+2,start+3);
//dejar en indice 0 el menor de los 4 (no es mediana)
if(puntos.get(start)[axis] > puntos.get(start+2)[axis])
swap(puntos,start,start+2);
//dejar en indice 3 el mayor de los 4 (no es mediana)
if(puntos.get(start+1)[axis] > puntos.get(start+3)[axis])
swap(puntos,start+1,start+3);
if(puntos.get(start+2)[axis] > puntos.get(start+4)[axis])
swap(puntos,start+1,start+3);
//dejar en indice 1 el menor de de los segundos 4 (no es mediana)
if(puntos.get(start+1)[axis] > puntos.get(start+2)[axis])
swap(puntos,start+1,start+2);
//como en el indice 2 se dejo un elemento que es menor que otros 2,
//y no es ni el primero ni segundo elemento menor, es mediana
return puntos.get(start+2)[axis];
} |
52f4b39a-2504-4611-bcee-a2ab5e1f285b | 6 | public String performSubtraction(String tal1, String tal2)
{
StringBuilder sBuilder = new StringBuilder();
int lenght = tal1.length();
tal2 = matchLenght(lenght, tal2);
int carry = 0;
int i = 0;
if(tal2.length() > lenght)
{
lenght = tal2.length();
tal1 = matchLenght(lenght, tal1);
}
// Reverse for the indexing.
tal1 = new StringBuilder(tal1).reverse().toString();
tal2 = new StringBuilder(tal2).reverse().toString();
while(i < lenght || carry == 1)
{
int temp;
if(i < lenght)
{
temp = (tal1.charAt(i) - 48)
- (tal2.charAt(i) - 48)
- carry;
}else
{
temp = carry;
}
//System.out.println(temp);
carry = 0;
if(temp < 0)
{
carry = 1;
sBuilder.append(10 + temp);
}else
{
sBuilder.append(temp);
}
i++;
}
if(sBuilder.charAt(sBuilder.length() - 1) == 48)
{
sBuilder.deleteCharAt(sBuilder.length() - 1);
}
return new StringBuilder(sBuilder.toString()).reverse().toString();
} |
e3ff8176-68d4-40b4-aea7-78701259c46f | 8 | private static String escapeJSON(String text) {
StringBuilder builder = new StringBuilder();
builder.append('"');
for (int index = 0; index < text.length(); index++) {
char chr = text.charAt(index);
switch (chr) {
case '"':
case '\\':
builder.append('\\');
builder.append(chr);
break;
case '\b':
builder.append("\\b");
break;
case '\t':
builder.append("\\t");
break;
case '\n':
builder.append("\\n");
break;
case '\r':
builder.append("\\r");
break;
default:
if (chr < ' ') {
String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4));
} else {
builder.append(chr);
}
break;
}
}
builder.append('"');
return builder.toString();
} |
14c50a72-8607-423e-b812-174f44a54199 | 4 | public double calcBuildingArea(double length, double width) {
if (length < 7 || length > 20) { // length value not within the accepted range?
return 0;
}
if (width < 5 || width > 15) { // width value not within the accepted range?
return 0;
}
double area = width * length;
return area;
} |
ceafdbc1-d042-4cae-bae3-526f94106c3e | 4 | private void initDirNames(File cfgFile) {
GenericObject cfg = EUGFileIO.load(cfgFile);
String mainDir = "";
String modDir = "";
if (cfg != null) {
mainDir = cfg.getString("maindir");
modDir = cfg.getString("moddir");
}
if(mainDir.equals("")) {
try {
if (System.getProperty("os.name").startsWith("Windows")) {
//try to read the registry
Regor regor = new Regor();
Key k = regor.openKey(Regor.HKEY_LOCAL_MACHINE, "SOFTWARE\\Paradox Interactive\\Europa Universalis III");
mainDir = new String(regor.readValue(k, "path")).replaceAll("\0", "");
}
else {
mainDir = defaultMainDir;
}
}
catch (Exception e) {
e.printStackTrace();
System.out.println("using default mod dir");
setMainDirectory(defaultMainDir);
setModName("");
return;
}
}
setMainDirectory(mainDir);
setModName(modDir);
} |
22574971-ef18-410a-8534-0089de2043d7 | 7 | public Move findbest(Game g) throws GameException {
try {
boolean max;
int bestVal;
// if first player, then find the max value
// otherwise find the min value
if (g.whoseTurn() == Game.FIRST_PLAYER) {
max = true;
bestVal = Integer.MIN_VALUE; // running max, starts at bottom
} else {
max = false;
bestVal = Integer.MAX_VALUE;
}
Move bestMove = null;
Iterator<Move> moves = g.getMoves();
while (moves.hasNext()) {
int value;
Move m = moves.next();
Game cp = g.copy();
cp.make(m);
value = getValue(cp);
System.out.println("val = " + value);
if ((max && value >= bestVal) || (!max && value <= bestVal)) {
bestVal = value;
bestMove = m;
}
}
return bestMove;
} catch (Exception e) {
throw new GameException(e.getMessage());
}
} |
32890c4e-4783-46ab-b6c9-d112f226a361 | 8 | @Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==this.b1)//write
{
l=new ArrayList<Exp>();
TextIO te=new TextIO();
te.readFile();
t1.setText(te.text);
for( String x : te.stringToArray()){
Exp ex=new Exp(x);
l.add(ex);
}
}
if(e.getSource()==this.b5)//write
{
String str=this.t1.getText();
TextIO te=new TextIO();
try {
te.WiteFile(str);
JOptionPane.showMessageDialog(null, "Write Done : \n output.txt");
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(e.getSource()==this.b2)
{
l=new ArrayList<Exp>();
Exp st=new Exp(this.t1.getText());
l.add(st);
JOptionPane.showMessageDialog(null, "Done");
}
if(e.getSource()==this.b3)
{
JOptionPane.showMessageDialog(null, "Done,click convert");
}
if(e.getSource()==this.b4)
{
String str="";
for(String x : t1.getText().split("\n") )
{
Exp st=new Exp(x);
Infix2Postfix inf=new Infix2Postfix(st.exp);
str+="infix : "+st.exp+"\n"+"postfix : "+inf.returnS+"\n---------------\n";
}
t1.setText(str);
// System.out.println();
}
// TODO Auto-generated method stub
} |
5bf726fd-7ea0-4478-a7a2-cae449ffe5e4 | 6 | public void train(List<DataEntry<double[], Integer>> data_set){
int m = data_set.size();
for(DataEntry<double[], Integer> entry:data_set){
phi[entry.label] += 1;
for(int i=0;i<N;i++){
mean[entry.label][i] += entry.data_vec[i];
}
}
for(int i=0;i<K;i++){
for(int j=0;j<N;j++){
mean[i][j] /= phi[i];
}
phi[i] /= m;
}
for(DataEntry<double[], Integer> entry:data_set){
double[][] data = new double[1][N];
for(int i=0;i<N;i++)
data[0][i] = entry.data_vec[i] - this.mean[entry.label][i];
SimpleMatrix curr_matrix = new SimpleMatrix(data);
SimpleMatrix temp = curr_matrix.transpose().mult(curr_matrix);
var_transpose = var_transpose.plus(temp);
}
var_transpose = var_transpose.scale(1./(double)(m));
this.var_transpose = var_transpose.invert();
} |
bfe3f38f-df51-489d-a876-7c3f64352099 | 6 | private void knightTopRightPossibleMove(Piece piece, Position position)
{
int x1 = position.getPositionX();
int y1 = position.getPositionY();
if((x1 >= 0 && y1 >= 0) && (x1 <= 5 && y1 <= 6))
{
if(board.getChessBoardSquare(x1+2, y1+1).getPiece().getPieceType() != board.getBlankPiece().getPieceType())
{
if(board.getChessBoardSquare(x1+2, y1+1).getPiece().getPieceColor() != piece.getPieceColor())
{
// System.out.print(" " + coordinateToPosition(x1+2, y1+1)+"*");
Position newMove = new Position(x1+2, y1+1);
piece.setPossibleMoves(newMove);
}
}
else
{
// System.out.print(" " + coordinateToPosition(x1+2, y1+1));
Position newMove = new Position(x1+2, y1+1);
piece.setPossibleMoves(newMove);
}
}
} |
708159a3-adc0-459b-9d70-6383d90c2521 | 8 | public boolean wearingHeldMetal(Environmental affected)
{
if(affected instanceof MOB)
{
final MOB M=(MOB)affected;
for(int i=0;i<M.numItems();i++)
{
final Item I=M.getItem(i);
if((I!=null)
&&(I.container()==null)
&&(CMLib.flags().isMetal(I))
&&(!I.amWearingAt(Wearable.IN_INVENTORY))
&&(!I.amWearingAt(Wearable.WORN_HELD))
&&(!I.amWearingAt(Wearable.WORN_WIELD)))
return true;
}
}
return false;
} |
8231b63d-76a9-4b2e-bc66-321475ad3bd9 | 3 | public String getResult_HTML(){
if(endtime==null) evaluateBenchmark();
String s ="";
//if(totaltime==0) return "0ms ???";
if(sections.size()==0) return "keine sections angegeben";
else {
s="<html><table style='width:330px;' cellspacing='2' cellpadding='0'><tr><th>section name</th><th>ms</th><th>%</th><th>Diagr</th></tr>";
for(String name:sections.keySet()){
s+="<tr><td>"+name+"</td><td align='right'>"+sections.get(name).getTimeUsage()+"</td><td align='right'>"+(sections.get(name).getTimeUsage()*100/totaltime)+"</td><td><div style='background-color:#8BA5C0; height:12px; width:"+(sections.get(name).getTimeUsage()*200/totaltime)+"px'></div></td></tr>";
}
s+="<tr><td>total</td><td align='right'>"+totaltime+"</td><td align='right'>100</td><td><div style='background-color:#8BA5C0; height:12px; width:200px;'></div></td></tr></table></html>";
}
return s;
} |
83a17332-3eef-46ee-8677-47647062689c | 5 | public void setMerges(Merge merge, MapperCounters counters) {
long inputRecsInPreviousMerges = 0;
long outputRecsInPreviousMerges = 0;
List<MergeInfo> list = merge.getMergeInfoList();
MergeInfo info = null;
for(int i = 0; i < list.size(); i++) {
info = list.get(i);
merges.add(new MergeAction(info));
if(i != list.size() - 1) {
inputRecsInPreviousMerges += info.getRecordsBeforeMerge();
outputRecsInPreviousMerges += info.getRecordsAfterMerge();
}
}
if(merge.hasCombine() == true)
{
diskCombineFunc = new DiskCombineFunc();
diskCombineFunc.settCombineInputRecords(info.getRecordsBeforeMerge());
long combineInputRecsInSpills = 0;
long combineOutputRecsInSpills = 0;
for(SpillPiece sp : spills) {
combineInputRecsInSpills += sp.getRecordsBefore();
combineOutputRecsInSpills += sp.getRecordsAfter();
}
diskCombineFunc.setInputRecsInPreviousMerges(inputRecsInPreviousMerges);
diskCombineFunc.setcCombineInputRecords(counters.getCombine_input_records()
- combineInputRecsInSpills - inputRecsInPreviousMerges);
diskCombineFunc.setcCombineOutputRecords(counters.getCombine_output_records()
- combineOutputRecsInSpills - outputRecsInPreviousMerges);
}
for(MergeAction action : merges) {
mapOutputSegs.add(new Segment(id, action.getPartitionId(), action.getRecordsAfter(), action.getBytesAfter()));
}
} |
2fa2e787-4d29-48d4-82f6-6ec4790744aa | 8 | public static String getLongestCommonSubsequence(String str1, String str2)
{
int[][] sol = new int[str1.length()+1][str2.length()+1];
int max = -1;
for(int i = 1; i < str1.length() + 1; i++)
{
for(int j = 1; j < str2.length() + 1; j++)
{
if(str1.charAt(i-1) == str2.charAt(j-1))
{
sol[i][j] = sol[i-1][j-1] + 1;
if (max < sol[i][j])
max = sol[i][j];
}
else
{
sol[i][j] = 0;
}
}
}
StringBuilder b = new StringBuilder();
for(int i = str1.length(); i > 0; i--)
{
for(int j = str2.length(); j > 0; j--)
{
if(max > 0 && sol[i][j] == max)
{
b.append(str1.charAt(i - 1));
max--;
}
}
}
return b.reverse().toString();
} |
bed430a0-f5b3-4ef1-836d-cab49e284f9a | 1 | public Pie getPie() {
if (pb.isBaked()) {
return pb.getPie();
} else {
BuilderClient.addOutput("error - your pie is not ready yet");
return null;
}
} |
35a7dd78-5db7-445b-91a6-4a5acb4de5bd | 4 | @Override
protected void handleMessage(String message) {
String[] parsed = message.split(":");
if(parsed[0].equals("collision")) {
if(parsed[1].equals(Projectile.ENT_NAME)) {
if(parsed[2].equals("no")) {
this.health--;
SpaceInvaders.statusBar.handleMessage(StatusBar.TAKE_DAMAGE);
if(this.health == 0) {
this.destroy();
}
}
}
else {
this.destroy();
}
}
} |
a868b1d6-33b6-4eac-ab03-7be52f66fbf4 | 6 | private void setupCloseBehaviour(final Stage primaryStage) {
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent event) {
if (StateMachine.isSongModified()
|| StateMachine.isArrModified()) {
final Stage dialog = new Stage();
dialog.setHeight(100);
dialog.setWidth(300);
dialog.setResizable(false);
dialog.initStyle(StageStyle.UTILITY);
Label label = new Label();
label.setMaxWidth(300);
label.setWrapText(true);
if (StateMachine.isSongModified()
&& StateMachine.isArrModified()) {
label.setText("The song and arrangement have\n"
+ "both not been saved! Really exit?");
} else if (StateMachine.isSongModified()) {
label.setText("The song has not been saved! "
+ "Really exit?");
} else if (StateMachine.isArrModified()) {
label.setText("The arrangement has not been saved! "
+ "Really exit?");
}
Button okButton = new Button("Yes");
okButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
dialog.close();
stop();
}
});
Button cancelButton = new Button("No");
cancelButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
dialog.close();
}
});
FlowPane pane = new FlowPane(10, 10);
pane.setAlignment(Pos.CENTER);
pane.getChildren().addAll(okButton, cancelButton);
VBox vBox = new VBox(10);
vBox.setAlignment(Pos.CENTER);
vBox.getChildren().addAll(label, pane);
Scene scene1 = new Scene(vBox);
dialog.setScene(scene1);
dialog.show();
} else {
stop();
}
event.consume();
}
});
} |
a44b2e28-5fb5-410d-a378-484577341651 | 0 | public String getDate_depreciated_by() {
return date_depreciated_by;
} |
cc53afb8-28fc-48e5-8aaf-4896d149c34e | 4 | public ArrayList<String> getModuletitles() {
try{
openDatabase();
}catch(Exception e){}
String query = "SELECT name FROM t8005t2 .modules";
ArrayList<String> modules = new ArrayList<String>();
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String name = rs.getString("name");
modules.add(name);
}
} catch (Exception e) {
System.err.println("Problem executing getmoduletitles query");
System.err.println(e.getMessage());
}
try{
closeDatabase();
}catch(Exception e){}
return modules;
} |
8b6161b6-f440-4742-9a13-8b7b8a697776 | 9 | @Test
public void testUpdateEditorsPick() {
Integer testISBN = 800;
Set<StockBook> books = new HashSet<StockBook>();
books.add(new ImmutableStockBook(testISBN, "Book Name", "Book Author",
(float) 100, 1, 0, 0, 0, false));
try {
storeManager.addBooks(books);
} catch (BookStoreException e) {
e.printStackTrace();
fail();
}
Set<BookEditorPick> editorPicksVals = new HashSet<BookEditorPick>();
BookEditorPick editorPick = new BookEditorPick(testISBN, true);
editorPicksVals.add(editorPick);
try {
storeManager.updateEditorPicks(editorPicksVals);
} catch (Exception e) {
e.printStackTrace();
fail();
}
List<Book> lstEditorPicks = new ArrayList<Book>();
try {
lstEditorPicks = client.getEditorPicks(1);
} catch (Exception e) {
e.printStackTrace();
fail();
}
Boolean testISBNisInEditorPicks = false;
for (Book book : lstEditorPicks) {
if (book.getISBN() == testISBN)
testISBNisInEditorPicks = true;
}
assertTrue("Chk if list contains testISBN!", testISBNisInEditorPicks);
editorPicksVals.clear();
editorPick = new BookEditorPick(testISBN, false);
editorPicksVals.add(editorPick);
try {
storeManager.updateEditorPicks(editorPicksVals);
} catch (BookStoreException e) {
e.printStackTrace();
fail();
}
Boolean exceptionThrown = false;
lstEditorPicks = new ArrayList<Book>();
try {
lstEditorPicks = client.getEditorPicks(1);
} catch (BookStoreException e) {
exceptionThrown = true;
}
assertTrue(exceptionThrown);
exceptionThrown = false;
editorPicksVals.clear();
editorPick = new BookEditorPick(-1, false);
editorPicksVals.add(editorPick);
try {
storeManager.updateEditorPicks(editorPicksVals);
} catch (BookStoreException e) {
exceptionThrown = true;
}
assertTrue(exceptionThrown);
exceptionThrown = false;
editorPicksVals.clear();
editorPick = new BookEditorPick(1000000000, false);
editorPicksVals.add(editorPick);
try {
storeManager.updateEditorPicks(editorPicksVals);
} catch (BookStoreException e) {
exceptionThrown = true;
}
assertTrue(exceptionThrown);
} |
77ef5189-fb17-4a95-a0be-c00f6bccf7e8 | 2 | private void initReportWriter() {
// Create an output factory
final XMLOutputFactory xmlof = XMLOutputFactory.newInstance();
// Create an XML stream writer
final File reportFile = new File(getOutputDirectory(), "report.xml");
try {
reportWriter = xmlof.createXMLStreamWriter(new FileWriter(reportFile));
} catch (final XMLStreamException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
}
} |
6052d5c1-231f-49e9-8279-6bf941a451a3 | 7 | public boolean sameStops(RoutePath b) {
boolean same = true;
ListIterator aLi = mStops.listIterator();
ListIterator bLi = b.getStops().listIterator();
while (aLi.hasNext() && bLi.hasNext()) {
Stop aS = (Stop) aLi.next();
Stop bS = (Stop) bLi.next();
System.out.println(aS.getID() + " -> " + bS.getID()
+ " distance: "
+ aS.getVertex().getDistanceInMeters(bS.getVertex()));
if (aS.getID() != bS.getID()
&& aS.getVertex().getDistanceInMeters(bS.getVertex()) > closenessThreshold) {
same = false;
break;
}
}
if (same && (aLi.hasNext() || bLi.hasNext())) {
System.out.println("Stops left!");
same = false;
}
return same;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.