body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I have the following function defined in a program that implements the 2048 game. I tried condensing the repeating part of the code into one loop containing +1 offset variables for the indices, which are either set to 0 or 1 depending on the direction passed into the function, but the outer and inner loop variables swap depending on the direction. Could anyone give me some pointers as to how to condense this code and make it more clean, pythonic and terse?</p>
<pre><code>def merge(direction):
#if adjacent cells are equal, they are merged into one with twice the value and then moved.
if direction == "up":
for col in range(nColumns):
for row in range(nRows-1):
if grid[row][col] == grid[row+1][col]:
grid[row][col] = grid[row+1][col]*2
grid[row+1][col] = 0
move(direction)
if direction == "down":
for col in range(nColumns):
for row in range(nRows-1):
if grid[row][col] == grid[row+1][col]:
grid[row+1][col] = grid[row][col]*2
grid[row][col] = 0
move(direction)
if direction == "left":
for row in range(nRows):
for col in range(nColumns-1):
if grid[row][col] == grid[row][col+1]:
grid[row][col] = grid[row][col]*2
grid[row][col+1] = 0
move(direction)
if direction == "right":
for row in range(nRows):
for col in range(nColumns-1):
if grid[row][col] == grid[row][col+1]:
grid[row][col+1] = grid[row][col]*2
grid[row][col] = 0
move(direction)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T14:30:55.083",
"Id": "79606",
"Score": "0",
"body": "Shouldn't your `if` be more indented?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T15:00:04.500",
"Id": "79616",
"Score": "0",
"body": "@Morwenn The lack of indentation evidently unintentional, so I've fixed it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T15:35:24.677",
"Id": "79633",
"Score": "1",
"body": "In one implementation I had seen, there was a trick like turning the board in one direction and then in the other in order to deal with moves in only one direction. For instance, if you have implemented \"move_down\", to do \"move_right\", you just need to : rotate clockwise, move_down and rotate anti-clockwise"
}
] | [
{
"body": "<p>Iterating more smartly can simplify your loops.</p>\n\n<p>To start with, run this standalone example and see that the <code>izip(…)</code> expression produces useful pairs of coordinates:</p>\n\n<pre><code>from itertools import product, izip\nnRows, nColumns = 3, 5\nfor dest, src in izip(product(range(nRows - 1), range(nColumns)),\n product(range(1, nRows), range(nColumns))):\n print(dest, src)\n</code></pre>\n\n<p>Then, you can reuse the loop just by changing which ranges you pass in.</p>\n\n<pre><code>from itertools import product, izip\n\ndef merge(direction):\n def merge(dest_iterator, src_iterator):\n for (dr, dc), (sr, sc) in izip(dest_iterator, src_iterator):\n if grid[dr][dc] == grid[sr][sc]:\n grid[dr][dc] == 2 * grid[sr][sc]\n grid[sr][sc] = 0\n move(direction)\n\n if direction == \"up\":\n merge(product(range(nRows - 1), range(nColumns)),\n product(range(1, nRows), range(nColumns)))\n elif direction == \"down\":\n merge(product(range(1, nRows), range(nColumns)),\n product(range(nRows - 1), range(nColumns)))\n elif direction == \"left\":\n merge(product(range(nRows), range(nColumns - 1)),\n product(range(nRows), range(1, nColumns)))\n elif direction == \"down\":\n merge(product(range(nRows), range(1, nColumns)),\n product(range(nRows), range(nColumns - 1)))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T19:38:40.203",
"Id": "79684",
"Score": "0",
"body": "Thank you for acquainting me with itertools. I can't say the solution is completely intuitive yet, but that will come in time."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T15:34:50.913",
"Id": "45621",
"ParentId": "45613",
"Score": "6"
}
},
{
"body": "<p>You could use a <code>dictionary</code> of <code>lambda</code>s to find locations of accepting and donating cells in the grid.. Then place the operations in <code>try</code>/<code>except</code>, that will simply fail if you go out of bounds</p>\n\n<pre><code>GetLocations = dict(\n up = lambda r,c: (r,c,r+1,c ),\n down = lambda r,c: (r+1,c,r,c ),\n right = lambda r,c: (r,c,r,c+1),\n left = lambda r,c: (r,c+1,r,c ))\n\ndef merge(direction):\n for col in range(nColumns):\n for row in range(nRows):\n #get acceptor and doner locations\n ar,ac,dr,dc = GetLocations[direction](row,col)\n try:\n #if the evaluation doesn't fail, nothing will fail\n if grid[ar][ac] == grid[dr][dc]:\n grid[ar][ac] = grid[dr][dc]*2\n grid[dr][dc] = 0\n move(direction)\n except IndexError:\n pass\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T15:43:50.143",
"Id": "79635",
"Score": "1",
"body": "I suggest catching just `IndexError` to avoid swallowing other exceptions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T15:44:51.863",
"Id": "79636",
"Score": "1",
"body": "I suggest don't making it throw `IndexError` in the first place by checking the bounds before you break them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T15:45:36.910",
"Id": "79638",
"Score": "0",
"body": "Good call,.. Added it!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T19:40:35.720",
"Id": "79685",
"Score": "1",
"body": "Thank you! This looks like what my approach would have been. I think you got `right` and `left` switched up."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T15:37:20.770",
"Id": "45622",
"ParentId": "45613",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "45621",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T14:23:52.777",
"Id": "45613",
"Score": "11",
"Tags": [
"python",
"game",
"matrix"
],
"Title": "Repetitive For Loops in 2048 Game"
} | 45613 |
<p>I've been working on a game prototype for a couple days and I think that code review would be really helpful. The basic idea of the game is that you are controlling some dwarves, and you dig up resources underground in order to build a tower above ground.</p>
<p>I'm doing this in Sprite Kit, and initially I wanted to have the dwarves represented by sprites and moved around by Sprite Kit animations. But I thought about it and it seemed to me that if the positions of the dwarves are controlled by the Sprite Kit scene, then it breaks the encapsulation of the game logic, which I am trying to keep totally separate from the scene so that I could possibly port the game to other platforms. So I have the positions of the dwarves controlled by an instance of the Game object which inherits from NSObject. The Sprite Kit scene just renders things based on their positions in the Game.</p>
<p>Is this a correct approach? And also, I am concerned about where I am wasting resources and being inefficient in the program. Please let me know if you need to see any other classes than the following.</p>
<p>First, the Game header:</p>
<pre><code>#import <Foundation/Foundation.h>
#import "DTTower.h"
#import "DTTowerFloor.h"
@interface DTGame : NSObject
@property DTTower *gameTower;
@property NSMutableArray *dwarves; //this will contain dwarf objects
@property CGSize worldSize;
@property BOOL isPaused;
@property BOOL hasTowerChanged;
//Need the size so that you can use it to position things similarly on iPad and iphone
-(id) initWithSize:(CGSize)size;
-(void) logTower;
-(void) selectFloorForDwarf:(int)floorNumber;
-(void) moveDwarves;
-(void) updateGameCounters;
@end
</code></pre>
<p>And now the Game implementation:</p>
<pre><code>#import "DTGame.h"
#import "DTDwarf.h"
@implementation DTGame
//randomness functions
static inline CGFloat skRandf() {
return rand() / (CGFloat) RAND_MAX;
}
static inline CGFloat skRand(CGFloat low, CGFloat high) {
return skRandf() * (high - low) + low;
}
#pragma mark - Initialization
-(id) initWithSize:(CGSize)size {
self = [super init];
self.worldSize = size;
[self createDwarves];
[self createGameTower];
return self;
}
-(void) createDwarves {
int numStartingDwarves = 7;
self.dwarves = [[NSMutableArray alloc]init];
for (int i = 0; i < numStartingDwarves; i++){
DTDwarf *tempDwarf = [[DTDwarf alloc]init];
tempDwarf.currentFloor = 0;
tempDwarf.worldSize = self.worldSize;
tempDwarf.position = CGPointMake(0, tempDwarf.currentFloor * self.worldSize.height/6);
[self.dwarves addObject:tempDwarf];
}
}
-(void) createGameTower {
self.gameTower = [[DTTower alloc]init];
}
#pragma mark - Game Update Loop
-(void) updateGameCounters {
[self countDownWorkTimers];
[self checkDwarfStatuses];
}
-(void) countDownWorkTimers {
for (DTDwarf *tempDwarf in self.dwarves) {
if (tempDwarf.isCountingWork) {
if ([tempDwarf jobCountdown]) {
tempDwarf.isCountingWork = NO;
}
}
}
}
-(void) checkDwarfStatuses {
for (DTDwarf *tempDwarf in self.dwarves) {
//perform the mining jobs
if (tempDwarf.hasMiningJobAssigned == YES &&![tempDwarf needsMoving]) {
[self handleMiningJobs:tempDwarf];
}
//set the dwarves to idle if they are not doing anything
if (tempDwarf.hasMiningJobAssigned == NO && tempDwarf.isMoving == NO && tempDwarf.isCountingWork == NO) {
tempDwarf.isIdle = YES;
}
}
}
-(void) handleMiningJobs:(DTDwarf *)dwarf {
NSNumber *floorNumber = [NSNumber numberWithInt:dwarf.currentFloor];
DTTowerFloor *tempFloor = [self.gameTower.towerDict objectForKey:floorNumber];
if (!dwarf.isCountingWork) {
dwarf.isCountingWork = YES;
if (![self.gameTower doMiningToFloor:tempFloor]) {
dwarf.hasMiningJobAssigned = NO;
self.hasTowerChanged = YES;
}
}
}
//right now this is called from inside the scene time step
-(void) moveDwarves {
for (DTDwarf *tempDwarf in self.dwarves) {
if ([tempDwarf needsMoving]) {
tempDwarf.isMoving = YES;
tempDwarf.destinationPosition = CGPointMake(0, tempDwarf.destinationFloor * self.worldSize.height/6);
CGFloat movementDistance = tempDwarf.position.y - tempDwarf.destinationPosition.y;
if (movementDistance > self.worldSize.height/18 || movementDistance < -self.worldSize.height/18) {
if (tempDwarf.position.y != tempDwarf.destinationPosition.y){
if (movementDistance < 0) {
[tempDwarf moveUp];
} else {
[tempDwarf moveDown];
}
}
} else {
tempDwarf.position = tempDwarf.destinationPosition;
tempDwarf.currentFloor = tempDwarf.destinationFloor;
tempDwarf.isMoving = NO;
}
}
if (tempDwarf.isIdle) {
CGPoint tempPosition = CGPointMake(tempDwarf.position.x + skRand(-25, 25),tempDwarf.position.y);
if (tempPosition.x < -self.worldSize.width/2) {
tempPosition.x = -self.worldSize.width/2 + 50;
}
if (tempPosition.x > self.worldSize.width/2){
tempPosition.x = self.worldSize.width/2 - 50;
}
tempDwarf.position = tempPosition;
}
}
}
#pragma mark - Game functions
-(void) selectFloorForDwarf:(int)floorNumber{
NSNumber *floorNum = [NSNumber numberWithInt:floorNumber];
DTTowerFloor *tempFloor = [self.gameTower.towerDict objectForKey:floorNum];
if (tempFloor.hasLadder) {
[self assignJobToDwarfForFloor:floorNumber];
}
}
-(void) assignJobToDwarfForFloor:(int)floorNumber {
for (DTDwarf *tempDwarf in self.dwarves) {
if (!tempDwarf.hasMiningJobAssigned && !tempDwarf.isMoving) {
tempDwarf.hasMiningJobAssigned = YES;
tempDwarf.destinationFloor = floorNumber;
tempDwarf.isIdle = NO;
return;
}
}
}
-(void) logTower {
//prints to the console
[self.gameTower logTower];
}
@end
</code></pre>
<p>And now the rendering methods in the SKScene implementation:</p>
<pre><code>#pragma mark - Scene rendering
-(void) renderTower {
[_sceneTower removeAllChildren];
for (id key in _game.gameTower.towerDict) {
DTTowerFloor *tempFloor = [_game.gameTower.towerDict objectForKey:key];
if (tempFloor.isRevealed && !tempFloor.isBackgroundRevealed) {
SKSpriteNode *tempFloorSprite = [[SKSpriteNode alloc]init];
tempFloorSprite.name = @"towerFloor";
[_sceneTower addChild:tempFloorSprite];
tempFloorSprite.position = CGPointMake(0, tempFloor.floorNumber * _initialScreenSize.height/6);
[tempFloorSprite setColor:[SKColor grayColor]];
tempFloorSprite.size = CGSizeMake(_initialScreenSize.width, _initialScreenSize.height/7);
} else if (tempFloor.isRevealed && tempFloor.isBackgroundRevealed) {
SKSpriteNode *tempFloorSprite = [[SKSpriteNode alloc]init];
tempFloorSprite.name = @"towerBackground";
[_sceneTower addChild:tempFloorSprite];
tempFloorSprite.position = CGPointMake(0, tempFloor.floorNumber * _initialScreenSize.height/6);
[tempFloorSprite setColor:[SKColor greenColor]];
tempFloorSprite.size = CGSizeMake(_initialScreenSize.width, _initialScreenSize.height/7);
}
}
}
-(void) renderTowerFloorBricks {
[_sceneTowerBricks removeAllChildren];
for (id key in _game.gameTower.towerDict) {
DTTowerFloor *tempFloor = [_game.gameTower.towerDict objectForKey:key];
if (tempFloor.isRevealed) {
CGFloat blockPercentageRemaining = tempFloor.blockPercentageRemaining;
for (CGFloat i = 0; i < blockPercentageRemaining; i+=0.10) {
SKSpriteNode *tempBlock = [[SKSpriteNode alloc]init];
tempBlock.name = @"towerBlock";
[tempBlock setColor:[SKColor brownColor]];
[tempBlock setSize:CGSizeMake(_initialScreenSize.width/10, _initialScreenSize.height/7)];
tempBlock.position = CGPointMake((-_initialScreenSize.width/2.22 + _initialScreenSize.width*i), tempFloor.floorNumber * _initialScreenSize.height/6);
[_sceneTowerBricks addChild:tempBlock];
}
}
}
}
-(void) renderTowerOverlay {
for (id key in _game.gameTower.towerDict) {
DTTowerFloor *tempFloor = [_game.gameTower.towerDict objectForKey:key];
SKSpriteNode *tempFloorSprite = [[SKSpriteNode alloc]init];
tempFloorSprite.name = @"towerOverlay";
[_sceneTowerOverlay addChild:tempFloorSprite];
tempFloorSprite.position = CGPointMake(0, tempFloor.floorNumber * _initialScreenSize.height/6);
[tempFloorSprite setColor:[SKColor colorWithRed:0.00 green:0.00 blue:0.00 alpha:0]];
tempFloorSprite.size = CGSizeMake(_initialScreenSize.width, _initialScreenSize.height/7);
}
}
-(void) renderDwarves {
[_sceneDwarves removeAllChildren];
for (DTDwarf *tempDwarf in _game.dwarves) {
SKSpriteNode *tempDwarfSprite = [[SKSpriteNode alloc]init];
[tempDwarfSprite setColor:[SKColor whiteColor]];
[tempDwarfSprite setSize:CGSizeMake(_initialScreenSize.width/50, _initialScreenSize.width/50)];
tempDwarfSprite.position = tempDwarf.position;
[_sceneDwarves addChild:tempDwarfSprite];
}
}
</code></pre>
| [] | [
{
"body": "<p>First thing I notice here is the lack of the proper <code>init</code> pattern:</p>\n<pre><code>-(id) initWithSize:(CGSize)size {\n self = [super init];\n if (self) {\n self.worldSize = size;\n [self createDwarves];\n [self createGameTower];\n }\n return self;\n}\n</code></pre>\n<p>Unfortunately, I'm not exactly certain what could cause <code>self</code> to be <code>nil</code> after <code>[super init]</code> from <code>NSObject</code>, but certainly when you're talking about additional levels of inheritance, returning <code>nil</code> from an <code>init</code> method isn't uncommon. So before we go into doing any sort of initializations, we need do a nil check after the call to <code>super</code>.</p>\n<p>Even if we're inheriting from an object we think we know will never return <code>nil</code>, the fact of the matter is, almost every object inherits from <code>NSObject</code> (there are I think two other base classes), and this is the Apple recommended pattern for <code>init</code> methods... which suggests that at least at one time there was a chance for <code>NSObject</code>'s <code>init</code> to return <code>nil</code>, and whether or not that chance remains today, the fact that this continues to be the recommended pattern means that could end up happening in the future, and your code would immediately have problems.</p>\n<hr />\n<p>The next thing I notice is this:</p>\n<h1>DTGame.h</h1>\n<pre><code>#import <Foundation/Foundation.h>\n#import "DTTower.h"\n#import "DTTowerFloor.h"\n</code></pre>\n<p>The only non-Foundation, non-C type that exists in <code>DTGame.h</code> is <code>DTTower</code>. Moreover, <code>DTTower</code> is a <code>@property</code>, not an argument. So anyone importing <code>DTGame.h</code> certainly doesn't have to know about anything in <code>DTTowerFloor.h</code> to use <code>DTGame</code> objects, and while they MIGHT want to know about <code>DTTower.h</code> in order to set this property, they don't necessarily HAVE to know about it.</p>\n<p>So, this isn't actually a run-time issue, and you're not wasting resources, but by importing more headers than you need to in more locations than are necessary, you're slowing down compile times and you're adding a lot of things to auto-complete menus that you don't really need.</p>\n<p><code>DTTowerFloor.h</code> can definitely be moved into the <code>.m</code>. If you need it in another file, you can always import it there too, but there's nothing about <code>DTGame</code> that suggest that anyone using it would also definitely be using <code>DTTowerFloor</code>.</p>\n<p>As for <code>DTTower.h</code>, this is a judgment call. You can still use the <code>DTTower</code> property without actually importing the file in the <code>.h</code> by moving the import to the <code>.m</code>, and replacing the <code>.h</code> import with this:</p>\n<pre><code>@class DTTower;\n</code></pre>\n<p>This let's the compiler know that the class does definitely exist, and before you use this property, it will be defined, but we don't need the import yet.</p>\n<p>But if there's a good chance that most people using <code>DTGame</code> will be using the <code>DTTower</code> property of <code>DTGame</code>, go ahead and leave the import in the <code>.h</code> file.</p>\n<hr />\n<p>I don't understand these two public properties:</p>\n<pre><code>@property BOOL isPaused;\n@property BOOL hasTowerChanged;\n</code></pre>\n<p>The seem odd.</p>\n<p>First of all, <code>isPaused</code> straight up isn't used at all in the entire class. And it's fine for a property to not be used. Take the <code>tag</code> property of <code>UIView</code> for example. It's not used at all. It exists simply for someone using <code>UIView</code> to set it to a value so they can retrieve that value later and compare the values. An <code>isPaused</code> seems like a very weird property to do something like this with.</p>\n<p>If the game is paused, should any of these actions even take place? If not, and the <code>isPaused</code> property exists on the class, then the class itself should enforce not allowing these actions to take place.</p>\n<pre><code>if (self.isPaused) return;\n</code></pre>\n<p>I just don't know. I think <code>isPaused</code> needs a lot of explanation on its intended use, because something is wrong with it.</p>\n<p>As for <code>hasTowerChanged</code>, I also don't understand it. I see we're setting it to <code>YES</code> in a certain condition. If the default is <code>NO</code>, we should explicitly set it to <code>NO</code> in our init method.</p>\n<p>But more, what's the intended use of this BOOL? Does it ever need to reset to <code>NO</code>?</p>\n<hr />\n<pre><code>-(void) selectFloorForDwarf:(int)floorNumber\n</code></pre>\n<p>This should be named to <code>moveDwarfToFloor:(int)floorNumber</code>. It makes it more clear that the argument we're sending is a floor number and that the method takes a dwarf (which the user has no control over which dwarf) and moves him to the specified floor. As named, your method could be confused as some way of automatically selecting a floor for a specific dwarf number to move to.</p>\n<hr />\n<pre><code>[self.gameTower.towerDict objectForKey:floorNumber]\n</code></pre>\n<p>You don't include this class here, but this is very suspect. Clearly, <code>towerDict</code> is an <code>NSDictionary</code> property of <code>DTTower</code>. What's unclear to me is why we're using <code>NSNumber</code> objects as keys in the dictionary. Why not just use an array? If we use an array, we don't have to be converting to and from <code>int</code>/<code>NSNumber</code>. We could just stick with <code>int</code>. Or if we want to use a dictionary for <code>DTTower</code>'s <code>towerDict</code> property, why is the <code>DTGame</code> class limiting use to <code>NSNumber</code> as the keys via taking <code>int</code> as the argument for moving dwarves to floors? Can't <code>selectFloorForDwarf:</code> (or better <code>moveDwarfToFloor:</code> take an <code>NSObject<NSCopying>*</code> argument so that users can use ANY sort of key they decide on and not be limited to using a dictionary as an array? Or perhaps better yet, just make <code>moveDwarfToFloor:</code> take a <code>DTTowerFloor*</code> argument, and you send a pointer to the floor the dwarf needs to move too, and <code>DTTower</code> can simply maintain an <code>NSSet</code> of all the floor objects.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T02:42:50.173",
"Id": "79732",
"Score": "0",
"body": "Lots of good points here! I am working on some of the suggestions. The reason for isPaused is that the SKScene pauses the game by setting it to isPaused, and the time step only runs while this condition is not true. The reason for hasTowerChanged is that the SKScene only re-renders the tower and some objects when they change, rather than every time step. Thanks for the response!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T16:19:13.963",
"Id": "79779",
"Score": "0",
"body": "I tried to convert everything to an array instead of using an NSDictionary, but when creating the array and trying to set an object to an arbitrary index, it crashes. I start the array at -100 and count up to 4. I guess you can't insert to an arbitrary location in an empty array? It works if I start at index 0 instead of -100, but this messes up the logic in the rest of the program."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T18:23:22.687",
"Id": "79788",
"Score": "1",
"body": "Arrays cannot have negative indexes. As far as inserting at arbitrary positive indexes, you have to `initWithCapacity:`, otherwise the array doesn't necessarily have the capacity. It sounds like using a dictionary may end up being easiest, but if this is the case, then we shouldn't limit the floor identifiers to simply `int`s. In your implementation of the game, it may make sense for simply using ints, but that limits the reusability."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T22:33:03.607",
"Id": "45657",
"ParentId": "45615",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "45657",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T14:31:18.433",
"Id": "45615",
"Score": "2",
"Tags": [
"game",
"objective-c",
"ios"
],
"Title": "Separating Game Logic from Rendering - Sprite Kit"
} | 45615 |
<p>I have created my first ping-pong game with JavaScript and Canvas. I will be glad if anybody can tell me how to optimize the code and functionality.</p>
<p><a href="https://github.com/nikitalarionov/js-pong" rel="nofollow">https://github.com/nikitalarionov/js-pong</a></p>
<p>First collision detection:</p>
<pre><code>//Function to check collision between ball and one of
//the paddles
function collides(b, p) {
if(b.x + ball.r >= p.x + p.w && b.x - ball.r <= p.x + p.w) {
if (b.y + b.r >= p.y && b.y + b.r <= p.y + p.h && b.x - b.r <= p.x) {
paddleHit = 1;
if(b.x < W/ 2) {
hit++;
} else if (b.x > W / 2) {
hit2++;
}
return true;
}
else if(b.y - b.r <= p.y && b.y - b.r >= p.y - p.h && b.x + b.r >= p.x) {
paddleHit = 2;
if(b.x < W/ 2) {
hit++;
} else if (b.x > W / 2) {
hit2++;
}
return true;
}
else return false;
}
}
</code></pre>
<p>I experience bad performance when the ball hits an angle of one of the paddles:</p>
<pre><code>// Function that updates everything, score, positions, main game logic
function update(){
// Move the padles
for(var i = 0; i <= padles.length; i++) {
var p = padles[i];
if (i === 0 && players[0].moveUp) {
if (p.y <= 0) {
p.y = 0;
}
else {
// is it how i move left paddle
// it is doesn't work good like a mousemove
// animations is slowly, i dont know how to fix it
p.y -=25;
}
}
if (i === 0 && players[0].moveDown) {
if (p.y + p.h >= H) {
p.y = H - p.h;
}
else {
p.y += 25;
}
}
if (mouse.y && i === 1) {
if (p.y + p.h >= H && mouse.y > p.y) {
p.y = H - p.h;
}
else {
p.y = (mouse.y -50) - p.w / 10;
}
}
}
// ... some code
}
</code></pre>
<p>There I have very lazy animation and moving of the left paddle. I use keys for it outside of the animation cycle:</p>
<pre><code> // Add Global Event to handle keyboards buttons
window.addEventListener('keydown', function(e) {
if (e.keyCode === 87) {
players[0].moveUp = true;
} else
if (e.keyCode === 83) {
players[0].moveDown = true;
}
}, false);
window.addEventListener('keyup', function(e) {
if (e.keyCode === 87) {
players[0].moveUp = false;
} else
if (e.keyCode === 83) {
players[0].moveDown = false;
}
}, false);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T15:08:30.940",
"Id": "79620",
"Score": "1",
"body": "I posted some code with problems, but it works, but not good :) It seems i have two problem (Collision Detection, Lazy Moving of left paddle)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T19:43:15.823",
"Id": "79687",
"Score": "0",
"body": "this code in action: http://jsfiddle.net/9vgq6/ for the lazy among us :)"
}
] | [
{
"body": "<p>From a once-over,</p>\n\n<ul>\n<li>Short 1 letter variables are terrible ( except for <code>x</code> and <code>y</code> ), <code>b</code>, <code>p</code> and <code>W</code> are just terrible</li>\n<li>Also please spellcheck your variables: <code>padles</code> -> <code>paddles</code></li>\n<li><p>You should only detect collision when the ball is going to the left and gets in the danger-zone or when it is going to the right and getting in the danger-zone. So instead of doing 8 accesses, 1 AND and 4 sums (<code>if(b.x + ball.r >= p.x + p.w && b.x - ball.r <= p.x + p.w) {</code>) you should rather do something like </p>\n\n<pre><code>if( deltaX < 0 && ball.x < someLimit ){\n testCollision( ball , leftPaddle );\n} else if( ball.x > someOtherLimit ) {\n testCollision( ball , rightPaddle );\n}\n</code></pre>\n\n<p>Where deltaX is the amount of pixels the ball is moving over the X axis, this should make paddle collision a lot more efficient</p></li>\n<li>Please don't use magical constants, in this case I see <code>25</code> all over the place</li>\n<li>Same for the keycodes, you should use constants for those</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-15T04:15:27.920",
"Id": "94661",
"Score": "0",
"body": "Remember that there aren't any *real* constants in JavaScript."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T20:59:01.353",
"Id": "45651",
"ParentId": "45618",
"Score": "6"
}
},
{
"body": "<ol>\n<li>The source of the slowness is due to the interaction with the\n <code>collision</code> object, I think.</li>\n<li><p>There is also a flaw with your collision management as the ball can\nnoclip out of the canvas.</p>\n\n<p>In pseudocode, you handle object position and speed like this (one\ndimensional simplification) :</p>\n\n<pre><code>x += v;\nif (collides) {v = -v;}\n</code></pre>\n\n<p>With this approach, if the objects speed is great enough then the\nobject can get past the barrier and it will noclip. Instead, you\nwant your code to look like this:</p>\n\n<pre><code>if (x += v leads to collision) {\n v = -v;\n}\nelse {\n x += v;\n} \n</code></pre>\n\n<p>or some variation thereof.</p></li>\n<li><p>Paddle movement feels fine to me.</p></li>\n<li><p>Whatever this 'particles' thing is, doesn't seem to work.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T21:01:11.897",
"Id": "45652",
"ParentId": "45618",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T14:42:45.023",
"Id": "45618",
"Score": "5",
"Tags": [
"javascript",
"performance",
"game",
"collision",
"canvas"
],
"Title": "Ping-pong game with JavaScript and Canvas"
} | 45618 |
<p>Like many ASP.NET developers, I use the Newtonsoft library to convert C# objects into JSON. Is this use of <code>Newtonsoft.Json.JsonConvert.SerializeObject</code> secure?</p>
<p>Here is how I use it in a Razor view:</p>
<pre><code><script type="text/javascript">
var json = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model))
</script>
</code></pre>
<p>In Web Forms I might have this in my ASPX:</p>
<pre><code><script type="text/javascript">
var json = <%= Newtonsoft.Json.JsonConvert.SerializeObject(Model)) %>
</script>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T16:00:00.693",
"Id": "79648",
"Score": "0",
"body": "I'm new here, brand new actually, and may not yet get the purpose of this Stack Exchange site. Would the person who down voted the question or someone in the know give me a clue as to why it might make sense to down vote it? (Not a very friendly way to say hello...)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T21:13:08.463",
"Id": "79694",
"Score": "2",
"body": "CodeReview is for improving working code. StackOverflow is for fixing broken code, and Programmers is for designing and 'strategizing' ways to make working code. Sometimes the cross-over is fuzzy, and this appears to be one of those times. That's all."
}
] | [
{
"body": "<p>An opinion question, my answer is; sure ( if you can trust Newtonsoft to escape properly all data, since JSON is such a simple format, it should not be a problem ).</p>\n\n<p>Regardless,</p>\n\n<ul>\n<li><p><code>var json</code> <- unfortunate name, the name should describe what data there is, not how it is encoded. <code>car</code>, <code>person</code>, <code>vendor</code> are properer names</p></li>\n<li><p><code><script type=\"text/javascript\"></code> -> Nowadays, people try to avoid puttin JavaScript inside HTML, instead they just include JavaScript files. I would suggest you go down that path as well</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T15:57:18.917",
"Id": "79646",
"Score": "0",
"body": "Thanks for the response. Perhaps this is the wrong place to post this question since it is primarily about security and whether or not that particular method encodes its output in a way that is safe in a JavaScript context."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T20:37:00.083",
"Id": "79693",
"Score": "0",
"body": "@JeremyCook Indeed ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T15:50:12.970",
"Id": "45628",
"ParentId": "45623",
"Score": "1"
}
},
{
"body": "<p>Take the following result :</p>\n\n<pre><code><script type=\"text/javascript\">\n var json = { \"key\" : \"</script>\" }\n</script>\n</code></pre>\n\n<p>Unless you HtmlEncoded your data somewhere, the \"</script>\" will break your code. With Html Encoding, the result should look like this :</p>\n\n<pre><code><script type=\"text/javascript\">\n var json = { \"key\" : \"&lt;/script&gt;\" }\n</script>\n</code></pre>\n\n<p>To easily encode all string, you can check this solution : <a href=\"http://pastebin.com/R2PWZkUq\" rel=\"nofollow\">http://pastebin.com/R2PWZkUq</a></p>\n\n<p>Note that this should happen only with object declare inline. JSon coming from Ajax don't have this problem.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T14:56:57.973",
"Id": "82774",
"Score": "0",
"body": "Why would it break ? Is there something he should change to prevent that ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T14:58:58.450",
"Id": "82776",
"Score": "2",
"body": "@Marc-Andre check out this jsfiddle: http://jsfiddle.net/4t3Mx/ Apparently the `</script>` tag takes precedence and closes the script. Definitely not what I would expect but there it is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T15:09:58.370",
"Id": "82779",
"Score": "0",
"body": "Here is a nice solution to fix that problem : http://pastebin.com/R2PWZkUq"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T15:14:40.893",
"Id": "82781",
"Score": "1",
"body": "That's the good old cross-site scripting attack. One never can be careful enough it seems..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T12:47:18.467",
"Id": "82941",
"Score": "0",
"body": "So, to the question \"Is this use of Newtonsoft.Json.JsonConvert.SerializeObject secure?\" My answer is No, and I proved why ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T13:02:20.750",
"Id": "82944",
"Score": "0",
"body": "Hmmm, you found a problem with jsfiddle, because it does funky stuff. But executing this in the console or jsbin.com is perfectly safe. You have not proved much."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T13:30:30.613",
"Id": "82946",
"Score": "0",
"body": "As @Vogel612 said, this is common cross-site scripting attack. JSBin does the same thing than JSFiddle, check this : http://jsbin.com/muhagujo/3"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T13:32:09.400",
"Id": "82947",
"Score": "1",
"body": "@konjin the question was specifically asked in respect to safety in the context of websites... Comparing that safety to the one in console is comparing apples to pears."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T14:16:08.407",
"Id": "47247",
"ParentId": "45623",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T15:37:29.660",
"Id": "45623",
"Score": "1",
"Tags": [
"javascript",
"asp.net",
"security",
"json"
],
"Title": "Newtonsoft.Json.JsonConvert.SerializeObject"
} | 45623 |
<p>I have written a code for an application/website that I wanted to be structured similarly to MVC design pattern (but I think it's rather MVP based on comparison I read). This functions as a kind of intranet where users can log in, see some news, short info about them - all on one page (some of the content is static and some dynamic based on the user).</p>
<p>I structured my code in the following way:</p>
<ul>
<li>presentation pages (index.php, main.php, admin.php, error.php)</li>
<li>all input is processed by JavaScript (jQuery) by <code>$.post</code> function which calls my router.php script passing name of a class & method to call and additional params to be passed to that method; this script processes the input and uses Controller.php class to handle that request</li>
<li>Controller class handles instantiating of the right class and calling its method and returning the results to presentation pages by using callbacks on $.post</li>
<li>Controller calls specific methods in classes representing user, news etc.</li>
</ul>
<p>Please mind the naming of my routher.php and Controller class - it's how I called them but this might not be correct from the MVC/MVP point of view - if so please point that out.</p>
<p>Questions that I have in my mind:</p>
<ul>
<li>Is this right structure?</li>
<li>Should I combine code in router.php & Controller.php into one entity?</li>
<li>How should JavaScript code be stored? At the moment I'm using one .js file for handling login included in index file and one for the rest of the presentation pages.</li>
<li>I'm storing all info (User object, news etc.) in $_SESSION variable.</li>
<li>Can I store connection details in global variable (I read a lot on Stack Overflow that this is discouraged/bad practice)?</li>
</ul>
<p>Please comment, advise and share your opinion - all constructive criticism is welcome.</p>
<p><strong>router.php</strong>:</p>
<pre><code><?php
require_once 'config.php';
require_once 'Controller.php';
ini_set("log_errors", 1);
ini_set("error_log", LOG_PATH . "Controller.log");
ini_set('display_errors', 0);
error_reporting(E_ALL);
startIntranetSession();
try
{
$appController = new Controller();
if (isset($_POST['params']))
{
if (sizeof($_POST['params']) > 1)
{
$method = filter_input(INPUT_POST, 'method', FILTER_SANITIZE_STRING);
$class = filter_input(INPUT_POST, 'class', FILTER_SANITIZE_STRING);
$params = filter_input(INPUT_POST, 'params', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
$methodToCall = $class . "::" . $method;
echo $appController->callMethod($methodToCall, $params);
}
elseif (sizeof($_POST['params']) == 1)
{
$method = filter_input(INPUT_POST, 'method', FILTER_SANITIZE_STRING);
$class = filter_input(INPUT_POST, 'class', FILTER_SANITIZE_STRING);
$params = filter_input(INPUT_POST, 'params', FILTER_DEFAULT);
$methodToCall = $class . "::" . $method;
echo $appController->callMethod($methodToCall, $params);
}
}
else
{
$method = filter_input(INPUT_POST, 'method', FILTER_SANITIZE_STRING);
$class = filter_input(INPUT_POST, 'class', FILTER_SANITIZE_STRING);
$methodToCall = $class . "::" . $method;
echo $appController->callMethod($methodToCall);
}
}
catch (Exception $e)
{
echo "error";
$file = LOG_PATH . 'router.log';
$date = date("d-m-Y H:i:s", time());
$message = $date . " - " . $e->getMessage() . " \r\n" . $e->getTraceAsString();
file_put_contents($file, $message, FILE_APPEND);
}
</code></pre>
<p><strong>Controller.php:</strong></p>
<pre><code><?php
require_once 'config.php';
require_once 'News.php';
require_once 'User.php';
require_once 'KPI.php';
ini_set("log_errors", 1);
ini_set("error_log", LOG_PATH . "Controller.log");
ini_set('display_errors', 0);
error_reporting(E_ALL);
startIntranetSession();
class Controller
{
public function __construct()
{
$GLOBALS['connection'] = new mysqli(SQL_HOST, SQL_USER, SQL_PASS, SQL_DB, SQL_PORT);
}
public function callMethod($classNameAndMethod, $parameters = null)
{
$callMethodArray = explode("::", $classNameAndMethod);
if (sizeof($callMethodArray) != 2)
{
throw new Exception("Wrong parameter in callMethod()");
}
$className = $callMethodArray[0];
$methodName = $callMethodArray[1];
if ($className == 'User')
{
if (isset($_SESSION['current_user']))
{
$classObject = unserialize($_SESSION['current_user']);
}
else
{
$classObject = new $className();
}
}
else
{
$classObject = new $className();
}
if (!method_exists($classObject, $methodName))
{
throw new Exception("Given method does not exist!");
}
if (!isset($parameters))
{
$parameters = array();
}
if (!$result = call_user_func_array(array($classObject, $methodName), $parameters))
{
throw new Exception("Call_user_func_array failed!");
}
else
{
return $result;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T15:32:33.770",
"Id": "80369",
"Score": "0",
"body": "question, there are a lot of frameworks that does MVC - is there a reason why you are re-inventing the wheel so that we know more into how we could look at your code in a critical sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T08:48:15.363",
"Id": "80521",
"Score": "0",
"body": "@azngunit81 I'm new to MVC frameworks and am yet to learn one (Zend2 is the choice), but the overhead of a framework & mostly the learning curve just to quickly create simple web app I think was not a good choice; also I'm not trying to re-invent anything, but to apply common design pattern and to structure (separate) the code properly"
}
] | [
{
"body": "<p>For now, here is what I have noticed. I'll come back when I get some time to take a better look.</p>\n\n<p>I'm seeing some repetition in that initial try statement too. It looks as though you can take</p>\n\n<pre><code>$method = filter_input(INPUT_POST, 'method', FILTER_SANITIZE_STRING);\n$class = filter_input(INPUT_POST, 'class', FILTER_SANITIZE_STRING);\n$methodToCall = $class . \"::\" . $method;\n</code></pre>\n\n<p>and place it outside of the <code>if</code> statements.</p>\n\n<p>Also, to better organize your errors, and keep a better record of error recording, I'd consider you create your own exception classes that extend the built-in <code>Exception</code> object, or use the SPL exceptions.</p>\n\n<p>For instance, you could, in <strong>Controller.php</strong>, throw a <code>InvalidParameterCallException</code>, <code>MethodExistanceException</code>, and a <code>FunctionCallException</code>. In your first file, you can use multiple <code>catch</code> statements to properly handle anything that's thrown. Like:</p>\n\n<pre><code>try {\n $appController = new Controller();\n ...\n} catch (InvalidParameterCallException $error) {\n ...\n} catch (MethodExistanceException $error) {\n ...\n} catch (FunctionCallException $error) {\n ...\n}\n</code></pre>\n\n<p>However, the best option may be to implement the SPL <code>BadFunctionCallException</code> or the <code>BadMethodCallException</code> class. I suggest you <a href=\"http://us.php.net/manual/en/spl.exceptions.php\" rel=\"nofollow noreferrer\">take a look at these classes</a>, I think you could benefit from them. <a href=\"http://ralphschindler.com/2010/09/15/exception-best-practices-in-php-5-3\" rel=\"nofollow noreferrer\">Here is a good article</a> on PHP 5.3 exception usage.</p>\n\n<p>This way you can supply the user (or the error logs) with a more specific error.</p>\n\n<blockquote>\n <p>Is this right structure?</p>\n</blockquote>\n\n<p>First off, <a href=\"https://stackoverflow.com/questions/2056/what-are-mvp-and-mvc-and-what-is-the-difference\">here is a very good, short and simple write-up</a> of MVC vs. MVP.</p>\n\n<p>I would say that <strong>router.php</strong> and <strong>Controller.php</strong> are the Presenter layer. However, in <strong>router.php</strong>, for me, it's hard to classify this explicitly. It's taking in user input and deciding how to react, but you end up using <code>echo</code>? Is a user physically visiting this page or not? If it's meant to be a Presenter (or Controller) file, then I think any visiting to it requires a 404 or a redirect.</p>\n\n<blockquote>\n <p>Should I combine code in router.php & Controller.php into one entity?</p>\n</blockquote>\n\n<p>No. They both handle very different things. <strong>router.php</strong> is taking in input and making a convienent way to use it. <strong>Controller.php</strong> is delegating the workload that your routing file used it for.</p>\n\n<p>I'm unsure of why you have the class and method passed as one argument, but then split it up right after? It would seem to make more sense if you allowed for:</p>\n\n<pre><code>function callMethod($className, $methodName, $parameters = null)\n</code></pre>\n\n<p>instead. That way you don't need to explode the sting. Now you can call:</p>\n\n<pre><code>$appController->callMethod($class, $method, $params);\n</code></pre>\n\n<p>I would rewrite your <code>callMethod()</code> function to something a bit like:</p>\n\n<pre><code>public function callMethod($className, $methodName, $parameters = null)\n{\n\n if (count($callMethodArray) !== 2) {\n throw new Exception(\"Wrong parameter in callMethod()\");\n }\n\n if ($className == 'User' && isset($_SESSION['current_user'])) {\n $classObject = unserialize($_SESSION['current_user']);\n } else {\n $classObject = new $className();\n }\n\n if (is_null($parameters)) {\n $parameters = array();\n }\n\n if (!method_exists($classObject, $methodName)) {\n throw new Exception(\"Given method does not exist!\");\n }\n\n if ($result = call_user_func_array(array($classObject, $methodName), $parameters)) {\n return $result;\n } else {\n throw new Exception(\"Call_user_func_array failed!\");\n }\n}\n</code></pre>\n\n<p>This clears up your code a bit, notice the minimization of the nested <code>if</code>s, the use of <code>is_null</code>, and my switching of the negation <code>if</code> at the end.</p>\n\n<p>To further break this down, you could create a <code>ClassValidator</code> class to validate classes, functions, and arguments.</p>\n\n<blockquote>\n <p>storing all info (User object, news etc.) in $_SESSION variable.</p>\n</blockquote>\n\n<p>User objects (Username, First name, User Id, etc.) are something that works well in the session global. When you say news though, I'm getting a little weary. How much news? If it's the top 5 or so article synopses, I think you'll be okay. If it's full length articles for 10+ different stories, you may run into issues down the line.</p>\n\n<p>Typically, the $_SESSION variable is used to store basic information about the user for quick and easy access.</p>\n\n<blockquote>\n <p>Can I store connection details in global variable (I read a lot on\n Stack Overflow that this is discouraged/bad practice)?</p>\n</blockquote>\n\n<p>I agree that this is a bad practice. Remember, you define it as:</p>\n\n<pre><code>$GLOBALS['connection'] = new mysqli(SQL_HOST, SQL_USER, SQL_PASS, SQL_DB, SQL_PORT);\n</code></pre>\n\n<p>The <a href=\"http://us3.php.net/manual/en/reserved.variables.globals.php\" rel=\"nofollow noreferrer\">$GLOBAL</a> variable is one that should be avoided. If you code your stuff correctly, there should hardly ever be a need for it. At the very least, you could create a new <code>private $_connection = null;</code> to hold your database.</p>\n\n<p>But since this is a controlling class, there should be no need to even declare a mysqli object! You should have a class (the model) that handles all of the database action for you.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T00:20:35.520",
"Id": "45667",
"ParentId": "45624",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T15:38:02.020",
"Id": "45624",
"Score": "2",
"Tags": [
"php",
"mvc"
],
"Title": "Is this right structure for MVC / MVP application?"
} | 45624 |
<p>I know that there may be better ways of writing this do you think that this code is written well enough to be used in a real world application?</p>
<pre><code> var pow = function ( base, power ) {
var result = 1;
if ( power < 0 ) {
return ( 1 / pow( base, -(power)) );
}
for ( var i = 1; i <= power; i++ ) {
result = result * base;
}
return result;
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T16:07:32.563",
"Id": "79649",
"Score": "3",
"body": "[Math.pow()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow) - it's built in (and roughly 5 times faster)"
}
] | [
{
"body": "<p>The code in the OP won't return a correct result for non-integer values of <code>power</code>: for example, <code>0.5</code> should return the square root of the number.</p>\n\n<p>Sometimes you want to use the <a href=\"http://en.wikipedia.org/wiki/Floating-point_unit\" rel=\"nofollow\">Floating Point Coprocessor</a> for a calculation: instead of implementing an algorithm using software running on the CPU.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T16:21:59.150",
"Id": "45633",
"ParentId": "45630",
"Score": "2"
}
},
{
"body": "<p>For a power function with an integer exponent you can loop through the bits in the exponent instead of making a linear loop:</p>\n\n<pre><code>function pow(base, power) {\n if (power < 0) return 1 / pow(base, -power);\n var b = base, result = 1;\n while (power > 0) {\n if ((power & 1) != 0) {\n result *= b;\n }\n power >>= 1;\n b *= b;\n }\n return result;\n}\n</code></pre>\n\n<p>This will only loop as many times as there are bits used in the exponent, for a value like 1000 that means 10 iterations instead of 1000.</p>\n\n<p>Testing this with <code>pow(2, 1000)</code> in Firefox shows that it is about 70 times faster (but the built in method is still even 8 times faster).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T16:44:46.833",
"Id": "45636",
"ParentId": "45630",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "45636",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T15:58:00.733",
"Id": "45630",
"Score": "5",
"Tags": [
"javascript",
"reinventing-the-wheel"
],
"Title": "Power function in JavaScript"
} | 45630 |
<p>I am looking to speed up the exchange from vba to IE. The sendkeys works, but I was curious if there were a better way to do this?</p>
<p>The site that it routes to is a form, but there is no submit button. The only way to pull the data is to tab to the next box or click somewhere on the screen. I was hoping, however, to have all of this automated through VBA.</p>
<p>Thoughts?</p>
<pre><code>Public Declare Function SetForegroundWindow Lib "user32" (ByVal HWND As Long) As Long
Function FillInternetForm()
Dim HWNDSrc As Long
Dim ie As Object
Set ie = CreateObject("InternetExplorer.Application")
'create new instance of IE. use reference to return current open IE if
'you want to use open IE window. Easiest way I know of is via title bar.
HWNDSrc = ie.HWND
ie.Navigate "http://helppointinfo.farmersinsurance.com/OCR/Labor_Rates/laborrates.asp"
'go to web page listed inside quotes
ie.Visible = True
While ie.Busy
DoEvents 'wait until IE is done loading page.
Wend
ie.Document.getElementById("DirectZip").Value = Sheets("NAT").Range("C2").Value
SetForegroundWindow HWNDSrc
Application.SendKeys "{TAB 11}", True
DoEvents
Application.SendKeys "{NUMLOCK}", True
End Function
Public Sub RunRates()
Call FillInternetForm
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T23:01:39.100",
"Id": "80924",
"Score": "0",
"body": "Hi, I've rolled back your edit. [Please avoid editing your question to include suggested changes from answers](http://meta.codereview.stackexchange.com/a/1483/23788)."
}
] | [
{
"body": "<p>Just reviewing what you've got here...</p>\n\n<h3>Indentation</h3>\n\n<p>The code would read much better with proper indentation:</p>\n\n<pre><code>Function FillInternetForm()\n Dim HWNDSrc As Long\n Dim ie As Object\n\n Set ie = CreateObject(\"InternetExplorer.Application\")\n HWNDSrc = ie.HWND\n\n ie.Navigate \"http://helppointinfo.farmersinsurance.com/OCR/Labor_Rates/laborrates.asp\"\n ie.Visible = True\n While ie.Busy\n DoEvents 'wait until IE is done loading page.\n Wend\n ie.Document.getElementById(\"DirectZip\").Value = Sheets(\"NAT\").Range(\"C2\").Value\n\n SetForegroundWindow HWNDSrc\n\n Application.SendKeys \"{TAB 11}\", True\n DoEvents\n Application.SendKeys \"{NUMLOCK}\", True\n\nEnd Function\n\nPublic Sub RunRates()\n Call FillInternetForm\nEnd Sub\n</code></pre>\n\n<h3><code>Call</code> Instruction</h3>\n\n<p>As answered in <a href=\"https://stackoverflow.com/q/479891/1188513\">this StackOverflow question</a>, the <code>Call</code> instrucation is a relic from ancient versions of VB, it's not needed and, IMO, only adds clutter.</p>\n\n<pre><code>Public Sub RunRates()\n FillInternetForm\nEnd Sub\n</code></pre>\n\n<h3>Coupling</h3>\n\n<p>The <code>FillInternetForm</code> function is needlessly coupled with the Excel object model - <code>Sheets(\"NAT\").Range(\"C2\").Value</code> should be passed as a <code>String</code> parameter to the function:</p>\n\n<pre><code>Function FillInternetForm(ByVal DirectZipValue As String)\n '...\n ie.Document.getElementById(\"DirectZip\").Value = DirectZipValue\n '...\nEnd Function\n\nPublic Sub RunRates()\n FillInternetForm Sheets(\"NAT\").Range(\"C2\").Value\nEnd Sub\n</code></pre>\n\n<h3>Function?</h3>\n\n<p>VB functions are procedures with a return value. If it's not specified, then it's returning a <code>Variant</code> - here <code>FillInternetForm</code> is never assigned a return value, and whatever it would be returning wouldn't be used. In other words, you have a <em>procedure</em> (<code>Sub</code>), not a <em>function</em>. The signature should be modified like this:</p>\n\n<pre><code>Public Sub FillInternetForm(ByVal DirectZipValue As String)\n</code></pre>\n\n<p>I like things explicit - if a member is going to be <code>Private</code>, it needs a <code>Private</code> access modifier; if it's going to be <code>Public</code>, I don't like relying on VB's \"defaults\", mostly because I code in different languages where these defaults differ (C#). Having explicit access modifiers eliminate the possible confusion, but that might be only me.</p>\n\n<p>Lastly, I don't understand why <code>FillInternetForm</code> would have to press <kbd>NUM LOCK</kbd>, this <em>looks</em> misplaced, and has a side-effect that could be surprising to whoever is running that code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T20:48:42.130",
"Id": "80429",
"Score": "1",
"body": "Thank you for the response - haven't gotten a chance, as of yet, to take your suggestions, but wanted to answer the `Num Lock` question. I have it in place because when I run the `Sendkeys` it actually turns the `Num Lock` off. By having this code it place it will turn it back on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T20:59:57.503",
"Id": "80433",
"Score": "0",
"body": "That would make a good reason to put a comment, so that call doesn't get inadvertantly removed by a future maintainer (could be future you!) - feel free to upvote any useful answers you get ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:28:37.697",
"Id": "80758",
"Score": "0",
"body": "My overall plan with this code is to return the values from the webpage back into the excel sheet:\n1. Wouldn't I need to leave it as a funciton as I am seeking to return a value?\n2. Do you know of any articles that will return results from `iframe`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:38:33.747",
"Id": "80762",
"Score": "0",
"body": "If `FillInternetForm` should return a value, then you're missing a line of code that would assign such a return value (`FillInternetForm = TheReturnValue`). You're not showing the code that's calling `FillInternetForm`, but if it's a procedure (sub) it will look like `FillInternetForm` and if it's a function it will look like `Value = FillInternetForm`. I don't know of any articles that return results from `iframe` (maybe Google does), but my initial thought was that if the form is on a `.asp` page you probably could get away with sending a simple HTTP request with your parameters, to the URL."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:39:45.243",
"Id": "80763",
"Score": "0",
"body": "It's not part of the code shown bc it's not created yet. I first wanted to make sure sending the information was quick and accurate, then I was going to work on the return portion of it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:47:08.393",
"Id": "80766",
"Score": "0",
"body": "If i were to use a `function` I should acrtually be doing it for the `RunRates ()` if I am wanting to return a value and not on the `FillInternetForm` correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:52:25.337",
"Id": "80768",
"Score": "0",
"body": "It all depends on what you want to do with the returned value, but if RunRates is going to return the value returned by FillInternetForm then both will have to be functions. Identify your inputs+outputs first, *then* write the code ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T14:06:39.447",
"Id": "80772",
"Score": "0",
"body": "I know some of the outputs, but not 100% on the inputs. I figured this question was good - thank you for all the help - so I posted a new one under [this StackExchange question](http://codereview.stackexchange.com//q/46276)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T19:48:43.317",
"Id": "46095",
"ParentId": "45635",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "46095",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T16:33:46.730",
"Id": "45635",
"Score": "8",
"Tags": [
"vba"
],
"Title": "Speed up processing between VBA and IE"
} | 45635 |
<p>I was asked this recently, and I couldn't figure out the best way. We are trying to replicate Google's search results where the search terms are bolded (using a b tag) in the results. </p>
<pre><code>Input Terms Output
The search is cool {sea} The <b>sea</b>rch is cool
</code></pre>
<p>Originally, I thought this was pretty easy:</p>
<pre><code>String results(String input, String[] terms)
{
for(String term : terms)
{
input = input.replace(term, "<b>" + term + "</b>");
}
return input;
}
</code></pre>
<p>However, this isn't correct. For example:</p>
<pre><code>Input Terms Output
The search is cool {sea, search} The <b>search</b> is cool
</code></pre>
<p>I struggled to figure out the best way to approach this. Obviously we can no longer find and replace immediately. I played around with using a <code>Map<Integer,String></code> where the key is the index returned by <code>input.indexOf(term)</code> and the value is the term, but this seemed potentially unnecessary. Any improvements? </p>
<pre><code>public String results(String input, String[] terms)
{
Map<Integer, String> map = new HashMap<Integer,String>();
for(String term : terms)
{
int index = input.indexOf(term);
if(index >= 0)//if found
{
String value = map.get(index);
if(value == null || value.length() < term.length())//use the longer term
map.put(index, term);
}
}
for(String term: map.values())
{
input = input.replace(term, "<b>" + term + "</b>");
}
return input;
}
</code></pre>
| [] | [
{
"body": "<p>I would go with Regex for this, with greedy matches so that nested results like your example above would only match the outer string.</p>\n\n<p>So with your example here:</p>\n\n<pre><code>Input Terms Output\nThe search is cool {sea, search} The <b>search</b> is cool\n</code></pre>\n\n<p>A Regex pattern of <code>search|sea</code> could be derived from the search terms, and only 'search' would be matched. Note that the longest term will need to first for this to work as desired.</p>\n\n<pre><code>String results(String input)\n{\n String retVal = input.replaceAll(\"search|sea\", \"<b>$1</b>\")\n\n return input;\n}\n</code></pre>\n\n<p>I think this should be close to what you need, but I havn't had time to test and check. Hope it helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T18:53:19.267",
"Id": "79680",
"Score": "1",
"body": "Just FYI - greedy is not what you think it is, I don't think: http://fiddle.re/9bmb4"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T18:23:18.237",
"Id": "45643",
"ParentId": "45638",
"Score": "1"
}
},
{
"body": "<p>The second version looks fine. Anyway, two other quick ideas:</p>\n\n<ol>\n<li><p>Consider replacing only complete words (substrings which has whitespace before and after).</p></li>\n<li><p>Sort the term list by length (descending) and ABC then replace every occurrence only once. <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#replaceEach%28java.lang.String,%20java.lang.String%5b%5d,%20java.lang.String%5b%5d%29\" rel=\"nofollow\"><code>StringUtils.replaceEach</code></a> from <a href=\"http://commons.apache.org/proper/commons-lang/\" rel=\"nofollow\">Apache Commons Lang</a> supports that.</p>\n\n<pre><code>String input = \"The sea search is cool\";\nString[] terms = new String[] { \"search\", \"sea\" };\nString[] replacementList = new String[] { \"<b>search</b>\", \"<b>sea</b>\" };\nString output = StringUtils.replaceEach(input, terms, replacementList);\nSystem.out.println(output);\n</code></pre>\n\n<p>The output is the following:</p>\n\n<pre><code>String input = \"The sea search is cool\";\nString[] terms = new String[] { \"search\", \"sea\" };\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T05:20:07.953",
"Id": "79735",
"Score": "0",
"body": "Words can be delimited by whitespace, but also by punctuation or the start/end of the string."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T19:31:59.873",
"Id": "45647",
"ParentId": "45638",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T16:56:27.667",
"Id": "45638",
"Score": "5",
"Tags": [
"java",
"strings"
],
"Title": "Find and replace String with a substring result"
} | 45638 |
<p>This is a baseline tagger coed I have written. How can I optimize this code?</p>
<pre><code>public class Tagger {
private ArrayList<List> copyTagsList = new ArrayList<List>();
public Tagger(WordChecker tagsList){
for(int i =0; i<tagsList.getCheckedTags().size();i++){
copyTagsList.add(i,tagsList.getCheckedTags().get(i));
copyTagsList.get(i).set(1,0);
}
}
public void extractTag(String word, ArrayList<ArrayList> trainList){
int freq = 0;
ArrayList<List> tagFreqOfWord = new ArrayList<List>();
System.out.println(word);
for(ArrayList wordState: trainList)
{
if (word.equals(wordState.get(1)))
{
freq+=1;
if (tagFreqOfWord.size() == 0)
{
for (int i = 0 ; i<copyTagsList.size();i++)
{
if (((String)wordState.get(4)).equalsIgnoreCase((String)copyTagsList.get(i).get(0)))
{
tagFreqOfWord.add(copyTagsList.get(i));
tagFreqOfWord.get(0).set(1, (int)1);
break;
}
}
}
else
{
Boolean exist= false;
for (List j :tagFreqOfWord)
{
if (((String)wordState.get(4)).equalsIgnoreCase((String)j.get(0)))
{
int var = (int)tagFreqOfWord.get(tagFreqOfWord.indexOf(j)).get(1);
var+=1;
tagFreqOfWord.get(tagFreqOfWord.indexOf(j)).set(1,var);
exist = true;
break;
}
}
if (!exist)
{
List newTag = new ArrayList();
newTag.add(wordState.get(4));
newTag.add(1, 1);;
tagFreqOfWord.add(newTag);
}
}
}
}
System.out.println(tagFreqOfWord);
}
}
</code></pre>
<p>Confusion matrix (Part of AccuracyChecker class):</p>
<pre><code>public ArrayList<List> createConfusionMatrix(WordChecker checkedTagsList, ArrayList<ArrayList> listOfWords){
//BeanComparator fieldComparator = new BeanComparator();
//Collections.sort(checkedTagsList, fieldComparator);
int distinctTagsSize = correctTags.size();
for(int i=0; i <distinctTagsSize;i++){
List<Integer> list = new ArrayList<Integer>();
confusionMatrix.add(i, list);;
for(int j=0;j<distinctTagsSize; j++ ){
confusionMatrix.get(i).add(j, 0);
if (i == j)
confusionMatrix.get(i).set(j, checkedTagsList.getCheckedTags().get(i).get(1));
}
}
for(int i=0; i <distinctTagsSize;i++){
for(int j=0;j<listOfWords.size();j++){
if (((String)correctTags.get(i).get(0)).equalsIgnoreCase((String)listOfWords.get(j).get(4))){
if(!((String)listOfWords.get(j).get(5)).equalsIgnoreCase((String)listOfWords.get(j).get(4))){
for (List m: correctTags){
if(((String)listOfWords.get(j).get(5)).equalsIgnoreCase((String)m.get(0))){
int freq= (int)confusionMatrix.get(i).get(correctTags.indexOf(m));
freq+=1;
confusionMatrix.get(i).set(correctTags.indexOf(m),freq);
}
}
}
}
}
}
return confusionMatrix;
}
</code></pre>
<p>Do you think using 2D ArrayList is better?</p>
| [] | [
{
"body": "<pre><code>private ArrayList<List> copyTagsList = new ArrayList<List>();\n</code></pre>\n\n<p>You should always use generic version (use raw type only if you have a good reason!)</p>\n\n<p>Same inside <code>extractTag</code> using generic version you will not need anymore <code>String</code> cast.</p>\n\n<p>The same will be for other collection.</p>\n\n<p>I usually tend to cache the <code>.size()</code> specially when using it in a for to avoid method call overhead, but i don't remember if JVM could optimizate the call.</p>\n\n<p>Example here:</p>\n\n<pre><code>for (int i = 0 ; i<copyTagsList.size();i++)\n</code></pre>\n\n<p>could be</p>\n\n<pre><code>int size = copyTagsList.size();\nfor (int i = 0 ; i<size;i++)\n</code></pre>\n\n<p>Avoid Wrapper objects if not needed (only in generic!)</p>\n\n<pre><code>tagFreqOfWord.get(0).set(1, (int)1);\n</code></pre>\n\n<p>No need for cast here.</p>\n\n<pre><code>Boolean exist= false;\n</code></pre>\n\n<p>Here <code>Boolean</code> refer to the wrapper class, not to the native type.. with this line you cause a boxing-unboxing everytime. Replace it with <code>boolean exist = false;</code>.</p>\n\n<p>Use better names</p>\n\n<pre><code>for (List j :tagFreqOfWord)\n</code></pre>\n\n<p>while reading <code>for (int i = 0; i < x; i++)</code> <code>i</code> is OK in most cases, reading this line could lead to confusion because someone could think: \"well, it's <code>j</code> it could be the second index in a inner-for!\"</p>\n\n<p>Or, it could lead to confusion yourself, use one-char-name only if you are working with indexs in for/while/etc. (outside you could use <code>idx</code>!)</p>\n\n<pre><code>int var = (int)tagFreqOfWord.get(tagFreqOfWord.indexOf(j)).get(1);\n</code></pre>\n\n<p>Do you really need the cast here? I don't think. If it's a <code>Integer</code> it will be read as <code>int</code>, so cast needed.</p>\n\n<pre><code>int var = tagFreqOfWord.get(tagFreqOfWord.indexOf(j)).get(1);\nvar+=1;\ntagFreqOfWord.get(tagFreqOfWord.indexOf(j)).set(1,var);\n</code></pre>\n\n<p>You do <code>indexOf()</code> two times, which could be a problem (it checks two times the same thing) just do it one time and save the result in a variable.</p>\n\n<pre><code>int indexOf = tagFreqOfWord.indexOf(j);\nint var = tagFreqOfWord.get(indexOf).get(1);\nvar+=1;\ntagFreqOfWord.get(indexOf).set(1,var);\n</code></pre>\n\n<p>Remember, indexOf:</p>\n\n<p><em>Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.</em></p>\n\n<p>You chould check if it returns <code>-1</code></p>\n\n<p>Seems like <code>wordState.get(4)</code> can be saved and avoid <code>.get()</code> call <code>N</code> times (In a LinkedList, call <code>.get</code> everytime could be a problem)</p>\n\n<p>So it could be</p>\n\n<pre><code>Boolean exist= false;\nString specialWord = (String)wordState.get(4);\nfor (List j :tagFreqOfWord)\n{\n if (specialWord.equalsIgnoreCase((String)j.get(0)))\n {\n int var = (int)tagFreqOfWord.get(tagFreqOfWord.indexOf(j)).get(1);\n var+=1;\n tagFreqOfWord.get(tagFreqOfWord.indexOf(j)).set(1,var);\n exist = true;\n break;\n }\n}\n\nif (!exist)\n{\n List newTag = new ArrayList();\n newTag.add(specialWord);\n newTag.add(1, 1);;\n tagFreqOfWord.add(newTag);\n}\n</code></pre>\n\n<p>So you avoid do a Cast everytime!</p>\n\n<hr>\n\n<pre><code>int distinctTagsSize = correctTags.size();\nfor(int i=0; i <distinctTagsSize;i++){\n List<Integer> list = new ArrayList<Integer>();\n confusionMatrix.add(i, list);;\n for(int j=0;j<distinctTagsSize; j++ ){\n confusionMatrix.get(i).add(j, 0);\n if (i == j)\n confusionMatrix.get(i).set(j, checkedTagsList.getCheckedTags().get(i).get(1));\n }\n}\n</code></pre>\n\n<p>Here you create a new list everytime, it's what you want? Ok i know it's Code review so you already know the code is correct, i just want to be sure you know what happens here.</p>\n\n<p>For now i can't see anything wrong in this block.</p>\n\n<p>Here</p>\n\n<pre><code>for(int i=0; i <distinctTagsSize;i++){\n for(int j=0;j<listOfWords.size();j++){\n if (((String)correctTags.get(i).get(0)).equalsIgnoreCase((String)listOfWords.get(j).get(4))){\n if(!((String)listOfWords.get(j).get(5)).equalsIgnoreCase((String)listOfWords.get(j).get(4))){\n for (List m: correctTags){\n if(((String)listOfWords.get(j).get(5)).equalsIgnoreCase((String)m.get(0))){\n int freq= (int)confusionMatrix.get(i).get(correctTags.indexOf(m));\n freq+=1;\n confusionMatrix.get(i).set(correctTags.indexOf(m),freq);\n }\n }\n }\n\n }\n }\n}\n</code></pre>\n\n<p><code>(String)correctTags.get(i).get(0)</code> will not change while <code>for(..; j; ..)</code> so you could do</p>\n\n<pre><code>for(int i=0; i <distinctTagsSize;i++){\n String cache1 = (String)correctTags.get(i).get(0);\n for(int j=0;j<listOfWords.size();j++){\n</code></pre>\n\n<p>and then use <code>cache1</code>. (example name!!!!)</p>\n\n<p>You could do the same thing for <code>(String)listOfWords.get(j).get(4)</code> and <code>(String)listOfWords.get(j).get(5)</code> but inside <code>for (..; j; ..)</code> scope.</p>\n\n<p>Again, as above</p>\n\n<pre><code>int freq= (int)confusionMatrix.get(i).get(correctTags.indexOf(m));\n</code></pre>\n\n<p>You don't need a cast here, and you can save <code>correctTags.indexOf(m)</code> return value inside a variable and reuse it inside </p>\n\n<pre><code>confusionMatrix.get(i).set(correctTags.indexOf(m),freq);\n</code></pre>\n\n<p>too</p>\n\n<pre><code>confusionMatrix.get(i).set(indexOfSaved, freq);\n</code></pre>\n\n<p>I hope my english is clear, i will try to fix grammar errors.. </p>\n\n<p>Anyway maybe i missed something.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T14:33:29.533",
"Id": "79765",
"Score": "0",
"body": "Thanks so much, I will go through all your comments and check the performance. but right now I can see how much better my code will be. Than you again for sparing so much time and explaining each part."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T14:42:10.967",
"Id": "79766",
"Score": "0",
"body": "Marco:\"int var = (int)tagFreqOfWord.get(tagFreqOfWord.indexOf(j)).get(1);\nDo you really need the cast here? I don't think. If it's a Integer it will be read as int, so cast needed.\" without casting, there would be an object which can' be converted to int. the right-hand side of equation is an object. in my lists mostly I have both strings and integers which determine the frequency of that word or tag. so I used nested lists (ArrayList) with this hope that I can store any kind of object. Do you have any better idea?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T14:52:06.997",
"Id": "79768",
"Score": "0",
"body": "You should avoid this kind of design, why you want to store \"any kind of object\" in an ArrayList? It could lead to bugs and ClassCastException."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T14:52:35.847",
"Id": "79769",
"Score": "0",
"body": "If you have an ArrayList of words use ArrayList<String> then the ArrayList of frequency will be ArrayList<Integer>"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T14:59:08.620",
"Id": "79771",
"Score": "0",
"body": "in this case, I want to keep the word with its frequency next to each other, then when you need it you must just find the word and get the frq. how your can then help me?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T15:01:18.220",
"Id": "79772",
"Score": "1",
"body": "Why not a class at this point? class Word { private String word; private int frequency; public void increment(); } and call increment() to increment, getFreq() to get. So you don't use two lists but only one"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T15:25:20.647",
"Id": "79775",
"Score": "0",
"body": "I see the point, but does it not increase the memory consumption when i need to have 1e6 objects of a class?!! so consequently lessen the time efficiency?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T13:44:34.853",
"Id": "79869",
"Score": "0",
"body": "Well, about the memory i think two List is wrost than the \"class\" design but i'm not sure. About performance ArrayList uses an Array internal (you can have Integer.MAX_INT classes) so time access (get) will be great anyway"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T19:04:02.490",
"Id": "45645",
"ParentId": "45640",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T17:28:26.063",
"Id": "45640",
"Score": "4",
"Tags": [
"java",
"optimization"
],
"Title": "Baseline tagger"
} | 45640 |
<p>I'm creating an app where the user will be able to create HTTP request matchers. So the <code>RequestMatchers</code> will match HTTP method, path, query parameters, etc., for incoming requests. </p>
<p>Can someone look over this gist to see if you think I'm on the right track for making it very extensible? Currently it only supports matching URLs, but that will grow and I want to make sure what I'm doing is reasonable moving forward.</p>
<p><strong>RequestMatcher.php</strong>
<pre><code>namespace MyBundle/Entity;
// Persistable to "request_matchers" table
class RequestMatcher
{
protected $urlMatcher;
public function __construct(UrlMatcher $urlMatcher)
{
$this->urlMatcher = $urlMatcher;
}
public function getUrlMatcher()
{
return $this->urlMatcher;
}
}
</code></pre>
<p><strong>UrlMatcher.php</strong>
<pre><code>namespace MyBundle/Model;
abstract class UrlMatcher
{
protected $path;
public function __construct($path)
{
$this->path = $path;
}
public function getPath()
{
return $this->path;
}
}
</code></pre>
<p><strong>ExactUrlMatcher.php</strong>
<pre><code>namespace MyBundle/Entity;
// Persistable to "url_matchers" table, using a discriminator map column
class ExactUrlMatcher extends MyBundle\Model\UrlMatcher
{
}
</code></pre>
<p><strong>ParameterizedUrlMatcher.php</strong>
<pre><code>namespace MyBundle/Entity;
// Persistable to "url_matchers" table, using a discriminator map column
class ParameterizedUrlMatcher extends MyBundle\Model\UrlMatcher
{
}
</code></pre>
<p><strong>RequestMatchEvent.php</strong>
<pre><code>namespace MyBundle/Event;
class RequestMatchEvent extends Event
{
protected $requestMatcher;
protected $request;
protected $matches = true;
public function __construct(Reques $request, RequestMatcher $requestMatcher)
{
$this->request = $request;
$this->->requestMatcher = $requestMatcher;
}
public function getRequestMatcher()
{
return $this->requestMatcher;
}
public function getRequest()
{
return $this->request;
}
public function setMatches($matches)
{
if ($this->matches) {
$this->matches = (bool) $matches;
}
if (!$this->matches) {
$this->stopPropagation();
}
return $this->matches;
}
public function isMatch()
{
return $this->matches;
}
}
</code></pre>
<p><strong>RequestMatchListener.php</strong>
<pre><code>namespace MyBundle/EventListener;
interface RequestMatchListener
{
public function onMatchRequest(RequestMatchEvent $event);
}
</code></pre>
<p><strong>ExactUrlRequestMatchListener.php</strong>
<pre><code>namespace MyBundle/EventListener;
// Registered with EventDispatcher
class ExactUrlRequestMatchListener implements RequestMatchListener
{
public function onMatchRequest(RequestMatchEvent $event)
{
$urlMatcher = $event->getRequestMatcher()->getUrlMatcher();
if (!$urlMatcher->getUrlMatcher() instanceof ExactUrlMatcher) {
return true;
}
$request = $event->getRequest();
$event->setMatches($urlMatcher->getPath() === $request->getUri());
}
}
</code></pre>
<p><strong>ParameterizedUrlRequestMatchListener.php</strong>
<pre><code>namespace MyBundle/EventListener;
// Registered with EventDispatcher
class ParameterizedUrlRequestMatchListener implements RequestMatchListener
{
public function onMatchRequest(RequestMatchEvent $event)
{
$urlMatcher = $$event->getRequestMatcher()->getUrlMatcher();
if (!$urlMatcher->getUrlMatcher() instanceof ParameterizedUrlMatcher) {
return true;
}
// determine if request matches
}
}
</code></pre>
<p>Bringing it all together with <strong>RequestMatcherController.php</strong>
<pre><code>namespace MyBundle/Controller;
class RequestMatcherController extends BaseController
{
protected $dispatcher;
public function process(Request $request)
{
$requestMatchers = $this->getRequestMatcherRepository()->requestMatchersByUser($this->getCurrentUser());
foreach ($requestMatchers as $requestMatcher) {
$this->dispatcher->dispatch('matching.request', $event = new RequestMatchEvent($request, $requestMatcher));
if ($event->isMatch()) {
// Do something with $requestMatcher
}
}
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T18:51:29.497",
"Id": "45644",
"Score": "2",
"Tags": [
"php",
"http",
"url"
],
"Title": "Persistable specifications in symfony"
} | 45644 |
<p>For a school project I am tasked to decrypt DES passwords. I have sample code provided below and I want to know if this is the best method. Also should I code in error handling for the dictionary file or does the <code>while</code> condition take care of this?</p>
<pre><code>#include <stdio.h>
#include <crypt.h>
#include <unistd.h>
#include <string.h>
#define _XOPEN_SOURCE
int main(int argc, char* argv[])
{
if (argc != 2)
{
printf("Usage: ./crack <password>\n");
return 1;
}
int n = strlen(argv[1]);
char password[n];
for (int i = 0; i < n; i++)
{
password[i] = argv[1][i];
}
char salt[2];
salt[0] = password[0];
salt[1] = password[1];
FILE *fp;
fp = fopen("/usr/share/dict/words", "r");
char line[50];
while(fgets(line,50,fp)!= NULL)
{
line[strlen(line) - 1] = '\0';
if (!strcmp(argv[1], crypt(line, salt)))
{
printf("Password found!\n");
return 0;
}
}
printf("Not found\n");
fclose(fp);
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>You're keeping us in suspense — I'm dying to know which password matched!</p>\n\n<p>Many password crackers also test for common character substitutions, e.g. o → 0, i → 1, s → $.</p>\n\n<p>Other than that, the general technique seems sound.</p>\n\n<p>I do have a few general remarks, though.</p>\n\n<ul>\n<li>What is <code>#define _XOPEN_SOURCE</code> for? Sometimes, defining it will change some of the functions you call. However, it would only have any effect if you put it before your <code>#include</code>s.</li>\n<li>It would be good to make a function, even for a simple program like this. I suggest that <code>main()</code> be responsible for parsing and validating the command line and opening the word list, calling <code>crack(const char *pwhash, FILE *wordlist)</code> to do the actual work.</li>\n<li>You don't close the word list if you find a match.</li>\n<li>Consider returning a non-zero exit status if the password is not found. That makes your program more useful to scripts.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T07:59:00.197",
"Id": "45677",
"ParentId": "45650",
"Score": "4"
}
},
{
"body": "<p>The code is neatly-formatted, the variables are well-named, which is good.</p>\n\n<hr>\n\n<p>I don't see why you have a variable named <code>password</code>. You only use for first two characters of it, to initialize <code>salt</code>. You could initialize <code>salt</code> from <code>argv</code> instead. If you want to have <code>password</code> then I recommend null-terminating it to make sure it behave like a C-string. I don't understand why <code>password</code> isn't of length <code>n+1</code>, why you didn't use <code>strcpy</code> or <code>strncpy</code>.</p>\n\n<hr>\n\n<p>The salt is required to be 2 characters; maybe you should check that <code>argv[1]</code> is long enough before starting.</p>\n\n<hr>\n\n<p>Do you have reason to believe that <code>50</code> is the length of the largest string in the dictionary?</p>\n\n<hr>\n\n<blockquote>\n <p>Also should I code in error handling for the dictionary file</p>\n</blockquote>\n\n<p>Probably yes; because you want to tell the difference between:</p>\n\n<ul>\n<li>Failed to find password because word wasn't in dictionary</li>\n<li>Failed to find password because couldn't open the dictionary</li>\n</ul>\n\n<hr>\n\n<p>Dictionary-based attack may be a fast way to find long, commonly-used passwords; but it's not the most reliable way (because if the word is not in the dictionary then it won't be found).</p>\n\n<p>The school project might have asking you to build all permutations, for example <a href=\"https://codereview.stackexchange.com/q/41510/34757\">like this</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T08:32:55.207",
"Id": "45680",
"ParentId": "45650",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "45677",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T20:44:46.890",
"Id": "45650",
"Score": "7",
"Tags": [
"c",
"homework",
"cryptography"
],
"Title": "Dictionary brute force on DES encrypted passwords"
} | 45650 |
<p>Expected behavior of the code below:</p>
<ul>
<li>There will be one static <code>SessionManager</code> accessed by many threads.</li>
<li>Multiple calls to <code>SessionManager.UseTheSession</code> for a given session ID must be processed on a first come first serve basis (similarly, calling <code>EndSession</code> should allow any currently executing <code>UseTheSession</code>'s to finish).</li>
<li>The goal of the individual session locks is that a call to <code>SessionManager.UseTheSession</code> by one thread doesn't hold up another thread that is calling the same method with a different session ID.</li>
</ul>
<p>Things I'm looking for input on are:</p>
<ul>
<li>Will this perform as expected.</li>
<li>Does <code>sessions</code> need to be a <code>ConcurrentDictionary</code> or does a regular <code>Dictionary</code> work fine here since I'm locking any access of the one key.</li>
<li>What's a good way to handle the memory leak that happens when I keep creating new locks but don't remove them for a given id after I stop using that it?</li>
</ul>
<p>The code (runnable in Linqpad with the inclusion of the <code>System.Collections.Concurrent</code> namespace):</p>
<pre><code>void Main()
{
var sm = new SessionManager();
Guid id = sm.StartSession();
sm.UseTheSession(id).Dump();
sm.UseTheSession(id).Dump();
sm.EndSession(id);
}
public class SessionManager
{
private ConcurrentDictionary<Guid, object> sessionLocks =
new ConcurrentDictionary<Guid, object>();
private ConcurrentDictionary<Guid, ASession> sessions =
new ConcurrentDictionary<Guid, ASession>();
public Guid StartSession()
{
Guid id = Guid.NewGuid();
// Takes a sec to create the session.
var session = new ASession(string.Format("Session {0}", id));
Thread.Sleep(1000);
if(!sessions.TryAdd(id, session))
throw new Exception("Astronomically unlikely situation encountered.");
return id;
}
public int UseTheSession(Guid id)
{
lock(this.GetSessionLocker(id))
{
ASession session;
if(sessions.TryGetValue(id, out session))
{
return this.DoSomethingWithSession(session);
}
else
{
throw new Exception(string.format("Session with id {0} does not exist.",
id));
}
}
}
public void EndSession(Guid id)
{
lock(this.GetSessionLocker(id))
{
ASession removedSession;
if(sessions.TryRemove(id, out removedSession))
{
this.CleanUpSessionRemnants(removedSession);
}
}
}
private object GetSessionLocker(Guid id)
{
return sessionLocks.GetOrAdd(id, x => new object());
}
private int DoSomethingWithSession(ASession session)
{
Thread.Sleep(1000);
return 1;
}
private void CleanUpSessionRemnants(ASession session)
{
Thread.Sleep(1000);
}
}
public class ASession
{
public ASession(string name)
{
this.Name = name;
}
public string Name { get; private set; }
}
</code></pre>
| [] | [
{
"body": "<p>In <a href=\"https://codereview.stackexchange.com/a/44490/23788\">this answer</a> I explain in details why <em>one should not throw System.Exception</em>. You should be throwing <code>InvalidOperationException</code> in the case of the <em>astronomically unlikely situation</em>, and probably an <code>ArgumentException</code> in the case of the non-existing session.</p>\n\n<p>As far as thread safety is concerned, I don't write multithreaded code very often so I might be completely wrong, but I since <code>ConcurrentDictionary</code> is a thread-safe <code>IDictionary</code> implementation, <code>sessions.TryGetValue(id, out session)</code> is already a thread-safe call, doesn't need to be wrapped in a <code>lock</code> block.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T23:29:23.747",
"Id": "79711",
"Score": "1",
"body": "You have many good points there, but the reason for the lock block seems to be to prevent multiple threads from simultaneously calling `DoSomethingWithSession` for the same session."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T23:31:46.413",
"Id": "79713",
"Score": "0",
"body": "@SimonAndréForsberg that's right, thanks - edited out that part ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T15:18:27.537",
"Id": "79774",
"Score": "0",
"body": "Good points about `System.Exception`. I wasn't really thinking much about the exceptions when putting this example together but I'll be sure to put more thought into the real version of the code."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T23:08:50.030",
"Id": "45660",
"ParentId": "45655",
"Score": "5"
}
},
{
"body": "<p>A few notes to address your specific questions:</p>\n\n<blockquote>\n <p>Will this perform as expected?</p>\n</blockquote>\n\n<p>Only you can answer that after testing it thoroughly.</p>\n\n<blockquote>\n <p>Does sessions need to be a ConcurrentDictionary or does a regular Dictionary work fine here since I'm locking any access of the one key.</p>\n</blockquote>\n\n<p>As the lock keys are different for different sessions, it is a whole lot more safe to use <code>ConcurrentDictionary</code>. That way you are at least sure that the dictionary won't screw up.</p>\n\n<p>However, your approach of the <code>sessionLocks</code> map I have some doubts about. What you really seem to want to synchronize is the <code>return this.DoSomethingWithSession(session);</code> and <code>this.CleanUpSessionRemnants(removedSession);</code> calls, so I would place the lock only around those.</p>\n\n<p>Speaking of placing the locks, consider placing them within the <code>ASession</code> class. In fact, I would try to move the <code>CleanUpSessionRemnants</code> and <code>DoSomethingWithSession</code> methods to the <code>ASession</code> class. If it needs the <code>SessionManager</code> object to perform its job, then pass the <code>SessionManager</code> as a parameter to the method. Right now your <code>ASession</code> seems to be only a <code>String</code>, make better use of that class. I think you created it for a reason.</p>\n\n<blockquote>\n <p>What's a good way to handle the memory leak that happens when I keep creating new locks but don't remove them for a given id after I stop using that it?</p>\n</blockquote>\n\n<p>Don't create them in the first place. Really. Or at least remove them when you're done. See above. Or the code below.</p>\n\n<pre><code>if(sessions.TryRemove(id, out removedSession))\n{\n sessionLocks.TryRemove(id);\n this.CleanUpSessionRemnants(removedSession);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T15:16:40.113",
"Id": "79773",
"Score": "0",
"body": "Good points. This was a contrived example similar to what I'm doing, so `ASession` definitely holds more than just a name :)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T23:40:40.167",
"Id": "45662",
"ParentId": "45655",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "45662",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T21:55:06.357",
"Id": "45655",
"Score": "11",
"Tags": [
"c#",
"multithreading",
"thread-safety",
"locking",
"concurrency"
],
"Title": "Thread-safe session manager"
} | 45655 |
<p>Unfortunately I get 3 warnings at jslint. Could someone please help?</p>
<p>I already tried a lot, but didn't get it yet.</p>
<p>Here's a jsfiddle: <a href="http://jsfiddle.net/KYjF9/21/" rel="nofollow">http://jsfiddle.net/KYjF9/21/</a></p>
<p>JSlint options:</p>
<pre><code>/*jslint browser: true indent: 2 */ /*global $ jQuery alert*/
</code></pre>
<p>JavaScript:</p>
<pre><code>var Typing = function (el, toType, period) {
"use strict";
this.toType = toType;
this.el = el;
this.loopNum = 0;
this.period = parseInt(period, 10) || 2000;
this.txt = '';
this.tick();
this.isDeleting = false;
};
Typing.prototype.tick = function () {
"use strict";
var fullTxt = this.toType[this.loopNum % this.toType.length];
if (this.isDeleting) {
this.txt = fullTxt.substring(0, this.txt.length - 1);
} else {
this.txt = fullTxt.substring(0, this.txt.length + 1);
}
$(this.el).html('<span class="wrap">' + this.txt + '</span>');
var delta = 300 - Math.random() * 100;
if (this.isDeleting) { delta /= 2; }
if (!this.isDeleting && this.txt === fullTxt) {
delta = this.period;
this.isDeleting = true;
} else if (this.isDeleting && this.txt === '') {
this.isDeleting = false;
this.loopNum = this.loopNum + 1;
delta = 500;
}
setTimeout(this.tick.bind(this), delta);
};
var data = {
"text": {
"list": ["hello", "hallo", "hola", "what", "ever"],
"period": "3000"
}
};
$(document).ready(function () {
"use strict";
var toType = data.text.list;
var period = data.text.period;
$(".js").each(function () {
if (toType) {
new Typing(this, toType, period);
}
});
});
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T22:50:51.780",
"Id": "79707",
"Score": "0",
"body": "The code works! It's just not perfectly valid in jslint."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T22:51:13.167",
"Id": "79708",
"Score": "0",
"body": "@Mat'sMug AFAICT the code works as intended; it's just giving off some linter warnings"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T22:53:54.380",
"Id": "79709",
"Score": "0",
"body": "Close vote retracted, but the question could be reworded to make it clearer that OP is looking for a review, not for specific help fixing/removing/addressing those warnings."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T23:01:48.817",
"Id": "79710",
"Score": "1",
"body": "re-post of http://codereview.stackexchange.com/questions/45516/insert-and-delete-a-list-of-specified-characters-words-in-headline ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T23:29:31.677",
"Id": "79712",
"Score": "0",
"body": "Whelp, now I'm voting to close. @Kvothe is correct; this seems like a repost. It's not an exact duplicate, but it's close enough that one of two questions should probably be closed"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T02:31:55.330",
"Id": "79731",
"Score": "0",
"body": "Closed [previous post](http://codereview.stackexchange.com/questions/45516/insert-and-delete-a-list-of-specified-characters-words-in-headline) as a duplicate of this, as there is an answer here."
}
] | [
{
"body": "<p>I suppose you're talking about these 3 JSLint warnings:</p>\n<pre><code>Combine this with the previous 'var' statement.\n var interval = 300 - Math.random() * 100;\n\nCombine this with the previous 'var' statement.\n var interval = 3000;\n\nDo not use 'new' for side effects.\n new Typing(this, toType, interval);\n</code></pre>\n<p>The first 2 are suggestions to combine multiple <code>var</code> declarations into one. For example, instead of:</p>\n<blockquote>\n<pre><code>var x = 3;\nvar y = 4;\n</code></pre>\n</blockquote>\n<p>The suggestion is to do like this instead:</p>\n<pre><code>var x = 3, y = 4;\n</code></pre>\n<p>The 3rd one is about instantiating something without storing the reference somewhere. <a href=\"http://jslinterrors.com/do-not-use-new-for-side-effects/\" rel=\"nofollow noreferrer\">This page</a> explains why this is not recommended, in particular:</p>\n<blockquote>\n<p>By not assigning the return value of a constructor to something you will lose the reference to that instance. Generally, by constructing an instance you would want to keep that reference, whether to use again later or for "internal" use as part of a comparison. What's the point of constructing something you are going to throw away as soon as it's been created?</p>\n<p>If you have a constructor function that performs work beyond simply setting up an instance, and you are calling that constructor just for these "side effects", consider reworking your code to allow you to call the function normally, without the new operator.</p>\n</blockquote>\n<p>Personally I disagree with the suggestion to combine the <code>var</code> statements, but agree with the 3rd warning.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T23:34:06.947",
"Id": "45661",
"ParentId": "45659",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T22:43:29.830",
"Id": "45659",
"Score": "4",
"Tags": [
"javascript",
"jquery"
],
"Title": "jquery script for inserting and deleting text"
} | 45659 |
<p>In the code below, I take the number of square the user wants, then calculate the size of each square (so that they all fit in the container.)</p>
<p>I then define <code>var square</code> as in the 3rd line of code. I find this string pasting technique very hard to read and error-prone. The general question is thus: Is there a better way to define an element using user input?</p>
<pre><code>var genGrid = function(num_square) {
var square_size = ($(".grid_container").height() / num_grid) + "px";
var square = "<div class='square' style='height:" + square_size + ";\
width: " + square_size + "'></div>";
$("body").append($(square));
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T00:33:46.690",
"Id": "79718",
"Score": "0",
"body": "Where does `num_square` come in?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T00:39:50.177",
"Id": "79719",
"Score": "0",
"body": "num_square is from user input due to a prompt"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T00:42:26.953",
"Id": "79720",
"Score": "0",
"body": "It's not used anywhere in the function..?"
}
] | [
{
"body": "<p>As you have already stated passing an HTML string is not the best way to create a new DOM element. You can create a new one using plain Javascript, like this:</p>\n\n<pre><code>var newDiv = document.createElement('div');\n</code></pre>\n\n<p>and together with few changes to your code, function could look similar to this:</p>\n\n<pre><code>function generateGrid(numGrid) {\n var squareSize = $('.grid_container').height() / numGrid;\n var $square = $(document.createElement('div')); // we create and fetch a new element\n\n // here come some handy methods from jQuery, please check'em out on jquery.com\n $square.width(squareSize).height(squareSize).addClass('square');\n $('.grid_container').append($square);\n}\n\ngenerateGrid(4);\n</code></pre>\n\n<p>Hope this will help you!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T00:47:47.803",
"Id": "79721",
"Score": "0",
"body": "Oh, the reason why I did not define `$square` as an element is because I have to append square multiple times. Can I just do `var square = \"(document.createElement('div'))\"` then?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T00:57:00.437",
"Id": "79723",
"Score": "1",
"body": "I have created a jsFiddle for you so you can play with the code. As you can see I've splitted this problem into two functions. One of them simply builds a square element and second one is responsible for drawing a grid. Just take a look:\n\n[link](http://jsfiddle.net/cv9JA/11/)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T00:42:11.560",
"Id": "45670",
"ParentId": "45663",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "45670",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T23:43:58.313",
"Id": "45663",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Javascript to change element property based on user input"
} | 45663 |
<p>In order to implement my own <code>Dictionary<TKey, TValue></code> in VB6, I've implemented a <code>KeyValuePair</code> class, which can accomodate any type as its key, or value.</p>
<p>This <code>KeyValuePair</code> class implements the <code>IComparable</code> and <code>IEquatable</code> interfaces which I'm also using in <a href="https://codereview.stackexchange.com/q/32618/23788">this custom <code>List<T></code> implementation</a></p>
<h3>KeyValuePair.cls</h3>
<pre class="lang-vb prettyprint-override"><code>Private Type tKeyValuePair
Key As Variant
value As Variant
End Type
Private this As tKeyValuePair
Implements IComparable
Implements IEquatable
Option Explicit
Private Function IsComparable() As Boolean
IsComparable = Not IsObject(this.Key) Or TypeOf this.Key Is IComparable
End Function
Public Property Get Key() As Variant
If IsObject(this.Key) Then
Set Key = this.Key
Else
Key = this.Key
End If
End Property
Public Property Let Key(k As Variant)
If IsEmpty(k) Then Err.Raise 5
this.Key = k
End Property
Public Property Set Key(k As Variant)
If IsEmpty(k) Then Err.Raise 5
Set this.Key = k
End Property
Public Property Get value() As Variant
If IsObject(this.value) Then
Set value = this.value
Else
value = this.value
End If
End Property
Public Property Let value(v As Variant)
this.value = v
End Property
Public Property Set value(v As Variant)
Set this.value = v
End Property
Public Function ToString() As String
ToString = TypeName(Me) & "<" & TypeName(this.Key) & ", " & TypeName(this.value) & ">"
End Function
Private Function IComparable_CompareTo(other As Variant) As Integer
Dim kvp As KeyValuePair
Set kvp = other
IComparable_CompareTo = ToString = kvp.ToString
If Not IComparable_CompareTo Then Exit Function
If IsObject(kvp.Key) Then
IComparable_CompareTo = CompareReferenceTypes(this.Key, kvp.Key)
Else
IComparable_CompareTo = CompareValueTypes(this.Key, kvp.Key)
End If
End Function
Private Function IEquatable_Equals(other As Variant) As Boolean
Dim kvp As KeyValuePair
Set kvp = other
IEquatable_Equals = ToString = kvp.ToString
If Not IEquatable_Equals Then Exit Function
If IsObject(kvp.Key) Then
IEquatable_Equals = EquateReferenceTypes(this.Key, kvp.Key)
Else
IEquatable_Equals = EquateValueTypes(this.Key, kvp.Key)
End If
End Function
Private Function EquateReferenceTypes(value As Variant, other As Variant) As Boolean
Dim equatable As IEquatable
If IsObject(this.Key) And TypeOf this.Key Is IEquatable Then
Set equatable = value
EquateReferenceTypes = equatable.Equals(other)
Else
Debug.Print "WARNING: Reference type doesn't implement IEquatable, using reference equality."
EquateReferenceTypes = (ObjPtr(value) = ObjPtr(other))
End If
End Function
Private Function EquateValueTypes(value As Variant, other As Variant) As Boolean
EquateValueTypes = (value = other)
End Function
Private Function CompareReferenceTypes(value As Variant, other As Variant) As Integer
Dim comparable As IComparable
If IsComparable Then
Set comparable = value
CompareReferenceTypes = comparable.CompareTo(other)
Else
Err.Raise 9 'object required
Exit Function
End If
End Function
Private Function CompareValueTypes(value As Variant, other As Variant) As Integer
If value < other Then
CompareValueTypes = -1
ElseIf value > other Then
CompareValueTypes = 1
End If
End Function
</code></pre>
<p>In C#, a <code>KeyValuePair</code> is a <code>struct</code>, a value type - this implementation being a class, makes it analoguous to a <em>reference type</em>, are there any major drawbacks to this? If so, are there any viable alternatives?</p>
| [] | [
{
"body": "<p>That has been said before in previous reviews, there's not really a gain in having a <code>Private Type</code> that lets you define a <code>Private this As tKeyValuePair</code>, which forces you to use <code>this.</code> to access what would otherwise be private fields.</p>\n\n<p>Actually there <em>is</em> one gain: doing that allows having a <code>Key</code> public member that encapsulates a <code>Key</code> private member, all without confusing poor old VB6 compiler.</p>\n\n<p>Other than that, one has to see the <code>List</code> and possibly also the <code>Dictionary</code> implementation to see the benefits of the additional complexity introduced by <code>IEquatable</code> and <code>IComparable</code> interface implementations.</p>\n\n<p>The code is fairly clean, straightforward and readable, breaking <code>IEquatable</code> and <code>IComparable</code> implementations into sub-functions respectively for reference and value types might be a little overboard, but it does make a nice abstraction level when one reads the implementation code.</p>\n\n<p>One nitpick, the interface implementations and the corresponding sub-functions could declare a local <code>result</code> variable and assign the function's return value in only a single location:</p>\n\n<pre><code>Dim result As Boolean\n\nIf IsObject(kvp.Key) Then\n result = CompareReferenceTypes(this.Key, kvp.Key)\nElse\n result = CompareValueTypes(this.Key, kvp.Key)\nEnd If\n\nIComparable_CompareTo = result\n</code></pre>\n\n\n\n<pre><code>Dim result As Boolean\n\nIf IsObject(kvp.Key) Then\n result = EquateReferenceTypes(this.Key, kvp.Key)\nElse\n result = EquateValueTypes(this.Key, kvp.Key)\nEnd If\n\nIEquatable_Equals = result\n</code></pre>\n\n\n\n<pre><code>Dim result As Boolean\nDim equatable As IEquatable\n\nIf IsObject(this.Key) And TypeOf this.Key Is IEquatable Then\n Set equatable = value\n result = equatable.Equals(other)\nElse\n Debug.Print \"WARNING: Reference type doesn't implement IEquatable, using reference equality.\"\n result = (ObjPtr(value) = ObjPtr(other))\nEnd If\n\nEquateReferenceTypes = result\n</code></pre>\n\n<p>Looking more closely at the shape of the code, vertical whitespaces aren't all that consistent: there's more vertical whitespaces near the bottom of the code module, while the code near the top doesn't seem to follow the same spacing style. Minor nitpick, but for a small specialized class like this, it's an easy fix.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T01:44:01.297",
"Id": "46127",
"ParentId": "45664",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "46127",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T00:00:19.543",
"Id": "45664",
"Score": "4",
"Tags": [
"vba",
"vb6"
],
"Title": "KeyValuePair implementation"
} | 45664 |
<p>This class encapsulates a <code>List<KeyValuePair></code> (see <code>List<T></code> implementation <a href="https://codereview.stackexchange.com/questions/32618/listt-implementation-for-vb6-vba">here</a>, and <code>KeyValuePair</code> implementation <a href="https://codereview.stackexchange.com/questions/45664/keyvaluepair-implementation">here</a>) and exposes a richer set of members than the typical <code>Scripting.Dictionary</code>, ..not to mention the anemic <code>Collection</code> class.</p>
<p>The class enforces some "type safety", in the sense that if you add a <code>KeyValuePair<String, Integer></code>, then you'll only be allowed to add <code>KeyValuePair<String, Integer></code> instances, the object will raise an error if you try adding, say, a <code>KeyValuePair<String, Control></code>, or anything that's not a <code>KeyValuePair<String, Integer></code>.</p>
<p>The <code>OptionStrict</code> property enables allowing more flexibility and adding a <code>KeyValuePair<String, Byte></code> to a <code>Dictionary<String, Integer></code>, for example (but not the opposite).</p>
<p>As with the <code>List<T></code> implementation, this class uses <em>procedure attributes</em> (not shown) which make the <code>Item</code> property the default property (so <code>myDictionary(i)</code> returns the value at index <code>i</code>), and the <code>NewEnum</code> property enables iterating all values with a <code>For Each</code> loop construct.</p>
<pre><code>Private Type tDictionary
Encapsulated As List
TKey As String
IsRefTypeKey As Boolean
TValue As String
IsRefTypeValue As Boolean
End Type
Private Enum DictionaryErrors
TypeMismatchUnsafeType = vbObjectError + 1001
End Enum
Private this As tDictionary
Option Explicit
Private Sub Class_Initialize()
Set this.Encapsulated = New List
this.Encapsulated.OptionStrict = True
End Sub
Private Sub Class_Terminate()
Set this.Encapsulated = Nothing
End Sub
Public Property Get Count() As Long
Count = this.Encapsulated.Count
End Property
Public Property Get Keys() As List
Dim result As New List
Dim kvp As KeyValuePair
result.OptionStrict = this.Encapsulated.OptionStrict
For Each kvp In this.Encapsulated
result.Add kvp.Key
Next
Set Keys = result
End Property
Public Property Get Values() As List
Dim result As New List
Dim kvp As KeyValuePair
result.OptionStrict = this.Encapsulated.OptionStrict
For Each kvp In this.Encapsulated
result.Add kvp.value
Next
Set Values = result
End Property
Public Property Get OptionStrict() As Boolean
OptionStrict = this.Encapsulated.OptionStrict
End Property
Public Property Let OptionStrict(value As Boolean)
this.Encapsulated.OptionStrict = value
End Property
Private Function ToKeyValuePair(k As Variant, v As Variant) As KeyValuePair
Dim result As New KeyValuePair
If IsObject(k) Then
Set result.Key = k
Else
result.Key = k
End If
If IsObject(v) Then
Set result.value = v
Else
result.value = v
End If
Set ToKeyValuePair = result
End Function
Public Property Get Item(k As Variant) As Variant
Dim i As Long
i = Keys.IndexOf(k)
If i = -1 Then Err.Raise 9 'index out of range
If this.IsRefTypeValue Then
Set Item = Values(i)
Else
Item = Values(i)
End If
End Property
Public Property Set Item(k As Variant, v As Variant)
Dim kvp As KeyValuePair
Dim i As Long
i = Keys.IndexOf(k)
If i <> -1 Then
Set kvp = ToKeyValuePair(k, v)
Set this.Encapsulated(i) = kvp
Else
Add k, v
End If
End Property
Public Property Let Item(k As Variant, v As Variant)
Dim kvp As KeyValuePair
Dim i As Long
i = Keys.IndexOf(k)
If i <> -1 Then
Set kvp = ToKeyValuePair(k, v)
Set this.Encapsulated(i) = kvp
Else
Add k, v
End If
End Property
Public Sub Add(k As Variant, v As Variant)
Dim kvp As KeyValuePair
Set kvp = ToKeyValuePair(k, v)
If Keys.Contains(k) Then Err.Raise 457 'key already exists
If ValidateItemType(kvp, ThrowOnUnsafeType:=True) Then this.Encapsulated.Add kvp
End Sub
Private Function ValidateItemType(kvp As KeyValuePair, Optional ThrowOnUnsafeType As Boolean = False) As Boolean
If this.TKey = vbNullString And this.TValue = vbNullString Then
this.TKey = TypeName(kvp.Key)
this.IsRefTypeKey = IsObject(kvp.Key)
this.TValue = TypeName(kvp.value)
this.IsRefTypeValue = IsObject(kvp.value)
End If
ValidateItemType = IsTypeSafe(kvp)
If ThrowOnUnsafeType And Not ValidateItemType Then RaiseErrorUnsafeType "ValidateItemType()", kvp.ToString
End Function
Public Function IsTypeSafe(kvp As KeyValuePair) As Boolean
'Determines whether a value can be safely added to the List.
IsTypeSafe = (this.TKey = vbNullString Or this.TKey = TypeName(kvp.Key)) _
And (this.TValue = vbNullString Or this.TValue = TypeName(kvp.value))
If IsTypeSafe Then Exit Function
Select Case this.TKey
Case "String":
IsTypeSafe = IsSafeKeyString(kvp.Key)
If IsTypeSafe Then kvp.Key = CStr(kvp.Key)
Case "Boolean"
IsTypeSafe = IsSafeKeyBoolean(kvp.Key)
If IsTypeSafe Then kvp.Key = CBool(kvp.Key)
Case "Byte":
IsTypeSafe = IsSafeKeyByte(kvp.Key)
If IsTypeSafe Then kvp.Key = CByte(kvp.Key)
Case "Date":
IsTypeSafe = IsSafeKeyDate(kvp.Key)
If IsTypeSafe Then kvp.Key = CDate(kvp.Key)
Case "Integer":
IsTypeSafe = IsSafeKeyInteger(kvp.Key)
If IsTypeSafe Then kvp.Key = CInt(kvp.Key)
Case "Long":
IsTypeSafe = IsSafeKeyLong(kvp.Key)
If IsTypeSafe Then kvp.Key = CLng(kvp.Key)
Case "Single"
IsTypeSafe = IsSafeKeySingle(kvp.Key)
If IsTypeSafe Then kvp.Key = CSng(kvp.Key)
Case "Double":
IsTypeSafe = IsSafeKeyDouble(kvp.Key)
If IsTypeSafe Then kvp.Key = CDbl(kvp.Key)
Case "Currency":
IsTypeSafe = IsSafeKeyCurrency(kvp.Key)
If IsTypeSafe Then kvp.Key = CCur(kvp.Key)
Case Else:
IsTypeSafe = False
End Select
If Not IsTypeSafe Then Exit Function
Select Case this.TValue
Case "String":
IsTypeSafe = IsSafeValueString(kvp.value)
If IsTypeSafe Then kvp.value = CStr(kvp.value)
Case "Boolean"
IsTypeSafe = IsSafeValueBoolean(kvp.value)
If IsTypeSafe Then kvp.value = CBool(kvp.value)
Case "Byte":
IsTypeSafe = IsSafeValueByte(kvp.value)
If IsTypeSafe Then kvp.value = CByte(kvp.value)
Case "Date":
IsTypeSafe = IsSafeValueDate(kvp.value)
If IsTypeSafe Then kvp.value = CDate(kvp.value)
Case "Integer":
IsTypeSafe = IsSafeValueInteger(kvp.value)
If IsTypeSafe Then kvp.value = CInt(kvp.value)
Case "Long":
IsTypeSafe = IsSafeValueLong(kvp.value)
If IsTypeSafe Then kvp.value = CLng(kvp.value)
Case "Single"
IsTypeSafe = IsSafeValueSingle(kvp.value)
If IsTypeSafe Then kvp.value = CSng(kvp.value)
Case "Double":
IsTypeSafe = IsSafeValueDouble(kvp.value)
If IsTypeSafe Then kvp.value = CDbl(kvp.value)
Case "Currency":
IsTypeSafe = IsSafeValueCurrency(kvp.value)
If IsTypeSafe Then kvp.value = CCur(kvp.value)
Case Else:
IsTypeSafe = False
End Select
ErrHandler:
'swallow overflow errors:
If Err.number = 6 Then
Err.Clear
Resume Next
ElseIf Err.number <> 0 Then
RaiseErrorUnsafeType "IsTypeSafe()", kvp.ToString
End If
End Function
Private Function IsSafeKeyString(value As Variant) As Boolean
On Error Resume Next
IsSafeKeyString = (this.TKey = vbNullString Or this.TKey = TypeName(value))
If IsSafeKeyString Or OptionStrict Then Exit Function
Dim result As Boolean
result = CStr(value)
IsSafeKeyString = (Err.number = 0)
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeKeyDate(value As Variant) As Boolean
On Error Resume Next
IsSafeKeyDate = (this.TKey = vbNullString Or this.TKey = TypeName(value))
If IsSafeKeyDate Or OptionStrict Then Exit Function
Dim result As Boolean
result = CDate(value)
IsSafeKeyDate = (Err.number = 0)
'If this.OptionTrace And IsSafeKeyString(Value) Then Debug.Print "TRACE: IsSafeKeyDate(" & CStr(Value) & ") : " & IsSafeKeyDate
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeKeyByte(value As Variant) As Boolean
On Error Resume Next
IsSafeKeyByte = (this.TKey = vbNullString Or this.TKey = TypeName(value))
If IsSafeKeyByte Or OptionStrict Then Exit Function
Dim result As Boolean
result = CByte(value)
IsSafeKeyByte = (Err.number = 0)
'If this.OptionTrace And IsSafeKeyString(Value) Then Debug.Print "TRACE: IsSafeKeyByte(" & CStr(Value) & ") : " & IsSafeKeyByte
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeKeyBoolean(value As Variant) As Boolean
On Error Resume Next
IsSafeKeyBoolean = (this.TKey = vbNullString Or this.TKey = TypeName(value))
If IsSafeKeyBoolean Or OptionStrict Then Exit Function
Dim result As Boolean
result = CBool(value)
IsSafeKeyBoolean = (Err.number = 0)
'If this.OptionTrace And IsSafeKeyString(Value) Then Debug.Print "TRACE: IsSafeKeyBoolean(" & CStr(Value) & ") : " & IsSafeKeyBoolean
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeKeyCurrency(value As Variant) As Boolean
On Error Resume Next
IsSafeKeyCurrency = (this.TKey = vbNullString Or this.TKey = TypeName(value))
If IsSafeKeyCurrency Or OptionStrict Then Exit Function
Dim result As Boolean
result = CCur(value)
IsSafeKeyCurrency = (Err.number = 0)
'If this.OptionTrace And IsSafeKeyString(Value) Then Debug.Print "TRACE: IsSafeKeyCurrency(" & CStr(Value) & ") : " & IsSafeKeyCurrency
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeKeyInteger(value As Variant) As Boolean
On Error Resume Next
IsSafeKeyInteger = (this.TKey = vbNullString Or this.TKey = TypeName(value))
If IsSafeKeyInteger Or OptionStrict Then Exit Function
Dim result As Boolean
result = CInt(value)
IsSafeKeyInteger = (Err.number = 0)
'If this.OptionTrace And IsSafeKeyString(Value) Then Debug.Print "TRACE: IsSafeKeyInteger(" & CStr(Value) & ") : " & IsSafeKeyInteger
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeKeyLong(value As Variant) As Boolean
On Error Resume Next
IsSafeKeyLong = (this.TKey = vbNullString Or this.TKey = TypeName(value))
If IsSafeKeyLong Or OptionStrict Then Exit Function
Dim result As Boolean
result = CLng(value)
IsSafeKeyLong = (Err.number = 0)
'If this.OptionTrace And IsSafeKeyString(Value) Then Debug.Print "TRACE: IsSafeKeyLong(" & CStr(Value) & ") : " & IsSafeKeyLong
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeKeyDouble(value As Variant) As Boolean
On Error Resume Next
IsSafeKeyDouble = (this.TKey = vbNullString Or this.TKey = TypeName(value))
If IsSafeKeyDouble Or OptionStrict Then Exit Function
Dim result As Boolean
result = CDbl(value)
IsSafeKeyDouble = (Err.number = 0)
'If this.OptionTrace And IsSafeKeyString(Value) Then Debug.Print "TRACE: IsSafeKeyDouble(" & CStr(Value) & ") : " & IsSafeKeyDouble
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeKeySingle(value As Variant) As Boolean
On Error Resume Next
IsSafeKeySingle = (this.TKey = vbNullString Or this.TKey = TypeName(value))
If IsSafeKeySingle Or OptionStrict Then Exit Function
Dim result As Boolean
result = CSng(value)
IsSafeKeySingle = (Err.number = 0)
'If this.OptionTrace And IsSafeKeyString(Value) Then Debug.Print "TRACE: IsSafeKeySingle(" & CStr(Value) & ") : " & IsSafeKeySingle
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeValueString(value As Variant) As Boolean
On Error Resume Next
IsSafeValueString = (this.TValue = vbNullString Or this.TValue = TypeName(value))
If IsSafeValueString Or OptionStrict Then Exit Function
Dim result As Boolean
result = CStr(value)
IsSafeValueString = (Err.number = 0)
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeValueDate(value As Variant) As Boolean
On Error Resume Next
IsSafeValueDate = (this.TValue = vbNullString Or this.TValue = TypeName(value))
If IsSafeValueDate Or OptionStrict Then Exit Function
Dim result As Boolean
result = CDate(value)
IsSafeValueDate = (Err.number = 0)
'If this.OptionTrace And IsSafeValueString(Value) Then Debug.Print "TRACE: IsSafeValueDate(" & CStr(Value) & ") : " & IsSafeValueDate
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeValueByte(value As Variant) As Boolean
On Error Resume Next
IsSafeValueByte = (this.TValue = vbNullString Or this.TValue = TypeName(value))
If IsSafeValueByte Or OptionStrict Then Exit Function
Dim result As Boolean
result = CByte(value)
IsSafeValueByte = (Err.number = 0)
'If this.OptionTrace And IsSafeValueString(Value) Then Debug.Print "TRACE: IsSafeValueByte(" & CStr(Value) & ") : " & IsSafeValueByte
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeValueBoolean(value As Variant) As Boolean
On Error Resume Next
IsSafeValueBoolean = (this.TValue = vbNullString Or this.TValue = TypeName(value))
If IsSafeValueBoolean Or OptionStrict Then Exit Function
Dim result As Boolean
result = CBool(value)
IsSafeValueBoolean = (Err.number = 0)
'If this.OptionTrace And IsSafeValueString(Value) Then Debug.Print "TRACE: IsSafeValueBoolean(" & CStr(Value) & ") : " & IsSafeValueBoolean
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeValueCurrency(value As Variant) As Boolean
On Error Resume Next
IsSafeValueCurrency = (this.TValue = vbNullString Or this.TValue = TypeName(value))
If IsSafeValueCurrency Or OptionStrict Then Exit Function
Dim result As Boolean
result = CCur(value)
IsSafeValueCurrency = (Err.number = 0)
'If this.OptionTrace And IsSafeValueString(Value) Then Debug.Print "TRACE: IsSafeValueCurrency(" & CStr(Value) & ") : " & IsSafeValueCurrency
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeValueInteger(value As Variant) As Boolean
On Error Resume Next
IsSafeValueInteger = (this.TValue = vbNullString Or this.TValue = TypeName(value))
If IsSafeValueInteger Or OptionStrict Then Exit Function
Dim result As Boolean
result = CInt(value)
IsSafeValueInteger = (Err.number = 0)
'If this.OptionTrace And IsSafeValueString(Value) Then Debug.Print "TRACE: IsSafeValueInteger(" & CStr(Value) & ") : " & IsSafeValueInteger
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeValueLong(value As Variant) As Boolean
On Error Resume Next
IsSafeValueLong = (this.TValue = vbNullString Or this.TValue = TypeName(value))
If IsSafeValueLong Or OptionStrict Then Exit Function
Dim result As Boolean
result = CLng(value)
IsSafeValueLong = (Err.number = 0)
'If this.OptionTrace And IsSafeValueString(Value) Then Debug.Print "TRACE: IsSafeValueLong(" & CStr(Value) & ") : " & IsSafeValueLong
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeValueDouble(value As Variant) As Boolean
On Error Resume Next
IsSafeValueDouble = (this.TValue = vbNullString Or this.TValue = TypeName(value))
If IsSafeValueDouble Or OptionStrict Then Exit Function
Dim result As Boolean
result = CDbl(value)
IsSafeValueDouble = (Err.number = 0)
'If this.OptionTrace And IsSafeValueString(Value) Then Debug.Print "TRACE: IsSafeValueDouble(" & CStr(Value) & ") : " & IsSafeValueDouble
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeValueSingle(value As Variant) As Boolean
On Error Resume Next
IsSafeValueSingle = (this.TValue = vbNullString Or this.TValue = TypeName(value))
If IsSafeValueSingle Or OptionStrict Then Exit Function
Dim result As Boolean
result = CSng(value)
IsSafeValueSingle = (Err.number = 0)
'If this.OptionTrace And IsSafeValueString(Value) Then Debug.Print "TRACE: IsSafeValueSingle(" & CStr(Value) & ") : " & IsSafeValueSingle
Err.Clear
On Error GoTo 0
End Function
Private Sub RaiseErrorUnsafeType(member As String, suppliedType As String)
Err.Raise DictionaryErrors.TypeMismatchUnsafeType, _
StringFormat("{0}.{1}", ToString, member), _
StringFormat("Type Mismatch. Expected: 'KeyValuePair<{0},{1}>', '{2}' was supplied.", this.TKey, this.TValue, suppliedType)
End Sub
Public Sub Clear()
this.Encapsulated.Clear
End Sub
Public Function Contains(v As Variant) As Boolean
Contains = Values.Contains(v)
End Function
Public Function ContainsKey(k As Variant) As Boolean
ContainsKey = Keys.Contains(k)
End Function
Public Property Get NewEnum() As IUnknown
'Gets an enumerator that iterates through the values held in the Dictionary.
Set NewEnum = this.Encapsulated.NewEnum
End Property
Public Function Remove(v As Variant) As Boolean
Dim i As Long
i = Values.IndexOf(v)
If i <> -1 Then
this.Encapsulated.RemoveAt i
Remove = True
Else
Remove = False
End If
End Function
Public Function RemoveKey(k As Variant) As Boolean
Dim i As Long
i = Keys.IndexOf(k)
If i <> -1 Then
this.Encapsulated.RemoveAt i
RemoveKey = True
Else
RemoveKey = False
End If
End Function
Public Function TryGetValue(k As Variant, ByRef outValue As Variant) As Boolean
Dim i As Long
i = Keys.IndexOf(k)
Dim kvp As KeyValuePair
If i <> -1 Then
Set kvp = this.Encapsulated(i)
If IsObject(kvp.value) Then
Set outValue = kvp.value
Else
outValue = kvp.value
End If
TryGetValue = True
Else
TryGetValue = False
End If
End Function
Public Function ToList() As List
Set ToList = this.Encapsulated
End Function
Public Function ToString() As String
ToString = TypeName(Me) & "<" & IIf(this.TKey = vbNullString, "Variant", this.TKey) & ", " & IIf(this.TValue = vbNullString, "Variant", this.TValue) & ">"
End Function
</code></pre>
<p>I've written this a little while ago, in the mean time I've learned about <code>CallByName</code>, so now I wonder if there wouldn't be a really clever way to rework the <code>IsTypeSafe</code> method so as to avoid the <code>Select Case</code> blocks (<code>CallByName</code> doesn't seem to work for functions / methods with a return value).</p>
| [] | [
{
"body": "<p>Although <code>CallByName</code> doesn't seem to have a return value (from the parameter tooltip), it does. This means if <code>IsSafeKeyXxxxxx</code> methods were <code>Public</code> you could use <code>CallByName</code> instead of the <code>Select..Case</code> block.</p>\n\n<p>However exposing all these methods through your <code>Dictionary</code> interface would be rather ugly. How about extracting all these small methods into their own <code>TypeValidator</code> class?</p>\n\n<pre><code>Private Type tValueTypeValidator\n TValue As String\n OptionStrict As Boolean\nEnd Type\n\nPrivate this As tValueTypeValidator\nOption Explicit\n\nPublic Property Get TValue() As String\n TValue = this.TValue\nEnd Property\n\nPublic Property Let TValue(ByVal value As String)\n this.TValue = value\nEnd Property\n\nPublic Property Get OptionStrict() As Boolean\n OptionStrict = this.OptionStrict\nEnd Property\n\nPublic Property Let OptionStrict(ByVal value As Boolean)\n this.OptionStrict = value\nEnd Property\n\nPublic Function ToString() As String\n ToString = TypeName(Me) & \"<\" & this.TValue & \">\"\nEnd Function\n\nPublic Function IsSafeBoolean(value As Variant) As Boolean\n On Error Resume Next\n\n IsSafeBoolean = (this.TValue = vbNullString Or this.TValue = TypeName(value))\n If IsSafeBoolean Or this.OptionStrict Then Exit Function\n\n Dim result As Boolean\n result = CBool(value)\n IsSafeBoolean = (Err.Number = 0)\n\n Err.Clear\n On Error GoTo 0\nEnd Function\n\nPublic Function IsSafeByte(value As Variant) As Boolean\n On Error Resume Next\n\n IsSafeByte = (this.TValue = vbNullString Or this.TValue = TypeName(value))\n If IsSafeByte Or this.OptionStrict Then Exit Function\n\n Dim result As Boolean\n result = CByte(value)\n IsSafeByte = (Err.Number = 0)\n\n Err.Clear\n On Error GoTo 0\nEnd Function\n\nPublic Function IsSafeCurrency(value As Variant) As Boolean\n On Error Resume Next\n\n IsSafeCurrency = (this.TValue = vbNullString Or this.TValue = TypeName(value))\n If IsSafeCurrency Or this.OptionStrict Then Exit Function\n\n Dim result As Boolean\n result = CCur(value)\n IsSafeCurrency = (Err.Number = 0)\n\n Err.Clear\n On Error GoTo 0\nEnd Function\n\nPublic Function IsSafeDate(value As Variant) As Boolean\n On Error Resume Next\n\n IsSafeDate = (this.TValue = vbNullString Or this.TValue = TypeName(value))\n If IsSafeDate Or this.OptionStrict Then Exit Function\n\n Dim result As Boolean\n result = CDate(value)\n IsSafeDate = (Err.Number = 0)\n\n Err.Clear\n On Error GoTo 0\nEnd Function\n\nPublic Function IsSafeDouble(value As Variant) As Boolean\n On Error Resume Next\n\n IsSafeDouble = (this.TValue = vbNullString Or this.TValue = TypeName(value))\n If IsSafeDouble Or this.OptionStrict Then Exit Function\n\n Dim result As Boolean\n result = CDbl(value)\n IsSafeDouble = (Err.Number = 0)\n\n Err.Clear\n On Error GoTo 0\nEnd Function\n\nPublic Function IsSafeInteger(value As Variant) As Boolean\n On Error Resume Next\n\n IsSafeInteger = (this.TValue = vbNullString Or this.TValue = TypeName(value))\n If IsSafeInteger Or this.OptionStrict Then Exit Function\n\n Dim result As Boolean\n result = CInt(value)\n IsSafeInteger = (Err.Number = 0)\n\n Err.Clear\n On Error GoTo 0\nEnd Function\n\nPublic Function IsSafeLong(value As Variant) As Boolean\n On Error Resume Next\n\n IsSafeLong = (this.TValue = vbNullString Or this.TValue = TypeName(value))\n If IsSafeLong Or OptionStrict Then Exit Function\n\n Dim result As Boolean\n result = CLng(value)\n IsSafeLong = (Err.Number = 0)\n\n Err.Clear\n On Error GoTo 0\nEnd Function\n\nPublic Function IsSafeSingle(value As Variant) As Boolean\n On Error Resume Next\n\n IsSafeSingle = (this.TValue = vbNullString Or this.TValue = TypeName(value))\n If IsSafeSingle Or this.OptionStrict Then Exit Function\n\n Dim result As Boolean\n result = CSng(value)\n IsSafeSingle = (Err.Number = 0)\n\n Err.Clear\n On Error GoTo 0\nEnd Function\n\nPublic Function IsSafeString(value As Variant) As Boolean\n On Error Resume Next\n\n IsSafeString = (this.TValue = vbNullString Or this.TValue = TypeName(value))\n If IsSafeString Or this.OptionStrict Then Exit Function\n\n Dim result As Boolean\n result = CStr(value)\n IsSafeString = (Err.Number = 0)\n Err.Clear\n\n On Error GoTo 0\nEnd Function\n</code></pre>\n\n<p>And since that code was copy-pasted from an existing <code>List</code> class in the first place, there's already a case for reusing that <code>TypeValidator</code> class.</p>\n\n<p>That change would require the <code>ValidateItemType</code> method to be modified as such:</p>\n\n<pre><code>Private Function ValidateItemType(kvp As KeyValuePair, Optional ThrowOnUnsafeType As Boolean = False) As Boolean\n\n If this.TKey = vbNullString And this.TValue = vbNullString Then\n this.TKey = TypeName(kvp.key)\n this.IsRefTypeKey = IsObject(kvp.key)\n this.TValue = TypeName(kvp.value)\n this.IsRefTypeValue = IsObject(kvp.value)\n this.KeyValidator.TValue = this.TKey '<<< here\n this.ValueValidator.TValue = this.TValue '<<< here\n End If\n\n ValidateItemType = IsTypeSafe(kvp)\n\n If ThrowOnUnsafeType And Not ValidateItemType Then RaiseErrorUnsafeType \"ValidateItemType()\", kvp.ToString\n\nEnd Function\n</code></pre>\n\n<p>The <code>OptionStrict</code> property setter would have to be affected as well:</p>\n\n<pre><code>Public Property Let OptionStrict(value As Boolean)\n this.Encapsulated.OptionStrict = value\n this.KeyValidator.OptionStrict = value ' <<< here\n this.ValueValidator.OptionStrict = value ' <<< here\nEnd Property\n</code></pre>\n\n<p>As well as the <code>Class_Initialize</code> method:</p>\n\n<pre><code>Private Sub Class_Initialize()\n Set this.Encapsulated = New List\n Set this.KeyValidator = New TypeValidator ' <<< here\n Set this.ValueValidator = New TypeValidator ' <<< here\n this.Encapsulated.OptionStrict = True\n this.KeyValidator.OptionStrict = True ' <<< here\n this.ValueValidator.OptionStrict = True ' <<< here\nEnd Sub\n</code></pre>\n\n<p>And of course the private type of <code>this</code>:</p>\n\n<pre><code>Private Type tDictionary\n Encapsulated As List\n TKey As String\n IsRefTypeKey As Boolean\n TValue As String\n IsRefTypeValue As Boolean\n KeyValidator As TypeValidator ' <<< here\n ValueValidator As TypeValidator ' <<< here\nEnd Type\n</code></pre>\n\n<p>The <code>IsTypeSafe</code> method implementation could then be simplified to this - gone, the <code>Select..Case</code> blocks!</p>\n\n<pre><code>Public Function IsTypeSafe(kvp As KeyValuePair) As Boolean\n'Determines whether a value can be safely added to the List.\n\n IsTypeSafe = (this.TKey = vbNullString Or this.TKey = TypeName(kvp.key)) _\n And (this.TValue = vbNullString Or this.TValue = TypeName(kvp.value))\n If IsTypeSafe Then Exit Function\n\n IsTypeSafe = CallByName(this.KeyValidator, \"IsSafe\" & this.TKey, VbMethod, kvp.key)\n If Not IsTypeSafe Then Exit Function\n\n IsTypeSafe = CallByName(this.ValueValidator, \"IsSafe\" & this.TValue, VbMethod, kvp.value)\n\nErrHandler:\n 'swallow overflow errors:\n If Err.Number = 6 Then\n Err.Clear\n Resume Next\n ElseIf Err.Number <> 0 Then\n RaiseErrorUnsafeType \"IsTypeSafe()\", kvp.ToString\n End If\nEnd Function\n</code></pre>\n\n<p>This also leaves you with a much, much cleaner list of members, as a side-effect of separating the type validation concerns into their own class:</p>\n\n<p><img src=\"https://i.stack.imgur.com/R9OWK.png\" alt=\"Members of Dictionary\">\n<img src=\"https://i.stack.imgur.com/4G9V5.png\" alt=\"Members of TypeValidator\"></p>\n\n<p><sub>Busted! Yes, I work with a French VB6 IDE!</sub></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T03:01:07.753",
"Id": "46134",
"ParentId": "45666",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "46134",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T00:18:56.587",
"Id": "45666",
"Score": "8",
"Tags": [
"hash-map",
"vb6"
],
"Title": "Dictionary<TKey, TValue> Implementation"
} | 45666 |
<p>I need to split up a sequence into equal segments of a given size (yes, the last one may be shorter), and I'm trying to find an efficient and idiomatic way to do it.</p>
<p>I have two versions of the function; <code>segment</code> is the F# version of an awkward and probably quite inefficient old C# extension method that I wrote, while <code>chop</code> is an attempt to do it in a more intelligent manner, but is still rather imperative. I would have liked to have a solution that doesn't need to use reference cells, but could not come up with one.</p>
<pre><code>module Seq =
let segment segmentSize source =
seq {
let segmentCount = ref 0
while !segmentCount * segmentSize < Seq.length source
do
let segment = source |> Seq.skip (!segmentCount * segmentSize) |> Seq.truncate segmentSize
segmentCount := !segmentCount + 1
yield segment
}
let chop segmentSize source =
seq {
let chopSource = ref source
while not <| Seq.isEmpty !chopSource
do
let segment = !chopSource |> Seq.truncate segmentSize
chopSource := !chopSource |> Seq.skip (Seq.length segment)
yield segment
}
</code></pre>
<p>As I said, I think <code>segment</code>, while it gets the job done, is far from good F#; how efficient and idiomatic is <code>chop</code>? What could have been done better? </p>
<p>As for naming, is <code>chop</code> or <code>segment</code> the better name for a function like this, or would something else be more fitting? Also, the argument name <code>segmentSize</code> seems a bit off for F#; would just <code>size</code> be better, or something else?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T01:48:27.807",
"Id": "79729",
"Score": "1",
"body": "link from SO for the same problem: https://stackoverflow.com/questions/3999584/f-split-sequence-into-sub-lists-on-every-nth-element (The accepted answer is from a MS F# dev)"
}
] | [
{
"body": "<p>Functional-first style tends to prefer immutability over mutability, so the fact that you're using <code>ref</code> can sometimes signify that the code could be more idiomatic.</p>\n\n<p><strong>Recursive Solution</strong></p>\n\n<p>But how do you keep track of the state of your program without mutation? The traditional functional solution is to use recursion so that each step of the algorithm is isolated in its own call context. Here is a fairly direct translation of your second example into a recursive function:</p>\n\n<pre><code>let rec chop segmentSize source = \n seq { \n if Seq.isEmpty source then () else\n let segment = source |> Seq.truncate segmentSize\n let rest = source |> Seq.skip (Seq.length segment)\n yield segment\n yield! chop segmentSize rest \n }\n</code></pre>\n\n<p>Don't be intimidated by my <code>if ... then () else</code> pattern - it's a trick I adopted to avoid needing to indent the rest of function when a precondition is used (I've seen it elsewhere, and it is nice since there's no early return from functions in F#).</p>\n\n<p>Note how I'm using <code>yield!</code> to flatten the sequence from the recursive call into the outer sequence. Also notice that there is no <code>chopSource</code> in this version, because what was <code>chopSource</code> in your example is simply <code>source</code> in the recursive call.</p>\n\n<p>One possible problem with the above solution is that it is not (as far as I know) tail-recursive. I'm not 100% sure how <code>seq</code> works behind the scenes, but I'm assuming that it is not in this case. This may not matter for your problem, but it's still something to consider. It could always be rewritten to use an accumulator argument so that it is tail-recursive and won't overflow the stack.</p>\n\n<p>Another option is to ditch the sequence expression altogether (note that this is <em>still</em> not tail-recursive):</p>\n\n<pre><code>let rec chop segmentSize source = \n if Seq.isEmpty source then Seq.empty else\n let segment = source |> Seq.truncate segmentSize\n let rest = source |> Seq.skip (Seq.length segment)\n Seq.append [segment] (chop segmentSize rest)\n</code></pre>\n\n<p><strong>Seq.unfold Solution</strong></p>\n\n<p>Although it's nice in this particular case, I'm not a huge fan of recursion because it can sometimes be hard to read and easy to get wrong. I normally use sequence functions as an alternative, as they handle those types of details behind the scenes, and I can worry about the problem at hand. Fortunately, the <code>Seq</code> module provides a nice function, <code>unfold</code>, which does exactly what we are trying to do here - it produces a sequence of values from an evolving state!</p>\n\n<p>The function is called <code>unfold</code> because it is the inverse of <code>fold</code>, which is the equivalent of <code>Enumerable.Aggregate</code> from C#. Here is the documentation:</p>\n\n<pre><code>// Signature:\nSeq.unfold : ('State -> 'T * 'State option) -> 'State -> seq<'T>\n\n// Usage:\nSeq.unfold generator state\n</code></pre>\n\n<p>The second argument, <code>state</code>, is the initial value that is going to be used to \"seed\" the operation (it may seem weird to have this as the <em>second</em> argument, but it is in that order to allow partial application / piping). That initial <code>state</code> value is going to be the first value passed in to our <code>generator</code> function. The <code>generator</code> function optionally returns a tuple containing the current value in the sequence along with the next <code>state</code> value that will be passed back in to generate the next value in the sequence. When the sequence is done, it returns <code>None</code>.</p>\n\n<p>Enough commentary, here is the implementation:</p>\n\n<pre><code>let chop segmentSize source =\n source\n |> Seq.unfold(fun chopSource ->\n if Seq.isEmpty chopSource then None else\n let segment = chopSource |> Seq.truncate segmentSize\n let rest = chopSource |> Seq.skip (Seq.length segment)\n Some(segment, rest)\n )\n</code></pre>\n\n<p>So as you can see, we're basically allowing <code>Seq.unfold</code> to call our <code>generator</code> repetitively as an alternative to recursion. Each iteration returns the segment and the rest of the sequence, which becomes the next <code>state</code> / <code>chopSoure</code>. I'm not actually sure if that is clearer than the recursive version, but it at least won't ever overflow the stack.</p>\n\n<p>As for your naming questions, I think it's somewhat arbitrary. I probably would have called the function <code>segment[ed]</code> (indeed, I think I have). The size argument could go either way. For what it's worth, here's a <a href=\"http://msdn.microsoft.com/en-us/library/ee340420.aspx\" rel=\"nofollow noreferrer\">similar function</a> defined in the <code>Seq</code> module, though it's dealing with a sliding window rather than fixed segments.</p>\n\n<p><strong>Addendum</strong></p>\n\n<p>All these solutions are assuming that it is fine to re-enumerate the sequence, i.e. by truncating once and then skipping. That might be an OK assumption for small, in-memory data-sets, but an <code>IEnumerable</code> doesn't <em>have</em> to allow multiple enumeration, and it can be expensive. As <a href=\"https://stackoverflow.com/a/4000490/166131\">pointed out</a> by Tomas Petricek on that other question, due to the forward-only nature of sequences, whenever you \"back up\" over a sequence like this it actually has to enumerate the entire thing from the beginning.</p>\n\n<p>But perhaps a sequence isn't the best choice of data types for input into this function. If the data is already in memory, you have a choice of turning it into a list or an array. Arrays are especially nice for this problem due to their support for slicing. Here's a solution that uses arrays instead of sequences:</p>\n\n<pre><code>let segmented (size:int) (source:'t[]) =\n let maxPos = source.Length - 1\n [| for pos in 0 .. size .. maxPos ->\n source.[pos .. min (pos + size - 1) maxPos] |]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T18:23:18.517",
"Id": "81068",
"Score": "0",
"body": "I updated my array solution."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T03:30:03.157",
"Id": "45673",
"ParentId": "45668",
"Score": "7"
}
},
{
"body": "<p>If in doubt, use <code>fold</code>.</p>\n\n<pre><code>let split n = let one, append, empty = Seq.singleton, Seq.append, Seq.empty\n Seq.fold (fun (m, cur, acc) x -> \n if m = n then (1, one x, append acc (one cur))\n else (m+1, append cur (one x), acc))\n (0, empty, empty)\n >> fun (_, cur, acc) -> append acc (one cur)\n</code></pre>\n\n<p>This has the advantage over the other proposed solution that it does not force the re-evaluation of IEnumerables: each element in the input sequence is touched only once(*).</p>\n\n<p>If you're not used to <code>fold</code>, this is arguably less readable than the solutions proposed in the other answer. However, using <code>fold</code> to solve problems <em>like</em> this one is highly idiomatic F#, so I think it's worth considering anyway. </p>\n\n<p>It works like this. We use <code>Seq.fold</code> to thread an accumulator through the sequence. \n<code>fold</code> applies a function to each element of a sequence. However, for each element, the function gets both the element and an accumulator, and must produce a new accumulator. That function is the anonymous one:</p>\n\n<pre><code> fun (m, cur, acc) x -> \n if m = n then (1, one x, append acc (one cur))\n else (m+1, append cur (one x), acc)\n</code></pre>\n\n<p>The accumulator contains a \"current segment\" <code>cur</code>, how many elements is in that segment <code>m</code>, and the segments we have already built <code>acc</code>. It has to produce a new accumulator. There are two cases: either we have enough elements to finalise the current segment (<code>m=n</code>), or we don't. If we do, we move the current segment to the \ncomplete segments (<code>append acc (one cur)</code>) and start a new segment with the current element (<code>1</code> and <code>one x</code>). If we don't, we add the current element to the current segment (<code>m+1</code> and <code>append cur (one x)</code>). </p>\n\n<p>The end-user of course doesn't care for our accumulator, so once the fold completes, we compact it by the line:</p>\n\n<pre><code> >> fun (_, cur, acc) -> append acc (one cur)\n</code></pre>\n\n<p>That is, we lose the counter <code>_</code>, and add the current (likely of length < n) segment <code>cur</code> to our accumulated result segments <code>acc</code>. </p>\n\n<p>This is idiomatic in two ways: First, <code>fold</code> is just very handy in so many cases. Second, if you think about how you'd implement this in an old-fashioned imperative language without native support for sequences, you'd have some kind of loop over the elements (<code>m</code>), a segment you're currently building (<code>cur</code>), and a collection of completed segments (<code>acc</code>). What we do in F# is make all this <em>state</em> explicit in one place: it all lives in the arguments to the anonymous function. </p>\n\n<p>You'll note that the first line</p>\n\n<pre><code>let split n = ...\n</code></pre>\n\n<p>doesn't actually mention the sequence <code>s</code>. We're exploiting here that \nfunctions are values, so instead of writing, say</p>\n\n<pre><code>let split n s = ... s\n</code></pre>\n\n<p>we can just write</p>\n\n<pre><code>let split n = ...\n</code></pre>\n\n<p>This is called points-free programming. It's idiomatic, but it's debated whether it is a \"good\" idiom. I like it, though. </p>\n\n<p>(*) I'm assuming that Seq.append has O(1) running time. I should certainly hope so, but I wasn't able to verify it. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T23:20:49.490",
"Id": "45715",
"ParentId": "45668",
"Score": "2"
}
},
{
"body": "<p>This question <a href=\"https://stackoverflow.com/questions/22545735/chunk-or-partition-seq-of-items-into-sequences-of-n-items\">has been asked</a> several times on StackOverflow, and I'm always amazed at the convoluted answers offered up (and the votes for them!). Brian (a member of the F# team) provided <a href=\"https://stackoverflow.com/a/4000413/162396\">a simple solution</a> back in 2010. It doesn't seem to be too popular, presumably because it uses (local) mutation (as do the built-in collections modules). But Brian's solution</p>\n\n<ul>\n<li>is concise and easy to understand</li>\n<li>outperforms (by a wide margin) solutions using <code>skip</code>/<code>take</code> or <code>yield!</code></li>\n</ul>\n\n<p>His solution, for reference:</p>\n\n<pre><code>let split size source =\n seq {\n let r = ResizeArray()\n for x in source do\n r.Add(x)\n if r.Count = size then\n yield r.ToArray()\n r.Clear()\n if r.Count > 0 then \n yield r.ToArray()\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T20:16:33.523",
"Id": "80055",
"Score": "0",
"body": "On the one hand, you're right: I tried out this solution vs my suggested one on lists of 100000 elements. Then this one is 2 orders of magnitude faster. On the other hand, I think people ask this question (and many like it) because they're looking to pick up \"idiomatic f#\". That's usually something with combinators, even if they are slower, because they're usually much clearer. With lists of 100 elements, speedup is only 30%, or a few hundredths of a millisecond."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T20:16:57.887",
"Id": "80056",
"Score": "0",
"body": "... that said, yeah, Brian's solution is beautiful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T21:02:44.840",
"Id": "80062",
"Score": "0",
"body": "I understand, but the solutions I've seen either depend on anti-patterns like multiple calls to `skip`/`take` or are virtually unreadable. If you're going for \"functional beauty\" take a look at [Tomas' solution](http://stackoverflow.com/a/8064600/162396)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T14:33:10.690",
"Id": "45836",
"ParentId": "45668",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T00:26:18.620",
"Id": "45668",
"Score": "7",
"Tags": [
"f#"
],
"Title": "Splitting a sequence into equal segments"
} | 45668 |
<p>I'm writing a jQuery plugin.</p>
<p>I'm allowing the user to pass options (optionally-- argument 2 to extend) but I also require some defaults (argument 1), and some things user is not allowed to modify (argument 3). </p>
<p>I follow the global override pattern recommended by most jQuery plugins. But I'm running into something I've never seen discussed which is where you have defaults that need to be set in a specific scope (caption being set to self._tableName, for example). </p>
<p>This forces you to do an extend pretty much everywhere you need options + internal state. It's not that terrible, but my code review sense is tingling.</p>
<p>Anything in the snippet is up for debate. Leave your thoughts, please.</p>
<p>For context, how I'm doing options in the constructor</p>
<pre><code> this.options = $.extend(true, $.fn.myPlugin.Defaults, options);
</code></pre>
<p>And here is the argument object I'm creating to be passed to a plugin. To reiterate, I'm forming this object much later when it's time to create the jqgrid.</p>
<pre><code> $.extend({ caption: self._tableName },
self.options ? self.options.jqgrid : {},
{
datatype: function (postdata) {
hubProxy.server.requestPage(postdata);
},
ColNames: ColNames,
colModel: ColModel,
pager: '#' + pager,
ondblClickRow: function (rowid) {
$(this).jqGrid('editGridRow', rowid, editTemplate);
}
});
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T20:58:05.587",
"Id": "79800",
"Score": "1",
"body": "Could you provide a little more context? From the above it's hard to tell if there are improvements to be made or not"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T22:24:44.647",
"Id": "79805",
"Score": "1",
"body": "It would just be more of the same. After considering it a bit more, I'm not sure there is a way to do things differently. How else could you do it but to $.extend 3 separate objects? As long as you order them correctly, the result is achieved. The base, options, and defaults all combine to form the behavior the user expects without letting them shoot themselves in the foot."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T23:42:01.417",
"Id": "79808",
"Score": "0",
"body": "You may well be right. I was thinking there might be stuff to find elsewhere in the code, before you reach the `extend` calls. But without seeing more of the code, it's impossible to tell. That said, your solution may well be the best. If you believe that's the case, feel free to self-review (or close) the question (you can always pick a different answer, if one appears). The fewer unanswered questions hanging around, the better for the site."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T18:17:41.690",
"Id": "79893",
"Score": "0",
"body": "Eh I'm not going to close it especially since there's a bug in my code no one caught; the first call to $.extend will overwrite all the global options with the object's options when there's a matching property. Vaguely insinuating I am yet to get a good code review."
}
] | [
{
"body": "<p>Not a lot ( of context ) to review;</p>\n\n<ul>\n<li><p><code>this.options = $.extend(true, $.fn.myPlugin.Defaults, options);</code> <- This will modify the defaults of the plugin, if you did not want that, then you should do</p>\n\n<pre><code>this.options = $.extend(true, {}, $.fn.myPlugin.Defaults, options);\n</code></pre></li>\n<li><p>You are talking about passing a third parameter for immutable settings/options/parameters, the 3rd parameter in your <code>$.extend</code> call will do no such thing, you will not even know which properties come from the 3 object.</p></li>\n<li><p><code>myPlugin</code> <- as plugin names go, not very original ;)</p></li>\n<li><p><code>datatype</code> is probably an unfortunate name, I would expect a function with that name to return a data type, also I would expect it to follow lowerCamelCase ( <code>dataType</code> )</p></li>\n<li><p>It is risky to not check for <code>jqGrid</code> in <code>self.options ? self.options.jqgrid : {},</code>, I would have gone for <code>(self.options && self.options.jqgrid) ? self.options.jqgrid : {},</code></p></li>\n<li><p>Finally, I have to say that the last code block looks like a large amorphous blob, I would have much rather seen chained setters.</p></li>\n</ul>\n\n<p>All in all, I am sure that you could have gotten more out of codereview if you had posted a bit more code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T15:30:14.020",
"Id": "45847",
"ParentId": "45674",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T05:35:50.167",
"Id": "45674",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"plugin"
],
"Title": "JavaScript jQuery plugin options. Defaults, User Options, and immutable settings pattern?"
} | 45674 |
<p>I've tried to make a portable way of ensuring endian-specific code gets generated at compile time using C++11, however I only have a computer with Windows on it to test at the moment. Because of this, I'm a bit limited in the amount of places where I can test my code. Also, would anyone be able to offer some best-practices or tips different ways to improve this? My intention is to use this in a small math library where serialization is a pretty high priority.</p>
<p>The function itself is fairly simple. It checks the values of an array for whichever byte comes first. It then returns a constant value, representing the target machine's endianness, through an enumeration. If everything works correctly, then this code can replace any runtime checks that either I or anyone else uses for endian checking.</p>
<pre><code>/*
* A simple compile-time endian test
* g++ -std=c++11 -Wall -Werror -Wextra -pedantic -pedantic-errors endian.cpp -o endian
*
* This can be used with specialized template functions, classes, and class
* methods in order better tailor code and reduce reliance on runtime
* checking systems.
*/
#include <cstdint>
#include <iostream>
/**
* hl_endianness
*
* This enumeration can be placed into templated objects in order to generate
* compile-time code based on a program's target endianness.
*
* The values placed in this enum are used just in case the need arises in
* order to manually compare them against the number order in the
* endianValues[] array.
*/
enum hl_endianness : uint32_t {
HL_LITTLE_ENDIAN = 0x03020100,
HL_BIG_ENDIAN = 0x00010203,
HL_PDP_ENDIAN = 0x01000302,
HL_UNKNOWN_ENDIAN = 0xFFFFFFFF
};
/**
* A constant array used to determine a program's target endianness. The
* values
* in this array can be compared against the values placed in the
* hl_endianness enumeration.
*/
static constexpr uint8_t endianValues[4] = {0, 1, 2, 3};
/**
* A simple function that can be used to help determine a program's endianness
* at compile-time.
*/
constexpr hl_endianness getEndianOrder() {
return
(0x00 == endianValues[0]) // If Little Endian Byte Order,
? HL_LITTLE_ENDIAN // return 0 for little endian.
: (0x03 == endianValues[0]) // Else if Big Endian Byte Order,
? HL_BIG_ENDIAN // return 1 for big endian.
: (0x02 == endianValues[0]) // Else if PDP Endian Byte Order,
? HL_PDP_ENDIAN // return 2 for pdp endian.
: HL_UNKNOWN_ENDIAN; // Else return -1 for wtf endian.
}
#define HL_ENDIANNESS getEndianOrder()
/*
* Test program
*/
int main() {
#if defined _WIN32 || defined _WIN64
static_assert(
HL_ENDIANNESS == HL_LITTLE_ENDIAN,
"Aren't Windows programs Little-Endian?"
);
#endif
constexpr hl_endianness endianness = HL_ENDIANNESS;
std::cout << "This machine is: ";
switch (endianness) {
case HL_LITTLE_ENDIAN:
std::cout << "LITTLE";
break;
case HL_BIG_ENDIAN:
std::cout << "BIG";
break;
case HL_PDP_ENDIAN:
std::cout << "PDP";
break;
case HL_UNKNOWN_ENDIAN:
default:
std::cout << "UNKNOWN";
}
std::cout << " endian" << std::endl;
}
</code></pre>
<p><strong>Edit:</strong></p>
<p>I can try dereferencing the pointer offset to the endianValues array but I'm still not sure if it will end up defaulting to 0 (the first explicitly set value in the array).</p>
<pre><code>constexpr hl_endianness getEndianOrder() {
return
(0x00 == *endianValues) // If Little Endian Byte Order,
? HL_LITTLE_ENDIAN // return 0 for little endian.
: (0x03 == *endianValues) // Else if Big Endian Byte Order,
? HL_BIG_ENDIAN // return 1 for big endian.
: (0x02 == *endianValues) // Else if PDP Endian Byte Order,
? HL_PDP_ENDIAN // return 2 for pdp endian.
: HL_UNKNOWN_ENDIAN; // Else return -1 for wtf endian.
}
</code></pre>
<p><strong>Edit #2</strong></p>
<p>So after looking into how the bits might be stored on different systems, I finally realized that I might be able to just use a single bit to test for endianness. It looks to be much less error-prone than using an array and I still get the correct answer on my Windows box.</p>
<pre><code>enum hl_endianness : uint32_t {
HL_LITTLE_ENDIAN = 0x00000001,
HL_BIG_ENDIAN = 0x01000000,
HL_PDP_ENDIAN = 0x00010000,
HL_UNKNOWN_ENDIAN = 0xFFFFFFFF
};
/**
* A simple function that can be used to help determine a program's endianness
* at compile-time.
*/
constexpr hl_endianness getEndianOrder() {
return
((1 & 0xFFFFFFFF) == HL_LITTLE_ENDIAN)
? HL_LITTLE_ENDIAN
: ((1 & 0xFFFFFFFF) == HL_BIG_ENDIAN)
? HL_BIG_ENDIAN
: ((1 & 0xFFFFFFFF) == HL_PDP_ENDIAN)
? HL_PDP_ENDIAN
: HL_UNKNOWN_ENDIAN;
}
#define HL_ENDIANNESS getEndianOrder()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T17:56:11.433",
"Id": "79783",
"Score": "0",
"body": "Or `#include <boost/predef/detail/endian_compat.h>` and then test for `BOOST_LITTLE_ENDIAN` or `BOOST_BIG_ENDIAN` or `BOOST_PDP_ENDIAN`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T18:06:45.033",
"Id": "79784",
"Score": "1",
"body": "@Loki I would rather not use Boost since this is also a personal exercise in learning how different computers process their data. Although if it was for production code then Boost would definitely not be a bad idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T08:04:14.910",
"Id": "389308",
"Score": "0",
"body": "In C++20, you can use [`std::endian`](https://en.cppreference.com/w/cpp/types/endian): https://wandbox.org/permlink/3FkeNpZx5Ix4PbdP."
}
] | [
{
"body": "<p>Just a couple points:</p>\n\n<ol>\n<li><p>Endian-ness is not generally based on the Operating System but on the processor. For example, Intel x86 processors are little-endian regardless of it running Windows or Linux.</p></li>\n<li><p>Your code will always return <code>HL_LITTLE_ENDIAN</code>. Why? Because if</p>\n\n<pre><code>static constexpr uint8_t endianValues[4] = {0, 1, 2, 3};\n</code></pre>\n\n<p>then <code>endianValues[0] == 0</code> will always be true! Suppose you had</p>\n\n<pre><code>char x[4] = {'c','o','d', 'e'};\n</code></pre>\n\n<p>Don't you think it would be shocking if <code>x[0] == 'e'</code> instead of <code>x[0] == 'c'</code>?</p>\n\n<p>The standard way is to use a union. Something like this:</p>\n\n<pre><code>union endian_tester {\n uint32_t n;\n uint8_t p[4];\n};\n\nconst endian_tester sample = {0x01020304}; // this initializes .n\n\nconstexpr hl_endianness getEndianOrder() {\n return\n (0x04 == sample.p[0]) // If Little Endian Byte Order,\n ? HL_LITTLE_ENDIAN \n : (0x01 == sample.p[0]) // Else if Big Endian Byte Order,\n ? HL_BIG_ENDIAN \n : (0x02 == sample.p[0]) // Else if PDP Endian Byte Order,\n ...(etc)...\n</code></pre>\n\n<p>Be aware that <code>constexpr</code> isn't fully supported in my version of Visual Studio 2013 Express.</p></li>\n<li><p>Not clear to me why you need to use fancy values for <code>HL_LITTLE_ENDIAN</code>, <code>HL_BIG_ENDIAN</code>, etc. You can use 1, 2, etc instead of 0x03020100, 0x00010203, etc.</p></li>\n<li><p>A related question answered on Stack Overflow (<a href=\"https://stackoverflow.com/questions/1001307/detecting-endianness-programmatically-in-a-c-program\">Detecting endianness programmatically in a C++ program</a>)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T08:05:35.910",
"Id": "79739",
"Score": "0",
"body": "Some processors can run in either big- or little-endian mode, [leaving the choice up to the operating system](http://www.linux-mips.org/wiki/Endianess). However, Windows will probably only ever run in [little-endian mode](http://support.microsoft.com/kb/102025)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T08:23:57.047",
"Id": "79740",
"Score": "0",
"body": "I originally tried a union but got errors from G++ for undefined behavior. After setting the data for one member, then trying to access the other, I'll get errors that prevent the code from compiling. I figured the current method would be a safe bet, but completely overlooked how the data would be accessed through an array. The problem is that using behavior defined by the standard seems to limit how byte-level data can be access during compilation. Neither casting to another data type or bit-leven operations seem to work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T16:37:44.783",
"Id": "79780",
"Score": "0",
"body": "@icdae you're right; I think someone mentioned that the standard technically prevents setting a union with one field but accessing it with a different one. But many compilers allow it. In that Stack Overflow link, there is one answer that uses the idea of casting `int` to `char` which might work better (but you should try `uint32_t` instead of `int`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-15T10:36:01.880",
"Id": "204196",
"Score": "0",
"body": "Your union \"standard way\" has undefined behavior according to the _Standard_."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-06T19:44:46.603",
"Id": "238825",
"Score": "0",
"body": "@200_success True, however any particular module of code running on a bi-endian machine is compiled *for a specific endianness*. The processor can't change its endianness in the middle of a binary, and expect that same binary to execute correctly henceforth."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-01T08:43:10.363",
"Id": "249594",
"Score": "3",
"body": "-1. Using unions for type punning in C++ is undefined behavior."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T07:57:11.617",
"Id": "45676",
"ParentId": "45675",
"Score": "4"
}
},
{
"body": "<p>I would change this:</p>\n\n<pre><code>static constexpr uint8_t endianValues[4] = {0, 1, 2, 3};\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code>static const uint32_t value = HL_LITTLE_ENDIAN; // 0x03020100\nstatic const uint8_t* endianValues = (uint8_t*)&value;\n</code></pre>\n\n<p><strong>Alternatively</strong>, you can change the <code>getEndianOrder</code> function to read the <code>endianValues</code> array as a <code>uint32</code>, but you will have to add a preprocessor directive (<code>#pragma</code>) to make sure that it is placed in a memory address aligned to 4 bytes (and that by itself might yield some platform-dependency issues, which is pretty much in contrast with your goal here to begin with):</p>\n\n<pre><code>constexpr hl_endianness getEndianOrder()\n{\n switch (*(uint32_t*)endianValues))\n {\n case HL_LITTLE_ENDIAN: return HL_LITTLE_ENDIAN;\n case HL_BIG_ENDIAN: return HL_BIG_ENDIAN;\n case HL_PDP_ENDIAN: return HL_PDP_ENDIAN;\n }\n return HL_UNKNOWN_ENDIAN;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T18:17:39.180",
"Id": "79785",
"Score": "0",
"body": "I tried your solution (had to remove the switch statement to make it a constexpr function) but I believe this will always return as little endian. Since the value stored in `HL_LITTLE_ENDIAN` is how it will actually be stored in memory on all computers, retrieving an 8-bit pointer to `value` is always going to grab the same value of `0x03`. I tried another solution though end edited it into the original question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T18:21:00.543",
"Id": "79787",
"Score": "0",
"body": "@icdae: It's not an 8-bit pointer, it's a 32-bit pointer (look inside the `switch` statement that you removed). Though I have to admit, I'm not really sure how it is applied into a `constexpr` during compile-time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T18:37:05.253",
"Id": "79793",
"Score": "0",
"body": "Oops, I misspoke (just woke up, everything's a bit fuzzy); being a pointer to a constant value won't change how the value itself is stored in memory. The function will always return the same result since `value = HL_LITTLE_ENDIAN`. As for the switch statement, one of the restrictions for a constexpr statement is that the body of the function can only consist of a single return statement. In this case the switch can be converted to a simple series of ternary operators."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T19:17:07.130",
"Id": "79797",
"Score": "0",
"body": "@icdae: Please note the emphasis on the word **Alternatively**, which means that you should leave `endianValues[4] = {0, 1, 2, 3}` as is, but read it using `*(uint32_t*)endianValues)`. The `value` variable is meant to be used **only in the first option suggested**."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-01T08:44:08.760",
"Id": "249596",
"Score": "0",
"body": "-1, this violates strict aliasing rules."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-01T10:27:05.260",
"Id": "249616",
"Score": "0",
"body": "@FaTony: I have pretty much mentioned that in `you will have to... make sure that it is placed in a memory address aligned to 4 bytes (and that by itself might yield some platform-dependency issues...)`."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T17:42:47.673",
"Id": "45700",
"ParentId": "45675",
"Score": "1"
}
},
{
"body": "<p>You have to use predefined compiler macros (<code>\\__BIG_ENDIAN__</code> or <code>\\__LITTLE_ENDIAN__</code> with clang, or <code>\\__BYTE_ORDER__</code> with gcc).</p>\n\n<p>The other compiler macro tricks mentioned will only detect the endianness of the architecture you are compiling on, not the endianness of the architecture you are compiling for, so something like this is wrong:</p>\n\n<pre><code>\\#define IS_BIG_ENDIAN ('\\x01\\x02\\x03\\x04' == 0x01020304)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-05T22:15:30.957",
"Id": "127647",
"ParentId": "45675",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T06:34:30.500",
"Id": "45675",
"Score": "4",
"Tags": [
"c++",
"c++11",
"integer",
"portability"
],
"Title": "Checking endianness at compile-time"
} | 45675 |
<p>Given a directed connected graphs, find all paths from source to destination.</p>
<p>Looking for code review, optimizations and best practices. Also need help figuring out complexity, which in my best attempt is O(E!), where E is the number of edges. </p>
<pre><code>class GraphFindAllPaths<T> implements Iterable<T> {
/* A map from nodes in the graph to sets of outgoing edges. Each
* set of edges is represented by a map from edges to doubles.
*/
private final Map<T, Map<T, Double>> graph = new HashMap<T, Map<T, Double>>();
/**
* Adds a new node to the graph. If the node already exists then its a
* no-op.
*
* @param node Adds to a graph. If node is null then this is a no-op.
* @return true if node is added, false otherwise.
*/
public boolean addNode(T node) {
if (node == null) {
throw new NullPointerException("The input node cannot be null.");
}
if (graph.containsKey(node)) return false;
graph.put(node, new HashMap<T, Double>());
return true;
}
/**
* Given the source and destination node it would add an arc from source
* to destination node. If an arc already exists then the value would be
* updated the new value.
*
* @param source the source node.
* @param destination the destination node.
* @param length if length if
* @throws NullPointerException if source or destination is null.
* @throws NoSuchElementException if either source of destination does not exists.
*/
public void addEdge (T source, T destination, double length) {
if (source == null || destination == null) {
throw new NullPointerException("Source and Destination, both should be non-null.");
}
if (!graph.containsKey(source) || !graph.containsKey(destination)) {
throw new NoSuchElementException("Source and Destination, both should be part of graph");
}
/* A node would always be added so no point returning true or false */
graph.get(source).put(destination, length);
}
/**
* Removes an edge from the graph.
*
* @param source If the source node.
* @param destination If the destination node.
* @throws NullPointerException if either source or destination specified is null
* @throws NoSuchElementException if graph does not contain either source or destination
*/
public void removeEdge (T source, T destination) {
if (source == null || destination == null) {
throw new NullPointerException("Source and Destination, both should be non-null.");
}
if (!graph.containsKey(source) || !graph.containsKey(destination)) {
throw new NoSuchElementException("Source and Destination, both should be part of graph");
}
graph.get(source).remove(destination);
}
/**
* Given a node, returns the edges going outward that node,
* as an immutable map.
*
* @param node The node whose edges should be queried.
* @return An immutable view of the edges leaving that node.
* @throws NullPointerException If input node is null.
* @throws NoSuchElementException If node is not in graph.
*/
public Map<T, Double> edgesFrom(T node) {
if (node == null) {
throw new NullPointerException("The node should not be null.");
}
Map<T, Double> edges = graph.get(node);
if (edges == null) {
throw new NoSuchElementException("Source node does not exist.");
}
return Collections.unmodifiableMap(edges);
}
/**
* Returns the iterator that travels the nodes of a graph.
*
* @return an iterator that travels the nodes of a graph.
*/
@Override public Iterator<T> iterator() {
return graph.keySet().iterator();
}
}
/**
* Given a connected directed graph, find all paths between any two input points.
*/
public class FindAllPaths<T> {
private final GraphFindAllPaths<T> graph;
/**
* Takes in a graph. This graph should not be changed by the client
*/
public FindAllPaths(GraphFindAllPaths<T> graph) {
if (graph == null) {
throw new NullPointerException("The input graph cannot be null.");
}
this.graph = graph;
}
private void validate (T source, T destination) {
if (source == null) {
throw new NullPointerException("The source: " + source + " cannot be null.");
}
if (destination == null) {
throw new NullPointerException("The destination: " + destination + " cannot be null.");
}
if (source.equals(destination)) {
throw new IllegalArgumentException("The source and destination: " + source + " cannot be the same.");
}
}
/**
* Returns the list of paths, where path itself is a list of nodes.
*
* @param source the source node
* @param destination the destination node
* @return List of all paths
*/
public List<List<T>> getAllPaths(T source, T destination) {
validate(source, destination);
List<List<T>> paths = new ArrayList<List<T>>();
recursive(source, destination, paths, new LinkedHashSet<T>());
return paths;
}
// so far this dude ignore's cycles.
private void recursive (T current, T destination, List<List<T>> paths, LinkedHashSet<T> path) {
path.add(current);
if (current == destination) {
paths.add(new ArrayList<T>(path));
path.remove(current);
return;
}
final Set<T> edges = graph.edgesFrom(current).keySet();
for (T t : edges) {
if (!path.contains(t)) {
recursive (t, destination, paths, path);
}
}
path.remove(current);
}
public static void main(String[] args) {
GraphFindAllPaths<String> graphFindAllPaths = new GraphFindAllPaths<String>();
graphFindAllPaths.addNode("A");
graphFindAllPaths.addNode("B");
graphFindAllPaths.addNode("C");
graphFindAllPaths.addNode("D");
graphFindAllPaths.addEdge("A", "B", 10);
graphFindAllPaths.addEdge("A", "C", 10);
graphFindAllPaths.addEdge("B", "D", 10);
graphFindAllPaths.addEdge("C", "D", 10);
graphFindAllPaths.addEdge("B", "C", 10);
graphFindAllPaths.addEdge("C", "B", 10);
FindAllPaths<String> findAllPaths = new FindAllPaths<String>(graphFindAllPaths);
List<List<String>> paths = new ArrayList<List<String>>();
// ABD
List<String> path1 = new ArrayList<String>();
path1.add("A"); path1.add("B"); path1.add("D");
// ABCD
List<String> path2 = new ArrayList<String>();
path2.add("A"); path2.add("B"); path2.add("C"); path2.add("D");
//ACD
List<String> path3 = new ArrayList<String>();
path3.add("A"); path3.add("C"); path3.add("D");
//ABCD
List<String> path4 = new ArrayList<String>();
path4.add("A"); path4.add("C"); path4.add("B"); path4.add("D");
paths.add(path1);
paths.add(path2);
paths.add(path3);
paths.add(path4);
findAllPaths.getAllPaths("A", "D");
assertEquals(paths, findAllPaths.getAllPaths("A", "D"));
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T15:46:19.507",
"Id": "79777",
"Score": "2",
"body": "You should probably specify if it is assumed that there are no cycles. It is not a small detail."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T18:31:21.227",
"Id": "79790",
"Score": "1",
"body": "It deals with cycles"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-17T03:27:18.627",
"Id": "151580",
"Score": "0",
"body": "Your solution is almost perfect.\nHowever, you should use `current.equals(destination)` in the recursive method."
}
] | [
{
"body": "<p>This is really an interesting problem. First of all I want to mention that IMHO there is no polynomial solution to this task, because it is not an optimization problem. The required result is not max/min of something but an enumeration of all possible paths. I think that all possible paths may result in n! different paths in a complete graph, where n is the number of nodes. So finding a solution depends on the size of the input. If a big graph is on the input, then using this algorithm will take a lot of time and memory and probably won't finish. I don't know the exact usage of this solution, but I guess it is kind of a map/navigation app. If you don't mind I will mark some useful points and share my considerations:</p>\n\n<ol>\n<li>I don't see where you use the double value, which is held for every edge. I guess it will be used to compute the cost of a path and return the paths sorted by this criteria. If so consider finding only small set of the paths, one by one, every time using some popular algorithm for <a href=\"http://en.wikipedia.org/wiki/Shortest_path_problem\">shortest path problem</a></li>\n<li>If you have a sparse graph on the input, then using Map per node will result in a lot of heavy objects, holding just a couple of values. This will increase the memory consumption unnecessarily. I don't know the use case, what type of nodes will be used (T), but I will suggest using single map from int to T and using the integers as node numbers. Then you can use double[][] matrix to hold the edge values and use the integers as indexes in the matrix. An example:\n<ul>\n<li>0 -> \"A\"</li>\n<li>1 -> \"B\"</li>\n<li>2 -> \"C\"</li>\n</ul></li>\n</ol>\n\n<p>Then an edge \"A\" --4.2--> \"C\" will be presented like this: matrix[0][2] = 4.2. Again this will result in a lot of unused cells of the matrix. Even a better solution will be to have a single array/list holding arrays/lists of neighbours for each node. Actually you are iterating over the neighbours so you do not need a HashMap, simply holding an list of key-value pairs is enough.What i mean is: <code>List<List<Double>> nodes</code> which represents the graph, and nodes.get(i) is another list holding pairs like (nodeNumber, edgeCost). Using the previous example:</p>\n\n<pre><code>List<Double> aNeighbours = nodes.get(0);\naNeighbours.set(2, 4.2);\n</code></pre>\n\n<p>If you use <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html\">ArrayList</a> consider providing small initial capacity, because the default is 16 I think. </p>\n\n<p>I hope you find a working solution for this problem :).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T10:29:44.587",
"Id": "79747",
"Score": "2",
"body": "I strongly disagree about your second point. Using a `Map<Node, Map<Node, Value>>` is the objectively best way to represent a sparse graph in this context. If the graph is not sparse, then of course using a matrix representation is preferable memory-wise. Your `List<List<Value>>` idea seems like a specialization of using `Map`s, but has the drawback that it's not really sparse either (it's actually the exact same as your matrix representation). Using `Map`s has the advantage over matrix representations that fetching the set of outgoing edges doesn't have to be an O(n) operation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T11:05:43.490",
"Id": "79749",
"Score": "0",
"body": "The List<List<Value>> won't have empty cells if you use LinkedList, but not the self-expanding ArrayList. I agree with you that using map will bring O(1) access to an edge, but as I saw the algorithm iterates over all neighbours and does not access them by key. And my concern about using a HashMap is that it has default load factor of 0.75 and in its best you will only use 0.75% of the allocated memory. It will resize itself (possibly double) when the load factor is reached. Actually you have a good point about using a Map. Here the productivity depends on the implementations of Map and List."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T11:36:21.543",
"Id": "79755",
"Score": "2",
"body": "If you use `List<List<Double>>`, then the only thing encoding which double belongs to which edge is the double's position in the list. Every possible edge must be represented, whether or not such an edge is present."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T09:52:07.193",
"Id": "45684",
"ParentId": "45678",
"Score": "6"
}
},
{
"body": "<p>This is beautiful, easy to read, and well-documented code. It is a joy reading this code, and there is very little to improve on the Java side. </p>\n\n<p>The greatest weakness that shows in this code is not your skill with Java (which surpasses mine by far), but your knowledge of the English language.</p>\n\n<ul>\n<li>In the <code>addEdge</code> JavaDoc you talk about <em>arcs</em> not <em>edges</em>.</li>\n<li>The grammer in the error messages of that same method could be improved: “<em>Source and Destination, both should be non-null.</em>” could be “<em>Both source and destination should be non-null</em>” or “<em>Source and destination should both be non-null</em>”.</li>\n<li>That method also sports the very confusing JavaDoc “<em>@param length if length if</em>” – I am not sure what that is supposed to mean.</li>\n</ul>\n\n<p>But let's move on to technical aspects.</p>\n\n<ul>\n<li><p>There is a nice bug in the <code>recursive</code> method: You are comparing <code>T</code> instances via <code>==</code>:</p>\n\n<pre><code>if (current == destination) {\n</code></pre>\n\n<p>However, this defaults to comparing pointers. It only works here because the constant strings <code>\"A\"</code>, <code>\"B\"</code>, etc. are pooled by your Java implementation. Unless comparing for identity is what you actually want, please compare for equivalence: <code>current.equals(destination)</code>.</p></li>\n<li><p>The comment that <code>recursive</code> would be <em>ignoring</em> cycles is wrong – it will only construct paths where each node is visited at most once. This is the only correct way to handle cycles, otherwise there would be an infinite number of paths in a cyclic graph.</p></li>\n<li><p>The error messages from <code>validate</code> make no sense.</p>\n\n<pre><code>if (source == null) {\n throw new NullPointerException(\"The source: \" + source + \" cannot be null.\");\n</code></pre>\n\n<p>So we'd get “<em>The source: null cannot be null</em>” as an error message. This is not helpful, and I'd suggest instead:</p>\n\n<pre><code>if (source == null) {\n throw new NullPointerException(\"The \\\"source\\\" parameter cannot be null.\");\n</code></pre></li>\n<li><p>In your testing code, you go through too much hassle generating the expected <code>paths</code>. I am very fond of <code>Arrays.asList(…)</code>:</p>\n\n<pre><code>List<List<String>> paths = Arrays.asList(\n Arrays.asList(\"A\", \"B\", \"D\"),\n Arrays.asList(\"A\", \"B\", \"C\", \"D\"),\n Arrays.asList(\"A\", \"C\", \"D\"),\n Arrays.asList(\"A\", \"C\", \"B\", \"D\")\n);\n</code></pre>\n\n<p>This code is terse and self-documenting. You put the paths into comments in addition to specifying them as code, which went wrong when the comment said <code>ABCD</code> above the <code>ACBD</code> path ;-)</p>\n\n<p>Furthermore, you test that the order of the returned paths is identical. The order of the paths should be considered irrelevant (you're actually interested in the set of paths), and unspecified as the usage of <code>HashMap</code> makes no guarantees about the order in which keys are kept. Indeed, you are iterating over the <code>keySet()</code>, which will determine the order of paths! A better test for equality might be:</p>\n\n<pre><code>assertEquals(new HashSet<List<String>>(paths), new HashSet<List<String>>(result));\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T18:40:36.393",
"Id": "79794",
"Score": "0",
"body": "path is a LinkedHashSet"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T18:50:29.500",
"Id": "79796",
"Score": "0",
"body": "@JavaDeveloper sorry for that, I've deleted that paragraph now. Don't know what I was thinking"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T05:53:54.003",
"Id": "79844",
"Score": "0",
"body": "I am glad I coded as you would have given me a feedback, further asserts my confidence"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-16T16:46:00.730",
"Id": "94875",
"Score": "1",
"body": "Referenced in [Graphic Design Review Proposal](http://discuss.area51.stackexchange.com/questions/14124/do-you-think-that-a-code-review-style-site-for-graphic-designers-will-be-support) FYI."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T11:56:50.767",
"Id": "45690",
"ParentId": "45678",
"Score": "17"
}
},
{
"body": "<p>Just a few minor things:</p>\n\n<ol>\n<li><p>The comment is not correct here, it should be <code>ACBD</code>:</p>\n\n<blockquote>\n<pre><code>//ABCD\nList<String> path4 = new ArrayList<String>();\npath4.add(\"A\"); path4.add(\"C\"); path4.add(\"B\"); path4.add(\"D\");\n</code></pre>\n</blockquote>\n\n<p>You could use <a href=\"https://code.google.com/p/guava-libraries/\">Guava</a>'s <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Lists.html#newArrayList%28E...%29\"><code>newArrayList</code></a> (or write a similar method) to remove some duplication from the testcode:</p>\n\n<pre><code>List<String> path4 = newArrayList(\"A\", \"C\", \"B\", \"D\");\n</code></pre></li>\n<li><p>The first call is unnecessary here:</p>\n\n<blockquote>\n<pre><code>findAllPaths.getAllPaths(\"A\", \"D\");\n\nassertEquals(paths, findAllPaths.getAllPaths(\"A\", \"D\"));\n</code></pre>\n</blockquote></li>\n<li><p>For this:</p>\n\n<blockquote>\n<pre><code>if (graph.containsKey(node)) return false;\n</code></pre>\n</blockquote>\n\n<p>According to the <a href=\"http://www.oracle.com/technetwork/java/codeconventions-142311.html#430\">Code Conventions for the Java Programming Language</a>,</p>\n\n<blockquote>\n <p>if statements always use braces {}.</p>\n</blockquote>\n\n<p>Omitting them is error-prone. I've found the one-liner above hard to read because if you scan the code line by line it's easy to miss that at the end of the line there is a <code>return</code> statement.</p></li>\n<li><p>I'd rename </p>\n\n<ul>\n<li><code>validate</code> to <code>validateNotSame</code>,</li>\n<li><code>paths</code> to <code>expectedPaths</code>,</li>\n</ul>\n\n<p>for better clarity.</p></li>\n<li><p><code>GraphFindAllPaths</code> could be simply <code>Graph</code>.</p></li>\n<li><p>From Clean Code, page 25: </p>\n\n<blockquote>\n <p>Classes and objects should have noun or noun phrase names like <code>Customer</code>, <code>WikiPage</code>,\n <code>Account</code>, and <code>AddressParser</code>. [...] A class name should not be a verb.</p>\n</blockquote>\n\n<p>Consider <code>AllPathFinder</code> instead of <code>FindAllPaths</code>, for example.</p></li>\n<li><p>You might want to create a defensive copy here:</p>\n\n<blockquote>\n<pre><code>public FindAllPaths(GraphFindAllPaths<T> graph) {\n if (graph == null) {\n throw new NullPointerException(\"The input graph cannot be null.\");\n }\n this.graph = graph;\n}\n</code></pre>\n</blockquote>\n\n<p>It would prohibit malicious clients to modify the internal data of the class and might save you a couple of hours of debugging. (<em>Effective Java, 2nd Edition, Item 39: Make defensive copies when needed</em>)</p></li>\n<li><p>The <code>Iterable</code> functionality and the <code>removeEdge</code> method are not used nor tested. You might be able to remove them.</p></li>\n<li><p>Test methods are usually in a <code>Test</code> file (FindAllPathsTest, for example) and run by JUnit. They are usually in a separated source folder which enables to not package <code>junit.jar</code> (and other test dependencies) with production code. <a href=\"https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html\">Maven's directory structure</a> is a well-known project structure, consider using it (as well as Maven, Gradle, or any other build tool).</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T18:41:49.630",
"Id": "79795",
"Score": "1",
"body": "I do agree with your naming conventions(eg: Graph), and seperate file for unit tests, but its just personally more convenient for me to club them all in a file. Although I agree with them"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T05:55:17.183",
"Id": "79846",
"Score": "0",
"body": "You might want to create a defensive copy here - I agree with this too however creating deep copy of graph isnt trivial."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T14:24:01.270",
"Id": "45694",
"ParentId": "45678",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "45690",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T08:03:01.657",
"Id": "45678",
"Score": "22",
"Tags": [
"java",
"algorithm",
"graph",
"complexity"
],
"Title": "Find all paths from source to destination"
} | 45678 |
<p>With a positive outlook, I posted <a href="https://codegolf.stackexchange.com/questions/24904/how-many-squares-can-you-see">this challenge</a> at <a href="https://codegolf.stackexchange.com/">Programming Puzzles & Code Golf</a>. I tried to come up with my own solution to the challenge which is as follows:</p>
<hr>
<p>The output is <em>displayed</em> (not yet exported to GIF) on a class extending <code>JPanel</code>:</p>
<pre><code>import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class Display extends JPanel implements Runnable {
private int points;
private int xRed;
private int yRed;
private int side;
// Side of the smallest square:
private static final int sideC = 80;
private static final int offSet = 20;
private Thread t;
private boolean stop;
private static final long updatePeriod = 1000;
public Display(int points) {
this.side = sideC;
this.points = points;
yRed = offSet;
xRed = yRed - side;
stop = false;
repaint();
start();
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2D = (Graphics2D) g;
// The stroke to apply.
BasicStroke stroke;
stroke = new BasicStroke(5.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
g2D.setStroke(stroke);
// Let the painting begin!
g2D.setColor(Color.WHITE);
g2D.fillRect(0, 0, getWidth(), getWidth());
g2D.setColor(Color.BLACK);
// paint the main grid.
for (int i = 0; i < points * sideC; i += sideC) {
for (int j = 0; j < points * sideC; j += sideC) {
g2D.drawRect(offSet + i, offSet + j, sideC, sideC);
}
}
// Paint the red square.
if (sideC * points >= side) {
g2D.setColor(Color.RED);
g2D.drawRect(xRed, yRed, side, side);
} else {
side = sideC;
yRed = offSet;
xRed = offSet - sideC;
}
}
@Override
public void run() {
while (side <= points * sideC && !stop) {
while (yRed < offSet + points * sideC && !stop) {
long s = System.currentTimeMillis();
repaint();
xRed += sideC;
if (xRed >= offSet + (points + 1) * sideC - side) {
xRed = offSet;
yRed += sideC;
}
if (yRed >= offSet + (points + 1) * sideC - side) {
yRed = offSet;
xRed = offSet - sideC;
break;
}
System.out.println(xRed + "\t" + yRed + "\t" + side);
try {
s = System.currentTimeMillis()- s;
s = s > 0 ? s : 500;
t.sleep(updatePeriod - s);
} catch (InterruptedException ie) {}
}
side += sideC;
}
}
public void start() {
System.out.println("Starting");
stop = false;
t = new Thread(this, "Hello!");
t.start();
}
public void stop() {
System.out.println("Stopping");
stop = true;
t = null;
}
}
</code></pre>
<p>The class extending <code>JFrame</code> is a very simple one (till now):</p>
<pre><code>import javax.swing.JFrame;
import javax.swing.SwingUtilities;
@SuppressWarnings("serial")
public class Squares extends JFrame {
public Squares() {
setSize(500, 500);
setDefaultCloseOperation(Squares.EXIT_ON_CLOSE);
setContentPane(new Display(5));
setVisible(true);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> { // Java 8 - lambda expression
new Squares();
});
}
}
</code></pre>
<hr>
<p>Sample output is:</p>
<p><img src="https://i.stack.imgur.com/3Nv06.png" alt="img1"><img src="https://i.stack.imgur.com/sisp5.png" alt="img2"></p>
<hr>
<p>Any help regarding simplification of the code, refactoring, cleaning up, improvisation, improving efficiency, the overall technique through comments, answers, downvotes (and perhaps upvotes?) would be greatly appreciated. Remarks on improving its <em>elegance</em> would be great!</p>
| [] | [
{
"body": "<ol>\n<li><p>A great comment from <a href=\"https://codereview.stackexchange.com/a/19459/7076\"><em>@tb-</em>'s answer</a>:</p>\n\n<blockquote>\n <p>Do not extend <code>JPanel</code>, instead have a private <code>JPanel</code> \n attribute and deal with it (Encapsulation). \n There is no need to give access to all \n <code>JPanel</code> methods for code dealing with a <code>UserPanel</code>\n instance. If you extend, you are forced to stay with this forever, \n if you encapsulate, you can change whenever you want without \n taking care of something outside the class.</p>\n</blockquote>\n\n<p>The is true for <code>JFrame</code>. It would also make <code>@SuppressWarnings(\"serial\")</code> unnecessary.</p>\n\n<p>So <code>Squares</code> would be something like this:</p>\n\n<pre><code>public class Squares {\n\n private final JFrame squareFrame = new JFrame();\n\n public Squares() {\n squareFrame.setSize(500, 500);\n squareFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n squareFrame.setContentPane(new Display(5));\n squareFrame.setVisible(true);\n }\n ...\n}\n</code></pre></li>\n<li><p>According to <a href=\"https://en.wikipedia.org/wiki/Event_dispatching_thread\" rel=\"nofollow noreferrer\">Wikipedia</a>:</p>\n\n<blockquote>\n <p>all user interface components should be created and <strong>accessed</strong> only from the AWT event dispatch thread.</p>\n</blockquote>\n\n<p>including <code>repaint()</code> in the <code>run</code> method (which is run by another thread). You should use <code>SwingUtilities.invokeLater</code> or <code>invokeAndWait</code> for this too:</p>\n\n<pre><code>try {\n SwingUtilities.invokeAndWait(() -> repaint());\n} catch (InvocationTargetException e) {\n throw new RuntimeException(e);\n} catch (InterruptedException e) {\n Thread.interrupted();\n break;\n}\n</code></pre></li>\n<li><p>Be careful about thread-safety. If you call <code>repaint()</code> on EDT it will use <code>xRed</code>, <code>yRed</code> etc from multiple threads (EDT and your own thread), so you need proper synchronization for visibility:</p>\n\n<blockquote>\n <p>[...] synchronization has no effect unless both read and write operations are synchronized.</p>\n</blockquote>\n\n<p>Source: <em>Effective Java, 2nd Edition, Item 66: Synchronize access to shared mutable data</em></p>\n\n<blockquote>\n <p>Locking is not just about mutual exclusion; it is also about memory visibility.\n To ensure that all threads see the most up-to-date values of shared mutable \n variables, the reading and writing threads must synchronize on a common lock.</p>\n</blockquote>\n\n<p>Source: <em>Java Concurrency in Practice, 3.1.3. Locking and Visibility</em>.</p>\n\n<p><code>stop</code> also suffers from proper synchronization. Changing its value (from another thread) might not be visible to your thread. For this I'd suggest you using an <code>AtomicBoolean</code> (which is thread safe).</p>\n\n<p>For doing proper synchronization between the timer thread and EDT you need to restructure the code but I guess it would be much easier with <a href=\"http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html\" rel=\"nofollow noreferrer\">Swing Timers</a> than your custom thread. It looks like that it has been designed for exactly these kind of problems.</p></li>\n<li><p>I would create another class for the <code>Runnable</code>/<code>run</code> implementation to fulfill the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single responsibility principle</a>. Currently it has too many responsibilities: draws the current state, update the current state, starts/stops the updating thread. It could be splitted to at least three classes. (You might not need this if you use Swing Timers - I'm not too familiar with them.)</p></li>\n<li><p>Calling overridable methods (like <code>stop</code>) from constructors is not a good practice. Child classes could see partially initialized objects in the overridden method. The <code>stop</code> should be <code>final</code> here. See <a href=\"https://stackoverflow.com/q/3404301/843804\">What's wrong with overridable method calls in constructors?</a> and <em>Effective Java 2nd Edition, Item 17: Design and document for inheritance, or else prohibit it</em></p></li>\n<li><p>The code calls a static method here on an instance which is misleading:</p>\n\n<blockquote>\n<pre><code>t.sleep(updatePeriod - s);\n</code></pre>\n</blockquote>\n\n<p>It should be the following:</p>\n\n<pre><code>Thread.sleep(updatePeriod - s);\n</code></pre></li>\n<li><p>The code never calls <code>stop</code>. If it's not necessary remove it, otherwise use it.</p></li>\n<li><p>I'd use longer variable names than these ones:</p>\n\n<blockquote>\n<pre><code>private Thread t;\nlong s = System.currentTimeMillis();\n</code></pre>\n</blockquote>\n\n<p>Choose variable names which describes their purpose. <code>t</code> could be <code>updateThread</code> and <code>s</code> could be <code>currentTimeMillis</code> ro <code>frameStartTime</code>.</p></li>\n<li><p>According to the Java Code Conventions, constants should be <code>UPPERCASED_WITH_UNDERSCORES</code>:</p>\n\n<blockquote>\n<pre><code>private static final int sideC = 80;\nprivate static final int offSet = 20;\nprivate static final long updatePeriod = 1000;\n</code></pre>\n</blockquote></li>\n<li><blockquote>\n<pre><code>BasicStroke stroke;\nstroke = new BasicStroke(5.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);\n</code></pre>\n</blockquote>\n\n<p>This could be one line:</p>\n\n<blockquote>\n<pre><code>BasicStroke stroke = new BasicStroke(5.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);\n</code></pre>\n</blockquote></li>\n<li><p>Use method names instead of commenting:</p>\n\n<blockquote>\n<pre><code>// paint the main grid.\nfor (int i = 0; i < points * sideC; i += sideC) {\n for (int j = 0; j < points * sideC; j += sideC) {\n g2D.drawRect(offSet + i, offSet + j, sideC, sideC);\n }\n}\n// Paint the red square.\nif (sideC * points >= side) {\n g2D.setColor(Color.RED);\n g2D.drawRect(xRed, yRed, side, side);\n} else {\n side = sideC;\n yRed = offSet;\n xRed = offSet - sideC;\n}\n</code></pre>\n</blockquote>\n\n<p>It could be:</p>\n\n<pre><code>paintMainGrid(g2D);\npaintRedSquare(g2D);\n\n...\n\nprivate void paintMainGrid(Graphics2D g2D) {\n for (int i = 0; i < points * sideC; i += sideC) {\n for (int j = 0; j < points * sideC; j += sideC) {\n g2D.drawRect(offSet + i, offSet + j, sideC, sideC);\n }\n }\n}\n\nprivate void paintRedSquare(Graphics2D g2D) {\n if (sideC * points >= side) {\n g2D.setColor(Color.RED);\n g2D.drawRect(xRed, yRed, side, side);\n } else {\n side = sideC;\n yRed = offSet;\n xRed = offSet - sideC;\n }\n}\n</code></pre>\n\n<p>Using these methods hides unnecessary details, increases the abstraction level of the code and it's easier to read. You still can check the details inside <code>paintMainGrid</code> and <code>paintRedSquare</code> if you need that but usually readers/maintainers happier with a higher level overview of the method which is easier to understand. (<a href=\"https://codereview.stackexchange.com/a/42504/7076\">This answer</a> and question contain another example.)</p>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Don’t Use a Comment When You Can Use a Function or a Variable</em>, p67)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T11:30:21.060",
"Id": "79753",
"Score": "0",
"body": "This is why I love this more than [Stack Overflow](http://stackoverflow.com/)! :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T11:33:11.910",
"Id": "79754",
"Score": "0",
"body": "Also, could you _please_ [elaborate] a bit more on points 1. 2. and 3. (preferrably all!) with some _very simple example code_?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T13:36:37.287",
"Id": "79760",
"Score": "1",
"body": "@ambigram_maker: I'm glad to hear that :) If you have time feel free to help us graduating, I bet you can find another useful questions answers on the site (http://codereview.stackexchange.com/questions/tagged/swing) to [vote on](http://meta.codereview.stackexchange.com/q/612/7076)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T13:37:07.170",
"Id": "79761",
"Score": "0",
"body": "@ambigram_maker: Answer updated, check it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T04:38:31.750",
"Id": "79838",
"Score": "0",
"body": "Could you help me on one more tiny aspect? I believe that the `while` loop i'm using can be improved. Could I get some suggestions?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T11:12:54.557",
"Id": "79864",
"Score": "1",
"body": "@ambigram_maker: I don't have time now but I'll try to check it later."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T09:30:06.343",
"Id": "45683",
"ParentId": "45681",
"Score": "8"
}
},
{
"body": "<p>A few minor notes about the nested loops:</p>\n\n<ol>\n<li><p>First, I'd create guard clauses for the stop flag instead of the <code>&&</code>. I've found that easier to follow:</p>\n\n<pre><code>while (side <= points * sideC) {\n if (stop) {\n return;\n }\n while (yRed < offSet + points * sideC) {\n if (stop) {\n return;\n }\n ...\n }\n ...\n\n}\n</code></pre>\n\n<p>(If you use Swing Timers, I guess you won't need it at all.)</p></li>\n<li><p>Then, <code>points</code> is <code>final</code>, <code>offset</code> and <code>sideC</code> are <code>static final</code>, so you could use a few explanatory variable before the loops:</p>\n\n<pre><code>final int maxSide = points * sideC;\nwhile (side <= maxSide) {\n if (stop) {\n return;\n }\n final int maxYRed = offSet + maxSide;\n while (yRed < maxYRed) {\n if (stop) {\n return;\n }\n</code></pre>\n\n<p>Feel free to choose better names, I'm just guessing here.</p>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>; <em>Refactoring: Improving the Design of Existing Code by Martin Fowler</em>, <em>Introduce Explaining Variable</em>)</p></li>\n<li><p><code>offSet + (points + 1) * sideC</code> also never changes it could also have an explanatory variable.</p></li>\n</ol>\n\n<p>That's all I have now, maybe somebody could do a more in depth review. If not, feel free to post <a href=\"https://codereview.meta.stackexchange.com/q/1065/7076\">a follow-up question</a> with the refactored code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T18:45:21.837",
"Id": "45970",
"ParentId": "45681",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T08:35:34.323",
"Id": "45681",
"Score": "4",
"Tags": [
"java",
"multithreading",
"swing"
],
"Title": "How many squares can you see?"
} | 45681 |
<p>I have tried to implement a Least Recently Used cache with only C++ STL containers. The main thing that I keep asking my self the static variable called <code>garbage_val</code>. Is it a good practice to have such a <code>static</code> variable just for garbage values? </p>
<pre><code>template<typename Key, typename Value>
class LRU_Cache
{
struct Node
{
Key k;
Value v;
};
public:
static Value garbage_val;
LRU_Cache(unsigned int capacity)
{
capacity_ = capacity;
}
Value get(Key key)
{
auto node = cache_.find(key);
if(node == cache_.end())
{
return garbage_val;
}
Value val = (*(node->second)).v;
recentlyList_.erase(node->second);
Node n; n.v = val; n.k = key;
recentlyList_.push_back(n);
cache_[key] = --recentlyList_.end();
return val;
}
void set(Key key, Value val)
{
auto node = cache_.find(key);
if(node != cache_.end())
{
recentlyList_.erase(node->second);
}
else
{
evict_if_needed();
}
Node n; n.v = val; n.k = key;
recentlyList_.push_back(n);
cache_[key] = --recentlyList_.end();
}
void evict_if_needed()
{
if(cache_.size() >= capacity_)
{
auto node = cache_.find(recentlyList_.begin()->k);
recentlyList_.pop_front();
cache_.erase(node);
}
}
virtual ~LRU_Cache(void)
{
}
void print()
{
std::cout << "Objects in Memory:" << std::endl;
for(auto& c : cache_)
{
std::cout << "(" << c.first << "," << (*(c.second)).v << ")" << std::endl;
}
std::cout << "Recently used:" << std::endl;
for(auto& r : recentlyList_)
{
std::cout << "(" << r.k << "," << r.v << ")" << std::endl;
}
}
private:
LRU_Cache(void){}
std::unordered_map<Key, typename std::list<Node>::iterator> cache_;
std::list<Node> recentlyList_;
unsigned int capacity_;
};
template<typename Key,typename Value> Value LRU_Cache<Key,Value> ::garbage_val;
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>Is it a good practice to have such a static variable just for garbage values?</p>\n</blockquote>\n\n<p>Maybe not:</p>\n\n<ul>\n<li><code>garbage_val</code> is a <code>Value</code>, so if you return it, then the caller doesn't know whether the <code>get</code> succeeded.</li>\n<li>If <code>garbage_val</code> is supposed to be a magic number (an impossible <code>Value</code>), different users of the class might want different magic numbers ... so why isn't <code>garbage_val</code> an instance member instead of a static member?</li>\n<li>Normally container classes expect the caller to check that <code>iterator != end()</code> before dereferencing the iterator.</li>\n</ul>\n\n<p>Instead, the following methods might be appropriate:</p>\n\n<pre><code>// throws an exception if key does exist.\nValue get(Key key) { ... }\n// tests whether key exists: use this before calling get.\nbool contains(Key key) { ... }\n// return true and initializes value iff key exists.\n// if key doesn't exist then valueOut is not initialized. \nbool tryGet(Key key, Value& valueOut) { ... }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T18:35:44.327",
"Id": "45703",
"ParentId": "45682",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "45703",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T09:19:22.720",
"Id": "45682",
"Score": "2",
"Tags": [
"c++",
"c++11",
"cache",
"stl"
],
"Title": "LRU Cache with a static variable for garbage value"
} | 45682 |
<p>Functionality that overwrite standard error message with trace to user friendly message with error number stored in DB.</p>
<p>Not yet completed some stuff with trx...</p>
<p>Please review this.</p>
<p><strong>DB table:</strong></p>
<pre><code>CREATE TABLE stored_error_msg
(
id number PRIMARY KEY
,msg VARCHAR2(2000)
,trace CLOB
,browser VARCHAR2(2000)
,date date
,user VARCHAR2(100)
,ses_id number
);
</code></pre>
<p><strong>@ UI</strong></p>
<pre><code>this.getCurrent().setErrorHandler(new StoredErrorWriter());
</code></pre>
<p><strong>StoredErrorWriter</strong></p>
<pre><code>package components;
import java.io.PrintWriter;
import java.io.StringWriter;
import com.vaadin.server.DefaultErrorHandler;
import com.vaadin.server.ErrorEvent;
import com.vaadin.server.ErrorHandler;
import com.vaadin.server.ErrorMessage;
import com.vaadin.server.UserError;
import com.vaadin.server.WebBrowser;
import com.vaadin.ui.AbstractComponent;
import com.vaadin.ui.UI;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* @author: Kristaps Zukovskis
* Write info about: user, date, err_msg, backtrace, browser info, ses_id
* @ DB table stored_error_msg
*/
public class StoredErrorWriter implements ErrorHandler {
private static final long serialVersionUID = 5117130906083582416L;
public static String ERROR_MSG = "System error! Error number in journal :";
private Logger logger = Logger.getAnonymousLogger();
@Override
public void error(ErrorEvent event) {
Throwable t = event.getThrowable();
if (t != null) {
String trace = getTrace(t);
final String msg = t.getMessage();
AbstractComponent component = DefaultErrorHandler
.findAbstractComponent(event);
if (component != null) {
final Integer errorNumber = InsertTrace(msg,trace);
ErrorMessage errorMessage = new UserError(ERROR_MSG
+ errorNumber);
if (errorMessage != null) {
component.setComponentError(errorMessage);
logger.log(Level.SEVERE, trace);
return;
}
}
}
DefaultErrorHandler.doDefault(event);
}
private static String getTrace(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
return sw.toString();
}
public static String getInfo() {
@SuppressWarnings("deprecation")
WebBrowser browser = UI.getCurrent().getSession().getBrowser();
String browserName = "unknown";
if (browser.isOpera())
browserName = "Opera";
else if (browser.isSafari())
browserName = "Apple Safari";
else if (browser.isChrome())
browserName = "Google Chrome";
else if (browser.isIE())
browserName = "Internet Explorer";
else if (browser.isFirefox())
browserName = "Mozilla Firefox";
String screenSize = " Screen Size: " + browser.getScreenWidth() + "x"
+ browser.getScreenHeight();
String version = String.valueOf(browser.getBrowserMajorVersion());
return browserName + " " + version + screenSize;
}
public static Integer InsertTrace(String msg, String trace) {
final String browser = getInfo();
final String user = null;// TODO
Integer id = getSeq();
java.util.Date utilDate = new java.util.Date();
java.sql.Date date = new java.sql.Date(utilDate.getTime());
// TODO ses_id
// TODO trx
System.out.println("==id == " + id + " msg " + msg + " trace "+ trace +" browser"
+ browser + " Date " + date);
return id;
}
public static Integer getSeq() {
Integer id =1;
String v_sql = "SELECT err_seq.NEXTVAL FROM DUAL";
// TODO trx
return id;
}
}
</code></pre>
<hr>
<p><strong>// Edit</strong> </p>
<pre><code>package components;
import java.io.PrintWriter;
import java.io.StringWriter;
import com.vaadin.server.DefaultErrorHandler;
import com.vaadin.server.ErrorEvent;
import com.vaadin.server.ErrorHandler;
import com.vaadin.server.ErrorMessage;
import com.vaadin.server.UserError;
import com.vaadin.server.WebBrowser;
import com.vaadin.ui.AbstractComponent;
import com.vaadin.ui.UI;
import java.sql.SQLException;
import java.util.logging.Logger;
/*
* @author: Kristaps Zukovskis
* Write info about: user, date, err_msg, backtrace, browser info, ses_id
* @ DB table stored_error_msg
*/
public class StoredErrorWriter implements ErrorHandler {
private static final long serialVersionUID = 5117130906083582416L;
public static String ERROR_MSG = "System error! Error number in journal :";
private Logger logger = Logger.getAnonymousLogger();
@Override
public void error(ErrorEvent event) {
Throwable throwable = event.getThrowable();
if (throwable == null) {
DefaultErrorHandler.doDefault(event);
return;
}
if (StoredErrorWriter.getException(throwable)) {
DefaultErrorHandler.doDefault(event);
return;
}
AbstractComponent component = DefaultErrorHandler
.findAbstractComponent(event);
if (component == null) {
DefaultErrorHandler.doDefault(event);
return;
}
final String trace = StoredErrorWriter.getTrace(throwable);
final String msg = throwable.getMessage();
final Integer errorNumber = insertTrace(msg, trace);
ErrorMessage errorMessage = new UserError(ERROR_MSG + errorNumber);
component.setComponentError(errorMessage);
logger.severe(trace);
}
private static String getTrace(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
return sw.toString();
}
public static String getInfo() {
@SuppressWarnings("deprecation")
WebBrowser browser = UI.getCurrent().getSession().getBrowser();
String browserName = "unknown";
if (browser.isOpera())
browserName = "Opera";
else if (browser.isSafari())
browserName = "Apple Safari";
else if (browser.isChrome())
browserName = "Google Chrome";
else if (browser.isIE())
browserName = "Internet Explorer";
else if (browser.isFirefox())
browserName = "Mozilla Firefox";
String screenSize = " Screen Size: " + browser.getScreenWidth() + "x"
+ browser.getScreenHeight();
String version = String.valueOf(browser.getBrowserMajorVersion());
return browserName + " " + version + screenSize;
}
public static Integer insertTrace(String msg, String trace) {
final String browser = getInfo();
final String user = null;// TODO
final Integer id = getSeq();
java.util.Date utilDate = new java.util.Date();
java.sql.Date date = new java.sql.Date(utilDate.getTime());
// TODO ses_id
// TODO trx
System.out.println("==id == " + id + " msg " + msg + " trace " + trace
+ " browser" + browser + " Date " + date);
return id;
}
public static Integer getSeq() {
final Integer id = 1;
String v_sql = "SELECT SETTINGS.err_seq.NEXTVAL FROM DUAL";
// TODO trx
return id;
}
private static Boolean getException(Throwable t) {
Boolean error = true;
IllegalArgumentException exception = getCauseOfType(t,
IllegalArgumentException.class);
if (exception != null) {
error = false;
}
SQLException sqlException = getCauseOfType(t, SQLException.class);
if (sqlException != null) {
error = false;
}
//...
return error;
}
@SuppressWarnings("unchecked")
private static <T extends Throwable> T getCauseOfType(Throwable th,
Class<T> type) {
while (th != null) {
if (type.isAssignableFrom(th.getClass())) {
return (T) th;
} else {
th = th.getCause();
}
}
return null;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T10:13:01.477",
"Id": "79745",
"Score": "5",
"body": "Welcome to Code Review! To make life easier for reviewers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T10:18:07.803",
"Id": "79746",
"Score": "0",
"body": "Edit: Functionality that overwrite standard error msg with trace to user friendly msg with error number stored in DB"
}
] | [
{
"body": "<p><strong>Proprietary indentation convention</strong><br>\nFor some reason the first line in every method in your code is blank. This might be consistent, but since I haven't seen it anywhere else, I find it breaks the read flow, and makes your code less readable.</p>\n\n<p><strong>Use of deprecated code</strong><br>\nDeprecation warnings are there for a reason - what they actually say is that \"this may not work in next versions of this library - be warned, change this as soon as you can\".<br>\nDeprecation warning also generally come with an alternative API you should use, in the case of <code>vaadin</code> - <a href=\"https://vaadin.com/api/com/vaadin/server/VaadinSession.html#getBrowser%28%29\">it suggests</a> you use <a href=\"https://vaadin.com/api/com/vaadin/server/Page.html#getWebBrowser%28%29\">Page.getWebBrowser()</a> instead.</p>\n\n<p><strong>Naming conventions</strong><br>\nGenerally, your method names are OK, but, for some reason, you've decided to uppercase the first letter in <code>InsertTrace</code>... it should start with lowercase, like the other methods.</p>\n\n<p><strong>Use static methods explicitly</strong><br>\nTo make sure your reader understand where your code lies, it is preferable that you call static methods in a fully qualified way - <code>StoredWriterError.getTrace(t)</code>. This way it is obvious that the method is static, and it <em>not</em> part of the current instance.</p>\n\n<p><strong>Missing code</strong><br>\nSince your code is missing all database-related parts, it is hard to tell whether this design is sound or not... perhaps you would like to revisit us after you complete that part.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T11:01:36.837",
"Id": "79748",
"Score": "0",
"body": "Thanks for answer i will finish source in next week and put it here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T12:40:37.963",
"Id": "79756",
"Score": "0",
"body": "@Speakwithsystem / Uri - about the blank line... I disagree. Code inside a method can be put in 'paragraphs' of logical blocks. Adding a blank line before the first paragraph is fine, and I believe it is even necessary if the method declaration is split on multiple lines (e.g. has many parameters or throws exceptions)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T13:07:13.127",
"Id": "79757",
"Score": "0",
"body": "@rolfl, I guess it is a matter for debate. I'm not familiar with any argument _against_ the empty line, I just know that it made the code more difficult to read _for me_. I copied it aside, and removed the lines, and could read it better. Maybe for long method declarations it might be better, but we are talking about `getInfo()`..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T10:54:24.413",
"Id": "45687",
"ParentId": "45685",
"Score": "6"
}
},
{
"body": "<ol>\n<li><p>I'd consider storing raw values of screen size, browser name, major and minor versions in the database as separate attributes too. It might help creating statistics later.</p></li>\n<li><p>Instead of an anonymous logger:</p>\n\n<blockquote>\n<pre><code>private Logger logger = Logger.getAnonymousLogger();\n</code></pre>\n</blockquote>\n\n<p>it would be easier for operations to use a named one:</p>\n\n<pre><code>private static final Logger logger = Logger.getLogger(StoredErrorWriter.class);\n</code></pre>\n\n<p>It makes possible to configure its level according to to their needs.</p></li>\n<li><p><code>errorMessage</code> is never <code>null</code> here:</p>\n\n<blockquote>\n<pre><code>ErrorMessage errorMessage = new UserError(ERROR_MSG\n + errorNumber);\n\nif (errorMessage != null) {\n component.setComponentError(errorMessage);\n logger.log(Level.SEVERE, trace);\n return;\n}\n</code></pre>\n</blockquote>\n\n<p>Two possible cases: <code>new UserError</code> throw an exception or returns a new object. Therefore, the comparison is unnecessary.</p></li>\n<li><p>Anyway, I'd use <a href=\"http://blog.codinghorror.com/flattening-arrow-code/\">guard clauses</a> here to make the code flatten, even if it requires a little bit duplication (<code>DefaultErrorHandler.doDefault(event)</code>).</p>\n\n<pre><code>@Override\npublic void error(ErrorEvent event) {\n Throwable throwable = event.getThrowable();\n if (throwable == null) {\n DefaultErrorHandler.doDefault(event);\n return;\n } \n String trace = getTrace(throwable);\n final String message = throwable.getMessage();\n AbstractComponent component = DefaultErrorHandler\n .findAbstractComponent(event);\n if (component == null) {\n DefaultErrorHandler.doDefault(event);\n return;\n }\n final Integer errorNumber = insertTrace(message, trace);\n ErrorMessage errorMessage = new UserError(ERROR_MSG + errorNumber);\n component.setComponentError(errorMessage);\n logger.log(Level.SEVERE, trace);\n}\n</code></pre>\n\n<p>Note the longer variable name for the <code>Throwable</code> instance and the message. Short variable names are not too readable. I suppose you have autocomplete, so using longer names does not mean more typing but it would help readers and maintainers a lot since they don't have to remember the purpose of each variable - the name would express the programmers intent. (<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Avoid Mental Mapping</em>, p25)</p></li>\n<li><p>Instead of</p>\n\n<blockquote>\n<pre><code>logger.log(Level.SEVERE, trace);\n</code></pre>\n</blockquote>\n\n<p>I guess you could use</p>\n\n<pre><code>logger.severe(trace);\n</code></pre></li>\n<li><p>This constant is used only once:</p>\n\n<blockquote>\n<pre><code>public static String ERROR_MSG = \"System error! Error number in journal :\";\n</code></pre>\n</blockquote>\n\n<p>I'd inline it for <a href=\"http://www.approxion.com/?p=120\">the principle of proximity</a></p></li>\n<li><p>I like <code>final</code> variables, they make the code easier to follow (readers know immediately that a value can't be changed), but the code doesn't use it consistently. Some variables are <code>final</code>, some aren't.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T11:08:17.843",
"Id": "79751",
"Score": "1",
"body": "I am pl/sql programmer so thank you very much for tips in java!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T11:11:07.480",
"Id": "79752",
"Score": "0",
"body": "@Speakwithsystem: You're welcome!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T11:00:49.733",
"Id": "45688",
"ParentId": "45685",
"Score": "6"
}
},
{
"body": "<p>@palacsint and @UriAgassi have both given good answers, and there is not much to add, except one thing: <em>Error</em></p>\n\n<p>In Java you have Exceptions, and Errors... <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html\" rel=\"nofollow\"><code>java.lang.Exception</code></a> and <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Error.html\" rel=\"nofollow\"><code>java.lang.Error</code></a>. They both extend <code>java.lang.Throwable</code>. Exceptions are thrown when the program or it's input/output has problems that can normally be resolved from inside the program. Errors are thrown when 'bigger things' happen, like a security problem, a physical resource problem (memory), or a class-path problem (Jars with classes incompatible with the current Java version), etc. It is very unusual for Java programs to trap and process Errors.</p>\n\n<p>Often, when an actual Error does occur, handling the Error in a way like you are doing it, is going to cause more problems than it solves (thinking out-of-memory errors here..).</p>\n\n<p>I strongly recommend that you only trap 'Exceptions' (not all Throwables). If there are specific Errors that you want to trap, then I recommend that you catch them explicitly, handle them appropriately, and then re-throw the situation (and log it) using the Error wrapped inside a normal Exception... Then replace all mention of Error in your logger with 'Exception', and replace <code>java.langl.Throwable</code> with <code>java.lang.Exception</code></p>\n\n<p>Error handling in Java is complicated... I generally recommend that you steer clear of them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T13:54:14.717",
"Id": "79762",
"Score": "0",
"body": "Hi! rolfl I am a bit of suspicion! I rewrite code like like posted palacsint `if (component == null) DefaultErrorHandler.doDefault(event)`@ Begining. This funcionality need for Vaadin based backend App with many of components and many DB transactions. + the whole look of glamor with many components see priview for default error indicator @ [link] (http://postimg.org/image/oxvjrmflj/). All other error if component not found will go around StoredErrorWriter by DefaultErrorHandler.So system/server critical and fatal error will processed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T13:55:57.390",
"Id": "79763",
"Score": "0",
"body": "I tested in some situations looks legally. I am wrong ? Some info I founded in Vaadin 7 book and in the this post [link](http://stackoverflow.com/questions/20615816/central-error-handling-in-vaadin)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T14:51:08.310",
"Id": "79767",
"Score": "0",
"body": "I agree with you i remake Writer with my locale Exceptions and some Sql, Hibernate default exceptions. It is like you said Error handling in java is complicated ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T14:55:26.913",
"Id": "79770",
"Score": "2",
"body": "@Speakwithsystem - `Error` handling is complicated, `Exception` handling is not complicated, it just takes discipline"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T13:06:13.777",
"Id": "45692",
"ParentId": "45685",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "45687",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T09:59:52.233",
"Id": "45685",
"Score": "5",
"Tags": [
"java",
"exception-handling",
"logging"
],
"Title": "StoredErrorWriter"
} | 45685 |
<p>Below is a full working code example of code which is used to compute stats on two class vectors (partitions). </p>
<p>There are two functions:</p>
<ul>
<li><code>pairwise_indication</code> and </li>
<li><code>to_clust_set</code>. </li>
</ul>
<p>The first one is the function in question and the second is just for completeness, since it's apparently not so time consuming. <code>pairwise_indication</code> returns the indicators <code>n11, n00, n10, n01</code> which are used to compute scores such as the <a href="http://en.wikipedia.org/wiki/Rand_index" rel="nofollow">RAND Index</a> (they're named <em>a, b, c, d</em> on that site). </p>
<p>The bottleneck probably are the loops (depth is 3) and the logic and look-up stuff inside of <code>pairwise_indication</code>. I already tried to improve the logical function in it by pulling forward the common cases. <strong>I was hoping it can be improved some further</strong>. What makes it interminable (if I get the profiling at the bottom of the post correct) are the loops and maybe the <code>set</code> look-ups using <code>in</code>, though I cannot imagine something faster.</p>
<pre><code>import itertools as it
import numpy as np
def pairwise_indication(part1, part2):
r"""
Computes the pairwise indicators.
Parameters
----------
part1, part2 : array, (n)
The two partition vectors
Returns
-------
n11, n00, n10, n01 : tuple (int)
Tuple with the counts of incidences
Examples
--------
>>> from cluvap.calc import pairwise_indication
>>> import numpy as np
>>> p1 = np.array([1, 2, 3, 3, 1, 2])
>>> p2 = np.array([3, 2, 3, 3, 1, 2])
>>> pairwise_indication(p1, p2)
(2, 10, 1, 2)
"""
n = len(part1)
if n != len(part2):
raise ValueError('Partition shapes do not match')
# Create clustering as set
A = to_clust_set(part1)
B = to_clust_set(part2)
observations = np.arange(n)
n11, n00, n10, n01 = 0, 0, 0, 0
# Count incidences
# function: P'QR'S v P'QRS v PQRS v PQR'S (' == not, v == or)
# condensed: P('QR('S v S) v QR('S v S))
# P: obs1 in a
# Q: obs2 in a
# R: obs1 in b
# S: obs2 in b
for obs1, obs2 in it.combinations(observations, 2):
for a in A:
for b in B:
if obs1 in a:
if obs2 not in a:
if obs1 in b:
if obs2 not in b:
n00 += 1
else:
n01 += 1
else:
if obs1 in b:
if obs2 in b:
n11 += 1
else:
n10 += 1
return n11, n00, n10, n01
def to_clust_set(part):
"""
Converts a partition to a set of clusters. Noise is considered a cluster.
Parameters
----------
part : arrays, (n)
Partitions. A partition ``p`` assigns the ``n``-th observation
to the cluster ``p[n]``.
Returns
-------
cset : list of sets
Examples
--------
>>> from cluvap.calc import to_clust_set
>>> import numpy as np
>>> p = np.array([1, 2, 3, 3, 1, 2])
>>> to_clust_set(p)
[set([0, 4]), set([1, 5]), set([2, 3])]
"""
clusters = set(part)
obs = np.arange(len(part))
return [set(obs[part == C]) for C in clusters]
if __name__ == "__main__":
from time import time
p1 = np.array([1, 2, 3, 4, 5] * 20)
p2 = np.array([2, 3, 4, 5, 1] * 20)
t0 = time()
pi = pairwise_indication(p1, p2)
t = (time() - t0) * 1000
print 'pairwise_indication(p1, p2) in {:.2f} ms:\n'.format(t), pi
</code></pre>
<p>Output</p>
<pre><code>pairwise_indication(p1, p2) in 19.00 ms:
(950, 4000, 0, 0)
</code></pre>
<p>line profiling</p>
<pre><code>>>> p1 = np.array([1, 2, 3, 4, 5] * 20)
>>> p2 = np.array([2, 3, 4, 5, 1] * 20)
>>> %lprun -f pairwise_indication pairwise_indication(p1, p2)
Timer unit: 4.10918e-07 s
File: cluvap\calc.py
Function: pairwise_indication at line 713
Total time: 0.603277 s
Line # Hits Time Per Hit % Time Line Contents
==============================================================
713 def pairwise_indication(part1, part2):
...
736 1 28 28.0 0.0 n = len(part1)
737 1 17 17.0 0.0 if n != len(part2):
738 raise ValueError('Partition shapes do not match')
739 # Create clustering as set
740 1 1455 1455.0 0.1 A = to_clust_set(part1)
741 1 1154 1154.0 0.1 B = to_clust_set(part2)
742 1 33 33.0 0.0 observations = np.arange(n)
743 1 14 14.0 0.0 n11, n00, n10, n01 = 0, 0, 0, 0
744 # Count incidences
745 # (can this be improved using some kind of indexing / logical compression?)
746 4951 19884 4.0 1.4 for obs1, obs2 in it.combinations(observations, 2):
747 29700 115151 3.9 7.8 for a in A:
748 148500 576491 3.9 39.3 for b in B:
749 123750 505606 4.1 34.4 if obs1 in a:
750 24750 100784 4.1 6.9 if obs2 not in a:
751 20000 84631 4.2 5.8 if obs1 in b:
752 4000 16489 4.1 1.1 if obs2 not in b:
753 4000 17915 4.5 1.2 n00 += 1
754 else:
755 n01 += 1
756 else:
757 4750 20272 4.3 1.4 if obs1 in b:
758 950 4005 4.2 0.3 if obs2 in b:
759 950 4185 4.4 0.3 n11 += 1
760 else:
761 n10 += 1
762
763 1 5 5.0 0.0 return n11, n00, n10, n01
</code></pre>
| [] | [
{
"body": "<p>If I understood what you want to do, this would be a more direct way to compute the same result. At least for the test cases provided, the result is indeed the same.</p>\n\n<pre><code>def pairwise_indication(part1, part2):\n if len(part1) != len(part2):\n raise ValueError('Partition shapes do not match')\n n11, n00, n10, n01 = 0, 0, 0, 0\n for (a1,a2), (b1,b2) in it.combinations(zip(part1, part2), 2):\n if a1 == b1:\n if a2 == b2:\n n11 += 1\n else:\n n10 += 1\n else:\n if a2 == b2:\n n01 += 1\n else:\n n00 += 1\n return n11, n00, n10, n01\n</code></pre>\n\n<p>On my computer this is 13 times faster than yours.</p>\n\n<hr>\n\n<p>Here's a completely different approach based on the idea that you can partition the partitions with one another (using <code>zip</code> in Python) to obtain a finer partition. (There must be a word for that?) From the size of each subset you can directly calculate the number of pairs that can be formed. Add up the numbers for each partition and subtract the overlap. This is 70 times faster than yours with the given example, and more importantly, operates in linear time, so it scales well to larger data.</p>\n\n<pre><code>from collections import Counter\n\ndef pairs(n):\n '''Calculate number of pairs that can be formed from n items'''\n return n * (n - 1) // 2\n\ndef partition_pairs(partition):\n '''Calculate number of pairs in subsets of partition'''\n return sum(pairs(x) for x in Counter(partition).values())\n\ndef pairwise_indication(part1, part2):\n n = len(part1)\n if n != len(part2):\n raise ValueError('Partition shapes do not match')\n\n n11 = partition_pairs(zip(part1, part2))\n n10 = partition_pairs(part1) - n11\n n01 = partition_pairs(part2) - n11\n n00 = pairs(n) - n11 - n10 - n01\n\n return n11, n00, n10, n01\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T17:29:54.050",
"Id": "80028",
"Score": "0",
"body": "Similarly on mine (15.3 times faster). That's already a big benefit. Could you be more concrete on the second suggestion? I doubt that would be even faster, would it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T20:16:27.573",
"Id": "80054",
"Score": "0",
"body": "@embert My second suggestion wasn't that good after all, but see my third suggestion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T06:55:04.583",
"Id": "80507",
"Score": "0",
"body": "I don't yet fully grab *why* this works, but apparently it does a good job."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T20:14:22.197",
"Id": "45708",
"ParentId": "45686",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "45708",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T10:17:23.133",
"Id": "45686",
"Score": "8",
"Tags": [
"python",
"algorithm",
"performance",
"combinatorics"
],
"Title": "Compute stats on two class vectors"
} | 45686 |
<p>I implemented an unordered_set like container for storing small sets of unsigned integers. It uses a trivial hash table for lookups and an unordered array for quickly iterating over small sets.</p>
<p>I'm looking for suggestions on best practices and correctness.</p>
<pre><code>#pragma once
#include <array>
#include <random>
#include <bitset>
// T - Type of integer.
// N - Number of integers in the set from 0 to N-1
template<typename T,T N> class integer_set
{
private:
static constexpr T NOT_IN_SET = ~static_cast<T>(0);
static const T MIN_SIZE_TO_SEARCH_INDEX;
public:
class iterator
{
public:
iterator(const iterator& it) = default;
iterator& operator=(const iterator& it) = default;
iterator();
iterator(const T* element);
bool operator==(const iterator& it) const;
bool operator!=(const iterator& it) const;
bool operator<(const iterator& it) const;
bool operator>(const iterator& it) const;
bool operator<=(const iterator& it) const;
bool operator>=(const iterator& it) const;
T operator*() const;
T operator[](T i) const;
iterator& operator++();
iterator operator++(int);
iterator& operator--();
iterator operator--(int);
iterator operator+(T i) const;
iterator operator-(T i) const;
iterator& operator+=(T i);
iterator& operator-=(T i);
private:
const T* m_element;
};
public:
// The following are undefined if the set is empty:
// front()
// back()
// operator[]()
// min()
// max()
// random()
integer_set();
integer_set(const integer_set& set);
integer_set& operator=(const integer_set& set);
bool operator==(const integer_set& set) const;
bool operator!=(const integer_set& set) const;
bool operator<=(const integer_set& set) const;
bool operator>=(const integer_set& set) const;
bool operator<(const integer_set& set) const;
bool operator>(const integer_set& set) const;
T front() const;
T back() const;
iterator begin() const;
iterator end() const;
iterator find(T v) const;
T operator[](T i) const;
T min() const;
T max() const;
template<class URNG> T random(URNG& gen) const;
T size() const;
bool empty() const;
bool contains(T v) const;
void clear();
void insert(T v);
void insert(const integer_set& set);
void erase(T v);
void erase(const integer_set& set);
public:
static integer_set union_(const integer_set& set1,const integer_set& set2);
static integer_set intersection(const integer_set& set1,const integer_set& set2);
static bool union_empty(const integer_set& set1,const integer_set& set2);
static bool intersection_empty(const integer_set& set1,const integer_set& set2);
private:
// Find the smallest size where searching the index has a probability >= 0.5 of requiring fewer operations than searching the list.
static T min_size_to_search_index();
// Probability that we will find at least one element in the set after picking size elements at random.
static double get_probability(T size);
private:
// m_index[element] is the index of that element in m_list or NOT_IN_SET. For checking if element is in set.
std::array<T,N> m_index;
// Unordered list of elements. For iterating over set.
std::array<T,N> m_list;
// Number of elements in set.
T m_size;
};
namespace std
{
template<typename T,T N> struct hash<integer_set<T,N>>
{
typedef integer_set<T,N> argument_type;
typedef std::size_t result_type;
result_type operator()(const argument_type& set) const
{
std::bitset<N> bits;
for(T v : set)
bits.set(v);
return std::hash<std::bitset<N>>()(bits);
}
};
}
template<typename T,T N> constexpr T integer_set<T,N>::NOT_IN_SET;
template<typename T,T N> const T integer_set<T,N>::MIN_SIZE_TO_SEARCH_INDEX = {min_size_to_search_index()};
////////////////////////////////////////////////
// integer_set
template<typename T,T N> integer_set<T,N>::integer_set()
:m_size{0}
{
m_index.fill(NOT_IN_SET);
static_assert(std::numeric_limits<T>::is_integer,"T must be an integer.");
static_assert(std::is_unsigned<T>::value,"T must be unsigned.");
static_assert(N<NOT_IN_SET,"N is too large.");
}
template<typename T,T N> integer_set<T,N>::integer_set(const integer_set& set)
:m_index(set.m_index),m_size{set.m_size}
{
for(T i=0; i<m_size; ++i)
m_list[i] = set.m_list[i];
}
template<typename T,T N> integer_set<T,N>& integer_set<T,N>::operator=(const integer_set& set)
{
m_size = set.m_size;
m_index = set.m_index;
for(T i=0; i<m_size; ++i)
m_list[i] = set.m_list[i];
return *this;
}
template<typename T,T N> bool integer_set<T,N>::operator==(const integer_set& set) const
{
if(m_size != set.m_size)
return false;
for(T v : set)
{
if(!contains(v))
return false;
}
return true;
}
template<typename T,T N> bool integer_set<T,N>::operator!=(const integer_set& set) const
{
return !operator==(set);
}
template<typename T,T N> bool integer_set<T,N>::operator<=(const integer_set& set) const
{
return m_index <= set.m_index;
}
template<typename T,T N> bool integer_set<T,N>::operator>=(const integer_set& set) const
{
return m_index >= set.m_index;
}
template<typename T,T N> bool integer_set<T,N>::operator<(const integer_set& set) const
{
return m_index < set.m_index;
}
template<typename T,T N> bool integer_set<T,N>::operator>(const integer_set& set) const
{
return m_index > set.m_index;
}
template<typename T,T N> T integer_set<T,N>::front() const
{
return m_list[0];
}
template<typename T,T N> T integer_set<T,N>::back() const
{
return m_list[m_size-1];
}
template<typename T,T N> typename integer_set<T,N>::iterator integer_set<T,N>::begin() const
{
return iterator(m_list.data());
}
template<typename T,T N> typename integer_set<T,N>::iterator integer_set<T,N>::end() const
{
return iterator(m_list.data()+m_size);
}
template<typename T,T N> typename integer_set<T,N>::iterator integer_set<T,N>::find(T v) const
{
if(m_index[v] == NOT_IN_SET)
return end();
else
return iterator(m_list.data()+m_index[v]);
}
template<typename T,T N> T integer_set<T,N>::operator[](T i) const
{
return m_list[i];
}
template<typename T,T N> T integer_set<T,N>::min() const
{
if(m_size >= MIN_SIZE_TO_SEARCH_INDEX)
{
for(T i=0; i<N; ++i)
{
if(m_index[i] != NOT_IN_SET)
return i;
}
}
else
{
T min = m_list[0];
for(T i=1; i<m_size; ++i)
{
if(m_list[i] < min)
min = m_list[i];
}
return min;
}
return NOT_IN_SET;
}
template<typename T,T N> T integer_set<T,N>::max() const
{
if(m_size >= MIN_SIZE_TO_SEARCH_INDEX)
{
for(T i=N; i>0; --i)
{
if(m_index[i-1] != NOT_IN_SET)
return i-1;
}
}
else
{
T max = m_list[0];
for(T i=1; i<m_size; ++i)
{
if(m_list[i] > max)
max = m_list[i];
}
return max;
}
return NOT_IN_SET;
}
template<typename T,T N> template<class URNG> T integer_set<T,N>::random(URNG& gen) const
{
return m_list[std::uniform_int_distribution<T>(0,m_size-1)(gen)];
}
template<typename T,T N> T integer_set<T,N>::size() const
{
return m_size;
}
template<typename T,T N> bool integer_set<T,N>::empty() const
{
return m_size == 0;
}
template<typename T,T N> bool integer_set<T,N>::contains(T v) const
{
return m_index[v] != NOT_IN_SET;
}
template<typename T,T N> void integer_set<T,N>::clear()
{
for(T v : *this)
m_index[v] = NOT_IN_SET;
m_size = 0;
}
template<typename T,T N> void integer_set<T,N>::insert(T v)
{
if(contains(v))
return;
m_index[v] = m_size;
m_list[m_size] = v;
++m_size;
}
template<typename T,T N> void integer_set<T,N>::insert(const integer_set& set)
{
for(T v : set)
insert(v);
}
template<typename T,T N> void integer_set<T,N>::erase(T v)
{
if(!contains(v))
return;
--m_size;
// If this element is not the last in the list
// move the last element in the list to the index of v.
if(m_index[v] != m_size)
{
m_list[m_index[v]] = m_list[m_size];
m_index[m_list[m_size]] = m_index[v];
}
m_index[v] = NOT_IN_SET;
}
template<typename T,T N> void integer_set<T,N>::erase(const integer_set& set)
{
for(T v : set)
erase(v);
}
template<typename T,T N> integer_set<T,N> integer_set<T,N>::union_(const integer_set& set1,const integer_set& set2)
{
if(set1.m_size <= set2.m_size)
{
integer_set out(set2);
out.insert(set1);
return out;
}
else
{
integer_set out(set1);
out.insert(set2);
return out;
}
}
template<typename T,T N> integer_set<T,N> integer_set<T,N>::intersection(const integer_set& set1,const integer_set& set2)
{
integer_set out;
if(set1.m_size <= set2.m_size)
{
for(T v : set1)
{
if(set2.contains(v))
out.insert(v);
}
}
else
{
for(T v : set2)
{
if(set1.contains(v))
out.insert(v);
}
}
return out;
}
template<typename T,T N> bool integer_set<T,N>::union_empty(const integer_set& set1,const integer_set& set2)
{
return set1.m_size == 0 && set2.m_size == 0;
}
template<typename T,T N> bool integer_set<T,N>::intersection_empty(const integer_set& set1,const integer_set& set2)
{
if(set1.m_size <= set2.m_size)
{
for(T v : set1)
{
if(set2.contains(v))
return false;
}
}
else
{
for(T v : set2)
{
if(set1.contains(v))
return false;
}
}
return true;
}
template<typename T,T N> T integer_set<T,N>::min_size_to_search_index()
{
// Bisection
T min_size = 1;
T max_size = N;
T mid_size = (min_size+max_size)/2;
do
{
if(get_probability(mid_size) >= 0.5)
max_size = mid_size;
else
min_size = mid_size;
mid_size = (min_size+max_size)/2;
}
while(mid_size != min_size);
return max_size;
}
template<typename T,T N> double integer_set<T,N>::get_probability(T size)
{
// Simplification of the hypergeometric distribution.
// 1-hygepdf(0,N,size,size) =
// (N-size)!*(N-size)!
// 1 - ___________________
// (N-size-size)!*N!
double num = static_cast<double>(N-size);
double den = static_cast<double>(N);
double p = num/den;
for(T i=1; i<size; ++i)
{
--num;
--den;
p *= num/den;
}
return 1.0-p;
}
////////////////////////////////////////////////
// integer_set::iterator
template<typename T,T N> integer_set<T,N>::iterator::iterator()
:m_element{nullptr}
{}
template<typename T,T N> integer_set<T,N>::iterator::iterator(const T* element)
:m_element{element}
{}
template<typename T,T N> bool integer_set<T,N>::iterator::operator==(const iterator& it) const
{
return m_element == it.m_element;
}
template<typename T,T N> bool integer_set<T,N>::iterator::operator!=(const iterator& it) const
{
return m_element != it.m_element;
}
template<typename T,T N> bool integer_set<T,N>::iterator::operator<(const iterator& it) const
{
return m_element < it.m_element;
}
template<typename T,T N> bool integer_set<T,N>::iterator::operator>(const iterator& it) const
{
return m_element > it.m_element;
}
template<typename T,T N> bool integer_set<T,N>::iterator::operator<=(const iterator& it) const
{
return m_element <= it.m_element;
}
template<typename T,T N> bool integer_set<T,N>::iterator::operator>=(const iterator& it) const
{
return m_element >= it.m_element;
}
template<typename T,T N> T integer_set<T,N>::iterator::operator*() const
{
return *m_element;
}
template<typename T,T N> T integer_set<T,N>::iterator::operator[](T i) const
{
return m_element[i];
}
template<typename T,T N> typename integer_set<T,N>::iterator& integer_set<T,N>::iterator::operator++()
{
++m_element;
return *this;
}
template<typename T,T N> typename integer_set<T,N>::iterator integer_set<T,N>::iterator::operator++(int)
{
iterator temp(*this);
operator++();
return temp;
}
template<typename T,T N> typename integer_set<T,N>::iterator& integer_set<T,N>::iterator::operator--()
{
--m_element;
return *this;
}
template<typename T,T N> typename integer_set<T,N>::iterator integer_set<T,N>::iterator::operator--(int)
{
iterator temp(*this);
operator--();
return temp;
}
template<typename T,T N> typename integer_set<T,N>::iterator integer_set<T,N>::iterator::operator+(T i) const
{
return iterator(m_element+i);
}
template<typename T,T N> typename integer_set<T,N>::iterator integer_set<T,N>::iterator::operator-(T i) const
{
return iterator(m_element-i);
}
template<typename T,T N> typename integer_set<T,N>::iterator& integer_set<T,N>::iterator::operator+=(T i)
{
m_element += i;
return *this;
}
template<typename T,T N> typename integer_set<T,N>::iterator& integer_set<T,N>::iterator::operator-=(T i)
{
m_element -= i;
return *this;
}
</code></pre>
<h2>Edit:</h2>
<p>I implemented this container to speed up a program that uses many set operations. This container gives me a speed up of two orders of magnitude compared to <code>std::unordered_set</code>.</p>
<p>These functions are nearly identical to <code>std::set</code> and <code>std::unordered_set</code>. Like <code>std::unordered_set</code>, iterators return the elements in no particular order.</p>
<pre><code>integer_set();
integer_set(const integer_set& set);
integer_set& operator=(const integer_set& set);
bool operator==(const integer_set& set) const;
bool operator!=(const integer_set& set) const;
iterator begin() const;
iterator end() const;
T front() const;
T back() const;
iterator find(T v) const;
void clear();
bool empty() const;
T size() const;
void insert(T v);
void erase(T v);
</code></pre>
<p>These are convenience functions not provided by <code>std::set</code> or <code>std::unordered_set</code>:</p>
<pre><code>// Same as insert(set.begin(),set.end())
void insert(const integer_set& set);
// Same as erase(set.begin,set.end())
void erase(const integer_set& set);
// Test if integer v is in set. Same as find(v) != end()
bool contains(T v) const;
// Smallest/largest integer in set.
T min() const;
T max() const;
// Random integer in set given a RNG e.g. std::mersenne_twister_engine
template<class URNG> T random(URNG& gen) const;
// Element of set. Same as *(begin()+i).
T operator[](T i) const;
// Lexicographical comparison
bool operator<=(const integer_set& set) const;
bool operator>=(const integer_set& set) const;
bool operator<(const integer_set& set) const;
bool operator>(const integer_set& set) const;
// Self Explanatory
integer_set union_(const integer_set& set1,const integer_set& set2);
integer_set intersection(const integer_set& set1,const integer_set& set2);
bool union_empty(const integer_set& set1,const integer_set& set2);
bool intersection_empty(const integer_set& set1,const integer_set& set2);
</code></pre>
<p>Here is an example:</p>
<pre><code>#include "integer_set.h"
#include <cassert>
int main()
{
typedef integer_set<uint16_t,256> set256;
set256 set1;
set1.insert(144);
set1.insert(255);
set1.insert(0);
assert(set1.find(0) != set1.end());
assert(set1.contains(144));
assert(set1.contains(255));
set1.clear();
assert(set1.begin() == set1.end());
for(uint16_t i=30;i<100;i+=7)
set1.insert(i);
set1.insert(2);
set1.insert(252);
for(uint16_t i=121;i<240;i+=3)
set1.insert(i);
assert(set1.min() == 2);
assert(set1.max() == 252);
set256 set2;
set2.insert(30);
assert( set256::intersection(set1,set2).contains(30) );
set2 = set1;
for(uint16_t member : set2)
set1.erase(member);
assert(set1.empty());
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>You should learn about <a href=\"http://en.cppreference.com/w/cpp/utility/bitset\" rel=\"nofollow\"><code>std::bitset</code></a>.</p>\n\n<p>It has almost everything you wants already with far less data storage. Encapsulate it inside your class to keep track of <code>min</code>, <code>max</code> and <code>count</code> in O(1) and write a custom iterator to list only the raised bits.</p>\n\n<p>But according to your real usage, it may be not even needed and a mere <code>std::bitset</code> will be enough.</p>\n\n<p>Below is your test case translated with a bitset:</p>\n\n<pre><code>#include <bitset>\n#include <iostream>\n\nint main() {\n std::cout << std::boolalpha;\n //typedef integer_set<uint16_t,256> set256;\n using set256 = std::bitset<256>;\n std::cout << \"byte count for 256 bits : \" << sizeof(set256) << '\\n';\n\n set256 set1;\n set1.set(144);\n set1.set(255);\n set1.set(0);\n\n std::cout << \"test separate bits : \";\n std::cout << set1.test(0) << \" \";\n std::cout << set1.test(144) << \" \";\n std::cout << set1.test(255) << \"\\n\";\n\n std::cout << \"count before after reset : \";\n std::cout << set1.count() << \" \";\n set1.reset();\n std::cout << set1.count() << \"\\n\";\n\n for(uint16_t i=30;i<100;i+=7)\n set1.set(i);\n set1.set(2);\n set1.set(252);\n for(uint16_t i=121;i<240;i+=3)\n set1.set(i);\n\n set256 set2;\n set2.set(30);\n\n auto inter = set1&set2;\n std::cout << \"test over an intersection : \" << inter.test(30) << \"\\n\";\n\n set2 = set1;\n set1 &= ~set2;\n std::cout << \"a complicated way to clear a bit set by anding a flipped copy : \" << set1.count() << \"\\n\";\n\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T12:19:56.417",
"Id": "45746",
"ParentId": "45689",
"Score": "5"
}
},
{
"body": "<p>The answer given by @galop1n is a good one, but since you asked for review, here is what could actually be improved in your code:</p>\n\n<ul>\n<li><p>Your class <code>iterator</code> is nothing but a wrapper which does exactly the same thing as <code>std::array<T, N>::iterator</code>. Therefore, you can simply write</p>\n\n<pre><code>using iterator = typename std::array<T, N>::iterator;\n</code></pre>\n\n<p>...and delete your whole iterator implementation. The only things that are really important are the values passed to it by <code>begin</code> and <code>end</code>.</p></li>\n<li><p>It's not really important, but I would have kept my includes in alphbetical order so that I know exactly whether I have to look for an included header higher or lower in the list:</p>\n\n<pre><code>#include <array>\n#include <bitset>\n#include <random>\n</code></pre></li>\n<li><p>You obviously have a naming problem with <code>union_</code>. Since you are creating a <code>set</code> class, I would use <code>operator&</code> for intersection and <code>operator|</code> for union. While it is not recommended to overload operators when the meaning is not obvious, these operators are already commonly used for set operations (<em>e.g.</em> <a href=\"https://docs.python.org/3.4/library/stdtypes.html?highlight=frozenset#set.union\" rel=\"nofollow\"><code>set</code> and <code>frozenset</code></a> in Python's standard library). To improve consistency and usability, you can also implement <code>operator&=</code> and <code>operator|=</code>; users will expect them to be available if you already provide <code>operator&</code> and <code>operator|</code>.</p></li>\n<li><p>We already tackled the problem for <code>union_</code> and <code>intersection</code> by making them operators, but I don't really like the fact that <code>union_empty</code> and <code>intersection_empty</code> are <code>static</code> functions. The need not be <code>static</code> since the only <code>private</code> member they access is <code>m_size</code>, and you can get this member by calling the method <code>size</code>. I would have made them free functions instead.</p></li>\n<li><p>I don't believe that checking for <code>std::numeric_limits<T>::is_integer</code> in the static assertions is useful since <code>is_unsigned</code> is only <code>true</code> for unsigned integer types. It is probably redundant.</p></li>\n<li><p>In the method <code>random</code>, you pass the random number generator by reference. The idiomatic way to pass a random number generator (<em>e.g.</em> <code>std::shuffle</code> or <code>std::sample</code>) is to pass it by universal reference and to <code>std::forward</code> it to the following function:</p>\n\n<pre><code>template<typename T,T N>\ntemplate<class URNG>\nT integer_set<T,N>::random(URNG&& gen) const\n{\n return m_list[std::uniform_int_distribution<T>(0,m_size-1)(std::forward<URNG>(gen))];\n}\n</code></pre></li>\n<li><p>This line:</p>\n\n<pre><code>template<typename T,T N> constexpr T integer_set<T,N>::NOT_IN_SET;\n</code></pre>\n\n<p>Since you already initialized <code>NOT_IN_SET</code> directly in the class declaration, this line is useless. You should remove it.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T09:31:05.220",
"Id": "45813",
"ParentId": "45689",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "45813",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T11:49:34.533",
"Id": "45689",
"Score": "7",
"Tags": [
"c++",
"c++11",
"set"
],
"Title": "Container for Sets of Integers"
} | 45689 |
<p>I looked at a search filter code code and edited it to catered to my functional needs. I understood most of the JavaScript except the <strong>extend</strong> method bit. Can someone explain that? Also, is this the best way to create such a filter? Please let me know of any ways to improve the code.</p>
<pre><code><style type="text/css">
/* Clearfix */
.display{display:block;}
.hidden{display:none;}
.clearfix:before, .clearfix:after {content: " ";display: table;}
.clearfix:after {clear: both;}
.clearfix {*zoom: 1;}
#brand-search{margin-bottom:10px;clear: both;border:1px solid #ccc;width:200px;}
#brand-search:hover{border:1px solid #666;}
#search-text {float:left;padding:6px;font-size:14px;color:#333;background:#eee;border:0 none;margin:0;outline:0;width:122px;}
.list-count {float:left;text-align:right;width:56px;padding:6px 10px 6px 0;color:#999;background:#eee;}
ul {float:left;width:100%;margin:0;padding:0;position:relative;}
li {float:left;clear:left;width:100%;margin:0;padding:0.5em 0.8em;list-style:none;background-color:#f2f2f2;border:1px solid #f2f2f2;cursor:pointer;color:#333;position:relative;z-index:2;}
li:hover {background-color:#fff;border:1px solid #ccc;}
.empty-item {color:#aaa;padding:0;border:none;text-align:center;float:left;clear:left;display:none;}
</style>
<section class="list-wrap">
<div id="brand-search" class="clearfix">
<input type="text" id="search-text" placeholder="search">
<span class="list-count"></span>
</div>
<ul id="list">
<li>red</li>
<li>orange</li>
<li>yellow</li>
<li>pink</li>
<li>blue</li>
<li>green</li>
<li>violet</li>
<li>purple</li>
<li>Indigo</li>
<li>grey</li>
<li>white</li>
<li>black</li>
<span class="empty-item">No items to show..</span>
</ul>
</section>
<script>
var list = $('#list'),
itemCount = list.find('li').length;
// list current items number
$('.list-count').text(itemCount + ' items');
$("#search-text").keyup(function(){
var searchBrand = $("#search-text").val(),
listItem = list.children('li'),
searchSplit = searchBrand.replace(/ /g, "'):containsi('");
//extends :contains to be case insensitive
$.extend($.expr[':'],{
'containsi': function(elem, i, match, array){
return (elem.textContent || elem.innerText || '').toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
}
});
$("#list li").not(":containsi('" + searchSplit + "')").each(function(e){
$(this).addClass('hidden');
});
$("#list li:containsi('" + searchSplit + "')").each(function(e){
$(this).removeClass('hidden');
});
//show .empty-item state text when no jobs found
var itemCount = listItem.length - list.find('.hidden').length;
$('.list-count').text(itemCount + ' items');
if(itemCount == '0'){
$('.empty-item').show();
}
else {
$('.empty-item').hide();
}
});
</script>
</code></pre>
| [] | [
{
"body": "<p>The <a href=\"http://api.jquery.com/jquery.extend/\" rel=\"nofollow\">extend</a> method is being applied to <code>jQuery.expr</code> which is the set of selectors <code>jQuery</code> will apply when selecting elements (<a href=\"http://james.padolsey.com/javascript/extending-jquerys-selector-capabilities/\" rel=\"nofollow\">see here</a>) -- <code>jQuery.expr[\":\"]</code> are the pseudo selectors <code>jQuery</code> acknowledges. The extend is useful if you want to add multiple jQuery selectors succinctly but for adding pseudo selectors I think its just a norm noting you can also add the selector as below</p>\n\n<pre><code>//extends :contains to be case insensitive\n$.expr[':'].containsi = function(elem, i, match, array){\n return (elem.textContent || elem.innerText || '').toLowerCase().indexOf((match[3] || \"\").toLowerCase()) >= 0;\n};\n</code></pre>\n\n<p>One more note: you probably want to add your custom selectors near the top of your code (and definitely outside of your keyup event handler!) in case you want to use your selector somewhere else in your code.</p>\n\n<p>Now some nitpicks</p>\n\n<p>Your Javascript near the end becomes difficult to read because the formatting of your <code>keyup</code> handler. Try pasting your code through an automatic formatter and notice how much easier it will be to follow (eg <a href=\"http://prettydiff.com\" rel=\"nofollow\">http://prettydiff.com</a>)</p>\n\n<pre><code>if(itemCount == '0'){ //dont compare to '0' mate we know its an integer as its the length of a collection\n $('.empty-item').show();\n}\nelse {\n $('.empty-item').hide();\n}\n</code></pre>\n\n<p>I would write that as simply: <code>$('.empty-item').toggle(itemCount === 0);</code></p>\n\n<p>You can also write the following code in this similar one liner: </p>\n\n<pre><code>$(\"#list li:containsi('\" + searchSplit + \"')\").each(function(e) {\n $(this).removeClass('hidden');\n});\n\n//more elegant:\n$(\"#list li:containsi('\" + searchSplit + \"')\").removeClass('hidden');\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T15:34:41.780",
"Id": "82158",
"Score": "0",
"body": "Hiya, I am using my code but abit more complicated with multiple lists. How do I searcg filter through the list and put the matching key search to be appended in first list only?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T19:17:59.383",
"Id": "82197",
"Score": "0",
"body": "Elaborate I don't understand what you're asking"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T14:31:33.787",
"Id": "45695",
"ParentId": "45693",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T14:07:04.537",
"Id": "45693",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"search"
],
"Title": "Search filter list using jQuery"
} | 45693 |
<p>The options for the 'cat' command are as follows:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code> -b Number the non-blank output lines, starting at 1.
-e Display non-printing characters (see the -v option), and display
a dollar sign (`$') at the end of each line.
-n Number the output lines, starting at 1.
-s Squeeze multiple adjacent empty lines, causing the output to be
single spaced.
-t Display non-printing characters (see the -v option), and display
tab characters as `^I'.
-u Disable output buffering.
-v Display non-printing characters so they are visible. Control
characters print as `^X' for control-X; the delete character
(octal 0177) prints as `^?'. Non-ASCII characters (with the high
bit set) are printed as `M-' (for meta) followed by the character
for the low 7 bits.
</code></pre>
</blockquote>
<hr>
<pre class="lang-c prettyprint-override"><code>#include 'stdlib.h'
#include 'stdio.h'
#include 'string.h'
#include 'unistd.h'
#define len 256;
/*function declarations*/
void non_blank (FILE *fin, FILE *fout, int writeLineNumbers);
void dollar_sign(FILE *fin, FILE *fout, int writeLineNumbers); //test comment
void output_line(FILE *fin, FILE *fout, int writeLineNumbers);
void squeeze (FILE *fin, FILE *fout, int writeLineNumbers);
void non_printing (FILE *fin, FILE *fout, int writeLineNumbers);
void non_printingvisible ((FILE *fin, FILE *fout, int writeLineNumbers);
int main(int argc, char *argv[])
{
int opt=0;
int bflag = 0;
int eflag = 0;
int nflag = 0;
int sflag = 0;
int tflag = 0;
int vflag = 0;
//Not sure what value is stored in opt?
while((opt=getopt(argc, argv, "benstv"))!=-1)
switch (opt)
{
case 'b':
bflag=1;
non_blank(stdin, stdout, opt);
break;
case 'e':
eflag=1;
dollar_sign(stdin, stdout, opt);
break;
case 'n': //test comment
nflag=1;
output_line(stdin, stdout, opt);
break;
case 's':
sflag=1;
squeeze(stdin, stdout, opt);
break;
case 't':
tflag=1;
non_printing(stdin, stdout, opt);
break;
case 'v':
vflag=1;
non_printingvisible(stdin, stdout, opt);
break;
default:
abort();
}
//test comment
//implementing -b functionality
void non_blank (FILE *fin, FILE *fout, int writeLineNumbers)
{
char line[len];
int linenumber=1;
while (fgets(line,len,fin))
{
if(writeLineNumbers)
printf("%d",linenumber);
if (fputs(line, fout)==EOF)
{ //test comment
printf(stderr,"Write to stdout failed.");
return;
}
if(line[0]!='\0')
++linenumber;
}
}
// implementing -e functionality.
void dollar_sign (FILE *fin, FILE *fout, int writeLineNumbers)
{
char line[len];
int linenumber=1;
while (fgets(line,len,fin)) //test comment
{
if(writeLineNumbers)
printf(" $");
if (fputs(line, fout)==EOF)
{
printf(stderr,"Write to stdout failed.");
return;
}
++linenumber;
}
}
//implementing -n functionality
void output_line (FILE *fin, FILE *fout, int writeLineNumbers)
{
char line[len];
int linenumber=1;
//test comment
while (fgets(line,len,fin))
{
if(writeLineNumbers)
printf("%d",linenumber);
if (fputs(line, fout)==EOF)
{
printf(stderr,"Write to stdout failed.");
return;
}
++linenumber;
}
}
/* void output_line (FILE *fin, FILE *fout, int writeLineNumbers)
{
char line[len];
int linenumber=1; //test comment
while (fgets(line,len,fin))
{
if(writeLineNumbers)
printf("%d",linenumber);
if (fputs(line, fout)==EOF)
{
printf(stderr,"Write to stdout failed.");
return;
}
++linenumber;
}
}
*/
//implementing -s functionality
void squeeze ( FILE *fin, FILE *fout, int writeLineNumbers)
{
char line[len] = {0};
// int linenumber=1;
//test comment
while (fgets(line,len,fin))
{
if(line[0]=='\n')
fin--=fin;
else if (fputs(line, fout)==EOF)
{
printf(stderr,"Write to stdout failed.");
return;
}
// ++linenumber;
}
}
//test comment
/*should converting each char to int (for ASCII value) and then printing back in char fix it? */
void non_printing ( FILE *fin, FILE *fout, int writeLineNumbers)
{
char line[len];
int linenumber= 1;
int i;
while (fgets(line,len,fin))
{
i=strlen(line); //test comment
for(i=0;i<strlen;i++) //test comment
line[i]
//test comment
if(line==NULL)
fin--;
if (fputs(line, fout)==EOF)
{
printf(stderr,"Write to stdout failed.");
return;
}
++linenumber;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T15:45:48.003",
"Id": "79776",
"Score": "2",
"body": "You seem to be missing some code in `main()`, as well as a level of indentation."
}
] | [
{
"body": "<p>You're initializing but not using local variables like <code>bflag</code>.</p>\n\n<p>Is the user allowed to specify more than one option? <a href=\"http://git.savannah.gnu.org/gitweb/?p=coreutils.git;a=blob_plain;f=src/cat.c;hb=HEAD\" rel=\"nofollow\">Source code for GNU's cat found here</a> says \"Yes, multiple options can be specified\". So instead of calling a different routine for each option, you should call the same routine for all options, and apply any/all specified options for each line read.</p>\n\n<p>You're always reading from <code>stdin</code> however <code>cat</code> allows the input filename to be specified on the command-line.</p>\n\n<p>Your version assumes that 256 is the maximum length of line in the input file.</p>\n\n<p>You're passing <code>writeLineNumbers</code> as a parameter to all subroutines but not using it in most of the subroutines.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T17:34:27.540",
"Id": "45699",
"ParentId": "45696",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T15:20:45.797",
"Id": "45696",
"Score": "5",
"Tags": [
"c",
"unix"
],
"Title": "Implementing the 'cat' command"
} | 45696 |
<p>I have a link (avatar)<code>#qam-account-toggle</code> and <code>div.qam-account-items</code>, the div containing user account links. I am toggling div on avatar click as well as click anywhere but <code>div.qam-account-items</code></p>
<p>Here is my code. How can I optimize this better?</p>
<pre><code>$('#qam-account-toggle').click(function(e){
e.stopPropagation();
$(this).toggleClass('account-active');
$('.qam-account-items').fadeToggle('fast');
});
$(document).click(function(){
$('#qam-account-toggle.account-active').removeClass('account-active');
$('.qam-account-items:visible').hide();
});
$('.qam-account-items').click(function(event){
event.stopPropagation();
});
</code></pre>
| [] | [
{
"body": "<p>I'd suggest wrapping the code in a function, so it's all in one place and can share variables. Then there's no need to find and re-find the same elements in each event handler.</p>\n\n<p>Also, you're doing some extra filtering by class name and such which is unnecessary. E.g. <code>.hide()</code> will hide whatever's visible, so you don't need to first use <code>:visible</code> to find the visible elements.</p>\n\n<pre><code>function enableAccountItemsToggling() {\n // find these once\n var accountToggle = $('#qam-account-toggle'),\n accountItems = $('.qam-account-items');\n\n // toggle items\n accountToggle.on(\"click\", function (event) {\n event.stopPropagation();\n accountToggle.toggleClass('account-active');\n accountItems.fadeToggle('fast');\n\n // a single click is enough; no need for a persistent event handler\n // so we use .one() instead of .on()\n $(document).one(\"click\", function () {\n accountToggle.removeClass(\"account-active\");\n accountItems.fadeOut(\"fast\");\n });\n });\n\n accountItems.on(\"click\", function (event) {\n event.stopPropagation();\n });\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T18:59:56.153",
"Id": "45704",
"ParentId": "45698",
"Score": "0"
}
},
{
"body": "<p>Not much to say here, it looks pretty good. I've moved to only using <code>.on</code> for attaching events as I think it encourages better practices. Remember it's better to save selectors as variables if you are going to reuse them. </p>\n\n<p>Instead of catching the click on <code>.qam-account-items</code> you can just fire the event on everything but those classes;</p>\n\n<pre><code>$(document).on('click', '*:not(.qam-account-items)', function() {\n $('#qam-account-toggle.account-active').removeClass('account-active');\n $('.qam-account-items:visible').hide();\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T16:08:25.130",
"Id": "80006",
"Score": "0",
"body": "Thanks for the answer but this code is not working. stopped show hide.. any idea why is that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T16:18:54.840",
"Id": "80013",
"Score": "0",
"body": "I see this code is only for ignoring `qam-account-items` but it is still hiding it when I click on input box within the div"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T18:44:12.763",
"Id": "80040",
"Score": "0",
"body": "@pixelngrain Yeah you're right... I'll mull it over."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T07:19:08.523",
"Id": "80509",
"Score": "0",
"body": "Any idea how to fix it?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T19:50:04.340",
"Id": "45707",
"ParentId": "45698",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T16:59:09.020",
"Id": "45698",
"Score": "6",
"Tags": [
"javascript",
"jquery"
],
"Title": "Optimizing an avatar toggle"
} | 45698 |
<p>Got this question in a test.</p>
<blockquote>
<p>Display the following number pattern using Java.</p>
<p>User inputs number of rows. For example 3</p>
<pre><code>1112
3222
3334
</code></pre>
<p>For 5</p>
<pre><code>111112
322222
333334
544444
555556
</code></pre>
<p>and so on.</p>
</blockquote>
<p>This is the solution I came up with:</p>
<pre><code> public static void NumberPattern(int n) {
int myarray[][] = new int[n][n + 1];
int i;
int j;
for (i = 0; i < 1; i++) //first row
{
for (j = 0; j < n; j++)
{
myarray[i][j] = i + 1;
}
myarray[i][n] = i + 2;
}
for (i = 1; i < myarray.length; i++)
{
if (i % 2 != 0) //odd rows
{
j = 1;
myarray[i][0] = i + 2;
while (j <= n)
{
myarray[i][j] = i + 1;
j++;
}
j = 1;
}
if (i % 2 == 0) //even rows
{
j = 0;
while (j < n) {
myarray[i][j] = i + 1;
j++;
}
myarray[i][n] = i + 2;
j = 0;
}
}
printArray(myarray);
}
public static void printArray(int n[][])
{
System.out.println("The Pattern is:");
for (int[] array : n) {
for (int v : array) {
System.out.print(" " + v);
}
System.out.println();
}
}
</code></pre>
<p>Is there a better way of solving this problem with only one <code>for</code> loop?</p>
| [] | [
{
"body": "<p>Since all you've been asked is to display output, a single simple nesting of two for loops without arrays should work just fine. Note that in all cases, you know in advance prior to performing a loop how many times the loop will iterate, and in this situation a for loop is cleaner than a while loop (though of course both would work):</p>\n\n<pre><code>// note that method namess should begin with a lower-case letter\npublic static void numberPattern(int rows) {\n for (int row = 0; row < rows; row++) {\n for (int col = 0; col < rows + 1; col++) {\n int number = 0;\n if (row % 2 == 0) {\n number = col < rows ? row + 1 : row + 2;\n } else {\n number = col == 0 ? row + 2 : row + 1;\n }\n System.out.print(number);\n }\n System.out.println();\n }\n}\n</code></pre>\n\n<p>If you need to store the numbers to be used elsewhere, then yes, put them into an array.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T21:55:59.407",
"Id": "45712",
"ParentId": "45701",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "45712",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T18:16:09.247",
"Id": "45701",
"Score": "7",
"Tags": [
"java"
],
"Title": "Number pattern problem using Java"
} | 45701 |
<p>I would like to display this data, callable at any time, but I'm not sure if this is the best practice to do so. </p>
<pre><code>countries = [
dict(Name = "China", Population = "1,363,560,000"),
dict(Name = "India", Population = "1,242,070,000"),
dict(Name = "United States", Population = "317,768,000"),
dict(Name = "Indonesia", Population = "249,866,000"),
dict(Name = "Brazil", Population = "201,032,714"),
dict(Name = "Pakistan", Population = "186,015,000"),
dict(Name = "Nigeria", Population = "173,615,000"),
dict(Name = "Bangladesh", Population = "152,518,015"),
dict(Name = "Russia", Population = "143,700,000"),
dict(Name = "Japan", Population = "127,120,000"),
dict(Name = "Mexico", Population = "119,713,203"),
dict(Name = "Philippines", Population = "99,329,000"),
dict(Name = "Vietnam", Population = "89,708,900"),
dict(Name = "Egypt", Population = "86,188,600"),
dict(Name = "Germany", Population = "80,716,000"),
dict(Name = "Iran", Population = "77,315,000"),
dict(Name = "Turkey", Population = "76,667,864"),
dict(Name = "Thailand", Population = "65,926,261"),
dict(Name = "France", Population = "65,844,000"),
dict(Name = "United Kingdom", Population = "63,705,000"),
dict(Name = "Italy", Population = "59,996,777"),
dict(Name = "South Africa", Population = "52,981,991"),
dict(Name = "South Korea", Population = "50,219,669"),
dict(Name = "Colombia", Population = "47,522,000"),
dict(Name = "Spain", Population = "46,609,700"),
dict(Name = "Ukraine", Population = "45,410,071"),
dict(Name = "Kenya", Population = "44,354,000"),
dict(Name = "Argentina", Population = "40,117,096"),
dict(Name = "Poland", Population = "38,502,396"),
dict(Name = "Sudan", Population = "37,964,000"),
dict(Name = "Uganda", Population = "35,357,000"),
dict(Name = "Canada", Population = "35,344,962"),
dict(Name = "Iraq", Population = "34,035,000"),
]
print countries
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:41:46.943",
"Id": "85220",
"Score": "0",
"body": "And what, exactly, does this question have to do with code review? **Nothing!** Is our new policy that anything goes as long as it is easy to answer and tangentially includes the words 'best practice'? This code does not display the data; the question is clearly about how solve the problem, not how to improve the existing code."
}
] | [
{
"body": "<p>To format the data nicely for printing you can use the <code>ljust</code> method:</p>\n\n<pre><code>print \"Country\".ljust(15),\"Population\"\nfor country in countries:\n print country[\"Name\"].ljust(15), country[\"Population\"]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T02:23:49.733",
"Id": "79825",
"Score": "0",
"body": "Thanks a ton. I'll eventually have my game on here I'm building with this for review."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T00:57:02.093",
"Id": "45721",
"ParentId": "45705",
"Score": "7"
}
},
{
"body": "<p>Starting with the data structure you have (a list of dicts), whose entries are already sorted in descending order of population, it appears that you want the output as a table.</p>\n\n<p>The country name should probably be left justified. The population, being numeric, should probably be right justified. You'll have to decide on some arbitrary column widths.</p>\n\n<p>Python has built in <a href=\"http://docs.python.org/2/library/stdtypes.html#string-formatting-operations\" rel=\"nofollow\">formatting capability</a> to accomplish this, with the ability to extract fields out of a dictionary.</p>\n\n<p>You could define a function that is callable from anywhere.</p>\n\n<pre><code>def print_countries(countries):\n for c in countries:\n print \"%(Name)-16s%(Population)16s\" % (c)\n</code></pre>\n\n<p>For flexibility, you could define a stringifying function instead of a printing function.</p>\n\n<pre><code>def countries_to_str(countries):\n return \"\\n\".join([\"%(Name)-16s%(Population)16s\" % (c) for c in countries])\n</code></pre>\n\n<p>Then you have the flexibility to output the result of <code>countries_to_str(countries)</code> anywhere you want, such as a file.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T01:12:14.003",
"Id": "45722",
"ParentId": "45705",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "45721",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T19:30:38.460",
"Id": "45705",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-2.x",
"formatting"
],
"Title": "Best way to display big data"
} | 45705 |
<blockquote>
<p><strong>Question</strong>: </p>
<p>One of Scotland Yard’s most wanted criminal (Mister X) is on the run
and needs to reach a certain destination safely. There are three modes
of transport available for him - By air, by train or by cab. With air
travel, he can go from station i to station i+3. Using a train would
make him reach station i+2 when starting from i and by taxi he could
go to the next station (i+1).</p>
<p>Now, clearly there can be multiple ways of travelling between two
stations. Thus, you need to help him find out the total number of ways
of reaching station N from station 0. Since the number of ways can be
very large output the answer mod 10<sup>9</sup> +7.</p>
<p><em><strong>Input Specification</em></strong>:</p>
<p>The first line contains the number of test cases, T. This is followed
by T lines each containing an integer N, the station ID.</p>
<p><em><strong>Output Specification</em></strong>:</p>
<p>Print T lines, each line having the corresponding test case's output.</p>
<p><strong>Sample Input</strong>:</p>
<p>2 3 4</p>
<p><strong>Sample Output</strong>:</p>
<p>4 7</p>
<p><strong>Constraints</strong>:</p>
<p>1 <= T <= 100000</p>
<p>2 <= N <= 10<sup>7</sup></p>
</blockquote>
<p><strong>My code to be optimized:</strong> </p>
<pre><code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Solution {
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int testCases=Integer.parseInt(br.readLine());
short ways[]=new short[testCases],i=0;
int stationId;
while(testCases!=0)
{
stationId = Integer.parseInt(br.readLine());
ways[i++] = (short)(getWays(stationId)%(10^9 +7));
testCases--;
}
for(int k:ways)
System.out.println(k);
}
static int getWays(int n)
{
int sum = 1,i=1;
while(i<=n)
{
sum+=(i-1);
i++;
}
return sum;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T19:48:55.100",
"Id": "79798",
"Score": "1",
"body": "You should only change an edit for improvement of formatting only if any meaning in your question was lost. In this case, there wasn't any information lost, so I rolled back the edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T22:08:30.123",
"Id": "79802",
"Score": "3",
"body": "Your sample input does not adhere to the input specification?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T22:12:32.467",
"Id": "79803",
"Score": "5",
"body": "Clarification: In the description it says: *Since the number of ways can be very large output the answer mod xxxx*. Is the `xxxx` *10-to-the-power-of-9-plus-7*, or is it *10-xor-9-plus-7* ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T22:33:37.613",
"Id": "79806",
"Score": "2",
"body": "http://stackoverflow.com/questions/460542/operator-in-java"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T06:44:43.143",
"Id": "79849",
"Score": "1",
"body": "Please do not change the code in the question after it has been answered, as it invalidates existing answers."
}
] | [
{
"body": "<p>Although this is not related to optimization, it looks like you could improve some of the ways you use loops. If you're using a counter, chances are you should use a <code>for</code> loop:</p>\n\n<pre><code>for (int i = number; i > 0; i--) { /*...*/ }\n</code></pre>\n\n<p>This works best if the loop counter initialization is pretty short. But if it's too long and should remain on its own line, then instead have a <code>while</code> loop that updates the counter within the statement:</p>\n\n<pre><code>int i; // some long initialization here instead...\n\nwhile (i-- > 0) { /*...*/ }\n</code></pre>\n\n<p>First, I want to mention that you should use whitespace between operators and keywords for readability. You use it in some places, but you should use it everywhere for consistency.</p>\n\n<p>Second, non-empty code blocks should have the opening curly brace at the end of the line, not on the following line. This is referenced in <a href=\"http://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s4.1.2-blocks-k-r-style\">Google Java Style</a>.</p>\n\n<p>Instead of decrementing <code>testCases</code> within the loop:</p>\n\n<pre><code>while(testCases!=0)\n{\n stationId = Integer.parseInt(br.readLine());\n ways[i++] = (short)(getWays(stationId)%(10^9 +7));\n testCases--;\n}\n</code></pre>\n\n<p>have it done in the <code>while</code> loop statement:</p>\n\n<pre><code>while (testCases-- > 0) {\n stationId = Integer.parseInt(br.readLine());\n ways[i++] = (short)(getWays(stationId)%(10^9 +7));\n}\n</code></pre>\n\n<p>Instead of incrementing <code>i</code> within the loop:</p>\n\n<pre><code>while(i<=n)\n{\n sum+=(i-1);\n i++;\n}\n</code></pre>\n\n<p>make it a <code>for</code> loop:</p>\n\n<pre><code>// move the initialization of i into the loop\n\nfor (int i = 1; i <= n; i++) {\n sum += (i-1);\n}\n</code></pre>\n\n<p>On another note, this:</p>\n\n<pre><code>short ways[]=new short[testCases],i=0;\n</code></pre>\n\n<p>should be on separate lines:</p>\n\n<pre><code>short ways[] = new short[testCases];\nshort i = 0;\n</code></pre>\n\n<p>Although they're of the same type, <code>i</code> is hard to see since it's crammed right next to <code>ways[]</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T21:41:26.667",
"Id": "45711",
"ParentId": "45706",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T19:34:41.253",
"Id": "45706",
"Score": "6",
"Tags": [
"java",
"optimization",
"complexity"
],
"Title": "Determine total number of ways of reaching a destination"
} | 45706 |
<p>I'm not much of a jQuery coder (more of a PHP coder), except to call a few get values out of class and id and Ajax calls. However, I need to make a checkout system work and one thing I would like to do is to put a loading wait while I send a form through Ajax. When it's finished, it would redirect the user.</p>
<p>So on click:</p>
<ol>
<li>load the loading spinner</li>
<li>fade the background out</li>
<li>Ajax call</li>
<li>when Ajax is done submitting a form which indirectly redirects.</li>
</ol>
<p>Here is my code, following why I don't like it:</p>
<pre><code>jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
return this;
}
$( ".buttonFinish" ).on('click', function(event) {
$('body').fadeOut('slow');
$('#loader').center();
$('#loading').center();
$('#loader').show();
$('#loading').show();
//Use the above function as:
var request = $.ajax({
url:'{{ URL::route('saveCart') }}',
type:'POST'
});
request.done(function(msg) {
$('.order_number').val(msg);
$('#summaryForm').submit();
event.preventDefault();
});
return false;
});
</code></pre>
<p>Let's get a few questions out of the way: <code>{{UR::route('')}}</code> is laravel syntax to call the routing name for URL. loader/loading are two div that I have for the spinner one is text the other is an animation through CSS. (I'd rather CSS it than to load a pix, but I am aware that loader.gif can be small)</p>
<p>My issue (and feeling) that this can be better. I am using CSS with display:none to hide my two div, and then I call <code>fadeOut</code>, show, show, and center center function to center my loading Ajax in order to center things. Is there a compact way to achieve all the 4 steps needed in a clean way? </p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T03:09:12.647",
"Id": "79828",
"Score": "0",
"body": "Does this code actually work? As far as I can tell, you hide (fade out) the `body` element, which hides _everything_. It doesn't matter that you call `.show()` on something later: it'll remain hidden because `body` is hidden."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T03:32:14.493",
"Id": "79832",
"Score": "0",
"body": "@flambino yes the code does work. As mentioned the first thing it does is hide the body, then pops the two div #loader #loading which in on the foreground with .show()"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T05:52:05.220",
"Id": "79843",
"Score": "0",
"body": "I see you've gotten a pretty good answer, but just to reiterate: There is no \"foreground\" that's not nested inside the `body` element. Again, _everything_ you see on the page is inside the `body` element, so if you hide the body, you hide everything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T08:48:40.143",
"Id": "79857",
"Score": "0",
"body": "@Flambino after reading it more throughly - what i saw as result was just a fast pace show() but clearly got masked by the fadedout...despite it seems that its appears in foreground as you have suggested it was not"
}
] | [
{
"body": "<p>Let's go through it one section at a time.</p>\n\n<pre><code>jQuery.fn.center = function () {\n this.css(\"position\",\"absolute\");\n this.css(\"top\", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + \"px\");\n this.css(\"left\", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + \"px\");\n return this;\n }\n</code></pre>\n\n<ul>\n<li><p>You don't have to explicitly append <code>'px'</code> to your numeric values. jQuery is smart enough to \ncorrectly format your CSS styles.</p></li>\n<li><p>Since this is a jQuery plugin, you <code>return this;</code> at the end of the function. This is good, as\nit preserves chaining.</p></li>\n<li><p>If the <code>.center</code> function is only used for the loading <code>div</code>s, consider removing it and instead\nstyling the <code>div</code>s with plain CSS.</p>\n\n<pre><code>#loader {\n position: fixed;\n top: 50%;\n left: 50%;\n margin-top: -50px; /* half of the height */\n margin-left: -100px; /* half of the width */\n}\n...\n</code></pre></li>\n</ul>\n\n<hr>\n\n<pre><code>$( \".buttonFinish\" ).on('click', function(event) {\n $('body').fadeOut('slow');\n $('#loader').center();\n $('#loading').center();\n $('#loader').show();\n $('#loading').show();\n</code></pre>\n\n<ul>\n<li><p>As mentioned by @Flambino, this particular code (as presented in the question) will fade out the entire body of the HTML document, which includes <em>everything</em>, <a href=\"http://jsfiddle.net/3n7BT/\" rel=\"nofollow\">even the <code>loader</code> elements</a>. Perhaps the code that you're actually using is slightly different (is the selector <code>.body</code> or <code>#body</code> instead?).</p></li>\n<li><p>It's best practice to enclose JavaScript that uses external dependencies inside an <a href=\"http://en.wikipedia.org/wiki/Immediately-invoked_function_expression\" rel=\"nofollow\">IIFE</a>.\nBy doing so, you can use the \"safe\" name of an external dependency while still being able to\nalias is to a more convenient identifier locally. In addition, you can freely create variables inside the scope\nof the IIFE without polluting the global namespace. Your example code is fairly short, but you likely have much\nmore code on the page, and it is a good habit to have regardless. Here's one way to do it:</p>\n\n<pre><code>(function($) {\n $( \".buttonFinish\" ).on('click', function(event) {\n ...\n });\n})(jQuery);\n</code></pre></li>\n<li><p>You can select both elements at the same time, just like in CSS: <code>$('#loader, #loading')</code>.</p></li>\n<li><p>You can chain the <code>.show()</code> and <code>.center()</code> together: <code>$('...').show().center()</code>.</p></li>\n</ul>\n\n<hr>\n\n<pre><code> //Use the above function as:\n var request = $.ajax({\n url:'{{ URL::route('saveCart') }}',\n type:'POST'\n });\n\n request.done(function(msg) {\n $('.order_number').val(msg);\n $('#summaryForm').submit();\n event.preventDefault();\n });\n return false;\n});\n</code></pre>\n\n<ul>\n<li><p>Since you're not using the <code>request</code> variable for anything other than <code>.done()</code>,\nyou can skip declaring it and simply chain <code>.done()</code> after <code>$.ajax()</code>:</p>\n\n<pre><code>$.ajax({\n ...\n}).done(function(msg) {\n ...\n});\n</code></pre></li>\n</ul>\n\n<p>As an overall note, the indentation of the code (as it is in the question) seems haphazard,\nmaking the control flow more difficult to see than it could be. Making matching\nbraces have the same indentation (and, in general, maintaining a consistent style)\nwill help make the code more readable and understandable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T03:50:45.070",
"Id": "79833",
"Score": "0",
"body": "appreciate the thorough input. As far as the indentation thats primarily due to only hitting ctrl+k after a copy paste. The center is only to center the div. If I style it does your code snippet ensures the loader is within view of the user (ie the user has scrolled down and the loader activates with the jquery its perfectly centered). As far as the body.fadeOut vs show() the intention was to make the body of the page be greyed out (pushed to the background even further) and have the loading more on the forefront (as mentioned in my goal). If its an incorrect method - please correct me. tks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T03:56:58.453",
"Id": "79834",
"Score": "1",
"body": "@azngunit81: Yes, `position: fixed;` does exactly what you're describing: it 'fixes' an element absolutely within the window (regardless of scroll position), instead of absolutely within the page. As for `fadeOut`, indeed, this method fade out and eventually _completely hides_ its target. Instead, you could group the main elements within your page inside something like `<div id=\"page-main\">`, add `#header` _outside of_ this div, and then use something like `jQuery.fn.fadeTo('slow', 0.6)` on `#page-main` to fade to 60% opacity."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T04:01:53.547",
"Id": "79835",
"Score": "0",
"body": "I see, one last question: is there any degradation in performance if two div requires a show()? (like th #loader, #loading)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T04:17:54.950",
"Id": "79836",
"Score": "0",
"body": "@azngunit81: No, `.show()` is a very fast operation (it's essentially just setting the `display` CSS style). However, if one of the elements is, display-wise, \"contained\" within the other one, you could actually just nest it within the outer one, and then you would only have to `.center()` and `.show()` the outer container."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T04:24:49.550",
"Id": "79837",
"Score": "0",
"body": "I tried that but the css i am using fpr #loader is animation: orbit 7.15s infinite; (basically little balls that rotates around a radius) and I wanted the text \"loading\" to be centered. The only way I found to do that effectively while having both correctly centered was to div both and center both."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T03:38:00.290",
"Id": "45725",
"ParentId": "45717",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "45725",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T00:17:53.120",
"Id": "45717",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"html",
"css"
],
"Title": "Fading and Loader jQuery Improvement"
} | 45717 |
<p>I'm doing my homework and it says to write a test program that prompts the user to enter ten double values, invokes this method, and displays the average value.</p>
<p>I was able to get this program working with an overloaded method... but I'm curious to hear your feedback on where I can improve and what I'm not understanding 100%. Please feel free to review this and let me know your constructive feedback as to my code and where you think I can do better.</p>
<pre><code>import java.util.Scanner;
public class PP68 {
public static void main(String [] args) {//start main
Scanner input = new Scanner(System.in); //new object of scanner type
double avg =0, total =0;
double[] average = new double[10]; //double array
for(int i = 0; i < 10; i++){ //enter 10 numbers to average
System.out.print("Enter a number to average.");
average[i] = input.nextDouble();
}
for(int j = 0; j < average.length; j++) {
total = total + average[j];
avg = total / average.length;
}
System.out.println("The average of your arrays numbers is: " + avg);
}//end main
public static int average(int[] array){ //1st method
int total =0;
int avg = total / array.length;
return avg;
}//end 1st method
public static double average(double[] array) {//Second method - overloaded
double total = 0;
double avg = total / array.length;
return avg;
}//end 2nd method
}
</code></pre>
<hr>
<p>New code follows below:</p>
<pre><code>import java.util.Scanner;
public class PP68v2 {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter 1 to average an INT or hit 2 to average a DOUBLE");
int entry = input.nextInt();
if (entry == 2) { //choose double and call double method
double[] array = new double[10];
for(int i = 0; i < 10; i++){
System.out.println("Enter a number to average.");
array[i] = input.nextDouble();
}
System.out.println("The average of your arrays numbers is: " + average(array));
} else if (entry == 1) { //choose int and call int method
int[] array = new int[10];
for(int b = 0; b < 10; b++) {
System.out.println("Enter a number to average.");
array[b] = input.nextInt();
}
System.out.println("The average of your arrays numbers is: " + average(array));
}
}
public static int average(int[] array){
int total =0;
int avg1 = 0;
for(int b=0; b < 10; b++) {
total = total + array[b];
avg1 = total / 10;
}
return avg1;
}
public static double average(double[] array) {
double total = 0;
double avg = 0;
for(int i =0; i < 10; i++) {
total = total + array[i];
avg = total / array.length;
}
return avg;
}
}
</code></pre>
| [] | [
{
"body": "<p>You wrote the <code>average</code> method but you're not calling it.</p>\n\n<p>The <code>average</code> method need not be overloaded because the problem doesn't ask for a version of it which works with <code>int</code> arrays (so you can delete the version which works with <code>int</code> arrays).</p>\n\n<p>The <code>average</code> method is setting <code>double total = 0;</code> but is then not summing the elements in the array (you're currently doing that, calculating the total, in your second <code>for</code> loop inside main: instead that <code>for</code> loop should be moved into the body of your <code>average</code> method, and your <code>main</code> should call that <code>average</code> method instead of running that <code>for</code> loop).</p>\n\n<p>In <code>main</code> the array is named <code>average</code>: it should probably be renamed to <code>input</code> or something like that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T01:03:18.237",
"Id": "79818",
"Score": "0",
"body": "Ew, that's a great point. How would I make use of the int average method? As this is the first overloaded method I'm trying to write, I'm a bit confused on that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T01:06:41.547",
"Id": "79819",
"Score": "0",
"body": "To invoke the `int average` method you would need to pass an array of type `int[]` as a parameter. Currently you only create one array in `main`, and that array is of type `double[]`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T01:38:10.913",
"Id": "79823",
"Score": "0",
"body": "Thanks, I'll repost once I've taken into account your help."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T00:49:27.003",
"Id": "45720",
"ParentId": "45718",
"Score": "2"
}
},
{
"body": "<p>The code produces the right output, which is good. It has some problems, though.</p>\n\n<h3>The <code>average()</code> functions</h3>\n\n<p>As @ChrisW points out, the two <code>average()</code> functions you defined are not being used. Since your inputs are <code>double</code>s, you only need one of them: the <code>double average(double[] array)</code> function.</p>\n\n<p>The <code>average()</code> functions are currently buggy:</p>\n\n<ul>\n<li><code>total = 0</code>, so of course they will each always return 0. Copy the summation code from <code>main()</code> to fix that.</li>\n<li>The <code>int</code> version uses integer arithmetic, so division rounds the result to an integer (towards 0). In general, the average of a set of integers is not an integer. You should use <code>double</code> to store the total, even in the integer version. (You did it correctly in <code>main()</code>.)</li>\n</ul>\n\n<p>In case you're wondering, if you want to be able to handle integral and floating-point input arrays, you do need to write out both the <code>int[]</code> and <code>double[]</code> versions explicitly.</p>\n\n<h3><code>main()</code></h3>\n\n<p>If you open a <code>Scanner</code>, it's good etiquette to close it. The idiom for doing that since Java 7 is to use a try-with-resources block:</p>\n\n<pre><code>try (Scanner input = new Scanner(System.in)) {\n …\n}\n</code></pre>\n\n<p>Avoid declaring and defining variables <code>avg</code> and <code>total</code> until you need them.</p>\n\n<p>The <code>average</code> array is poorly named. It's an array of ten user input numbers, not an array of ten averages.</p>\n\n<p>You hard-coded <code>10</code> twice. The first for-loop should be more like the second, which uses <code>average.length</code>.</p>\n\n<p>The average only needs to be computed once, not ten times. Pull the division operation out of the loop.</p>\n\n<p>Of all the comments in the class, the only one worth keeping is <code>// enter 10 numbers to average</code>. All of the others are redundant noise.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T02:24:40.720",
"Id": "79826",
"Score": "0",
"body": "Thanks. I've been working on a revised version and I'd like to post that and reply to some of your comments. Sadly, I'm still having trouble with the syntax."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T02:56:48.893",
"Id": "79827",
"Score": "0",
"body": "@Pivo If the syntax you are having trouble with is calling a method with an array as a parameter, I tried https://www.google.com/search?q=java+call+method+array+parameter as a Google query and it found http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/09/array-param.html which you might find useful."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T02:03:56.573",
"Id": "45723",
"ParentId": "45718",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T06:35:33.707",
"Id": "45718",
"Score": "6",
"Tags": [
"java",
"beginner",
"homework"
],
"Title": "Pass an array of numbers into a method that's overloaded"
} | 45718 |
<p>The code here will be directly pasted from <a href="https://github.com/fge/largetext" rel="nofollow noreferrer">this project</a>. Quick summary: it is related to a <a href="https://stackoverflow.com/q/22017480/1093528">Stack Overflow question</a>.</p>
<p>So, basically, all the code below aims to implement <code>CharSequence</code> over a large text file, within the limitation of <code>CharSequence</code> itself (that is, up to <code>Integer.MAX_VALUE</code> chars). All the code below is extracted from <a href="https://github.com/fge/largetext/tree/master/src/main/java/com/github/fge/largetext/load" rel="nofollow noreferrer">the same package</a>.</p>
<p>The process is as follows:</p>
<ul>
<li>a <code>TextDecoder</code> is issued for one file which (supposedly) contains text; it will decode byte sequences into char sequences;</li>
<li>it instantiates one instance of a <code>DecodingStatus</code>; this class will keep track of how many characters were successfully decoded so far, and if necessary will report an error instead;</li>
<li>processes "waiting" for a given amount of characters will create a <code>CharWaiter</code> instance; they will be queues into the <code>DecoderStatus</code> only if their requirement (character offset) has not been meant;</li>
<li>should a decoding error happen, the <code>DecodingStatus</code> instance will terminate all <code>CharWaiter</code>s for an instance.</li>
</ul>
<p>OK; so, first things first: the code works and is mostly tested; my problem is that it is ugly. In particular, in <code>DecodingStatus</code>, all methods <em>except one</em> are synchronized. Also, error "recovery" code is duplicated in several places.</p>
<p>How can I improve upon this code? In particular, can I avoid making (nearly) all methods in <code>DecodingStatus</code> <code>synchronized</code>? Can I avoid duplicating error checking?</p>
<p>First, the <code>CharWaiter</code>:</p>
<pre><code>import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.PriorityQueue;
import java.util.concurrent.CountDownLatch;
/**
* A waiter on a number of available characters in a {@link TextDecoder}
*
* <p>When it is woken up, it will check for the status of the operation; it
* will throw a {@link RuntimeException} if the decoding operation fails, or it
* has waited to more characters than what is actually available.</p>
*
* <p>It implements {@link Comparable} since instances of this class are used in
* a {@link PriorityQueue}.</p>
*
* <p>Inspired from <a href="https://stackoverflow.com/a/22055231/1093528">this
* StackOverflow answer</a>.</p>
*
* @see DecodingStatus
* @see TextDecoder#needChars(int)
*/
final class CharWaiter
implements Comparable<CharWaiter>
{
private final int required;
private final CountDownLatch latch = new CountDownLatch(1);
private int nrChars = 0;
private IOException exception = null;
CharWaiter(final int required)
{
if (required < 0)
throw new ArrayIndexOutOfBoundsException(required);
this.required = required;
}
void setNrChars(final int nrChars)
{
this.nrChars = nrChars;
}
void setException(final IOException exception)
{
this.exception = exception;
}
int getRequired()
{
return required;
}
void await()
throws InterruptedException
{
latch.await();
if (exception != null)
throw new RuntimeException("decoding error", exception);
if (nrChars < required)
throw new ArrayIndexOutOfBoundsException(required);
}
void wakeUp()
{
latch.countDown();
}
@Override
public int compareTo(@Nonnull final CharWaiter o)
{
return Integer.compare(required, o.required);
}
@Override
public String toString()
{
return "waiting for " + required + " character(s)";
}
}
</code></pre>
<p>Then, the <code>DecodingStatus</code>:</p>
<pre><code>import javax.annotation.concurrent.ThreadSafe;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.concurrent.CountDownLatch;
/**
* The watchdog class for a text decoding operation
*
* <p>This class takes care of {@link CharWaiter}s and callers to {@link
* TextDecoder#getTotalChars()}.</p>
*
* <p>The decoding process in {@link TextDecoder} will update the internal
* status of this object when the decoding operation makes progress; on an
* update, this class will wake up the relevant waiters.</p>
*
* <p>In the event of an error, all waiters are woken up.</p>
*
* @see CharWaiter
*/
@ThreadSafe
final class DecodingStatus
{
private boolean finished = false;
private int nrChars = -1;
private IOException exception = null;
private final Queue<CharWaiter> waiters = new PriorityQueue<>();
private final CountDownLatch endLatch = new CountDownLatch(1);
synchronized boolean addWaiter(final CharWaiter waiter)
{
if (exception != null)
throw new RuntimeException("decoding error", exception);
final int required = waiter.getRequired();
if (required <= nrChars)
return false;
if (!finished) {
waiters.add(waiter);
return true;
}
if (required > nrChars)
throw new ArrayIndexOutOfBoundsException(required);
return false;
}
synchronized void setNrChars(final int nrChars)
{
this.nrChars = nrChars;
CharWaiter waiter;
while (!waiters.isEmpty()) {
waiter = waiters.peek();
if (waiter.getRequired() > nrChars)
break;
waiter.setNrChars(nrChars);
waiters.remove().wakeUp();
}
}
synchronized void setFailed(final IOException exception)
{
this.exception = exception;
final List<CharWaiter> list = new ArrayList<>(waiters);
waiters.clear();
for (final CharWaiter waiter: list) {
waiter.setException(exception);
waiter.wakeUp();
}
endLatch.countDown();
}
synchronized void setFinished(final int nrChars)
{
finished = true;
this.nrChars = nrChars;
final List<CharWaiter> list = new ArrayList<>(waiters);
waiters.clear();
for (final CharWaiter waiter: list) {
waiter.setNrChars(nrChars);
waiter.wakeUp();
}
endLatch.countDown();
}
int getTotalSize()
{
try {
endLatch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("interrupted", e);
}
if (exception != null)
throw new RuntimeException("decoding error", exception);
return nrChars;
}
@Override
public synchronized String toString()
{
if (exception != null)
return "decoding error after reading " + nrChars + " character(s)";
return "currently decoded: " + nrChars + " character(s); finished: "
+ finished;
}
}
</code></pre>
<p>And finally, the <code>TextDecoder</code>:</p>
<pre><code>import com.github.fge.largetext.LargeText;
import com.github.fge.largetext.LargeTextFactory;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Range;
import com.google.common.collect.RangeMap;
import com.google.common.collect.TreeRangeMap;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
import java.io.Closeable;
import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
/**
* Text file decoder
*
* <p>This is the first core class of this package (the second is {@link
* TextLoader}. Its role is to decode a text file chunk by chunk. The size of
* chunks to use is determined when you build your {@link LargeTextFactory}.</p>
*
* <p>{@link LargeText} will call upon this class to obtain a {@link TextRange}
* (or a list of them) containing the character at a given index (or the range
* of characters), by using the methods {@link #getRange(int)} and {@link
* #getRanges(com.google.common.collect.Range)} respectively.</p>
*
* <p>These methods are blocking, but they <em>do not</em> throw {@link
* InterruptedException}; if an interruption occurs, these methods reset the
* thread interruption status and throw the appropriate {@link
* RuntimeException} (for instance, an {@link ArrayIndexOutOfBoundsException} if
* the requested offset exceeds the number of characters in the file).</p>
*
* <p>Implementation note: this class uses a <em>single threaded</em> {@link
* ExecutorService} to perform the decoding operation. Decoding is not done in
* parallel, and cannot be, since it is not guaranteeed that a byte mapping can
* be decoded exactly to a character sequence (for instance, using UTF-8, the
* end of the mapping may contain one byte only of a three-byte sequence).</p>
*
* @see DecodingStatus
*/
@ThreadSafe
public final class TextDecoder
implements Closeable
{
private static final ThreadFactory THREAD_FACTORY
= new ThreadFactoryBuilder().setDaemon(true).build();
private final ExecutorService executor
= Executors.newSingleThreadExecutor(THREAD_FACTORY);
private final DecodingStatus status = new DecodingStatus();
@GuardedBy("ranges")
private final RangeMap<Integer, TextRange> ranges = TreeRangeMap.create();
private final FileChannel channel;
private final Charset charset;
private final long fileSize;
private final long targetMapSize;
/**
* Constructor; don't use directly!
*
* @param channel the {@link FileChannel} to the target file
* @param charset the character encoding to use
* @param targetMapSize the target byte mapping size
* @throws IOException error obtaining information on the channel
*/
public TextDecoder(final FileChannel channel, final Charset charset,
final long targetMapSize)
throws IOException
{
this.channel = channel;
fileSize = channel.size();
this.targetMapSize = targetMapSize;
this.charset = charset;
executor.submit(decodingTask());
}
/**
* Return the appropriate text range containing the character at the given
* offset
*
* @param charOffset the offset
* @return the appropriate {@link TextRange}
* @throws RuntimeException method has been interrupted, or a decoding error
* has occurred
* @throws ArrayIndexOutOfBoundsException offset requested is out of range
*/
public TextRange getRange(final int charOffset)
{
try {
needChars(charOffset + 1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted", e);
}
synchronized (ranges) {
return ranges.get(charOffset);
}
}
/**
* Return an ordered iterable of text ranges covering the requested range
*
* @param range the range
* @return the appropriate list of text ranges
* @throws RuntimeException method has been interrupted, or a decoding error
* has occurred
* @throws ArrayIndexOutOfBoundsException range is out of bounds for this
* decoder
*/
public List<TextRange> getRanges(final Range<Integer> range)
{
try {
needChars(range.upperEndpoint());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted", e);
}
final Collection<TextRange> ret;
synchronized (ranges) {
ret = ranges.subRangeMap(range).asMapOfRanges().values();
}
return ImmutableList.copyOf(ret);
}
/**
* Return the total number of characters in this decoder
*
* <p>This method sleeps until the decoding operation finishes (either
* successfully or with an error).</p>
*
* @return the total number of characters
* @throws RuntimeException method has been interrupted, or a decoding error
* has occurred
*
* @see DecodingStatus#getTotalSize()
*/
public int getTotalChars()
{
return status.getTotalSize();
}
@Override
public void close()
throws IOException
{
executor.shutdown();
}
private void needChars(final int needed)
throws InterruptedException
{
final CharWaiter waiter = new CharWaiter(needed);
if (status.addWaiter(waiter))
waiter.await();
}
// TODO: move to another class?
private Runnable decodingTask()
{
return new Runnable()
{
@Override
public void run()
{
final CharsetDecoder decoder = charset.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
final CharBuffer charMap
= CharBuffer.allocate((int) targetMapSize);
long byteOffset = 0L;
int charOffset = 0;
TextRange range;
while (byteOffset < fileSize) {
try {
range = nextRange(byteOffset, charOffset, decoder,
charMap);
if (range.getByteRange().isEmpty())
throw new IOException("unable to read file as text "
+ "starting from byte offset " + byteOffset);
} catch (IOException e) {
status.setFailed(e);
break;
}
byteOffset = range.getByteRange().upperEndpoint();
charOffset = range.getCharRange().upperEndpoint();
status.setNrChars(charOffset);
synchronized (ranges) {
ranges.put(range.getCharRange(), range);
}
}
status.setFinished(charOffset);
}
};
}
private TextRange nextRange(final long byteOffset, final int charOffset,
final CharsetDecoder decoder, final CharBuffer charMap)
throws IOException
{
long nrBytes = Math.min(targetMapSize, fileSize - byteOffset);
final MappedByteBuffer byteMap
= channel.map(FileChannel.MapMode.READ_ONLY, byteOffset, nrBytes);
charMap.rewind();
decoder.reset();
final CoderResult result = decoder.decode(byteMap, charMap, true);
// FIXME
if (result.isUnmappable())
result.throwException();
/*
* Incomplete byte sequence: in this case, the mapping position reflects
* what was actually read; change the mapping size
*/
if (result.isMalformed())
nrBytes = (long) byteMap.position();
return new TextRange(byteOffset, nrBytes, charOffset,
charMap.position());
}
}
</code></pre>
| [] | [
{
"body": "<ol>\n<li><p><code>TextRandge</code> could be declared inside the loop and could be <code>final</code>: </p>\n\n<blockquote>\n<pre><code>TextRange range;\n\nwhile (byteOffset < fileSize) {\n</code></pre>\n</blockquote>\n\n<p>The same is true for <code>waiter</code> here:</p>\n\n<blockquote>\n<pre><code>CharWaiter waiter;\nwhile (!waiters.isEmpty()) {\n waiter = waiters.peek();\n</code></pre>\n</blockquote>\n\n<p>(<em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>)</p></li>\n<li><p>I'd rename this to <code>createDecodingTask</code>:</p>\n\n<blockquote>\n<pre><code>// TODO: move to another class?\nprivate Runnable decodingTask()\n</code></pre>\n</blockquote>\n\n<p>From <em>Clean Code, Chapter 2: Meaningful Names</em>:</p>\n\n<blockquote>\n <p><strong>Method Names</strong></p>\n \n <p>Methods should have verb or verb phrase names like <code>postPayment</code>, <code>deletePage</code>, or <code>save</code>.\n [...]</p>\n</blockquote></li>\n<li><p>For the <code>TODO</code> comment above: I'm usually working with a lot smaller classes than 240 lines, I'd move it to another class. It makes testing easier.</p></li>\n<li><p>I'd wait here a little bit with <code>executor.awaitTermination</code> and check its return value.</p>\n\n<blockquote>\n<pre><code>@Override\npublic void close()\n throws IOException\n{\n executor.shutdown();\n}\n</code></pre>\n</blockquote>\n\n<p>I see that the code uses daemon threads but if the application doesn't stop entirely, just closes the <code>TextDecoder</code> it may have some threads running in the background needlessly and without any notice. Failing early usually helps preventing bigger bugs/shutdowns.</p></li>\n<li><p>Moving this code to another class and passing an <code>Executor</code> to the constructor would help testing also (probably with a <a href=\"https://stackoverflow.com/q/6581188/843804\">current thread executor</a>):</p>\n\n<blockquote>\n<pre><code>private static final ThreadFactory THREAD_FACTORY\n = new ThreadFactoryBuilder().setDaemon(true).build();\n\nprivate final ExecutorService executor\n = Executors.newSingleThreadExecutor(THREAD_FACTORY);\n</code></pre>\n</blockquote>\n\n<p>It would separate the concerns, you could test the parts isolated.</p></li>\n<li><p>Starting another thread/Runnable from the constructor <a href=\"https://softwareengineering.stackexchange.com/a/48941/36726\">smells a little bit</a>. It looks safe as its the last call in the constructor but I'd still try to avoid that.</p></li>\n<li><p>You could move this logic to a <code>checkException</code> method, it's used twice:</p>\n\n<blockquote>\n<pre><code>if (exception != null)\n throw new RuntimeException(\"decoding error\", exception);\n</code></pre>\n</blockquote></li>\n<li><p>The code already uses Guava, so I'd consider using <code>Preconditions.checkArgument</code> here (although it throws <code>IllegalArgumentException</code>):</p>\n\n<blockquote>\n<pre><code>if (required < 0)\n throw new ArrayIndexOutOfBoundsException(required);\n</code></pre>\n</blockquote></li>\n<li><p>A more descriptive name than <code>nrChars</code> (<code>loadedChars</code>, <code>readChars</code>, <code>decodedChars</code>?) and a named constants for <code>-1</code> (with a descriptive name) would help readers here:</p>\n\n<blockquote>\n<pre><code>private int nrChars = -1;\n</code></pre>\n</blockquote></li>\n<li><p>I would be a little bit more defensive here and check that the <code>nrChars</code> parameter's value is higher than the field's value:</p>\n\n<blockquote>\n<pre><code>synchronized void setNrChars(final int nrChars)\n{\n this.nrChars = nrChars;\n</code></pre>\n</blockquote>\n\n<p>(<em>The Pragmatic Programmer: From Journeyman to Master</em> by <em>Andrew Hunt</em> and <em>David Thomas</em>: <em>Dead Programs Tell No Lies</em>.)</p></li>\n<li><p>The following is used more than once, I'd create a method for it:</p>\n\n<blockquote>\n<pre><code>final List<CharWaiter> list = new ArrayList<>(waiters);\nwaiters.clear();\n</code></pre>\n</blockquote></li>\n<li><p>I don't think that <code>DecodingStatus</code> is thread-safe. Reading of <code>nrChars</code> should be also in a synchronized block (in <code>getTotalSize()</code>).</p>\n\n<blockquote>\n <p>[...] synchronization has no effect unless both read and write operations are synchronized.</p>\n</blockquote>\n\n<p>Source: <em>Effective Java, 2nd Edition, Item 66: Synchronize access to shared mutable data</em></p>\n\n<blockquote>\n <p>Locking is not just about mutual exclusion; it is also about memory visibility.\n To ensure that all threads see the most up-to-date values of shared mutable \n variables, the reading and writing threads must synchronize on a common lock.</p>\n</blockquote>\n\n<p>Source: <em>Java Concurrency in Practice, 3.1.3. Locking and Visibility</em>.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T11:24:36.440",
"Id": "79865",
"Score": "0",
"body": "As to point 1, I prefer it this way... Minimizing the scope is all good all well, but I prefer to declare my variables _out_ of the loop in this case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T11:31:41.310",
"Id": "79866",
"Score": "0",
"body": "Point 8: no! I implement `CharSequence` here, so I need to throw this exception"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T11:11:56.907",
"Id": "45745",
"ParentId": "45724",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T02:32:22.197",
"Id": "45724",
"Score": "2",
"Tags": [
"java",
"thread-safety",
"concurrency",
"guava"
],
"Title": "Decoding big text input: potential concurrency bugs?"
} | 45724 |
<p>Solved the ford-fulkerson algorithm, which is too vast to explain it comprehensively here. Check <a href="http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm">Wikipedia for Ford-Fulkerson</a> and <a href="https://www.youtube.com/watch?v=_yOSku77w0o">Princeton lecture on Ford-Fulkerson</a>.</p>
<p>Looking for code review, optimizations and best practices. Also I request you avoid mentioning renaming <code>GraphFordFuklerson</code> and unit tests not done in separate files as I am aware it's not good practices, but deliberately done for personal convenience.</p>
<pre><code>/**
* A duplex edge is two edges(forward and reverse edge) combined into one.
* In ford-fulkerson algo, we have a concept of forward edge and a reverse edge.
*
* The forward edge is when the "from" node equals "from" node set by constructor
* and
* "to" node equals "to" node set by constructor.
*
* Duplex emulates both these edges by returning different values based on "to" and "from"
* ie, it behaves as both "forward edge" and "backward egde" based on its input parameters.
*
* @param <T>
*/
final class DuplexEdge<T> {
private final T from;
private final T to;
private final double capacity;
private double consumedCapacity;
public DuplexEdge (T from, T to, double capacity, double consumedCapacity) {
if (from == null || to == null) {
throw new NullPointerException("Neither from nor to should be null.");
}
this.from = from;
this.to = to;
this.capacity = capacity;
this.consumedCapacity = consumedCapacity;
}
/**
* Returns the remaining capacity of that pipe/edge/channel.
* From `from` and `to` a determination is made if its a forward edge of backward edge.
* Depending on edge type the capacity is returned.
*
* @param from the from/source node
* @param to the to node.
* @return the remaining capacity on determing if its a forward or reverse edge.
*/
public double getCapacity(T from, T to) {
if (this.from.equals(from) && this.to.equals(to)) {
return capacity - consumedCapacity;
}
// indicates reverse flow.
if (this.from.equals(to) && this.to.equals(from)) {
return consumedCapacity;
}
throw new IllegalArgumentException("Both from: " + from + " and to : " + to + " should be part of this edge.");
}
/**
* Adjusts/modifies the remaining capacity of that pipe/edge/channel.
* From `from` and `to` a determination is made if its a forward edge of backward edge.
* Depending on edge type the capacity is adjusted.
*
* @param from the from/source node
* @param to the to node.
* @return the remaining capacity on determing if its a forward or reverse edge.
*/
public double adjustCapacity(T from, T to, double consumedCapacity) {
if (consumedCapacity > getCapacity(from, to)) {
throw new IllegalArgumentException("The consumedCapacity " + consumedCapacity + " exceeds limit.");
}
if (this.from.equals(from) && this.to.equals(to)) {
this.consumedCapacity = this.consumedCapacity + consumedCapacity;
}
// indicates reverse flow.
if (this.from.equals(to) && this.to.equals(from)) {
this.consumedCapacity = this.consumedCapacity - consumedCapacity;
}
throw new IllegalArgumentException("Both from: " + from + " and to : " + to + " should be part of this edge.");
}
}
class GraphFordFuklerson<T> implements Iterable<T> {
/* A map from nodes in the graph to sets of outgoing edges. Each
* set of edges is represented by a map from edges to doubles.
*/
private final Map<T, Map<T, DuplexEdge<T>>> graph;
public GraphFordFuklerson() {
graph = new HashMap<T, Map<T, DuplexEdge<T>>>();
}
/**
* Adds a new node to the graph. If the node already exists then its a
* no-op.
*
* @param node Adds to a graph. If node is null then this is a no-op.
* @return true if node is added, false otherwise.
*/
public boolean addNode(T node) {
if (node == null) {
throw new NullPointerException("The input node cannot be null.");
}
if (graph.containsKey(node)) return false;
graph.put(node, new HashMap<T, DuplexEdge<T>>());
return true;
}
/**
* Given the source and destination node it would add an arc from source
* to destination node. If an arc already exists then the value would be
* updated the new value.
*
* @param source the source node.
* @param destination the destination node.
* @param capacity if length if
* @throws NullPointerException if source or destination is null.
* @throws NoSuchElementException if either source of destination does not exists.
*/
public void addEdge (T source, T destination, double capacity) {
if (source == null || destination == null) {
throw new NullPointerException("Source and Destination, both should be non-null.");
}
if (!graph.containsKey(source) || !graph.containsKey(destination)) {
throw new NoSuchElementException("Source and Destination, both should be part of graph");
}
DuplexEdge<T> duplexEdge = new DuplexEdge<T>(source, destination, capacity, 0);
/* A node would always be added so no point returning true or false */
graph.get(source).put(destination, duplexEdge);
graph.get(destination).put(source, duplexEdge);
}
/**
* Removes an edge from the graph.
*
* @param source If the source node.
* @param destination If the destination node.
* @throws NullPointerException if either source or destination specified is null
* @throws NoSuchElementException if graph does not contain either source or destination
*/
public void removeEdge (T source, T destination) {
if (source == null || destination == null) {
throw new NullPointerException("Source and Destination, both should be non-null.");
}
if (!graph.containsKey(source) || !graph.containsKey(destination)) {
throw new NoSuchElementException("Source and Destination, both should be part of graph");
}
graph.get(source).remove(destination);
graph.get(destination).remove(source);
}
/**
* Given a node, returns the edges going outward that node,
* as an immutable map.
*
* @param node The node whose edges should be queried.
* @return An immutable view of the edges leaving that node.
* @throws NullPointerException If input node is null.
* @throws NoSuchElementException If node is not in graph.
*/
public Map<T, DuplexEdge<T>> edgesFrom(T node) {
if (node == null) {
throw new NullPointerException("The node should not be null.");
}
Map<T, DuplexEdge<T>> edges = graph.get(node);
if (edges == null) {
throw new NoSuchElementException("Source node does not exist.");
}
return Collections.unmodifiableMap(edges);
}
/**
* Returns the iterator that travels the nodes of a graph.
*
* @return an iterator that travels the nodes of a graph.
*/
@Override public Iterator<T> iterator() {
return graph.keySet().iterator();
}
}
public final class FordFulkerson<T> {
private final GraphFordFuklerson<T> graph;
/**
* Takes in a graph, which should not be modified by client.
* However client should note that graph object is going to be changed by
* FordFulkerson algorithm.
*
* @param graph the input graph.
*/
public FordFulkerson (GraphFordFuklerson<T> graph) {
if (graph == null) {
throw new NullPointerException("The graph should not be null");
}
this.graph = graph;
}
private void validate(T source, T destination) {
if (source == null || destination == null) {
throw new NullPointerException("Neither source nor destination should be null");
}
if (source.equals(destination)) {
throw new IllegalArgumentException("The source should not be the same as destination.");
}
}
/**
* Determines the max flow based on ford-fulkerson algorithm.
*
*
* @param source the source node.
* @param destination the destination node
* @return the max-flow
*/
public double maxFlow(T source, T destination) {
validate(source, destination);
double max = 0;
List<T> nodes = getPath(source, destination);
while (nodes.size() > 0) {
double maxCapacity = maxCapacity(nodes);
max = max + maxCapacity;
drainCapacity(nodes, maxCapacity);
nodes = getPath(source, destination);
}
return max;
}
/**
* Gets the path from source node to destination node, such that there is
* capacity > 0 at each edge from source to destination.
*
* @param source the source node
* @param destination the destination node
* @return the path from source to destination,
*/
private List<T> getPath(T source, T destination) {
synchronized (graph) {
final LinkedHashSet<T> path = new LinkedHashSet<T>();
depthFind(source, destination, path);
return new ArrayList<T>(path);
}
}
private boolean depthFind(T current, T destination, LinkedHashSet<T> path) {
path.add(current);
if (current.equals(destination)) {
return true;
}
for (Entry<T, DuplexEdge<T>> entry : graph.edgesFrom(current).entrySet()) {
// if not cycle and if capacity exists.
if (!path.contains(entry.getKey()) && entry.getValue().getCapacity(current, entry.getKey()) > 0) {
// if end has been reached.
if (depthFind(entry.getKey(), destination, path)) {
return true;
}
}
}
path.remove(current);
return false;
}
/**
* Returns the maximum capacity in the path.
* Maximum capacity is the minimim capacity available on the path
* from source to destination
*
* @param nodes the nodes that contibute a path
* @return the max capacity on the path.
*/
private double maxCapacity(List<T> nodes) {
double maxCapacity = Double.MAX_VALUE;
for (int i = 0; i < nodes.size() - 1; i++) {
T source = nodes.get(i);
T destination = nodes.get(i + 1);
DuplexEdge<T> duplexEdge = graph.edgesFrom(source).get(destination);
double capacity = duplexEdge.getCapacity(source, destination);
if (maxCapacity > capacity) {
maxCapacity = capacity;
}
}
return maxCapacity;
}
/**
* Reduces the capacity along the path from source to destination
*
* @param nodes the nodes that contribute the path
* @param maxCapacity the maximum capacity along the path.
*/
private void drainCapacity (List<T> nodes, double maxCapacity) {
for (int i = 0; i < nodes.size() - 1; i++) {
T source = nodes.get(i);
T destination = nodes.get(i + 1);
DuplexEdge<T> duplexEdge = graph.edgesFrom(source).get(destination);
duplexEdge.adjustCapacity(source, destination, maxCapacity);
}
}
public static void main(String[] args) {
final GraphFordFuklerson<String> graph = new GraphFordFuklerson<String>();
graph.addNode("A");
graph.addNode("B");
graph.addNode("C");
graph.addNode("D");
graph.addNode("E");
graph.addNode("F");
graph.addNode("G");
graph.addNode("H");
graph.addEdge("A", "B", 10);
graph.addEdge("A", "C", 5);
graph.addEdge("A", "D", 15);
graph.addEdge("B", "C", 4);
graph.addEdge("C", "D", 4);
graph.addEdge("B", "E", 9);
graph.addEdge("B", "F", 15);
graph.addEdge("C", "F", 8);
graph.addEdge("D", "G", 16);
graph.addEdge("E", "F", 15);
graph.addEdge("F", "G", 15);
graph.addEdge("G", "C", 6);
graph.addEdge("E", "H", 10);
graph.addEdge("F", "H", 10);
graph.addEdge("G", "H", 10);
FordFulkerson<String> ff = new FordFulkerson<String>(graph);
double value = ff.maxFlow("A", "H");
assertEquals(28.0, value, 0);
}
}
</code></pre>
| [] | [
{
"body": "<p>Some small remarks:</p>\n\n<ul>\n<li>I would change the <code>NullPointerException</code> to <code>IllegalArgumentException</code> when you check for <code>null</code> in the arguments of the method.</li>\n<li>I would add an <code>addNodes(T ...)</code> convenience method.</li>\n<li>addNode(T node) javadoc: \"returns <code>false</code> if the node is not added\". It only does so when the node is already in your <code>Graph</code>. Better to add that to the docs too.</li>\n<li>What is the use of the <code>synchronized</code> block in the <code>getPath</code> method?</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T15:39:07.413",
"Id": "46288",
"ParentId": "45729",
"Score": "2"
}
},
{
"body": "<p>I don't think your implementation is bad, but I would have done things differently, so here is my implementation. I did not have much time to do it, so it is completely untested and probably not complete.</p>\n\n<p>I am using Java 8, Google guava and I tried to make things as immutable as possible. I also made a bit of code multi-threaded (look for <code>stream().parallel()</code>). The only class that is mutable is Flow and if I had more time, I would look at making it immutable too. (I would have to check if it would impact the performance when the flow values are modified since a new Flow would have to be created each time we change one value in the flow.)</p>\n\n<p>The Java 8 bits might be a bit hard to understand if you have never seen Java 8. However, I think you can look at my \"high-level\" design (Node, Edge, Graph, Path and Flow) and maybe get some inspiration from that. For example, I did not put the \"consumed capacity\" in the Edge class, but outside in class Flow.</p>\n\n<pre><code>import com.google.common.collect.HashMultimap;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Multimap;\n\n/**\n * Finds the maximum flow in a directed graph with capacity.\n * http://codereview.stackexchange.com/questions/45729\n */\npublic class FordFulkersonMaximumFlowFinder {\n\n public static Flow fordFulkersonFindMaximumFlow(Graph graph) {\n Collection<Path> paths = Path.findPathsDepthFirst(graph);\n Flow flow = Flow.createZeroFlow(graph);\n Optional<Path> onePathWithSlackCapacity;\n while ((onePathWithSlackCapacity = findOnePathWithSlackCapacity(paths, flow)).isPresent()) {\n // Note: there is some slight inefficiency here since it would be\n // possible to compute\n // the slack capacity amount while the check for slack capacity is\n // done.\n Stream<Edge> pathEdges = onePathWithSlackCapacity.get().getEdges().stream();\n DoubleStream slackCapacitiesPerEdge = pathEdges.mapToDouble(edge -> (edge.getCapacity() - flow.getFlow(edge)));\n double slackCapacity = slackCapacitiesPerEdge.min().getAsDouble();\n flow.subtractFlow(pathEdges, slackCapacity);\n }\n return flow;\n }\n\n private static Optional<Path> findOnePathWithSlackCapacity(Collection<Path> paths, Flow flow) {\n // Parallelize code when there are many paths.\n Stream<Path> pathsStream = paths.size() < 2000 ? paths.stream() : paths.stream().parallel();\n return pathsStream.filter(path -> doesPathHaveSlackCapacity(path, flow)).findFirst();\n }\n\n /**\n * @return true if each and every edge has a capacity which is strictly\n * greater than the flow on that edge.\n */\n private static boolean doesPathHaveSlackCapacity(Path path, Flow flow) {\n // Note: this could be parallelize using stream().parallel(), but it\n // would slow things down unless the\n // paths are very long.\n return path.getEdges().stream().allMatch(edge -> edge.getCapacity() > flow.getFlow(edge));\n }\n\n /**\n * Immutable.\n */\n public static class Node {\n private final String name;\n\n /**\n * Immutable.\n */\n public Node(String name) {\n super();\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n\n @Override\n public String toString() {\n return \"Node[\" + name + \"]\";\n }\n }\n\n /**\n * Immutable.\n */\n public static class Edge {\n private final Node start;\n private final Node end;\n private final double capacity;\n\n public Edge(Node start, double capacity, Node end) {\n this.start = start;\n this.capacity = capacity;\n this.end = end;\n }\n\n public Node getStart() {\n return start;\n }\n\n public Node getEnd() {\n return end;\n }\n\n public double getCapacity() {\n return capacity;\n }\n }\n\n /**\n * Immutable.\n */\n public static class Graph {\n private final Multimap<Node, Edge> edges;\n private final Node startNode;\n private final Node endNode;\n\n public Graph(Node startNode, Node endNode, Collection<Edge> allEdges) {\n // TODO should check no incoming edge on startNode, no outgoing edge\n // on endNode and no cycles.\n // Also, check that it is connected, from start to end.\n this.startNode = startNode;\n this.endNode = endNode;\n edges = HashMultimap.create();\n {\n allEdges.stream().forEach(edge -> edges.put(edge.getStart(), edge));\n }\n }\n\n public Node getStartNode() {\n return startNode;\n }\n\n public Node getEndNode() {\n return endNode;\n }\n\n public Set<Node> getAllNodes() {\n return edges.keySet();\n }\n\n /**\n * @return empty collection if the node does not exist in the graph.\n */\n public Collection<Edge> getEdgesFrom(Node node) {\n return edges.get(node);\n }\n }\n\n /**\n * Immutable.\n */\n public static class Path {\n public static final Path EMPTY = new Path(ImmutableList.of());\n private ImmutableList<Edge> edges;\n\n public Path(List<Edge> edges) {\n this.edges = ImmutableList.copyOf(edges);\n }\n\n public ImmutableList<Edge> getEdges() {\n return edges;\n }\n\n public Path createNewPathAdding(Edge edge) {\n return new Path(ImmutableList.<Edge> builder().addAll(edges).add(edge).build());\n }\n\n public static Collection<Path> findPathsDepthFirst(Graph graph) {\n return findPathsDepthFirstRecursive(graph.getStartNode(), Path.EMPTY, graph);\n }\n\n public static Collection<Path> findPathsDepthFirstRecursive(Node currentNode, Path pathSoFar, Graph graph) {\n if (currentNode.equals(graph.getEndNode()))\n return Arrays.asList(pathSoFar);\n if (pathSoFar.getEdges().stream().anyMatch(edge -> currentNode.equals(edge.getStart())))\n throw new IllegalStateException(\"Holy Molly! There's a cycle.\");\n Stream<Path> paths = graph.getEdgesFrom(currentNode).stream().flatMap(edge -> {\n Node nextNode = edge.getEnd();\n Path nextPathSoFar = pathSoFar.createNewPathAdding(edge);\n return findPathsDepthFirstRecursive(nextNode, nextPathSoFar, graph).stream();\n });\n return paths.collect(Collectors.toList());\n }\n }\n\n /**\n * Mutable.\n */\n // TODO make immutable? Subtract would take a collection of edges and one\n // value. Is Guava ImmutableMap efficient enough for creating new\n // ImmutableMaps when subtracting?\n public static class Flow {\n private final Map<Edge, Double> edgeFlows = new HashMap<>();\n\n private Flow() {\n }\n\n public static Flow createZeroFlow(Graph graph) {\n Flow zeroFlow = new Flow();\n {\n graph.edges.values().stream().forEach(edge -> zeroFlow.edgeFlows.put(edge, 0.0));\n }\n return zeroFlow;\n }\n\n public double getFlow(Edge edge) {\n return edgeFlows.get(edge);\n }\n\n public void setFlow(Edge edge, double flowValue) {\n edgeFlows.put(edge, flowValue);\n }\n\n public void subtractFlow(Stream<Edge> pathEdges, double amountToSubtract) {\n pathEdges.forEach(edge -> edgeFlows.put(edge, edgeFlows.get(edge) - amountToSubtract));\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T00:51:51.417",
"Id": "46513",
"ParentId": "45729",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T06:08:12.347",
"Id": "45729",
"Score": "6",
"Tags": [
"java",
"algorithm",
"graph"
],
"Title": "Ford-Fulkerson algorithm"
} | 45729 |
<p>I have a function <code>initialize_path_statistics()</code>. I have used openMP to make it parallel. I am not sure where certain lines such as</p>
<pre><code>float length_enclosed = Nodes::get_length_enclosed(i);
</code></pre>
<p>need additional <code>pragma</code> like <code>#pragma omp atomic</code>. </p>
<pre><code>void Path_Statistics :: initialize_Path_statistics()
{
path_match_score.resize(no_of_valid_nodes);
combinatorial_structures.resize(no_of_valid_nodes);
node_path_matches.resize(no_of_valid_nodes);
path_loop_indexes.resize(no_of_valid_nodes);
node_path_energy.resize(no_of_valid_nodes);
#pragma omp parallel for
for(unsigned int i = 0;i < no_of_valid_nodes;i++)
{
int matches = node_matches[i];
float length_enclosed = Nodes::get_length_enclosed(i);
float match_density = float(matches)/length_enclosed;
path_match_score[i] = match_density;
int child_count = (adjacency_table_vector[i].second).size();
if((adjacency_table_vector[i].second).empty())
{
combinatorial_structures[i] = 1;
}
else
{
combinatorial_structures[i] = child_count+1;
}
node_path_matches[i] = matches;
int loop_start_position = node_start[i] + node_matches[i];
int loop_end_position = node_end[i] - node_matches[i];
path_loop_indexes[i].first = loop_start_position;
path_loop_indexes[i].second = loop_end_position;
//the size of the loop
int loop_size = node_end[i] - node_start[i] - 2*node_matches[i] + 1;
//if the node can form a valid loop node
if(loop_size <= MAXIMUM_SIZE_OF_LOOP)
{
//the loop path energy will also have the energy of the node + loop formed
float energy = get_loop_energy(i) + node_energy[i];
node_path_energy[i] = energy;
}
else
{
node_path_energy[i] = float(INFINITE);
}
}
</code></pre>
<p>The code for <code>nodes::get_length_enclosed(i)</code> is:</p>
<pre><code>//calculates the length enclosed by the given node
inline int Nodes :: get_length_enclosed(int node_id)
{
int length = node_end[node_id] - node_start[node_id] +1;
return(length);
}
</code></pre>
<p>Can I make it more parallel using sections somehow? I tried <code>#pragma omp parallel</code> for sections, which doesn't work. Also, is this code thread safe?</p>
| [] | [
{
"body": "<p>The code seems thread-safe to me. All operations are either done with local variables or with data addressed via the loop index, so data races are seemingly absent. Thus, no additional protection like <code>#pragma omp atomic</code> is necessary.</p>\n\n<p>I do not think you can make it \"more parallel\". Though technically parts of the loop iteration are independent and can be computed in parallel, the overall amount of computation seems rather small, so exploiting that \"inner\" parallelism is unlikely to bring more performance. If you want to try it though, I would recommend you to use <code>#pragma omp task</code>, not sections.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T15:50:33.960",
"Id": "45758",
"ParentId": "45731",
"Score": "3"
}
},
{
"body": "<p>Although a bit nitpicky, <code>get_length_enclosed()</code> can just be one line:</p>\n\n<pre><code>return node_end[node_id] - node_start[node_id] +1;\n</code></pre>\n\n<p>The variable isn't necessary since the function name already reveals its intent.</p>\n\n<p>The <code>inline</code> keyword isn't necessary. The compiler itself will decide if it's worth inlining and can still ignore this hint.</p>\n\n<p>It should also be <code>const</code> since it's is a member function that doesn't modify any data members:</p>\n\n<pre><code>int Nodes :: get_length_enclosed(int node_id) const\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-20T04:41:51.727",
"Id": "74241",
"ParentId": "45731",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "45758",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T06:40:33.880",
"Id": "45731",
"Score": "4",
"Tags": [
"c++",
"beginner",
"thread-safety",
"vectors",
"openmp"
],
"Title": "OpenMP loop parallel for loop with function calls and STL vector"
} | 45731 |
<p>Task:</p>
<blockquote>
<p>Given a dictionary of words, and a set of characters, judge if all the
characters can form the words from the dictionary, without any
characters left. For example, given the dictionary {hello, world, is,
my, first, program}, if the characters set is "iiifrssst", you should
return 'true' because you can form {is, is, first} from the set; if
the character set is "eiifrsst", you should return 'false' because you
cannot use all the characters from the set. </p>
<p>P.S. there may be tens of thousands of words in the dictionary, and
the chars set length could be up to hundreds, so I really need some
efficient algorithm.</p>
</blockquote>
<p>Source: <a href="http://www.careercup.com/question?id=5841660122497024" rel="noreferrer">http://www.careercup.com/question?id=5841660122497024</a></p>
<p>Here is my solution in Python:</p>
<pre><code>from collections import Counter
from itertools import combinations_with_replacement
import copy
# Check if word can be made up with the characters in char_count
def valid_word(word):
# build character count for word
word_char_count = Counter(word)
# check if character count for word
for char in word_char_count.keys():
if char not in char_count or word_char_count[char] > char_count[char]:
return False
return True
# Only return words that can be made up from characters with char_set
def prune_words(words):
res = []
for word in words:
if valid_word(word):
res.append(word)
return res
def main(words, char_set):
global char_count
char_count = Counter(char_set) # count character occurrences
# Prune words that cannot possible be made from the set of characters
words = prune_words(words)
words_len = [len(word) for word in words]
# Maximum number of r with generating combinations
max_r = len(char_set) / min(words_len)
# Generate permutations with the valid words
for r in range(1, max_r + 1):
for comb in combinations_with_replacement(words, r):
# If the total length of the combination matches length of char_set,
# do further checks
if sum(map(len, comb)) == len(char_set):
temp_count = copy.deepcopy(char_count)
# Subtract char count of each word in combination from char_set
for word in comb:
temp_count.subtract(word)
# If the remaining count are all zero, then we have found an
# answer
if all([count == 0 for count in temp_count.values()]):
print comb
return True
return False
if __name__ == '__main__':
print main(['hello', 'world', 'is', 'my', 'first', 'program'],
'iiifrssst')
</code></pre>
<p>What improvements can be made to my code (e.g. algorithmic speed, make it more 'Python', style, etc etc)? Happy to hear any constructive comments!</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T07:06:52.557",
"Id": "79851",
"Score": "1",
"body": "My initial impression is that this sounds like a [Set Cover](http://en.wikipedia.org/wiki/Set_cover_problem) problem, which would be NP-complete."
}
] | [
{
"body": "<h3>Replace <code>prune_words</code> with a <a href=\"http://docs.python.org/2.7/library/functions.html#filter\" rel=\"nofollow\">filter</a>.</h3>\n\n<ul>\n<li>Replace <code>words = prune_words(words)</code> with <code>words = filter(valid_word, words)</code>.</li>\n<li>You can now remove <code>prune_words</code>.</li>\n</ul>\n\n<h3>Avoid Deepcopy</h3>\n\n<p>There doesn't appear to be any reason to preserve <code>char_sets</code>, so why not subtract directly from it?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T02:16:25.963",
"Id": "79917",
"Score": "0",
"body": "Thanks. Just a question regarding \"filter\" - why do I need to change `valid_word` to return `None` instead of `False`? I read the docs but it's not clear to me what they mean."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T08:35:57.047",
"Id": "79946",
"Score": "0",
"body": "It is not necessary to change `valid_word` to return `None`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T20:38:29.967",
"Id": "45775",
"ParentId": "45733",
"Score": "3"
}
},
{
"body": "<ul>\n<li>Since \"the chars set length could be up to hundreds\", it can easily contain enough letters to form any word in an English dictionary. In such a case <code>prune_words</code> would not prune any words. This makes me think the pruning is an example of premature optimization.</li>\n<li>Instead of using <code>Counter</code> to check a match, I believe it would be faster to compare sorted lists of characters, i.e. compare <code>sorted(\"\".join(comb))</code> to a pre-computed <code>sorted(char_set)</code>.</li>\n<li>Copying a Counter by <code>Counter(char_count)</code> is faster than by <code>copy.deepcopy</code>.</li>\n<li>To check if all counts are zeros you don't need the list comprehension as you can simply use <code>if not any(temp_count.itervalues())</code></li>\n<li>You check lots of combinations that are the wrong length. Even though the length check is the first thing inside the loop, it would be better to generate the combinations in a way that allows you to back off when the combined length exceeds the length of <code>char_set</code>. I would use recursion to explore the combinations.</li>\n<li>A more clever approach might be found from representing the dictionary as a prefix tree.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T16:01:52.257",
"Id": "45855",
"ParentId": "45733",
"Score": "4"
}
},
{
"body": "<p>Because you don't really care about the order of the letters in the word, you could perform some simple preprocessing in order to deal with fewer words :</p>\n\n<pre><code>>>> with open('/etc/dictionaries-common/words', 'r') as f:\n... words = {w.strip().lower() for w in f}\n... \n>>> words_anagram = { ''.join(sorted(w)) for w in words}\n>>> len(words)\n97723\n>>> len(words_anagram)\n90635\n</code></pre>\n\n<p>It might not help much but it's so simple that it cannot hurt much neither.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T16:15:51.183",
"Id": "45860",
"ParentId": "45733",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "45855",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T06:45:54.247",
"Id": "45733",
"Score": "9",
"Tags": [
"python",
"interview-questions",
"python-2.x"
],
"Title": "Use up all characters to form words"
} | 45733 |
<p>I've been trying to create a calculator to find mass using any and all known equations. The program will also return the steps used to find mass so the user can 'check their work' on physics assignments.</p>
<p>My biggest problem so far (and was solved by much copy-pasta) is the equations themselves. I'd like to be able to create an equation variable that contains other variables inside itself, if possible, I want the variable to state:</p>
<pre><code>var.mass = var.force / var.acceleration && var.energy / var.c^2 && var.density / var.volume
</code></pre>
<p>How, if possible, would I go about creating this variable? I could certainly define a different variable for each equation, but that would be extremely time-consuming and I'm sure Python has <em>something</em> that could help! I haven't tried an array, and would prefer not to as I have very little experience with them. However, if someone could give me an idea, even just the command name I would be very appreciative!</p>
<p>Feel free to use the code however and with whatever you want.</p>
<pre><code>#this script is for solving for mass
#Define variables
g = 9.8
c = 3.00 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10
c2 = c * c
E = mass * c * c
#Ask if the user wants to see how problem was solved
show_work = input('Show work? ')
#Asks for variable input
force_val = float(input('Force? (In Newtons) '))
mass_val = float(input('Mass? (In kg) '))
acceleration_val = float(input('acceleration? (In m/s^2) '))
p_val = float(input('density? (In Kg/m^3) '))
volume_val = float(input('Volume? (m^3) '))
weight_val = float(input('Weight? (Normal Force) '))
energy_val = float(input('Energy? '))
kinetic_val = float(input('Kinetic Energy? '))
velocity_val = float(input('Velocity? (In m/s) '))
#Solve for mass based on known values
#show work off
if show_work == 'no':
if mass_val > 0.00:
print(mass_val)
elif force_val > 0:
if acceleration_val > 0:
mass_val = force_val / acceleration_val
print(mass_val)
elif p_val > 0:
if volume_val > 0:
mass_val = p_val / volume_val
print(mass_val)
elif weight_val > 0:
mass_val = weight_val / g
print(mass_val)
elif energy_val > 0:
mass_val = energy_val / c2
print(mass_val)
elif kinetic_val > 0:
if velocity_val > 0:
mass_val = 1/2 * kinetic_val / velocity_val / velocity_val
print(mass_val)
#show work on
if show_work == 'yes':
if mass_val > 0.00:
print(mass_val)
elif force_val > 0:
if acceleration_val > 0:
mass_val = force_val / acceleration_val
print('Force = Mass * Acceleration ')
print('Mass = Force / Acceleration ')
print('Mass =', force_val, '/', acceleration_val)
print('Mass =', mass_val)
elif p_val > 0:
if volume_val > 0:
mass_val = p_val / volume_val
print('Mass = Density / Volume ')
print('Mass =', p_val, '/', volume_val)
print('Mass =', mass_val)
elif weight_val > 0:
mass_val = weight_val / g
print('Mass = Weight / Gravity ')
print('Mass =', weight_val, '/', g)
print('Mass =', mass_val)
elif energy_val > 0:
mass_val = energy_val / c2
print('E=mc^2')
print('m=E/c^2')
print('Mass =', energy_val, '/', 'c^2')
print('Mass =', mass_val)
elif kinetic_val > 0:
if velocity_val > 0:
mass_val = 2 * kinetic_val / velocity_val / velocity_val
print('KE = 1/2mv^2')
print('Mass = 2(KE/v^2)')
print('Mass =', kinetic_val, '/', velocity_val, '^2')
print('Mass =', mass_val)
print(mass_val)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T08:01:56.627",
"Id": "79852",
"Score": "2",
"body": "I don't think you can blindly apply Physics formulas like that. The appropriate formula to choose depends entirely on context. For example, there are [many processes](http://en.wikipedia.org/wiki/Energy_density) to obtain different kinds of energy from a material; pure energy-mass conversion is pretty rare."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T08:38:02.547",
"Id": "79853",
"Score": "0",
"body": "Are we talking specifically the E=mc^2 formula, or did you mean as a generalization of the calculator as a whole?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T08:45:32.030",
"Id": "79855",
"Score": "0",
"body": "I think that the calculator concept is fundamentally flawed; E = mc^2 is just an example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T08:51:27.363",
"Id": "79858",
"Score": "0",
"body": "Ah, well thanks for the input ^_^ I'm just trying to come up with a calculator that will work in my conceptual physics course, I have thought of many issues myself in the application of it, but if I'm going to fail, I'll at least fail in the most time-consuming way I can."
}
] | [
{
"body": "<p>I’m not going to have a go at the big problem of “equation variable” (which might be better suited to Stack Overflow), but I do have some comments on your existing code:</p>\n\n<ul>\n<li><p>Python uses the operator <code>**</code> for powers; i.e., <code>a ** b</code> means “a to the power b”. You can use this to tidy up your constants at the top of the file:</p>\n\n<pre><code>c = 3.00 * 10 ** 8\nE = mass * c ** 2\n</code></pre>\n\n<p>I think that’s easier to read, and makes it clear where they’re coming from.</p>\n\n<p>I see no reason to define a <code>c2</code> variable, especially when you use it inconsistently (sometimes you have <code>c2</code>, sometimes <code>c * c</code>.</p>\n\n<p>The <a href=\"http://docs.scipy.org/doc/scipy/reference/constants.html\"><code>scipy.constants</code></a> module contains lots of these constants built-in to high levels of precision, but that may be inappropriate for your work.</p></li>\n<li><p>At the point when <code>E</code> is defined, the variable <code>mass</code> hasn’t been defined. In fact, I can’t find any mention of the variable in the script. What’s it doing here?</p></li>\n<li><p>Something only happens if the user types exactly <code>yes</code> or <code>no</code> when asked “Show work?” You might be better off defining a list of “acceptable” responses which means the user wants their work shown.</p>\n\n<p>For example:</p>\n\n\n\n<pre><code>yes_list = ['yes', 'y', 'true', 't', 'yep']\nif input('Show work?').lower() in yes_list:\n show_input = True\nelse:\n show_input = False\n</code></pre></li>\n<li><p>Most of the code is duplicated: once in the branch of the if statement which shows the working, and again in the branch which doesn’t. You’d be better off defining a <code>working_print</code> function which only prints anything if the user wants it. Further, you can skip defining a <code>show_input</code> variable, and get it directly from the user input:</p>\n\n\n\n<pre><code>yes_list = ['yes', 'y', 'true', 't', 'yep']\nif input('Show work?').lower() in yes_list:\n def working_print(x):\n print(x)\n return None\nelse:\n def working_print(x)\n return None\n</code></pre>\n\n<p>Then you can replace instances of <code>print()</code> which are optional with <code>working_print()</code>. For example, the branch</p>\n\n\n\n<pre><code>print('E=mc^2')\nprint('m=E/c^2')\nprint('Mass =', energy_val, '/', 'c^2')\nprint('Mass =', mass_val)\n</code></pre>\n\n<p>would become</p>\n\n\n\n<pre><code>working_print('E=mc^2')\nworking_print('m=E/c^2')\nworking_print('Mass =', energy_val, '/', 'c^2')\nprint('Mass =', mass_val)\n</code></pre></li>\n<li><p>You have lots of nested if statements of the form</p>\n\n\n\n<pre><code>elif p_val > 0:\n if volume_val > 0:\n # code goes here\n\nelif something_else\n</code></pre>\n\n<p>I think you’d be better off combining the <code>elif</code> and the <code>if</code> into a single line, e.g. something like</p>\n\n\n\n<pre><code>if p_val > 0 and volume_val > 0\nif min(p_val, volume_val) > 0\n</code></pre>\n\n<p>It makes it easier to see what the conditions for each branch are. It also leaves you open to less unexpected bugs if none of the branches get run correctly.</p>\n\n<p>And why <code>p_val</code> instead of <code>density_val</code>?</p></li>\n<li><p>Add an <code>else</code> block at the end of the code which lets you know when it got there, even if it prints something as silly as “Uh oh, don’t know how I got here.” It makes life easier when debugging – you can tell whether none of your branches ran, or whether one of the branches ran but aren’t printing anything.</p></li>\n<li><p>In several places, you’re checking that variables are positive where it doesn’t seem appropriate.</p>\n\n<p>For example, consider the F = ma branch. Both force and acceleration are vectors, so it makes sense for them both to be negative (corresponding to force/acceleration in the opposite direction). When computing mass, all you require is that they both have the same sign. So your if statement should become</p>\n\n<pre><code>if force_val * acceleration_val > 0\n</code></pre>\n\n<p>Velocity is also a vector, so it can be signed, and I see no reason why energy (or several other quantities) have to be non-zero.</p></li>\n<li><p>There’s a great app called <a href=\"http://omz-software.com/pythonista/\">Pythonista</a> for iOS which can edit and run Python scripts. (It doesn’t do Python 3, but your script is sufficiently simple that converting to run on 2.x shouldn’t cause any problems.) I don’t know enough about other platforms to suggest anything else.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T08:47:03.770",
"Id": "79856",
"Score": "3",
"body": "You could just write `c = 3e8`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T08:53:21.697",
"Id": "79859",
"Score": "0",
"body": "I cannot upvote you due to being a new member and requiring 15 rep, but when I get it, I will upvote."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T08:55:59.857",
"Id": "79860",
"Score": "0",
"body": "The random, unspecified junk variable for E and mass were from previous attempts that I did not clean... now that you point it out, I'm surprised the program ran at all. Normally it (IDLE 3) gives an error when a variable is not defined... Thank you so much for the help!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T08:42:32.890",
"Id": "45742",
"ParentId": "45734",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "45742",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T07:15:04.903",
"Id": "45734",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"physics"
],
"Title": "Calculator for finding mass"
} | 45734 |
<p><a href="http://www.open-mpi.org/" rel="nofollow">Open MPI</a> is a BSD-licensed Message Passing Interface library for building distributed applications to run on clusters. It is the result of merging MPI implementations FT-MPI, LA-MPI, and LAM/MPI with contributions from PACX-MPI.</p>
<p>Not to be confused with <a href="/questions/tagged/openmp" class="post-tag" title="show questions tagged 'openmp'" rel="tag">openmp</a>.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T07:23:14.967",
"Id": "45735",
"Score": "0",
"Tags": null,
"Title": null
} | 45735 |
Open MPI is a Message Passing Interface library for building distributed applications to run on clusters. (Not to be confused with OpenMP.) | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T07:23:14.967",
"Id": "45736",
"Score": "0",
"Tags": null,
"Title": null
} | 45736 |
<p><a href="http://en.wikipedia.org/wiki/Message_Passing_Interface" rel="nofollow">Message Passing Interface</a> is a standardized and portable system for building distributed applications to run on parallel computing systems. It consists of a communications protocol and multiple independent libraries that implement standard APIs. Nodes in a computing cluster can use MPI to communicate with each other without having to worry about the details of TCP/IP <a href="/questions/tagged/networking" class="post-tag" title="show questions tagged 'networking'" rel="tag">networking</a>.</p>
<p>For example, <a href="http://www.open-mpi.org/" rel="nofollow">Open MPI</a> is a BSD-licensed MPI library. It is the result of merging MPI implementations FT-MPI, LA-MPI, and LAM/MPI with contributions from PACX-MPI.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T07:34:56.667",
"Id": "45737",
"Score": "0",
"Tags": null,
"Title": null
} | 45737 |
Message Passing Interface (MPI) is a standardized and portable system for building distributed applications to run on parallel computing systems. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T07:34:56.667",
"Id": "45738",
"Score": "0",
"Tags": null,
"Title": null
} | 45738 |
<p><a href="http://en.wikipedia.org/wiki/OpenMP" rel="nofollow">OpenMP</a> is an API that supports multi-platform shared memory multiprocessing programming in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged 'c'" rel="tag">c</a>, <a href="/questions/tagged/c%2b%2b" class="post-tag" title="show questions tagged 'c++'" rel="tag">c++</a>, and <a href="/questions/tagged/fortran" class="post-tag" title="show questions tagged 'fortran'" rel="tag">fortran</a>, on most processor architectures and operating systems. It consists of a set of compiler directives, library routines, and environment variables that influence runtime behavior.</p>
<p>For example, writing <code>#pragma omp parallel for</code> before a <code>for</code> loop in a C program woulc cause the loop to be split up and run in parallel among multiple threads.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T07:43:16.793",
"Id": "45739",
"Score": "0",
"Tags": null,
"Title": null
} | 45739 |
OpenMP is an API that supports shared memory multiprocessing in C, C++, and Fortran. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T07:43:16.793",
"Id": "45740",
"Score": "0",
"Tags": null,
"Title": null
} | 45740 |
<p>I am not sure about the place where flush should be used (if it is used at all here).</p>
<pre><code>int Window_Shift :: get_window_shift()
{
int window_shift = INFINITE;
#pragma omp parallel for
for(unsigned int node_id = 0;node_id< no_of_valid_nodes ;node_id++)
{
//for all the nodes that can be extended
//finds the minimum possible window shift
if(can_node_determine_window_shift(node_id) == true)
{
int node_window_shift = get_window_shift_for_node(node_id);
#pragma omp flush(window_shift)
#pragma omp critical(get_window_shift_for_node)
{
window_shift = min(window_shift,node_window_shift);
#pragma omp flush(window_shift)
}
}
}
</code></pre>
<p>Please review the code, especially the <code>flush()</code> commands. Should atomic be used instead of a critical section?</p>
| [] | [
{
"body": "<ul>\n<li><p>With just one function provided and some return information, it's hard to tell everything about it. Since this is a member function with \"get\" in its name (meaning it's an accessor), and only local variables are being modified (no data members), then this should likely be a <code>const</code> function.</p>\n\n<pre><code>int Window_Shift :: get_window_shift() const {}\n</code></pre>\n\n<p>If you <em>are</em> actually modifying data members somewhere, then disregard this.</p></li>\n<li><p>The whitespace in the <code>for</code> loop statement is a little inconsistent:</p>\n\n<blockquote>\n<pre><code>for(unsigned int node_id = 0;node_id< no_of_valid_nodes ;node_id++)\n</code></pre>\n</blockquote>\n\n<p>This is how it could look:</p>\n\n<pre><code>for (unsigned int node_id = 0; node_id < no_of_valid_nodes; node_id++)\n</code></pre></li>\n<li><p>In a conditional statement, you don't need to explicitly use <code>true</code> or <code>false</code>. It's also safer to avoid this as it'll prevent a possible mismatch of <code>=</code> and <code>==</code>. This will cause bugs if the compiler doesn't warn you about it (although you should have compiler warnings turned up high).</p>\n\n<p>This is the same as <code>== true</code>:</p>\n\n<pre><code>if (someConditional)\n</code></pre>\n\n<p>This is the same as <code>== false</code>:</p>\n\n<pre><code>if (!someConditional)\n</code></pre></li>\n<li><p><code>INFINITE</code> isn't defined anywhere, so either this is your own definition, or this is supposed to be <a href=\"http://en.cppreference.com/w/cpp/numeric/math/INFINITY\" rel=\"nofollow noreferrer\"><code>INFINITY</code> from <code><cmath></code></a>. You could instead use C++'s alternatives from <code><limits></code>.</p>\n\n<p>If you <em>must</em> use <code>int</code>, which is finite, you can use <a href=\"http://en.cppreference.com/w/cpp/types/numeric_limits/max\" rel=\"nofollow noreferrer\"><code>std::numeric_limits::max()</code></a> to get its maximum value, which is normally 2<sup>31</sup> -1:</p>\n\n<pre><code>int max = std::numeric_limits<int>::max();\n</code></pre>\n\n<p>If you <em>can</em> use a floating-point type (<code>float</code> or <code>double</code>), then you can get true infinity by using <a href=\"http://en.cppreference.com/w/cpp/types/numeric_limits/infinity\" rel=\"nofollow noreferrer\"><code>std::numeric_limits::infinity()</code></a>:</p>\n\n<pre><code>float infinity = std::numeric_limits<float>::infinity();\n</code></pre>\n\n<p></p>\n\n<pre><code>double infinity = std::numeric_limits<double>::infinity();\n</code></pre>\n\n<p>More information regarding infinity <a href=\"https://stackoverflow.com/questions/8690567/setting-an-int-to-infinity-in-c\">here</a>.</p></li>\n<li><p>You could consider defining <code>private()</code> and <code>shared()</code> for the variables, which goes inside of the <code>parallel for</code> directive. You'll also need <code>default(none)</code> so that the compiler will allow you to set this yourself. This can give you more control over your code, as the compiler would otherwise have to determine what should be private and what should be shared.</p></li>\n<li><blockquote>\n <p>Should atomic be used instead of a critical section?</p>\n</blockquote>\n\n<p>You may have to test this yourself, but atomic may be faster. Critical sections, on the other hand, may lead to more serialization, especially if you have one in a loop. Always try to avoid unnecessary serialization in parallel code. Atomics can also cause this, but usually not as greatly since it doesn't lock an entire code section for all of the threads, unlike a critical section.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-13T14:07:33.670",
"Id": "87290",
"Score": "0",
"body": "You could even say that comparing things with `== true` is almost never a good idea since `2` for example evaluates to `true` while `2 == true` evaluates to `false` :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-13T14:09:58.217",
"Id": "87291",
"Score": "0",
"body": "@Morwenn: Interesting. I was also thinking that it'll prevent a possible `=`/`==` mismatch."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-13T01:02:06.057",
"Id": "49592",
"ParentId": "45743",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "49592",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T09:10:09.757",
"Id": "45743",
"Score": "6",
"Tags": [
"c++",
"beginner",
"thread-safety",
"openmp"
],
"Title": "OpenMP parallel for critical section and use of flush"
} | 45743 |
<p>How can I test this C program for "efficiency"? The most interesting usage is that it returns negative output for large enough input, otherwise the behavior is about expected. Will you suggest how to improve the code, both the ui used in main that should be both efficient and preferably platform-indepedent and not use too much libraries for portability and optimization. I think the obvious improvement that I can make is recoding the <code>int</code> to <code>unsigned int</code>: </p>
<pre><code>/*
* NextPrime
*
* Return the first prime number larger than the integer
* given as a parameter. The integer must be positive.
*/
#define PRIME_FALSE 0 /* Constant to help readability. */
#define PRIME_TRUE 1 /* Constant to help readability. */
#include <stdio.h>
#include <stdlib.h>
int nextprime(int inval) {
int perhapsprime; /* Holds a tentative prime while we check it. */
int testfactor; /* Holds various factors for which we test perhapsprime. */
int found; /* Flag, false until we find a prime. */
if (inval < 3) /* Initial sanity check of parameter. */
{
if (inval <= 0)
return (1); /* Return 1 for zero or negative input. */
if (inval == 1)
return (2); /* Easy special case. */
if (inval == 2)
return (3); /* Easy special case. */
} else {
/* Testing an even number for primeness is pointless, since
* all even numbers are divisible by 2. Therefore, we make sure
* that perhapsprime is larger than the parameter, and odd. */
perhapsprime = (inval + 1) | 1;
}
/* While prime not found, loop. */
for (found = PRIME_FALSE; found != PRIME_TRUE; perhapsprime += 2) {
/* Check factors from 3 up to perhapsprime/2. */
for (testfactor = 3; testfactor <= (perhapsprime >> 1) + 1; testfactor
+= 1) {
found = PRIME_TRUE; /* Assume we will find a prime. */
if ((perhapsprime % testfactor) == 0) /* If testfactor divides perhapsprime... */
{
found = PRIME_FALSE; /* ...then, perhapsprime was non-prime. */
goto check_next_prime;
/* Break the inner loop, go test a new perhapsprime. */
}
}
check_next_prime: ; /* This label is used to break the inner loop. */
if (found == PRIME_TRUE) /* If the loop ended normally, we found a prime. */
{
return (perhapsprime); /* Return the prime we found. */
}
}
return (perhapsprime); /* When the loop ends, perhapsprime is a real prime. */
}
int main(int argc, char *argv[]) {
int intvar;
if (sscanf(argv[1], "%i", &intvar) != 1) {
printf("please use an integer parameter to compute the next prime\n");
} else
printf("%d => %d\n", intvar, nextprime(intvar));
return 0;
}
</code></pre>
| [] | [
{
"body": "<h1>Things you could improve</h1>\n\n<h3>Efficiency</h3>\n\n<ul>\n<li><p>As @rolfl stated, you want to use a <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">Sieve of Eratosthenes</a> (+1 to that answer).</p>\n\n<p><img src=\"https://i.stack.imgur.com/uMQ5O.gif\" alt=\"enter image description here\"></p></li>\n<li><p>I can't see if you are doing this already, but you should be compiling with your compiler's highest optimization level. With GCC for example, this would be <code>-O3</code>.</p></li>\n</ul>\n\n<h3>Portability</h3>\n\n<ul>\n<li><p>Keep in mind to adhere to the standards as closely as possible, because a system that supports C must adhere to the standards as well. </p></li>\n<li><p>If you want your program to be as portable as possible, take a look into the <a href=\"https://en.wikipedia.org/wiki/GNU_build_system\" rel=\"nofollow noreferrer\">AutoTools suite</a> for packaging your program. This is a bit extreme in your case, since you aren't using external libraries, and your program doesn't have a lot of system dependencies.</p></li>\n</ul>\n\n<h3>Standards</h3>\n\n<ul>\n<li><p>You don't have to return <code>0</code> at the end of <code>main()</code>, just like you wouldn't bother putting <code>return;</code> at the end of a <code>void</code>-returning function. The C standard knows how frequently this is used, and lets you not bother.</p>\n\n<blockquote>\n <p><strong>C99 & C11 §5.1.2.2(3)</strong></p>\n \n <p>...reaching the <code>}</code> that terminates the <code>main()</code> function returns a\n value of <code>0</code>.</p>\n</blockquote></li>\n<li><p>Use the standard library <code><stdbool.h></code> instead of defining your own boolean values.</p>\n\n<blockquote>\n<pre><code>#define PRIME_FALSE 0 /* Constant to help readability. */\n#define PRIME_TRUE 1 /* Constant to help readability. */\n</code></pre>\n</blockquote>\n\n<p>It still helps with readability. And since it is part of the standard in C, systems are guaranteed to have it if they support C.</p></li>\n</ul>\n\n<h3>Syntax/Styling</h3>\n\n<ul>\n<li><p><a href=\"https://stackoverflow.com/q/46586/1937270\">Don't use <code>goto</code>.</a> </p>\n\n<p><img src=\"https://i.stack.imgur.com/kMDAj.png\" alt=\"Neal Stephenson thinks it's cute to name his labels 'dengo'\"></p>\n\n<p>Yes, there are some rare situations where you may find it necessary to use it. This is not one of them. A simple <code>break;</code> will suffice in it's place, since you are only breaking out of the inner loop.</p></li>\n<li><p>Right now you are using a somewhat odd way to test if you have an integer input into the command line arguments.</p>\n\n<blockquote>\n<pre><code>if (sscanf(argv[1], \"%i\", &intvar) != 1)\n</code></pre>\n</blockquote>\n\n<p>Use <code>argc</code> to test the number of arguments input into the program instead, and <code>isdigit</code> to test if the input contains numbers.</p>\n\n<pre><code>if (argc != 2 || !isdigit(**(argv+1))) printf(\"Please use an integer parameter to compute the next prime.\\n\");\n</code></pre>\n\n<p>Then convert that input into an integer.</p>\n\n<pre><code>int intvar = atoi(*(argv+1));\n</code></pre>\n\n<p>Note that the order I put it in is important. We want to test <code>argc</code> first, so we put it first in the test conditional. If that fails, the second part on the other side of the <code>||</code> isn't even evaluated, and the statements following the conditional are executed. If we switched those tests around, undefined behavior could occur if we didn't enter in a command line argument.</p></li>\n<li><p>Use <a href=\"http://www.cplusplus.com/reference/cstdio/puts/\" rel=\"nofollow noreferrer\"><code>puts()</code></a> instead of <code>printf()</code> when you aren't formatting your strings. This allows you to not worry about the newline (<code>\\n</code>) character at the end of your printed out strings.</p>\n\n<pre><code>puts(\"Please use an integer parameter to compute the next prime.\");\n</code></pre></li>\n<li><p>You don't modify the value of <code>intval</code> within your <code>nextprime()</code> function, therefore the parameter should be declared constant.</p>\n\n<pre><code>int nextprime(const int inval)\n</code></pre></li>\n<li><p>You can reduce down one of your test conditionals.</p>\n\n<blockquote>\n<pre><code>if (inval == 1)\n return (2); /* Easy special case. */\nif (inval == 2)\n return (3); /* Easy special case. */\n</code></pre>\n</blockquote>\n\n<pre><code>if (inval == 1 || inval == 2) return (inval + 1); /* Easy special case. */\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T03:17:47.137",
"Id": "79920",
"Score": "1",
"body": "\"`*(argv+1)`\" why not `argv[1]`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T03:23:52.823",
"Id": "79922",
"Score": "1",
"body": "@NiklasB. It doesn't really matter. You could write it either way. That is just the way I chose."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T13:36:23.133",
"Id": "45749",
"ParentId": "45744",
"Score": "21"
}
},
{
"body": "<p>Let's review the context of this function.</p>\n\n<p>If this function will be called often with a wide range of inputs, then it makes sense to pre-compute a bunch of prime numbers and then just find where the input value is in amongst the pre-coumputed set. When pre-computing the primes the most common way is through using a <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\"><em>Sieve of Eratosthenes</em> (wikipedia)</a>.</p>\n\n<p>Your function is not a Sieve, and, as a result, will only be efficient for calculating just one prime number.... This is not actually a criticism, it is just a contextualization.</p>\n\n<p>Now, about your code:</p>\n\n<h2>Simplified IF statement</h2>\n\n<p>Your statement is:</p>\n\n<blockquote>\n<pre><code>if (inval < 3) /* Initial sanity check of parameter. */\n{\n if (inval <= 0)\n return (1); /* Return 1 for zero or negative input. */\n if (inval == 1)\n return (2); /* Easy special case. */\n if (inval == 2)\n return (3); /* Easy special case. */\n} else {\n /* Testing an even number for primeness is pointless, since\n * all even numbers are divisible by 2. Therefore, we make sure\n * that perhapsprime is larger than the parameter, and odd. */\n perhapsprime = (inval + 1) | 1;\n}\n</code></pre>\n</blockquote>\n\n<p>This has a few 'features' I don't like:</p>\n\n<ul>\n<li>the 'true' side of the block has the fall-though <code>if (intval == ?)</code> conditions. The last condition will always be true, so why test it?</li>\n<li>1 is not a prime number. The first prime is 2.</li>\n<li>The 'true' side of the main <code>if</code> will always return, so there is no need for the <code>else</code> block.</li>\n</ul>\n\n<p>Bottom line is I would simplify this condition to:</p>\n\n<pre><code>if (inval < 2) /* Initial sanity check of parameter. */\n{\n return (2); /* Easy special case. */\n}\n\n/* Testing an even number for primeness is pointless, since\n * all even numbers are divisible by 2. Therefore, we make sure\n * that perhapsprime is larger than the parameter, and odd. */\nperhapsprime = (inval + 1) | 1;\n</code></pre>\n\n<h2>Simplified Loops</h2>\n\n<p><strong>Exit conditions</strong>:</p>\n\n<p>your code has a relatively simple 'big' for loop:</p>\n\n<blockquote>\n<pre><code>for (found = PRIME_FALSE; found != PRIME_TRUE; perhapsprime += 2) {\n</code></pre>\n</blockquote>\n\n<p>...but, inside that loop, just before it iterates, you double-check the <code>found</code> condition and return if it is <code>PRIME_TRUE</code>.... Why the double-check? The double-check makes the outside-the-loop return statement unreachable.</p>\n\n<p>The awkwardness of your code suggests you are using the wrong structures. I would recommend a different system entirely.... this problem space is well-suited for a do-while loop with a 'special' initializer. Consider the following loop:</p>\n\n<pre><code>// set up 'special' initializer (it will be re-incremented in the loop)\nperhapsprime -= 2;\ndo {\n perhapsprime += 2;\n\n // check if perhapsprime is true now\n ....\n\n} while (found != PRIME_TRUE);\nreturn perhapsprime;\n</code></pre>\n\n<p>Now, in the interest of readability, I would actually extract the entire content of that loop to another function, say <code>is_prime(int perhapsprime)</code>, then your entire <code>nextprime</code> function will become:</p>\n\n<pre><code>int nextprime(int inval) {\n int perhapsprime; /* Holds a tentative prime while we check it. */\n int found;\n\n if (inval < 2) /* Initial sanity check of parameter. */\n {\n return (2); /* Easy special case. */\n }\n\n /* Testing an even number for primeness is pointless, since\n * all even numbers are divisible by 2. Therefore, we make sure\n * that perhapsprime is larger than the parameter, and odd. */\n perhapsprime = (inval + 1) | 1;\n\n perhapsprime -= 2; /* pre-set the loop variable */\n do {\n perhapsprime += 2;\n found = is_prime(perhapsprime);\n } while (found != PRIME_TRUE);\n return perhapsprime;\n}\n</code></pre>\n\n<p><strong><em>BUT</em></strong>: now that the function-extraction has happened, it can be replaced by a simple while loop instead of the do-while:</p>\n\n<pre><code> /* Testing an even number for primeness is pointless, since\n * all even numbers are divisible by 2. Therefore, we make sure\n * that perhapsprime is larger than the parameter, and odd. */\n perhapsprime = (inval + 1) | 1;\n\n while (is_prime(perhapsprime) != PRIME_TRUE) {\n perhapsprime += 2;\n }\n return perhapsprime;\n</code></pre>\n\n<h2>is_prime</h2>\n\n<p>OK, now we have to move the inner-guts of your loop to a <code>is_prime</code> function. For the most part, this is a copy-paste exercise....</p>\n\n<pre><code>int is_prime(int perhapsprime) {\n\n int limit;\n int testfactor;\n\n limit = (perhapsprime >> 1) + 1; /** SEE NOTES!!! */\n\n for (testfactor = 3; testfactor <= limit; ++testfactor) {\n if ((perhapsprime % testfactor) == 0) /* If testfactor divides perhapsprime... */\n {\n return PRIME_FALSE; /* ...then, perhapsprime was non-prime. */\n }\n }\n\n return PRIME_TRUE;\n}\n</code></pre>\n\n<p>Special notes here:</p>\n\n<ul>\n<li>Using <code>limit = (perhapsprime >> 1) + 1</code> may improve performance by only computing the limit one time. My C experience is not enough to tell you that for sure. It makes the code more readable anyway.</li>\n<li>using <code>limit = (perhapsprime >> 1) + 1</code> is not the best limit. It should be <code>sqrt(perhapsprime)</code> to get the true limit.</li>\n<li>I have used <code>++testfactor</code> in the loop incrementor because it is best-practice to do a pre-inrement rather than a <code>+= 1</code>.</li>\n</ul>\n\n<h2>Conclusion</h2>\n\n<p>Hopefully this will give you a few ideas, and show that the for-loop is not necessarily the best, or only loop structure.</p>\n\n<p>Edit: <a href=\"http://ideone.com/Kv7Kin\" rel=\"nofollow\">I have put this all together in an ideone</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T19:24:37.923",
"Id": "79898",
"Score": "2",
"body": "Minor quibble on wording: the sieve is useful primarily when you expect a lot of queries in a fairly *narrow* range. For a wide range of inputs, you end up using only a small percentage of the data you computed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T16:05:27.793",
"Id": "45760",
"ParentId": "45744",
"Score": "17"
}
}
] | {
"AcceptedAnswerId": "45749",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T09:11:44.080",
"Id": "45744",
"Score": "23",
"Tags": [
"optimization",
"c",
"performance",
"beginner",
"primes"
],
"Title": "First prime number larger than given integer"
} | 45744 |
<p>This is self-explaining example with usage in doctests (it's not that fast as implementation with dict key-lookups, but it's a lot more readable, and don't require callables and lambdas):</p>
<pre><code>class Switch(object):
"""
Switch, simple implementation of switch statement for Python, eg:
>>> def test_switch(val):
... ret = []
... with Switch(val) as case:
... if case(1, fall_through=True):
... ret.append(1)
... if case(2):
... ret.append(2)
... if case.call(lambda v: 2 < v < 4):
... ret.append(3)
... if case.call(lambda v: 3 < v < 5, fall_through=True):
... ret.append(4)
... if case(5):
... ret.append(5)
... if case.default:
... ret.append(6)
... return ret
...
>>> test_switch(1)
[1, 2]
>>> test_switch(2)
[2]
>>> test_switch(3)
[3]
>>> test_switch(4)
[4, 5]
>>> test_switch(5)
[5]
>>> test_switch(7)
[6]
>>> def test_switch_default_fall_through(val):
... ret = []
... with Switch(val, fall_through=True) as case:
... if case(1):
... ret.append(1)
... if case(2):
... ret.append(2)
... if case.call(lambda v: 2 < v < 4):
... ret.append(3)
... if case.call(lambda v: 3 < v < 5, fall_through=False):
... ret.append(4)
... if case(5):
... ret.append(5)
... if case.default:
... ret.append(6)
... return ret
...
>>> test_switch_default_fall_through(1)
[1, 2, 3, 4]
>>> test_switch_default_fall_through(2)
[2, 3, 4]
>>> test_switch_default_fall_through(3)
[3, 4]
>>> test_switch_default_fall_through(4)
[4]
>>> test_switch_default_fall_through(5)
[5]
>>> test_switch_default_fall_through(7)
[6]
"""
class StopExecution(Exception):
pass
def __init__(self, test_value, fall_through=False):
self._value = test_value
self._fall_through = None
self._default_fall_through = fall_through
self._use_default = True
self._default_used = False
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is self.StopExecution:
return True
return False
def __call__(self, expr, fall_through=None):
return self.call(lambda v: v == expr, fall_through)
def call(self, call, fall_through=None):
if self._default_used:
raise SyntaxError('Case after default is prohibited')
if self._finished:
raise self.StopExecution()
elif call(self._value) or self._fall_through:
self._use_default = False
if fall_through is None:
self._fall_through = self._default_fall_through
else:
self._fall_through = fall_through
return True
return False
@property
def default(self):
if self._finished:
raise self.StopExecution()
self._default_used = True
if self._use_default:
return True
return False
@property
def _finished(self):
return self._use_default is False and self._fall_through is False
class CSwitch(Switch):
"""
CSwitch is a shortcut to call Switch(test_value, fall_through=True)
"""
def __init__(self, test_value):
super(CSwitch, self).__init__(test_value, fall_through=True)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T05:05:49.230",
"Id": "80488",
"Score": "0",
"body": "If you want to preserve the `case/break` syntax of C, here is an interesting implementation: http://code.activestate.com/recipes/410692/."
}
] | [
{
"body": "<p>I like your trick to create this syntactic sugar. The implementation is also pretty good, as are the doctests.</p>\n\n<h3>Feature suggestions</h3>\n\n<p>I think it would be nice if a <code>case()</code> could test for multiple values. A <code>case('jack', 'queen', 'king')</code> should match if the <code>Switch</code> was created with any of those three strings.</p>\n\n<p>It would also be nice if there were a <code>case.match()</code> that performed a regular expression match.</p>\n\n<h3>Minor issues</h3>\n\n<ol>\n<li><p>If execution ends up inside <code>case.call()</code> due to fall-through, then I would expect the test function not to be called at all, as a kind of short-circuiting behaviour. Specifically,</p>\n\n<pre><code>elif call(self._value) or self._fall_through:\n</code></pre>\n\n<p>should be reversed and written as</p>\n\n<pre><code>elif self._fall_through or call(self._value):\n</code></pre></li>\n<li><p>Having a parameter named <code>call</code> when the method is also named <code>call</code> is confusing. I suggest renaming the parameter to <code>test</code>.</p></li>\n<li><p>Avoid testing variables for equality with <code>True</code> and <code>False</code> explicitly. Just use boolean expressions. For example, in <code>__exit__()</code>, change</p>\n\n<pre><code>def __exit__(exc_type, exc_val, exc_tb):\n if exc_type is self.StopExecution:\n return True\n return False\n</code></pre>\n\n<p>to</p>\n\n<pre><code>def __exit__(exc_type, exc_val, exc_tb):\n return exc_type is self.StopExecution\n</code></pre></li>\n<li><p>Initialize <code>_fall_through</code> to <code>False</code> instead of <code>None</code>; it's slightly more informative.</p></li>\n<li><p>Rename <code>expr</code> → <code>case_value</code>. Rename <code>_value</code> → <code>_switch_value</code>.</p></li>\n<li><p>Rename / invert <code>_use_default</code> to <code>not _matched_case</code>, because <code>_use_default</code> is too confusingly similar to <code>_default_used</code>. Also, by inverting the logic, all three private variables can be initialized to <code>False</code>, which is more elegant.</p></li>\n<li><p>Instead of a <code>_finished</code> property, write a <code>_check_finished()</code> method that raises <code>StopException</code> too.</p></li>\n</ol>\n\n<h3>Proposed solution</h3>\n\n<pre><code>import re\n\nclass Switch(object):\n \"\"\"\n Switch, simple implementation of switch statement for Python, eg:\n\n >>> def test_switch(val):\n ... ret = []\n ... with Switch(val) as case:\n ... if case(1, fall_through=True):\n ... ret.append(1)\n ... if case.match('2|two'):\n ... ret.append(2)\n ... if case.call(lambda v: 2 < v < 4):\n ... ret.append(3)\n ... if case.call(lambda v: 3 < v < 5, fall_through=True):\n ... ret.append(4)\n ... if case(5, 10):\n ... ret.append('5 or 10')\n ... if case.default:\n ... ret.append(6)\n ... return ret\n ...\n >>> test_switch(1)\n [1, 2]\n\n >>> test_switch(2)\n [2]\n\n >>> test_switch(3)\n [3]\n\n >>> test_switch(4)\n [4, '5 or 10']\n\n >>> test_switch(5)\n ['5 or 10']\n\n >>> test_switch(10)\n ['5 or 10']\n\n >>> test_switch(7)\n [6]\n\n\n >>> def test_switch_default_fall_through(val):\n ... ret = []\n ... with Switch(val, fall_through=True) as case:\n ... if case(1):\n ... ret.append(1)\n ... if case(2):\n ... ret.append(2)\n ... if case.call(lambda v: 2 < v < 4):\n ... ret.append(3)\n ... if case.call(lambda v: 3 < v < 5, fall_through=False):\n ... ret.append(4)\n ... if case(5):\n ... ret.append(5)\n ... if case.default:\n ... ret.append(6)\n ... return ret\n ...\n >>> test_switch_default_fall_through(1)\n [1, 2, 3, 4]\n\n >>> test_switch_default_fall_through(2)\n [2, 3, 4]\n\n >>> test_switch_default_fall_through(3)\n [3, 4]\n\n >>> test_switch_default_fall_through(4)\n [4]\n\n >>> test_switch_default_fall_through(5)\n [5]\n\n >>> test_switch_default_fall_through(7)\n [6]\n \"\"\"\n\n class StopExecution(Exception):\n pass\n\n def __init__(self, switch_value, fall_through=False):\n self._switch_value = switch_value\n self._default_fall_through = fall_through\n self._fall_through = False\n self._matched_case = False\n self._default_used = False\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n return exc_type is self.StopExecution\n\n def __call__(self, case_value, *case_values, **kwargs):\n def test(switch_value):\n return any(switch_value == v for v in (case_value,) + case_values)\n return self.call(test, **kwargs)\n\n def call(self, test, fall_through=None):\n if self._default_used:\n raise SyntaxError('Case after default is prohibited')\n\n self._check_finished()\n if self._fall_through or test(self._switch_value):\n self._matched_case = True\n self._fall_through = fall_through if fall_through is not None else self._default_fall_through\n return True\n\n return False\n\n def match(self, regex, fall_through=None):\n if self._default_used:\n raise SyntaxError('Match after default is prohibited')\n\n self._check_finished()\n if isinstance(regex, str):\n regex = re.compile(regex)\n if self._fall_through or regex.match(str(self._switch_value)):\n self._matched_case = True\n self._fall_through = fall_through if fall_through is not None else self._default_fall_through\n return True\n\n return False\n\n @property\n def default(self):\n self._check_finished()\n self._default_used = True\n return not self._matched_case\n\n def _check_finished(self):\n if self._matched_case and not self._fall_through:\n raise self.StopExecution()\n\n\nclass CSwitch(Switch):\n \"\"\"\n CSwitch is a shortcut to call Switch(switch_value, fall_through=True)\n \"\"\"\n def __init__(self, switch_value):\n super(CSwitch, self).__init__(switch_value, fall_through=True)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T11:52:01.150",
"Id": "82301",
"Score": "0",
"body": "Thanks, I've added also ability to have multiple regexp patterns within single `case/match` call, code is available on pypi: https://pypi.python.org/pypi/switch/1.1.0"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T05:57:20.117",
"Id": "46988",
"ParentId": "45747",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T12:46:24.850",
"Id": "45747",
"Score": "7",
"Tags": [
"python"
],
"Title": "Switch like context manager in Python"
} | 45747 |
<p>I am just starting out in my Clojure journey and I wonder if anybody can point out my beginners mistakes in my function below that simply reverses a list. I know that there is already a reverse function so this is purely for learning.</p>
<pre><code>(defn rev
([l]
(if (= (count l) 1) l (rev '() l)))
([l orig]
(if (= (count orig) 0)
l
(rev (conj l (first orig)) (rest orig)))))
</code></pre>
<p>In my defence, it does work, but what I am finding myself doing a lot in Clojure is overloading the arguments list to take into account when I need a working list like in this example where I <code>conj</code> new items onto.</p>
| [] | [
{
"body": "<p>Sometimes using arity overloading like you've done is the best way to write a function. </p>\n\n<p>I tried to rewrite your function using destructuring, like this:</p>\n\n<pre><code>(defn rev [[x & more]]\n (if more\n ...\n</code></pre>\n\n<p>however, it doesn't really work because you need some way of storing your \"result sequence\" in progress, which in your function is <code>l</code>. Because we're trying to write a reverse function, it's hard to do what we want without having some way of \"building up\" the sequence as we go and storing it in an intermediate value.</p>\n\n<p>Taking a look at <a href=\"https://github.com/clojure/clojure/blob/master/src/clj/clojure/core.clj#L906\" rel=\"nofollow noreferrer\">how reverse is actually implemented in Clojure</a>, we can see that a more concise way to express this idea of iterating over a sequence and building up a result sequence is by using <code>reduce</code> with a starting value of <code>'()</code>:</p>\n\n<pre><code>(defn reverse [coll]\n (reduce conj '() coll))\n</code></pre>\n\n<p>The magic behind this is that we're starting with a seq, <code>'()</code>. When you <code>conj</code> something onto a seq, it adds it to the beginning, not the end. So what this does is it starts with an empty seq, then goes through the input list items one by one and adds them to the beginning of the result list, so that you end up with a list that's reversed.</p>\n\n<p>EDIT: Leonid has a more thorough answer <a href=\"https://stackoverflow.com/a/22744672/2338327\">here</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T15:28:33.743",
"Id": "45756",
"ParentId": "45748",
"Score": "3"
}
},
{
"body": "<ul>\n<li>The 2 argument version of your function ought not to be exposed. Define\nit with a <code>let</code> or <code>letfn</code> form instead.</li>\n<li>You say you are reversing a list. Wherever you call for a list, a\nlazy sequence can turn up. Then <code>count</code> runs right to the end of the\nsequence <em>every time</em>. SLOW, for sequences of any length. So use\n<code>empty?</code> instead.</li>\n<li>You deal with case <code>1</code> of length separately. There is no need to.</li>\n<li>(More advanced) You are using explicit recursion: consuming one stack\nframe for every element in the original sequence. This sets a fairly \nlow limit on the length of the list you can deal with: probably<br>\naround the 10K mark (YMMV). Luckily, the recursive call to <code>rev</code> is\nthe last thing that happens: you can replace it with <code>recur</code>. </li>\n<li>And - trivially - you don't need to quote <code>()</code>.</li>\n</ul>\n\n<p>Those who don't want to see the outcome should look away now. </p>\n\n<pre><code>(defn rev [l] \n (letfn [(rev2 [l orig]\n (if (empty? orig)\n l\n (recur (conj l (first orig)) (rest orig))))]\n (rev2 () l))) \n</code></pre>\n\n<p>This is pretty well what you get using the standard <code>reverse</code>: though it's much more concisely expressed using <code>reduce</code>. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T16:40:01.413",
"Id": "90031",
"Score": "0",
"body": "I've just looked at [Leonid's answer elsewhere](http://stackoverflow.com/a/22744672/1562315) referred to by Dave Yarwood. He's not bothered about exposing `(rev [x y])`. Apart from that, there's little more to learn from my answer. And he's shown you the `(if-let [[x & xs] (seq s)] ... )` trick."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T16:24:52.793",
"Id": "52012",
"ParentId": "45748",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T13:09:13.733",
"Id": "45748",
"Score": "3",
"Tags": [
"beginner",
"clojure"
],
"Title": "Basic reverse function"
} | 45748 |
<p>I had written a solution for <a href="http://projecteuler.net/problem=18" rel="nofollow">Project Euler problem 18</a> in Python 3. It is good in its efficiency but the problem is the readability and I think reuse. </p>
<p>The algorithm used is that at every iteration the maximum for all numbers in a row is calculated starting from the top and going down to find the largest path.</p>
<pre><code>#This function is in "files" and used in the solution
def get_lines(path, file_name):
with open(path + os.sep + file_name) as f:
for line in f:
yield line.rstrip('\n')
def prob_018():
matrix = [[int(i) for i in line.split(' ')]
for line in files.get_lines(RESOURCES, "018.txt")]
for row_num in range(1, len(matrix)):
pre = matrix[row_num - 1]
cur = matrix[row_num]
for el_num in range(len(cur)):
total = cur[el_num]
if el_num == 0:
total += pre[el_num]
elif el_num == len(cur) - 1:
total += pre[el_num - 1]
else:
total += pre[el_num - 1] if pre[el_num - 1] > pre[el_num] \
else pre[el_num]
matrix[row_num][el_num] = total
return max(matrix[len(matrix) - 1])
</code></pre>
| [] | [
{
"body": "<p>The purpose of your program was unclear to me before reading the problem description. I could understand the logic flow, but I had no idea what answer it was seeking.</p>\n\n<ul>\n<li><p>The name <code>matrix</code> implies a rectangle. While <code>triangle</code> or <code>pyramid</code> are more descriptive, I'd go with <code>rows</code> for readability and a comment about the shape they form. The special handling of the first and last values of <code>cur</code> was confusing when assuming each row was the same size.</p></li>\n<li><p>Since this same code will be reused in problem 67 and to improve testability, rename the function and move the specifics of problem 18 to its own method.</p></li>\n</ul>\n\n<p>These two simple changes yield the following:</p>\n\n<pre><code>def prob_018():\n print(maximum_path(read_rows(\"018.txt\")))\n\ndef read_rows(file):\n return [[int(i) for i in line.split(' ')]\n for line in files.get_lines(RESOURCES, file)]\n\ndef maximum_path(rows): ...\n</code></pre>\n\n<p>The main algorithm has three steps:</p>\n\n<ol>\n<li>Iterate over each pair of rows.</li>\n<li>Calculate the better path to each cell in the lower row from the two cells above it.</li>\n<li>Return the maximum value from the last row.</li>\n</ol>\n\n<p>One thing that makes this difficult is that you're modifying the rows along the way. This makes extracting functions harder since they have side-effects. Instead, leave the original values untouched and build up an accumulator to hold the best path sums. Extracting this to a new <code>accumulate_steps</code> function yields a very readable outer algorithm:</p>\n\n<pre><code>def maximum_path(rows):\n paths = None\n for row in rows:\n paths = accumulate_steps(paths, row)\n return max(paths) if paths else None\n</code></pre>\n\n<p>This introduces a common trick to simplify high-level logic: moving special-case checks into extracted methods. Writing <code>accumulate_steps</code> to accept <code>None</code> for <code>paths</code> also allows <code>maximum_path</code> to handle the empty list and single-row corner cases.</p>\n\n<p>With that out of the way we can focus on combining the current best paths (accumulator) with the next row to form the new best paths. Rewriting your original code to build a new row is sufficient:</p>\n\n<pre><code>def accumulate_steps(paths, row):\n if paths is None:\n return row\n el_num in range(len(row)):\n total = row[el_num]\n if el_num == 0:\n total += paths[el_num]\n elif el_num == len(row) - 1:\n total += paths[el_num - 1]\n else:\n total += paths[el_num - 1] if paths[el_num - 1] > paths[el_num] \\\n else paths[el_num]\n row[el_num] = total\n</code></pre>\n\n<p>but I found it easier to move the first/last element handling out of the loop. Also, negative list indexes reduce the calls to <code>len</code> which cleans up the logic a bit. My first refactoring built a new list in-place with similar procedural code:</p>\n\n<pre><code>def accumulate_steps(paths, row):\n if paths is None:\n return row\n sums = [0] * len(row)\n sums[0] = paths[0] + row[0]\n sums[-1] = paths[-1] + row[-1]\n for i in range(1, len(row) - 1):\n sums[i] = row[i] + max(paths[i - 1], paths[i])\n</code></pre>\n\n<p>While it works, converting this to a list comprehension and adding on the first and last cells using <code>+</code> seems more Pythonic to me:</p>\n\n<pre><code>def accumulate_steps(paths, row):\n if paths is None:\n return row\n return ([paths[0] + row[0]]\n + [row[i] + max(paths[i - 1], paths[i]) for i in range(1, len(row) - 1)]\n + [paths[-1] + row[-1]])\n</code></pre>\n\n<p><strong>Putting it Together</strong></p>\n\n<pre><code>def prob_018():\n return maximum_path(read_rows(\"018.txt\"))\n\ndef read_rows(file):\n return [[int(i) for i in line.split(' ')]\n for line in files.get_lines(RESOURCES, file)]\n\ndef maximum_path(rows):\n paths = None\n for row in rows:\n paths = accumulate_steps(paths, row)\n return max(paths)\n\ndef accumulate_steps(paths, row):\n if paths is None:\n return row\n return ([paths[0] + row[0]]\n + [row[i] + max(paths[i - 1], paths[i]) for i in range(1, len(row) - 1)]\n + [paths[-1] + row[-1]])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T17:40:26.000",
"Id": "79888",
"Score": "0",
"body": "Point 4 of problem 67 I had done after posting this question. Good point about the name. But how do you go about extracting the functions from a big block that someone(me) wrote earlier? I can understand `read_rows` but what about the others? Any pointers on that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T18:56:27.223",
"Id": "79896",
"Score": "0",
"body": "@AseemBansal I've broken it down into steps to show my thinking."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T17:28:59.360",
"Id": "45767",
"ParentId": "45750",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "45767",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T13:59:44.023",
"Id": "45750",
"Score": "5",
"Tags": [
"python",
"programming-challenge",
"python-3.x"
],
"Title": "Increasing readability of maximum path sum algorithm"
} | 45750 |
<p>I created a singleton class for managing sound effects on Android. This class will only be instanced and loaded once at the beginning, and each activity will use the loaded songs.</p>
<p>I don't know either if this is the good approach for Singleton, nor if this is the good way to play sounds in Android. This is working like a charm, and I'm wondering about the resource utilizations.</p>
<pre><code>public class SoundManager {
private static SoundManager mInstance;
private SoundPool mSoundPool;
private HashMap<Integer, Integer> mSoundPoolMap;
private Vector<Integer> mAvailibleSounds = new Vector<Integer>();
private Vector<Integer> mKillSoundQueue = new Vector<Integer>();
private Handler mHandler = new Handler();
private boolean mMuted = false;
private static final int MAX_STREAMS = 2;
private static final int KILL_AFTER = 3000;
public static final int SOUND_SELECT = 0;
public static final int SOUND_LOCKED = 1;
@SuppressLint("UseSparseArrays")
private SoundManager(Context context) {
mSoundPool = new SoundPool(MAX_STREAMS, AudioManager.STREAM_MUSIC, 0);
mSoundPoolMap = new HashMap<Integer, Integer>();
loadSounds(context);
}
public static SoundManager getInstance(Context context){
if(mInstance == null){
mInstance = new SoundManager(context);
Log.d("SPARTA", "Instanciation");
}
return mInstance;
}
/**
* Load all sounds and put them in their respective keys.
* @param context
*/
private void loadSounds(Context context){
addSound(context, SOUND_SELECT, R.raw.metallic_knock);
addSound(context, SOUND_LOCKED, R.raw.licorice);
}
/**
* Put the sounds to their correspondig keys in sound pool.
* @param context
* @param key
* @param soundID
*/
public void addSound(Context context, int key, int soundID) {
mAvailibleSounds.add(key);
mSoundPoolMap.put(key, mSoundPool.load(context, soundID, 1));
}
/**
* Find sound with the key and play it
* @param key
*/
public void playSound(int key) {
if(mMuted)
return;
//If we have the sound
if(mAvailibleSounds.contains(key)) {
//We play it
int soundId = mSoundPool.play(mSoundPoolMap.get(key), 1, 1, 1, 0, 1f);
mKillSoundQueue.add(soundId);
//And schedule the current sound to stop after set milliseconds
mHandler.postDelayed(new Runnable() {
public void run() {
if (!mKillSoundQueue.isEmpty()) {
mSoundPool.stop(mKillSoundQueue.firstElement());
}
}
}, KILL_AFTER);
}
}
/**
* Initialize the control stream with the activity to music
* @param activity
*/
public static void initStreamTypeMedia(Activity activity){
activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
/**
* Is sound muted
* @param muted
*/
public void setMuted(boolean muted) {
this.mMuted = muted;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T21:17:31.530",
"Id": "80066",
"Score": "0",
"body": "Here is the corrected version : https://gist.github.com/FR073N/9902559"
}
] | [
{
"body": "<p>Let me start by saying I have very limited Android experience. That said, I did look into the <code>SoundPool</code> class a bit and have some questions/comments about your implementation:</p>\n\n<ol>\n<li>If you aren't already aware of some of the reasons why people consider Singletons an anti-pattern, I suggest you do some research on the topic and make sure you're ok with the downsides.</li>\n<li>Your class, for the most part, seems to be wrapping a <code>SoundPool</code> with a key value pair structure despite <code>SoundPool</code> already being a key value pair structure. I would imagine you could do away with most of this class and just use the <code>SoundPool</code> class directly.</li>\n<li>If you don't want to use <code>SoundPool</code> directly for some reason, why not at least use the soundId as a key? It already appears to be unique, and it's what the calling code probably wants anyway. If not, you may want to do some checking to make sure that duplicate keys aren't entered, or take the key assignment out of the hands of the caller and simply return an id as the result of the <code>addSound</code> function.</li>\n<li>Using both <code>mSoundPoolMap</code> and <code>mAvailibleSounds</code> means you have to manage keys in two locations which could lead to them getting out of sync or some confusion as to why there are two fields holding the same information. Using only <code>mSoundPoolMap</code> would be sufficient and avoid duplication. <a href=\"https://codereview.stackexchange.com/questions/32743/mutually-exclusive-properties\">This</a> highly voted question isn't quite the same, but it touches on a lot of good points why this kind of duplication can be bad.</li>\n</ol>\n\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T21:12:01.717",
"Id": "80064",
"Score": "0",
"body": "Your answer pointed out what others have explained. I could have accepter your answer as well, but the others gave me a little more information. Just one thing, for point 3, I used mSoundPoolMap to prevent from using the SoundPool load method each time. But you're true when you say that mAvailableSounds had the same function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T01:34:55.950",
"Id": "80091",
"Score": "0",
"body": "I wasn't suggesting doing away with caching if it was necessary, I was suggesting that you don't need to create a new key when `soundId` already existed and provides a direct map to what the consumer probably already wants to find a sound by (since they ask for it by `soundId` also)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T15:12:40.210",
"Id": "45754",
"ParentId": "45751",
"Score": "8"
}
},
{
"body": "<p>Unlike Ocelot20, I have quite a lot of Android experience, and this answer will focus on only one thing, namely:</p>\n\n<h1>Getting rid of the Singleton pattern in Android</h1>\n\n<p>Quote from a <a href=\"https://stackoverflow.com/a/3888560/1310566\">Stack Overflow answer</a>:</p>\n\n<blockquote>\n <p>Although the app context can be considered a singleton itself, it is framework-managed and has a well defined life-cycle, scope, and access path. Hence I believe that if you do need to manage app-global state, it should go here, nowhere else. For anything else, rethink if you really need a singleton object, or if it would also be possible to rewrite your singleton class to instead instantiate small, short-lived objects that perform the task at hand.</p>\n</blockquote>\n\n<p>In your Android.XML file there is the tag <code><application></code>. This tag can have the property <code>android:name</code>. This property can be set to a classname that extends <code>android.app.Application</code>.</p>\n\n<pre><code><application android:name=\"com.mypackage.MyApplication\" ...>\n</code></pre>\n\n<p>The <code>com.mypackage.MyApplication</code> class is very easy to make, simply this would be enough:</p>\n\n<pre><code>public class Register extends Application {\n}\n</code></pre>\n\n<p>But that's kind of boring, so you'd probably would want a <code>public void doSomething()</code> method, or - in your example:</p>\n\n<pre><code>public class Register extends Application {\n private SoundManager soundManager;\n\n public SoundManager getSoundManager() {\n if (soundManager == null) {\n // Application extends Context so just pass along 'this'!\n soundManager = new SoundManager(this); \n }\n return soundManager;\n }\n}\n</code></pre>\n\n<h3>How to get an instance of the <code>MyApplication</code> class then?</h3>\n\n<p>When your application starts, if you have specified the <code>android:name</code> property then Android will create an instance of the classname that you put here. This instance will be available through the Android <code>Context</code> that gets passed around to all Views, Activities and Fragments.</p>\n\n<p>That said, it is very easy to get access to the instance of <code>com.mypackage.MyApplication</code> from more or less anywhere, whether you have an <code>Activity</code>, a <code>View</code> or a <code>Fragment</code>. (If you haven't used Fragments yet by the way, <a href=\"http://developer.android.com/guide/components/fragments.html\" rel=\"nofollow noreferrer\">you really should</a> - there is a <a href=\"http://developer.android.com/tools/support-library/setup.html\" rel=\"nofollow noreferrer\">compatibility library available</a> if you are targeting API <= 10).</p>\n\n<p>All your Android Activities have the <code>getApplication</code> method, this retreives an instance of an <code>Application</code> class, in your case it will return the <code>MyApplication</code> instance.</p>\n\n<p>All Android Views have the <code>getContext</code> method, which has a <code>getApplicationContext</code> method which will return an <code>Application</code> instance, again; this will be your <code>MyApplication</code> instance.</p>\n\n<h3>Examples</h3>\n\n<p>In a method in your activity:</p>\n\n<pre><code>MyApplication myApp = (MyApplication) getApplication();\nmyApp.doSomething();\n</code></pre>\n\n<p>When you have no <code>Activity</code> nearby but instead have a <code>View</code> or another way to get a <code>Context</code>:</p>\n\n<pre><code>MyApplication myApp = (MyApplication) getContext().getApplicationContext();\nmyApp.doSomething();\n</code></pre>\n\n<p>In a fragment, use either <code>getView</code> or <code>getActivity</code> and then use one of the methods described above (<code>getApplication</code> or <code>getContext().getApplicationContext()</code>)</p>\n\n<p><strong>That</strong>, my friend, is how you avoid making your own singletons in Android. This is <em>the</em> recommended way of doing it, and it <em>can</em> also be used for passing data from one activity to another (when you are unable to use <code>getExtra</code> and <code>putExtra</code> to pass data between activities).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T19:51:15.613",
"Id": "80050",
"Score": "1",
"body": "I wasn't aware of that way. This answers my problematique of creating a singleton class in Android."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T20:03:24.470",
"Id": "45772",
"ParentId": "45751",
"Score": "5"
}
},
{
"body": "<p>I totally agree with Ocelot20, but wanted to point out some more things and provide some comments of my own about some things that has been already mentioned:</p>\n\n<h3>About <code>mAvailableSounds</code>:</h3>\n\n<ul>\n<li><p><strong>Vector is deprecated</strong>, use <code>List</code> (interface) and <code>ArrayList</code> (implementation) instead.</p>\n\n<pre><code>private List<Integer> mAvailibleSounds = new ArrayList<Integer>();\n</code></pre></li>\n<li><p>Does the order of the sounds matter in the <code>mAvailableSounds</code> list? No. Use a <code>HashSet</code> instead:</p>\n\n<pre><code>private Set<Integer> mAvailibleSounds = new HashSet<Integer>();\n</code></pre></li>\n<li><p>Discard the <code>mAvailibleSounds</code> variable entirely and use <code>mSoundPoolMap.containsKey()</code> instead.</p></li>\n</ul>\n\n<h3>Mapping int to int...</h3>\n\n<p>You have used <code>@SuppressLint(\"UseSparseArrays\")</code> to suppress a warning. However, you should know that there is some performance benefit in using a <code>SparseArray</code> rather than a <code>HashMap<Integer, Integer></code>.</p>\n\n<p>You create a mapping from integer to integer, by using your own keys. I don't see the need of this, honestly. Instead you can declare the <code>R.raw.metallic_knock</code> and similar as constants, such as:</p>\n\n<pre><code>public static final int SOUND_KNOCK = R.raw.metallic_knock;\n</code></pre>\n\n<h3>Flexibility</h3>\n\n<p>Your class seems to be coded in a way intended to be quite flexible, which would be good, but this code is limited to your project only:</p>\n\n<pre><code>private void loadSounds(Context context){\n addSound(context, SOUND_SELECT, R.raw.metallic_knock);\n addSound(context, SOUND_LOCKED, R.raw.licorice);\n}\n</code></pre>\n\n<p>If you would like to make another project and use this class, you would have to copy it and change those values. That's not a good idea. Programmers hate copy-pasting code within their projects. This class could be made more flexible by not making it dependent of which project is using it. The best way to do that would be to store the constants in a project-specific class, and that the project calls your <code>SoundManager</code> class with the resource-ids (such as <code>R.raw.licorice</code>).</p>\n\n<p>Currently, if you've forgotten to call <code>addSound</code> for a sound but try to play it directly with <code>playSound</code>, you wouldn't hear anything. You could save yourself some debugging time from making it either log a warning or try to play a sound with that id. Using the <code>R.raw</code> values directly would help with this.</p>\n\n<h3>Some final words</h3>\n\n<p>As you've said yourself: <strong>This is working like a charm</strong>. Your code works, be happy! Really, I mean it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T20:57:01.270",
"Id": "80059",
"Score": "0",
"body": "Indeed, mAvailableSounds was useless. I get rid of that and used mSoundPoolMap as a SparseIntArray instead. Flexbility wise, I created another class loading all my sounds."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T21:18:38.837",
"Id": "80067",
"Score": "1",
"body": "@FR073N Good work! Welcome back whenever you need more code reviewed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T20:28:59.540",
"Id": "45774",
"ParentId": "45751",
"Score": "8"
}
},
{
"body": "<ol>\n<li><p>I agree with <em>Simon</em> that <code>Vector</code> is deprecated and should be changed but its thread-safety is used in the case of <code>mKillSoundQueue</code> (it's used by multiple threads), so be careful. If you change it make sure that it will remain thread-safe. The name of the field also suggests that it's a queue, so I'd probably go with a thread-safe <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html\" rel=\"nofollow\"><code>Queue</code></a> implementation here.</p></li>\n<li><p>Just a question: wouldn't it be safer using <code>soundId</code> here too? (It have to be <code>final</code> for that.)</p>\n\n<blockquote>\n<pre><code>if (!mKillSoundQueue.isEmpty()) {\n mSoundPool.stop(mKillSoundQueue.firstElement());\n}\n</code></pre>\n</blockquote>\n\n<p>If I'm right the following is the same and you could get rid of the <code>mKillSoundQueue</code> field completely:</p>\n\n<pre><code>mSoundPool.stop(soundId);\n</code></pre>\n\n<p><a href=\"http://developer.android.com/reference/android/media/SoundPool.html#stop%28int%29\" rel=\"nofollow\"><code>SoundPool.stop</code></a> says the following:</p>\n\n<blockquote>\n <p>If the stream is not playing, it will have no effect.</p>\n</blockquote></li>\n<li><p>Using <code>m</code> prefixes to access fields not really necessary and it's just noise. Modern IDEs use highlighting to separate local variables from fields.</p>\n\n<blockquote>\n<pre><code>private static SoundManager mInstance;\n</code></pre>\n</blockquote></li>\n<li><p>I'd use a <code>_MILLIS</code> (or anything which is appropriate) postfix here for better clarity:</p>\n\n<blockquote>\n<pre><code>private static final int KILL_AFTER = 3000;\n</code></pre>\n</blockquote></li>\n<li><p>This:</p>\n\n<blockquote>\n<pre><code>mSoundPoolMap = new HashMap<Integer, Integer>();\n</code></pre>\n</blockquote>\n\n<p>could be in the same line as the declaration:</p>\n\n<pre><code>private HashMap<Integer, Integer> mSoundPoolMap = \n new HashMap<Integer, Integer>();;\n</code></pre></li>\n<li><p>It's really bad formatting:</p>\n\n<blockquote>\n<pre><code>if(mMuted)\nreturn;\n</code></pre>\n</blockquote>\n\n<p>Indentation of the <code>return</code> statement would make it readable.</p></li>\n<li><p>According to the <a href=\"http://www.oracle.com/technetwork/java/codeconventions-142311.html#430\" rel=\"nofollow\">Code Conventions for the Java Programming Language</a></p>\n\n<blockquote>\n <p><code>if</code> statements always use braces <code>{}</code>.</p>\n</blockquote>\n\n<p>Omitting them is error-prone.</p></li>\n<li><p>Comments like this are just noise, so they're unnecessary, remove them:</p>\n\n<blockquote>\n<pre><code>* @param key\n</code></pre>\n</blockquote>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n<li><p>Instead of comments like</p>\n\n<blockquote>\n<pre><code>//If we have the sound\nif(mAvailibleSounds.contains(key)) {\n</code></pre>\n</blockquote>\n\n<p>and </p>\n\n<blockquote>\n<pre><code> //And schedule the current sound to stop after set milliseconds\nmHandler.postDelayed(new Runnable() {\n</code></pre>\n</blockquote>\n\n<p>You could create explanatory variables and methods.</p>\n\n<pre><code>boolean hasSound = mAvailibleSounds.contains(key);\nif (hasSound) {\n ...\n</code></pre>\n\n<p>and <code>scheduleCurrentSoundStop()</code>.</p>\n\n<p>References:</p>\n\n<ul>\n<li><em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Bad Comments</em>, <em>Don’t Use a Comment When You Can Use a Function or a Variable</em>, p67</li>\n<li><em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em></li>\n<li><em>Refactoring: Improving the Design of Existing Code by Martin Fowler</em>, <em>Introduce Explaining Variable</em></li>\n</ul></li>\n<li><p>In the first case above I'd use a <a href=\"http://blog.codinghorror.com/flattening-arrow-code/\" rel=\"nofollow\">guard clause</a> to make the code flatten:</p>\n\n<pre><code>boolean hasSound = mAvailibleSounds.contains(key);\nif (hasSound) {\n return;\n}\n...\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T21:01:33.053",
"Id": "80061",
"Score": "1",
"body": "Your answer and Simon's really improved my code. I accepted his answer because I learned something about singleton with Android, but I could have accepted yours as well. Just one last question, about the third point : when should we use the m prefix ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T22:48:18.770",
"Id": "80078",
"Score": "1",
"body": "@FR073N: Sure, thanks for the feedback! (If you have time feel free to help [graduating the site](http://meta.codereview.stackexchange.com/q/1572/7076). I'm sure that you can find another useful questions and answers on the site to [vote on](http://meta.codereview.stackexchange.com/q/612/7076))."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T22:51:16.607",
"Id": "80080",
"Score": "0",
"body": "@FR073N: I don't know any valid use-cases for the `m` prefix right now, nothing comes to mind."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T02:04:06.227",
"Id": "45792",
"ParentId": "45751",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "45774",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T14:31:28.543",
"Id": "45751",
"Score": "10",
"Tags": [
"java",
"android",
"singleton",
"audio"
],
"Title": "Sound manager for Android"
} | 45751 |
<p>I am going on with refactoring my code base while migrating from Python 2 to Python 3. I am using generators to make reusable components this time as I am more comfortable with them this time then last time. But there are times when I am stuck at their use. Like below example. These two are essentially same with one infinitely generating and other with a limit.</p>
<p>Is there a way to make these as one function? Normally an extra optional parameter as limit will do the trick but with generators I am not sure how to use them. Is there some way to do that?</p>
<pre><code>def fibonacci_inf(a, b):
"""Lazily generates Fibonacci numbers Infinitely"""
while True:
yield b
a, b = b, a + b
def fibonacci(a, b, num):
"""Lazily generates Fibonacci numbers"""
while b < num:
yield b
a, b = b, a + b
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T15:27:46.297",
"Id": "79874",
"Score": "0",
"body": "I don't use Python much, but why wouldn't an optional argument work here? Pseudocode: `while(!optionalArgumentExists || optionalArgumentCondition)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T15:28:46.353",
"Id": "79875",
"Score": "0",
"body": "@Ocelot20 Exactly my point. But I couldn't wrap my head around actual syntax without making this a mess."
}
] | [
{
"body": "<p>Something like this should work:</p>\n\n<pre><code>def sequence(start, end = None):\n loopIndefinitely = end is None \n\n curr = start \n while loopIndefinitely or curr <= end:\n yield curr\n curr += 1\n\n## Prints: 1 2 3 4 5 6 7 8 9 10\nfor i in sequence(1, 10):\n print(i)\n\n## Prints: 1 2 3 4 5 6 7 8 9 10\nfor j in sequence(1):\n if(j > 10):\n break\n else:\n print(j)\n</code></pre>\n\n<p>Used <code>sequence</code> instead since the variable names more clearly show the use vs. <code>a, b, num</code>.</p>\n\n<p>I think it's important to:</p>\n\n<ol>\n<li>Clearly define what argument values lead to what functionality (for example, defining a clearly named variable like <code>loopIndefinitely</code> to show immediately what an <code>end</code> value of <code>None</code> means).</li>\n<li>Determine when it's appropriate to use an optional argument. This one is a bit tougher, but it may have been clearer to define two functions called <code>range</code> and <code>infiniteSequence</code>. In this example the code is pretty simple to share or even duplicate, but with a more complex function you may want to have two functions that both point to a third one that has most of the reusable code.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T16:19:35.467",
"Id": "79882",
"Score": "0",
"body": "One variation when the logic is this simple is to check the optional argument once and branch--either to separate functions as you suggest or inline. It's a minor performance improvement but may help to highlight how the optional argument applies."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T16:04:51.483",
"Id": "45759",
"ParentId": "45752",
"Score": "5"
}
},
{
"body": "<p>You could just implement the infinite generator, and use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.takewhile\"><code>itertools.takewhile</code></a> to limit it:</p>\n\n<pre><code>>>> list(itertools.takewhile(lambda x : x < 8, fibonacci_inf(0,1)))\n[1, 1, 2, 3, 5]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T17:28:24.047",
"Id": "79887",
"Score": "0",
"body": "Having spent some time with Haskell I can really appreciate this now. Another reason why I should go over the standard library again once in a while."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T17:18:26.320",
"Id": "45765",
"ParentId": "45752",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "45765",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T14:55:04.677",
"Id": "45752",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"generator"
],
"Title": "Wrapping my head around generators"
} | 45752 |
<p>I implemented the <code>atoi()</code> function! Here is my code: </p>
<pre><code>int my_atoi(char* pointer)
{
int result = 0;
char* pointer1;
multiplier = 1;
char sign = 1;
if(*pointer == '-')
sign =- 1;
pointer1 = pointer;
while(*pointer != '\0')
{
if(*pointer >= '0' && *pointer <= '9')
multiplier = multiplier * 10;
pointer = pointer + 1;
}
pointer = pointer1;
while(*pointer != '\0')
{
if(*pointer >= '0' && *pointer <= '9')
{
result = result + ( (*pointer%48) * multiplier);
multiplier = multiplier / 10;
}
pointer = pointer+1;
}
return (result * sign) / 10;
}
</code></pre>
<p>I wonder if there is any way that I can improve my function. I know there is a problem with my function. What if the user wants to convert from <code>char*</code> to <code>int</code> this string: "232-19". What should I do then? Any advice would be really helpful!</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T15:59:04.487",
"Id": "79877",
"Score": "0",
"body": "how is the problem \"string to int: 232-19\" connected with the code at hand?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T16:08:05.327",
"Id": "79878",
"Score": "0",
"body": "Well what if i want to convert from string to int the number -255 and by accident i type \"8-255\" .Then according to my algorith the number 8255 will be returned.I know it's pretty stupid to worry about these things but what if the user is extremely dumb? Furthermore i know it is really difficult for someone to type 8-255 instead of -255 but you never know, it may happen!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T16:10:37.710",
"Id": "79880",
"Score": "0",
"body": "raise an error. the input format is faulty. you shouldn't guess what the user wanted, but make him make his intent unmistakably clear ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T18:23:13.630",
"Id": "79894",
"Score": "0",
"body": "You only need one pass of the string (not two)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T20:03:53.540",
"Id": "79899",
"Score": "2",
"body": "Please do not edit your code after it has been reviewed so that it could make any reviews irrelevant."
}
] | [
{
"body": "<h1>Things you could improve</h1>\n\n<h3>Variables/Initialization</h3>\n\n<ul>\n<li><p>Where do you declare <code>multiplier</code>? I assume that since it is not declared within the method, it is declared as a global variable. Try to avoid global variables.</p>\n\n<p>The problem with global variables is that since every function has access to these, it becomes increasingly hard to figure out which functions actually read and write these variables.</p>\n\n<p>To understand how the application works, you pretty much have to take into account every function which modifies the global state. That can be done, but as the application grows it will get harder to the point of being virtually impossible (or at least a complete waste of time).</p>\n\n<p>If you don't rely on global variables, you can pass state around between different functions as needed. That way you stand a much better chance of understanding what each function does, as you don't need to take the global state into account.</p>\n\n<p>So instead of using global variables, initialize the variables in <code>main()</code>, and pass them as arguments to functions if necessary. In this case, I don't see the need for <code>multiplier</code> to be used outside of the function at all, so simply keep it declared within the function.</p></li>\n<li><p><code>sign</code> should be an <code>int</code>, and not a <code>char</code>.</p></li>\n</ul>\n\n<h3>Algorithm</h3>\n\n<ul>\n<li><p>Right now you are implementing a complicated and hard to follow method of converting a character into a number. The easy way is to have <a href=\"http://www.cplusplus.com/reference/cctype/isdigit/\"><code>isdigit()</code></a> do the hard work for you. This also will help you implement the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\">DRY principle</a>.</p>\n\n<blockquote>\n<pre><code>while(*pointer != '\\0')\n{\n if(*pointer >= '0' && *pointer <= '9')\n multiplier = multiplier * 10;\n\n pointer = pointer + 1; \n}\n\npointer = pointer1;\n\nwhile(*pointer != '\\0')\n{ \n if(*pointer >= '0' && *pointer <= '9')\n {\n result = result + ( (*pointer%48) * multiplier);\n multiplier = multiplier / 10; \n }\n\n pointer = pointer+1;\n}\n</code></pre>\n</blockquote>\n\n<p>See how you have two loops doing almost identical things? Here is how I simplified all of that by using <code>isdigit()</code>.</p>\n\n<pre><code>while (isdigit(*c)) \n{\n value *= 10;\n value += (int) (*c - '0');\n c++;\n}\n</code></pre>\n\n<p>You loop through the characters in the string as long as they are digits. For each one, add to the counter you're keeping - the value to add is the integer value of the character. This is done by subtracting the ASCII value of <code>'0'</code> from the ascii value of the digit in question.</p></li>\n<li><p>Note that this code doesn't handle overflow. If you pass in \"89384798719061231\" (which won't fit in an <code>int</code>), the result is undefined. The fix is simple enough, just use a <code>long long int</code> to mitigate against that. We'll still have issues for extremely long numbers, but fixing that so that the function works as intended is a bit more complicated.</p></li>\n</ul>\n\n<h3>Documentation</h3>\n\n<ul>\n<li><p>Where did all of your comments go? A newer developer would simply gawk at some of your code.</p>\n\n<blockquote>\n<pre><code>result = result + ( (*pointer%48) * multiplier);\n</code></pre>\n</blockquote>\n\n<p>Comments can really go a long way into helping other understand your code. Don't go overboard with them though, you will have to balance how much of them to put into your program.</p></li>\n</ul>\n\n<h3>Syntax/Styling</h3>\n\n<ul>\n<li><p>This looks like a typo.</p>\n\n<blockquote>\n<pre><code>if(*pointer == '-')\n sign =- 1;\n</code></pre>\n</blockquote>\n\n<p>Add a space for clarity.</p>\n\n<pre><code>if(*pointer == '-') sign = -1;\n</code></pre></li>\n<li><p>You should <strong>not</strong> be modifying your <code>char*</code> you accept as a parameter into the function. Therefore, declare the parameter as constant.</p>\n\n<pre><code>int my_atoi(const char* pointer)\n</code></pre></li>\n<li><p>Use more shorthand operators.</p>\n\n<pre><code>pointer++; // same as pointer = pointer+1;\nmultiplier /= 10; // same as multiplier = multiplier / 10;\nmultiplier *= 10; // same as multiplier = multiplier * 10;\n</code></pre></li>\n</ul>\n\n<h1>Final Code</h1>\n\n<pre><code>#include <stdio.h>\n#include <assert.h>\n#include <ctype.h>\n\nlong long int my_atoi(const char *c)\n{\n long long int value = 0;\n int sign = 1;\n if( *c == '+' || *c == '-' )\n {\n if( *c == '-' ) sign = -1;\n c++;\n }\n while (isdigit(*c))\n {\n value *= 10;\n value += (int) (*c-'0');\n c++;\n }\n return (value * sign);\n}\n\nint main(void)\n{\n assert(5 == my_atoi(\"5\"));\n assert(-2 == my_atoi(\"-2\"));\n assert(-1098273980709871235 == my_atoi(\"-1098273980709871235\"));\n puts(\"All good.\"); // I reach this statement on my system\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T03:25:39.517",
"Id": "79923",
"Score": "5",
"body": "You shouldn't change return types arbitrarily. `atoi()` traditionally returns an `int`, so `my_atoi()` should, too. If you want to parse a `long long`, then emulate `strtoll()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T03:42:52.763",
"Id": "80092",
"Score": "4",
"body": "`isdigit(*c)` is not define for `*c` values less than 0 (other than EOF). Better to `while (isdigit((unsigned char) (*c) ))`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-11-17T21:38:41.513",
"Id": "343141",
"Score": "0",
"body": "Missed corner: When `my_atoi()` result should be `LLONG_MIN`, `value += (int) (*c-'0');` is signed integer overflow (UB) as it tries to form `LLONG_MAX + 1`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-01-13T05:38:46.173",
"Id": "352749",
"Score": "0",
"body": "Using `isdigit` is wrong at all, since it doesn't have a related function `numeric_value`. Therefore, if your character set has two ranges of digits (0 to 9, and ٠ to ٩), the Indic numbers will be parsed wrong. Just stick to `'0' <= c && c <= '9'` to be safe. This also avoids the undefined behavior from using the ctype function incorrectly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-02-21T21:10:35.163",
"Id": "359076",
"Score": "0",
"body": "You missed an important point when you wrote _\"ASCII value of '0'\"_: there's nothing that says the host character set needs to be ASCII (only that 0..9 are contiguous). That's why you write `'0'` rather than an encoding-specific codepoint number."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-02-21T21:11:48.990",
"Id": "359077",
"Score": "0",
"body": "Not only is `=-` a likely typo, it has a very different meaning in early dialects of C (where it meant the same as modern `-=`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-29T12:22:13.997",
"Id": "398340",
"Score": "0",
"body": "I would add a \"sanity check\" at the beginning of the function to make sure that `c` is not NULL (otherwise, in the first if `if( *c == '+' || *c == '-' )` you will crash)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T19:16:31.043",
"Id": "45769",
"ParentId": "45755",
"Score": "13"
}
},
{
"body": "<p>[Edit]</p>\n\n<p>Except for the behavior on error, <code>atoi()</code> is equivalent to <code>(int)strtol(nptr, (char **)NULL, 10)</code>. <code>strtol()</code> accepts leading white space. OP's <code>my_atoi(char* pointer)</code> does not. To remedy:</p>\n\n<pre><code>int my_atoi(const char* pointer) {\n while (isspace((unsigned char) *pointer)) {\n pointer++;\n }\n ...\n</code></pre>\n\n<p>The below does describe a good way to handle <code>INT_MIN</code>.</p>\n\n<p>OTOH, handing values outside <code>[INT_MIN...INT_MAX]</code> is is not defined by the C spec, so some simplifications can be had. See far below.</p>\n\n<hr>\n\n<p>When a string represents <code>INT_MIN</code>, (let's assume 32-bit <code>int</code>) such as <code>\"-2147483648\"</code>, code runs into <code>int</code> overflow attempting to get to calculate <code>2147483648</code>. A simple way to solver this is rather than finding the positive value and then negating it, embrace the <strong>negative side</strong> of things. By doing the lion share of the math in the <code>INT_MIN</code> to <code>0</code> range, we avoid UB. Down-side: some find this approach more challenging to follow.</p>\n\n<p>Going to a wider integer or <code>unsigned</code> it not always possible as the integer size of \"text--> integer\" routine may be the maximum size. Strictly speaking <code>unsigned</code> does not always have a wider positive range than <code>int</code>. In any case, all the math can be handled at the desired signed integer size without resorting to other types.</p>\n\n<pre><code>#include <ctype.h>\n#include <limits.h>\n\nint my_atoi(const char* pointer) { // good idea to make the `const`\n int result = 0;\n while (isspace((unsigned char) *pointer)) {\n pointer++;\n }\n char sign = *pointer;\n if (*pointer == '-' || *pointer == '+') { // text could lead with a '+'\n pointer++;\n }\n int ch;\n // isdigit() expects an unsigned char or EOF, not char\n while ((ch = (unsigned char)(*pointer)) != 0) {\n if (!isdigit(ch)) break;\n ch -= '0';\n // Will overflow occur?\n if ((result < INT_MIN/10) || \n (result == INT_MIN/10 && ch > -(INT_MIN%10))) Handle_Overflow(); \n result *= 10;\n result -= ch; // - , not +\n pointer++;\n }\n if (sign != '-') {\n if (result < -INT_MAX) Handle_Overflow();\n result = -result;\n }\n return result;\n}\n</code></pre>\n\n<p>Notes:</p>\n\n<p><code>pointer%48</code> is confusing. What is special about 48? If you mean <code>'0'</code>, then use <code>pointer % '0'</code>.</p>\n\n<p>\"string: \"232-19\". What should I do then?\" Recommend stopping conversion at \"232\" and returning the value 232. <em>Could</em> set <code>errno</code>, but the typical <code>atoi()</code> function does not do too much error handling.</p>\n\n<p>On overflow, setting <code>errno</code>, could happen, but again, typical <code>atoi()</code> function does not do too much error handling. Suggest simple returning <code>INT_MAX</code> or <code>INT_MIN</code>.</p>\n\n<p>If you want better error handling, change to something like the following and set an error status.</p>\n\n<pre><code>int my_atoi(const char *s, int *ErrorCode);\n</code></pre>\n\n<p><strong>or</strong> location where things ended. If this are good, they ended at the <code>'\\0'</code>.</p>\n\n<pre><code>int my_atoi(const char *s, const char **endptr); \n</code></pre>\n\n<hr>\n\n<p>[Edit] Simplified: Removed out-of-range detection as C spec allows that. \"If the value of the result cannot be represented, the behavior is undefined.</p>\n\n<pre><code>int my_atoi(const char* pointer) {\n int result = 0;\n while (isspace((unsigned char) *pointer)) {\n pointer++;\n }\n char sign = *pointer;\n if (*pointer == '-' || *pointer == '+') {\n pointer++;\n }\n while (isdigit((unsigned char)*pointer)) {\n result = result*10 - (*pointer++ - '0');\n }\n if (sign != '-') {\n result = -result;\n }\n return result;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-27T19:40:42.243",
"Id": "237141",
"Score": "1",
"body": "`INT_MIN/10` and `INT_MIN%10` require C99 behavior."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T04:19:31.830",
"Id": "45912",
"ParentId": "45755",
"Score": "6"
}
},
{
"body": "<pre><code> char sign = *pointer;\n if (*pointer == '-' || *pointer == '+') {\n pointer++;\n }\n</code></pre>\n\n<p>Why de-referencing \"pointer\" three times? One time is enough:</p>\n\n<pre><code> char sign = *pointer;\n if (sign == '-' || sign == '+') {\n pointer++;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-16T18:13:46.107",
"Id": "276685",
"Score": "1",
"body": "Welcome to Code Review, your first answer looks good, enjoy your stay! Though I wonder if it makes a difference in the generated code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-16T16:44:55.467",
"Id": "147211",
"ParentId": "45755",
"Score": "3"
}
},
{
"body": "<p>if you are ok with recursion then code could be shortened to one below</p>\n\n<pre><code>#include <string.h>\n#include <math.h>\n#include <stdbool.h>\n\nint natural_number(const char* string) {\n int index = strlen(string) - 1;\n int number = pow(10, index) * (*string - '0');\n\n return (index == 0) ? number : number + natural_number(string + 1);\n}\n\nint my_atoi(const char* string) {\n int sign = (*string == '-') ? -1 : 1;\n int offset = (*string == '-') ? 1 : 0;\n\n return sign * natural_number(string + offset);\n}\n\n/* test cases */\nmy_atoi(\"-100\") == -100;\nmy_atoi(\"0\") == 0;\nmy_atoi(\"100\") == 100;\n</code></pre>\n\n<p>Stack exhaustion could be mitigated by <code>-foptimize-sibling-calls</code> compiler flag, that being supported by both GCC and Clang compilers.</p>\n\n<p><strong>Update:</strong></p>\n\n<p>As noted by <em>Roland Illig</em> implementation does not handle malformed input.\nIf it is desired closelly follow <code>atoi</code> <a href=\"http://www.cplusplus.com/reference/cstdlib/atoi/\" rel=\"nofollow noreferrer\">semantics</a> then next code should be <a href=\"http://tpcg.io/9ImVAz\" rel=\"nofollow noreferrer\">fine</a> <sub>don't forget set <code>Compile Options</code> to one in comments</sub>.</p>\n\n<pre><code>int digit(char symbol) {\n return symbol - '0';\n}\n\n/* tail call optimized */\nint natural_number_tc(const char* string, int number) {\n return !isdigit(*string)\n ? number\n : natural_number_tc(string + 1, 10 * number + digit(*string));\n}\n\nint natural_number(const char* string) {\n return natural_number_tc(string, 0);\n}\n\nconst char* left_trim_tc(const char* string, const char* symbol) {\n return !isspace(*string) ? symbol : left_trim_tc(string + 1, symbol + 1);\n}\n\nconst char* left_trim(const char* string) {\n return left_trim_tc(string, string);\n\n}\n\nint my_atoi(const char* string) {\n const char* symbol = left_trim(string);\n int sign = (*symbol == '-') ? -1 : 1;\n size_t offset = (*symbol == '-' || *symbol == '+') ? 1 : 0;\n\n return sign * natural_number(symbol + offset);\n}\n</code></pre>\n\n<p>This is still <em>chux</em>'s code where loops replaced with recursion</p>\n\n<pre><code>int result = 0;\nwhile (isdigit((unsigned char)*pointer)) {\n result = 10 * result + (*pointer - '0');\n pointer++;\n}\n\n// VS\n\nint loop(const char* pointer, int result) {\n return !isdigit((unsigned char)*pointer)\n ? result\n : loop(pointer + 1, 10 * result + (*pointer - '0'))\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-01-13T05:46:09.353",
"Id": "352750",
"Score": "0",
"body": "Test case: `buf = malloc(65536); buf[0] = '\\0'; my_atoi(buf)` will probably crash."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-01-13T05:50:29.260",
"Id": "352752",
"Score": "0",
"body": "Test case: `bufsize = 1 << 20; buf = malloc(bufsize); memset(buf, '0', bufsize); buf[bufsize - 1] = '\\0'; my_atoi(buf)` will take a _very_ long time."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-01-13T02:56:37.253",
"Id": "185005",
"ParentId": "45755",
"Score": "0"
}
},
{
"body": "<p>For a exercise in <a href=\"https://leetcode.com/problems/string-to-integer-atoi/description/\" rel=\"nofollow noreferrer\">leetcode</a>, wrote following impl: <a href=\"https://pastebin.com/dPJhsUnb\" rel=\"nofollow noreferrer\">atoi cpp code</a></p>\n\n<pre><code> class Solution {\nprivate:\n bool checkMin(int a, int b=10, int c=0, int min_val=INT_MIN) {\n /*\n accepts a*b + c, min\n a>min; b>min; c>min\n check a*b+c > min or not\n b>0; a<0 -ive; c<0\n a!=0\n */\n\n min_val = min_val -c;\n\n //std::cout<<\"new min input: \"<<a <<\" , \"<< c<<\" iter: \"<<b << \" \"<<min_val <<std::endl;\n\n //compare with a now\n if(a<min_val)\n return false;\n int cur_prod = 0;\n if(a==0)\n return true;\n for(;b>1;b--) {\n cur_prod += a;\n int curr_diff = min_val-cur_prod; \n /*\n subtraction possible because \n min_val<prod,\n min_val-prod<prod-prod \n min_val-prod<0 ---1\n prod<0\n -prod>0\n min_val+(-prod )> min_val+0 [x+ (+ive quantity)>x ]\n min_val-prod>min_val --2\n from 1, 2\n min_val< min_val-prod < 0 ---3\n from 3, min_val-prod can be expressed in integer\n\n check if curr_diff still can hold a deduction of a\n which means: curr_diff<a should hold, for a further a deduction in prod\n -5, -6\n for ex of min_val = 59, a = -6 at b = 2 (9th iteration) prod = -54\n you can't add -6 now, since it will cross definable limit\n only b-1 iterations\n because at i-1 th iteration, ith product formation is checked\n */\n //std::cout<<\"check function for input: \"<<a <<\" , \"<< c<<\" iter: \"<<b << \" prod now = \"\n //<< cur_prod << \" diff = \" <<curr_diff<<\" is curr_dif<a \"<<(curr_diff<a)<<std::endl;\n if(curr_diff>a) {\n //std::cout<<\" not possible\"<<std::endl;\n return false;\n }\n\n }\n return true;\n }\n\n bool checkMax(int a, int b=10, int c=0, int max_val=INT_MAX) {\n /*\n accepts a*b + c, min\n a<max; b<max; c<max\n check a*b+c < max or not\n b>0; a>0, c>0\n */\n\n max_val = max_val -c;\n\n //std::cout<<\"new max input: \"<<a <<\" , \"<< c<<\" iter: \"<<b << \" \"<<max_val <<std::endl;\n\n //compare with a now\n if(a>max_val) return false;\n int cur_prod = 0;\n if(a==0) return true;\n for(;b>1;b--) {\n cur_prod += a;\n int curr_diff = max_val-cur_prod; \n /*\n subtraction possible because \n max_val>prod,\n max_val-prod>prod-prod \n max_val-prod>0 ---1\n prod>0\n -prod<0\n max_val+(-prod )< max_val+0 [x+ (-ive quantity)<x ]\n max_val-prod<max_val --2\n from 1, 2\n 0< max_val-prod < max_val ---3\n from 3, max_val-prod can be expressed in integer\n\n check if curr_diff still can hold a increment of a\n which means: curr_diff>a should hold, for a further a deduction in prod\n 5>6 fails\n for ex of max_val = 59, a = 6 at b = 2 (9th iteration) prod = 54\n you can't add 6 now, since it will cross definable limit\n only b-1 iterations\n because at i-1 th iteration, ith product formation is checked\n */\n //std::cout<<\"check function for input: \"<<a <<\" , \"<< c<<\" iter: \"<<b << \" prod now = \"\n // << cur_prod << \" diff = \" <<curr_diff<<\" is curr_dif<a \"<<(curr_diff>a)<<std::endl;\n if(curr_diff<a) {\n //std::cout<<\" not possible\"<<std::endl;\n return false;\n }\n\n }\n return true;\n }\n\npublic:\n int myAtoi(string str) {\n //code to trim string\n int i =0, end=str.length()-1;\n //std::cout<<i<<\" \"<<end<<std::endl;\n while(i<end && str.at(i)==' ') {i++;continue;}\n while(end>-1 && str.at(end)==' ') {end--;continue;} \n\n\n if(end<i) return 0;\n\n int sign=1;\n if(str.at(i)=='-') {sign = -1; i++;}\n else if(str.at(i)=='+') {i++;}\n\n\n string tr_str = str.substr(i, end-i+1);\n\n int num = 0;\n\n for(char& digit : tr_str) {\n if(digit<'0' || digit>'9') return num; // not convertable character - exit\n int c= digit-'0';\n if(sign==-1) {\n //std::cout<<\"Evaluating \"<<c<<std::endl;\n //number cannot be lower than INT_MIN\n // do a check of num * 10 - c \n //num<0 already\n\n if(checkMin(num, 10, -c, INT_MIN))\n num = num*10 -c;\n else {\n num = INT_MIN;\n break;\n }\n //std::cout<<\"number is\"<<num<<std::endl;\n }\n else {\n if(checkMax(num, 10, c, INT_MAX))\n num = num*10 +c;\n else {\n num = INT_MAX;\n break;\n }\n //std::cout<<\"number is\"<<num<<std::endl;\n }\n }\n return num;\n\n\n }\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-02-21T20:58:26.177",
"Id": "359073",
"Score": "1",
"body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-02-23T04:16:47.477",
"Id": "359293",
"Score": "0",
"body": "the code uses a method, where checkMin, where no direct multiplication is performed until the result is validated. to be greater than INT_MIN."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-02-21T20:25:11.187",
"Id": "188055",
"ParentId": "45755",
"Score": "-1"
}
}
] | {
"AcceptedAnswerId": "45769",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T15:25:02.740",
"Id": "45755",
"Score": "12",
"Tags": [
"c",
"parsing",
"reinventing-the-wheel",
"integer"
],
"Title": "Implementation of atoi()"
} | 45755 |
<blockquote>
<p>Find the element the occurs more than \$\dfrac{n}{2}\$ times in an input array, where \$n\$ is input array length.</p>
</blockquote>
<p>I'm looking for code review, optimizations and best practices.</p>
<pre><code> public final class VotingAlgorithm {
// non-instantiable.
private VotingAlgorithm() {}
/**
* Returns the number which occurs more than n/2 times.
* If such a number does not exist, then results are unpredicatable.
*
* @param a the input array
* @return the number occuring more than n/2 times.
*/
public static int maxElement(int[] a) {
int maxElementIndex = 0;
int counter = 1;
for (int i = 1; i < a.length; i++) {
if (a[maxElementIndex] == a[i]) {
counter++;
} else {
counter--;
}
if (counter == 0) {
maxElementIndex = i;
counter++;
}
}
return a[maxElementIndex];
}
public static void main(String[] args) {
int[] a1 = {1, 2, 3, 1, 1, 1};
assertEquals(1, maxElement(a1));
int[] a2 = {2, 3, 1, 1, 1, 1};
assertEquals(1, maxElement(a2));
int[] a3 = {1, 1, 1, 1, 2, 3};
assertEquals(1, maxElement(a3));
int[] a4 = {1, 2, 1, 3, 1, 1};
assertEquals(1, maxElement(a4));
int[] a5 = {1, 2, 3, 4, 1, 1, 1};
assertEquals(1, maxElement(a5));
int[] a6 = {2, 3, 4, 1, 1, 1, 1};
assertEquals(1, maxElement(a6));
int[] a7 = {1, 1, 1, 1, 2, 3, 4};
assertEquals(1, maxElement(a7));
int[] a8 = {1, 2, 1, 3, 1, 4, 1};
assertEquals(1, maxElement(a8));
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T17:42:41.000",
"Id": "79889",
"Score": "0",
"body": "Use the test input `int[] a9 = {1, 2, 2, 1, 3, 3, 1, 4, 4, 1, 5, 5, 5};` ... what's the result?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T18:04:13.020",
"Id": "79891",
"Score": "0",
"body": "Well there is a javadoc stating 'If such a number does not exist, then results are unpredicatable.' Is that what you were upto ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T18:51:55.127",
"Id": "79895",
"Score": "0",
"body": "You are right, the JavaDoc does say that, and, you are right, the results are unpredictable. As a consequence, this question gets my -1 vote because there is no way for a calling program to know whether it has a right result or not.... The function should be called `mightGetMaxElement(...)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T19:07:29.943",
"Id": "79897",
"Score": "1",
"body": "@rofl: I'm new here so maybe I misunderstand the nature of this site, but a -1 vote seems a bit spiteful. Your issue with the question appears to be a criticism of the *code* (the whole point of the site), not a criticism of the question itself..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T12:37:25.803",
"Id": "79962",
"Score": "0",
"body": "@Ocelot20 - *This question does not show any research effort, is unclear, or is not useful* ... (tool-tip for down-vote button). I believe this question is neither 'clear', nor 'useful'."
}
] | [
{
"body": "<p>The JavaDoc and the method names do not agree.</p>\n\n<p>The method name <code>maxElement</code> implies the method will get either:</p>\n\n<ol>\n<li><em>the element that occurs most frequenly</em></li>\n<li><em>the element with the largest value</em></li>\n</ol>\n\n<p>This function may, or may not, do both.</p>\n\n<p>The JavaDoc indicates that this function will return the value that occurs more more than half-the-time, and that if there is no such element, the result is undefined.</p>\n\n<p>This makes the method useless, because anyone calling the method will then have to re-scan the entire data set to see whether the method is returning a right answer, or an undefined answer.</p>\n\n<p>Since repeating all the work to check whether the method produced a reliable result or not is required anyway, you may as well do it in the method itself, and then return a result which removes the non-determinism.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T18:58:03.357",
"Id": "45768",
"ParentId": "45766",
"Score": "5"
}
},
{
"body": "<p>Your code is very clever, perhaps a little <em>too</em> clever... It almost looks like you wrote the code first, and then asked yourself - what can this achieve?<br>\nAs @rolfl said - as it is currently written - the code is all but useless, because most of the time the result is unpredictable. Calling this method will return a value, which could either have more than half the length of occurrences, or... not? </p>\n\n<p>You could achieve <em>at least</em> as much information with the same complexity, by keeping more complete score.</p>\n\n<p>Here is an example, where you can save the count of each element, and keep the one with most occurrences:</p>\n\n<pre><code>public int elementWithMostOccurrences(int[] inputArray) {\n\n HashMap<Integer, Integer> occurrenceCount = new HashMap<Integer, Integer>();\n int currentMaxElement = inputArray[0];\n\n for (int i = 1; i < inputArray.length; i++) {\n Integer elementCount = occurrenceCount.get(inputArray[i]);\n if (elementCount != null)) {\n occurrenceCount.put(inputArray[i], elementCount + 1);\n if (elementCount >= occurrenceCount.get(currentMaxElement)) {\n currentMaxElement = inputArray[i];\n }\n } else {\n occurrenceCount.put(inputArray[i], 1);\n }\n }\n\n // if you want to return the element only if it has more than half the array size you can:\n // if (occurrenceCount.get(currentMaxElement) > inputArray.Length / 2) { ... }\n\n return currentMaxElement;\n}\n</code></pre>\n\n<p>This example is also \\$O(n)\\$ complexity, but gives a valuable result every time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T20:35:58.597",
"Id": "79900",
"Score": "0",
"body": "Even though you have a very good alternative code here, your code is C# while the question is Java. Want some help in translating it to Java?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T06:35:06.450",
"Id": "79934",
"Score": "0",
"body": "@SimonAndréForsberg - Woops... didn't even notice I switched languages... Thanks for pointing it out... I'm a little rusty with auto-boxing, could you please verify my java version?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T09:57:45.023",
"Id": "79949",
"Score": "0",
"body": "Use `HashMap` instead of `Hashtable`, and use the `.get` and `.put` methods of it. You can't access it by indexes directly. besides that, it looks fine."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T19:52:38.120",
"Id": "45771",
"ParentId": "45766",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T17:27:57.990",
"Id": "45766",
"Score": "5",
"Tags": [
"java",
"algorithm",
"array"
],
"Title": "Voting Algorithm"
} | 45766 |
<p>Is this the right way? Any comments on the hash functions? If asked a question like this in an interview, do I need to follow all OOP concepts(because I am using Java)? Like encapsulating the variables by writing getter and setter functions? </p>
<pre><code>import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class HashMapY<K,V> {
private static int capacity = 100;
private Map[] arr;
private int size;
public HashMapY () {
arr = (Map[]) Array.newInstance(Map.class, capacity);
size = 0;
}
public V get(Object key) {
assert key!=null;
int i = -1;
if (key instanceof String || key instanceof Character){
i = hash(key.toString(), capacity) % capacity;
}
if (key instanceof Integer)
i = hash(Integer.parseInt(key.toString()))%capacity;
while (!key.equals(arr[i].k) && i < capacity)
i = (i+1)%capacity;
return arr[i]==null ? null : arr[i].v;
}
public int hash(String value, int maxValue) {
long hash = doHash(value);
return (int) Math.abs(hash % maxValue);
}
private int hash(int k) {
k *= 357913941;
k ^= k << 24;
k += ~357913941;
k ^= k >> 31;
k ^= k << 31;
return k;
}
private long doHash(String str) {
long hash = 5381;
for (int i = 0; i < str.length(); i++) {
hash = ((hash << 5) + hash) + str.charAt(i);
}
return hash;
}
public boolean isEmpty() {
return size==0;
}
public void put(K key, V value) {
assert key != null;
int i=-1;
if (key instanceof String || key instanceof Character){
i = hash(key.toString(), capacity) % capacity;
}
if (key instanceof Integer)
i = hash(Integer.parseInt(key.toString()))%capacity;
while (arr[i]!=null) {
i = (i+1);
}
if(arr[i] == null) {
size++;
}
arr[i] = new Map(key, value);
}
public V remove(Object key) {
List<Map> pairs = new ArrayList<Map>();
assert key!=null;
int i = -1;
if (key instanceof String || key instanceof Character)
i = hash(key.toString(), capacity) % capacity;
if (key instanceof Integer)
i = hash(Integer.parseInt(key.toString()))%capacity;
while (!arr[i].k.equals(key) && capacity > i){
i = i + 1;
}
if (capacity >= i){
Object temp = arr[i].v;
while (arr[i]!= null && arr[i].k.equals(key)){
pairs.add(arr[i]);
arr[i] = null;
size--;
}
for (Map m : pairs){
this.put(m.k, m.v);
}
return (V) temp;
}
return null;
}
public int size() {
return size;
}
class Map {
K k;
V v;
public Map(K key, V val){
k = key;
v = val;
}
}
public boolean containsKey(K key) {
assert key!=null;
int i = -1;
if (key instanceof String || key instanceof Character)
i = hash(key.toString(), capacity) % capacity;
if (key instanceof Integer)
i = hash(Integer.parseInt(key.toString()))%capacity;
if (arr[i] == null) return false;
while (i<capacity && !arr[i].k.equals(key)){
i = i+1;
}
return i<capacity;
}
public Set<K> keySet() {
Set<K> set = new HashSet<K>();
for (Map m : arr){
if (m != null){
set.add(m.k);
}
}
return set;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T10:07:22.900",
"Id": "79950",
"Score": "1",
"body": "@Ocelot20 Whitespace is subject to review, just like any other aspect of the code, so it should not be edited in the question. I've rolled back to Rev 1."
}
] | [
{
"body": "<p>No, this is not the correct way to implement a hash map in Java, and especially not to implement the <code>java.util.Map</code> interface.</p>\n\n<ul>\n<li><p>You aren't even explicitly implementing the <code>Map</code> interface.</p></li>\n<li><p>What is <code>(Map[]) Array.newInstance(Map.class, capacity)</code> supposed to be? I'd think a simple <code>new Map[capacity]</code> would be sufficient.</p></li>\n<li><p>You calculate your hashes yourself. However, every <code>Object</code> has a <code>hashCode()</code> method – use that instead.</p></li>\n<li><p>Because you shouldn't calculate the hash code yourself, you shouldn't do any special handling of <code>String</code> and <code>Character</code> or <code>Integer</code>.</p></li>\n<li><p>In your <code>get</code> method, what happens when the key is not one of your special classes? Not only will you be doing a linear search through your bins which breaks my expectations about the algorithmic complexity of a hash map, you'll also start at index <code>-1</code>, which will greet you with an <code>ArrayIndexOutOfBoundsException</code>.</p></li>\n<li><p>Should you be implementing <code>java.util.Map</code>, the <code>get</code> method should throw an explicit <code>NullPointerException</code> rather than an optional assertion error as you do not want to allow <code>null</code> keys.</p></li>\n<li><p>For some reason, the <code>hash</code> method is public. Furthermore, <code>hash</code> and <code>doHash</code> are not static although they don't access any object state.</p></li>\n<li><p>Many criticisms about <code>get</code> also apply to <code>put</code>.</p></li>\n<li><p>Your <code>remove</code> method sports this code: <code>arr[i].k.equals(key)</code>. That risks a null pointer exception when <code>arr[i]</code> is null. Instead: <code>arr[i] != null && key.equals(arr[i].k)</code></p></li>\n<li><p><code>remove</code> also has a loop that will only execute once or nonce:</p>\n\n<pre><code>while (arr[i]!= null && arr[i].k.equals(key)){\n pairs.add(arr[i]);\n arr[i] = null;\n size--;\n}\n</code></pre>\n\n<p>Note that you never modify <code>i</code>.</p></li>\n<li><p>In <code>remove</code>, it would be much simpler to look up the bin for that key, and then empty that bin rather. Consider putting your main <code>get</code> logic into a <code>private int getBin(Object key)</code>, which you could use both in <code>get</code>:</p>\n\n<pre><code>int i = getBin(key);\n... // assert i in range\nif (arr[i] != null) {\n return arr[i].v;\n}\n</code></pre>\n\n<p>and <code>remove</code>:</p>\n\n<pre><code>int i = getBin(key);\n... // assert i in range\nif (arr[i] != null) {\n V value = arr[i].v;\n arr[i] = null;\n size--;\n return value;\n}\n</code></pre></li>\n<li><p>The <code>Map</code> class would usually be named <code>Entry</code>. Note that the <code>java.util.Map</code> interface contains a nested interface <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html\"><code>java.util.Map.Entry</code></a> which you'd also have to implement for compatibility.</p></li>\n<li><p><code>containsKey</code> could be implemented using a <code>getBin</code> helper as</p>\n\n<pre><code>int i = getBin(key);\n... // assert i in range\nreturn arr[i] != null;\n</code></pre></li>\n<li><p>Your hash map can only contain <code>100</code> elements. If it grows larger, you should reallocate the storage array. You are furthermore resolving hash collisions via “open addressing” (using the next free bucket). Alternatively, you could use linked lists in each bucket, which also simplifies growing the hash table.</p></li>\n</ul>\n\n<p>Then, there are many style problems in your code.</p>\n\n<ul>\n<li><p>Consider changing a few <code>while</code>s to easier to read <code>for</code> loops.</p></li>\n<li><p><code>i = i + 1</code> could be abbreviated to <code>i += 1</code>, but is most often written <code>i++</code>.</p></li>\n<li><p>Always use braces around the blocks of an <code>if</code>:</p>\n\n<pre><code>if (key instanceof Integer) {\n i = hash(Integer.parseInt(key.toString())) % capacity;\n}\n</code></pre></li>\n<li><p>Many of your casts could be prevented with the use of generics. In <code>remove</code>, you have</p>\n\n<pre><code>Object temp = arr[i].v;\n...\nreturn (V) temp;\n</code></pre>\n\n<p>Instead:</p>\n\n<pre><code>V temp = arr[i].v;\n...\nreturn temp;\n</code></pre></li>\n</ul>\n\n<p>Regarding the question: “<em>do I need to follow all OOP concepts(because I am using Java)?</em>” – the answer is <em>yes</em>, but not because you are using Java. Instead, you'll want to write solid OOP code simply because your are writing object-oriented code, the language does not matter. Applying best practices is vastly preferable to producing shoddy, almost-working, bug-ridden code.</p>\n\n<h3>What now?</h3>\n\n<p>Your hash map implementation does not hold up to a code review. But that's not a problem.</p>\n\n<ul>\n<li>First, learn more about the topic: there is the <a href=\"https://en.wikipedia.org/wiki/Hash_table\">Wikipedia article on hash tables</a>, there is also the source code for <code>java.util.HashMap</code> (e.g. <a href=\"http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7u40-b43/java/util/HashMap.java\">here</a>). Compare what you've learned with your code, and try to understand your errors.</li>\n<li>Along the way, you'll probably also get better at actual Java programming.</li>\n<li>Then, try again. Start with a clean slate, and write another <code>HashMap</code> implementation. I'm sure you'll have improved by leaps and bounds. And please come back to have your new code reviewed :)</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T21:01:21.017",
"Id": "45776",
"ParentId": "45770",
"Score": "14"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T19:27:07.553",
"Id": "45770",
"Score": "10",
"Tags": [
"java",
"hash-map"
],
"Title": "Is this the right way to implement a hashmap?"
} | 45770 |
<p>I put together this Ruby script (1.9.3) to load data into MySQL from many .xlsx files that contain data entered by people. These files typically have many illegal characters and it has been difficult to handle the different errors. I have tried multiple rescue and character escaping approaches but now this method is not good and I have several more in the same class that are similar but load from different formats.</p>
<p>I would love some code review to help make this more functional. This is a standalone Ruby script without Rails or activerecord. I am using the logger, rubyXL, and MySQL2 gems.</p>
<pre><code> def paid_adv_load_ppc
begin
Dir["#{@paid_adv_work_path}*.xlsx"].each do |file|
if file =~ /(PPC)/ && file !~ /(~)/
begin
@file = file
begin
workbook = RubyXL::Parser.parse(file)
data = workbook.worksheets[0]
sheet1 = data.extract_data
begin
sheet1.each_with_index do |row,index|
if index > 0 && row[1] != nil
service = row[3].to_s.gsub(/['"]/, '')
impressions = row[9].to_i
clicks = row[10].to_i
cost = row[11].to_f
total = row[12].to_f
puts "index: #{index} row: #{row}"
@db.query("INSERT INTO ppc
(service,impressions,clicks,cost,total)
VALUES ('#{service}',#{impressions},#{clicks},#{cost},#{total}) ")
end
end
rescue Exception => e
@log.info("There is a problem loading row for index #{index} :#{row} because of #{e.message}")
next
end
rescue Exception => e
@log.info("There is a problem loading #{@file}: #{e.message}")
next
end
end
@log.info("Loaded file #{@file} into database")
FileUtils.rm(@file)
end
end
rescue Exception => e
@log.warn("Unable to process the data feed: #{@file} because #{e.message}")
end
end
</code></pre>
| [] | [
{
"body": "<p>For starters, I'd break the script up into many more methods. If nothing else it'll avoid the \"pyramid code\" (all that nested indentation) you've got going on. But it should also make the code easier to understand, maintain and extend.</p>\n\n<p>I'd also, as an overall approach, favor writing a file of <code>INSERT</code> statements, rather than inserting each row, one at a time. At least for testing, I'd highly recommend this. You can always read this file directly into mysql later. The point is that if, say, the first 2 rows get inserted fine, but the 3rd fails, you'll already have those first 2 row in the database, when you run the script again. And since the .xlsx files only get removed if <em>everything</em> works out, the same file may be imported several times - perhaps failing halfway several times - resulting in a bunch of doubled rows.</p>\n\n<p>Speaking of files, I'd avoid completely removing the xlsx file once it's done. Probably better to move it or rename it, so you still have it, but it won't get read again. In general, just try to avoid destructive operations unless necessary.</p>\n\n<p>Anyway, the code below is an attempt to break up your code. I haven't tried it, so don't just blindly run it or anything.</p>\n\n<p>Moreover, I'm using RubyXL's <code>get_table</code> method here - I don't know if that's actually useful in your case. However, I imagine that the xlsx-files have a header row, since you always skip the first row. If those headers are sensical, you can use them to your advantage, and avoid the hard-coded (and opaque) column indices.</p>\n\n<p>Some of the methods here have optional arguments that default to instance variables. I won't recommend that for production use; it's there for testing purposes. You can either make the arguments required, or you can remove the arguments, and rely on instance variables.</p>\n\n<pre><code># Hash for translating xlsx columns to mysql columns\n# The procs may not be necessary; get_table may handle conversion\nCOLUMN_TRANSLATIONS = {\n \"Service\" => { column: \"service\", proc: :to_s },\n \"Impressions\" => { column: \"impressions\", proc: :to_i },\n \"Clicks\" => { column: \"clicks\", proc: :to_i },\n \"Cost\" => { column: \"cost\", proc: :to_f },\n \"Total\" => { column: \"total\", proc: :to_f }\n}.freeze\n\n# Gets the relevant .xlsx-files\ndef xlsx_files(directory = @paid_adv_work_path)\n path = File.join(directory, \"*(PPC)*.xlsx\")\n files = Dir.glob(path)\n files.reject { |file| File.basename(file) =~ /^~/ }\nend\n\n# Use get_table to get structured data\ndef read_xlsx(file)\n workbook = RubyXL::Parser.parse(file)\n worksheet = workbook.worksheets[0]\n worksheet.get_table(COLUMN_TRANSLATIONS.keys)[:table]\nend\n\n# Translate into a mysql-friendly format\ndef translate_table(table)\n table.map do |row|\n row.map do |column, value|\n lookup = COLUMN_TRANSLATIONS[name.to_s] # get_table uses symbol keys; we want strings\n value = value.send(lookup[:proc])\n [lookup[:column], value]\n end\n end\nend\n\n# Insert a row\ndef insert_rows(rows, connection = @db)\n columns = COLUMN_TRANSLATIONS.map { |name, info| info[:column] }\n rows.each do |row|\n columns = row.keys.join(\", \")\n values = row.values.map { |value| \"'#{connection.escape(value)}'\" }.join(\", \")\n query = \"INSERT INTO ppc (#{columns}) VALUES (#{values});\"\n connection.query(query)\n end\nend\n\n# Put it together per-file\ndef import_xlsx_file(file, connection = @db)\n table = read_xlsx(file)\n rows = translate_table(table)\n insert_rows(rows, connection)\nend\n\n# And all together now...\ndef import\n xlsx_files.each do |file|\n begin\n import_xlsx_file(file)\n # Handle file removal/renaming here\n rescue => e\n @log.info \"Failed to import #{file}: #{e.message}\"\n end\n end\nend\n</code></pre>\n\n<p>An advantage of having the optional arguments is that you can swap out the database connection with a stand-in object, like:</p>\n\n<pre><code>class QueryLogger\n def initialize(logger)\n @logger = logger\n end\n\n def query(string)\n @logger.info(string)\n end\nend\n</code></pre>\n\n<p>And try something like <code>import_xlsx_file(some_file, QueryLogger.new(@log))</code> to log the queries instead of actually running them on the server.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T18:38:55.547",
"Id": "80039",
"Score": "1",
"body": "one detail: `rescue Exception => exc` is no good, should capture only `StandardError`, which is completely equivalent to `rescue => exc`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T19:04:11.863",
"Id": "80045",
"Score": "0",
"body": "@tokland Oops, you're right - amending the code. Thanks"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T22:13:58.700",
"Id": "45778",
"ParentId": "45773",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "45778",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T20:24:54.100",
"Id": "45773",
"Score": "5",
"Tags": [
"ruby",
"mysql",
"file",
"excel"
],
"Title": "Ruby script to load .xlsx files into a MySQL database"
} | 45773 |
<p>My goal is to make File_Path_Handler constructor the only thing a user can access. Oh, is it too coupled? but the main question is: <strong>is File_Path_Handler the only accessible part of this package?</strong></p>
<p>The handler: </p>
<pre><code>package file_path_handler;
//| File_Path_Handler
//| - a component that lets the user pick a file,
//| then the file path will be displayed accordingly
//| imports
import javax.swing.JPanel; //? the base class
import java.awt.BorderLayout; //? the organizing layout
public class File_Path_Handler extends JPanel {
private File_Path_Load_Button button;
private File_Path_Display display; //? the UI part
private File_Path_Load_Button_Click_Listener trigger;
private File_Path_Relay relay; //? the internal logic part
//| constructor
public File_Path_Handler( final String button_label, final String default_display_label ) {
this.display = new File_Path_Display( default_display_label ); //? the UI part
this.relay = new File_Path_Relay( display );
this.trigger = new File_Path_Load_Button_Click_Listener( relay ); //? the logic that wires all the UI together
this.button = new File_Path_Load_Button( button_label, trigger ); //? the other UI part
this.setLayout( new BorderLayout() );
this.add( button, BorderLayout.WEST );
this.add( display, BorderLayout.CENTER );
}
}
</code></pre>
<p>The display: </p>
<pre><code>package file_path_handler;
// imports
import javax.swing.JTextField; //? the base class
//| File_Path_Display
//| - displays the current selected file
class File_Path_Display extends JTextField { //? the public interface will be the JPanel that houses this couplet, this can stay hidden in the package
public File_Path_Display( final String default_label ) {
this.setText( default_label );
this.setEnabled( false );
}
public void update_text( final String file_path ) {
this.setText( file_path );
}
}
</code></pre>
<p>The ActionListener: </p>
<pre><code>package file_path_handler;
//| import
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent; //? the base interface
import javax.swing.JFileChooser; //? for user input
//| File_Path_Load_Button_Click_Listener
//| - lets the user pick a file; then obtain_file_path_for( file )
class File_Path_Load_Button_Click_Listener implements ActionListener { //? package visibility: the JPanel that holds this all will be the public interface
File_Path_Relay relay; //? the central control logic between UI input and output
public void actionPerformed( ActionEvent action ) {
JFileChooser file_chooser = new JFileChooser();
int ret_val = file_chooser.showOpenDialog( null ); //? lets the user pick a file
if ( JFileChooser.APPROVE_OPTION == ret_val ) { //? user succesfully picked a file
relay.relay_file_path( file_chooser.getCurrentDirectory().toString() + file_chooser.getSelectedFile().getName() ); //? relay the path
}
}
public File_Path_Load_Button_Click_Listener( File_Path_Relay relay ) { //? handed a relay by the housing
this.relay = relay;
}
}
</code></pre>
<p>The accompanying button:</p>
<pre><code>package file_path_handler;
//| import
import javax.swing.JButton; //? the base class
import file_path_handler.File_Path_Load_Button_Click_Listener; //? the action that this button would perform
//| File_Path_Load_Button
//| - lets the user choose a file, then obtain_file_path_of(file)
class File_Path_Load_Button extends JButton { //? package visibility: this couplet scheme is the only one that will use File_Path_Load_Button
private File_Path_Load_Button_Click_Listener trigger;
public File_Path_Load_Button( final String button_label, File_Path_Load_Button_Click_Listener trigger ) { //? so it is given by the housing
this.setText( button_label );
this.addActionListener( trigger );
}
}
</code></pre>
<p>The logical relay:</p>
<pre><code>package file_path_handler;
//| imports
import file_path_handler.File_Path_Display;
class File_Path_Relay { //? package visibility: the JPanel housing is the interface, this can stay hidden
File_Path_Display display;
public void relay_file_path( final String file_path ) {
this.display.update_text( file_path );
}
public File_Path_Relay( File_Path_Display display ) {
this.display = display;
}
}
</code></pre>
| [] | [
{
"body": "<pre><code>package file_path_handler;\n</code></pre>\n\n<p>Package names should be in the format <code>tld.organization.application.package</code>. For example like this:</p>\n\n<pre><code>package com.company.application.package;\npackage com.github.username.application;\npackage com.gmail.username.application;\n</code></pre>\n\n<p>This can be ignored for test applications and similar, but the moment you release code \"into the wild\" you should make sure that it is in a correct package.</p>\n\n<hr>\n\n<pre><code>//| File_Path_Handler\n//| - a component that lets the user pick a file, \n//| then the file path will be displayed accordingly\n</code></pre>\n\n<hr>\n\n<p>What is this? You should always use <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/javadoc-137458.html\">JavaDoc</a> to document your code. Not some obscure self-made format that is incompatible with everything.</p>\n\n<p>If in doubt, look at the documentation of the language you're using. Never forget, you're not the first to use that language, you're not the first who needs whatever you need, somebody else already did it and they did it better in 99% of the cases.</p>\n\n<hr>\n\n<pre><code>//| imports\nimport javax.swing.JPanel; //? the base class\n\nimport java.awt.BorderLayout; //? the organizing layout\n</code></pre>\n\n<p>Again, these comments are not helpful in any way and should be left out.</p>\n\n<hr>\n\n<pre><code>public class File_Path_Handler extends JPanel {\n</code></pre>\n\n<p>This violates the Java Naming Conventions which state the classes should be <code>UpperCamelCase</code>.</p>\n\n<hr>\n\n<pre><code>private File_Path_Load_Button button;\n</code></pre>\n\n<p>This violates the Java Naming Conventions which state that the variables should be <code>lowerCamelCase</code>.</p>\n\n<p>Also prefixing every variable with the class name is not helpful and not a good idea. It only clutters up everything and having a \"common prefix\" for variables is the whole idea of classes in the first place.</p>\n\n<hr>\n\n<pre><code>public File_Path_Handler( final String button_label, final String default_display_label ) {\n</code></pre>\n\n<p>This violates the Java Naming Conventions which states the functions should be <code>lowerCamelCase</code> with the exception of constructors which mimic the class name. Also variable names.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T13:37:24.437",
"Id": "79963",
"Score": "0",
"body": "but how about its encapsulation?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T01:28:52.187",
"Id": "80090",
"Score": "0",
"body": "@user2738698: Reviews don't have to be complete and may comment any part of the code (http://codereview.stackexchange.com/help/on-topic)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T04:34:37.547",
"Id": "80095",
"Score": "0",
"body": "Uh huh, still want the encapsulation question answered though"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T10:58:28.427",
"Id": "45816",
"ParentId": "45777",
"Score": "5"
}
},
{
"body": "<blockquote>\n <p>Oh, is it too coupled? </p>\n</blockquote>\n\n<p>It looks OK for me (but apply the suggestions by <em>Bobby</em> and above).</p>\n\n<blockquote>\n <p>is <code>File_Path_Handler</code> the only accessible part of this package?</p>\n</blockquote>\n\n<p>It seems to me, that it is.</p>\n\n<p>Another notes:</p>\n\n<ol>\n<li><p>You cuold use <code>fileChooser.getSelectedFile().getAbsolutePath()</code> here:</p>\n\n<blockquote>\n<pre><code>relay.relay_file_path( file_chooser.getCurrentDirectory().toString() + \n file_chooser.getSelectedFile().getName() ); //? relay the path\n</code></pre>\n</blockquote></li>\n<li><p>A great comment from <a href=\"https://codereview.stackexchange.com/a/19459/7076\"><em>@tb-</em>'s answer</a>:</p>\n\n<blockquote>\n <p>Do not extend <code>JPanel</code>, instead have a private <code>JPanel</code> \n attribute and deal with it (Encapsulation). \n There is no need to give access to all \n <code>JPanel</code> methods for code dealing with a <code>UserPanel</code>\n instance. If you extend, you are forced to stay with this forever, \n if you encapsulate, you can change whenever you want without \n taking care of something outside the class.</p>\n</blockquote>\n\n<p>See also: <a href=\"https://codereview.stackexchange.com/a/45683/7076\">#1 at How many squares can you see?</a></p></li>\n<li><p>I'd use a factory method instead of inheritance:</p>\n\n<blockquote>\n<pre><code>class File_Path_Display extends JTextField {\n public File_Path_Display( final String default_label ) {\n this.setText( default_label );\n this.setEnabled( false );\n }\n\n public void update_text( final String file_path ) {\n this.setText( file_path );\n }\n}\n</code></pre>\n</blockquote>\n\n<p>The following is much simpler:</p>\n\n<pre><code>private JTextField createFilePathDisplay(String defaultDisplayLabel) {\n JTextField filePathDisplay = new JTextField();\n filePathDisplay.setText(defaultDisplayLabel);\n filePathDisplay.setEnabled(false);\n return filePathDisplay;\n}\n</code></pre>\n\n<p>You can call <code>setText</code> directly (it's inherited), I don't see any additional value of <code>update_text</code>.</p>\n\n<p>You could create a similar method instead of <code>File_Path_Load_Button</code> too.</p>\n\n<p>(If you really want to do it for information hiding you should use composition instead of inheritance. Related: <em>Effective Java, Second Edition</em>, <em>Item 16: Favor composition over inheritance</em>.)</p></li>\n<li><p>According to the Java Code Conventions constructors should be the first in a class, before the other methods.</p></li>\n<li><p>The <code>trigger</code> field is unused here:</p>\n\n<blockquote>\n<pre><code>class File_Path_Load_Button extends JButton {\n private File_Path_Load_Button_Click_Listener trigger;\n\n public File_Path_Load_Button( final String button_label, \n File_Path_Load_Button_Click_Listener trigger ) {\n this.setText( button_label );\n this.addActionListener( trigger );\n }\n}\n</code></pre>\n</blockquote>\n\n<p>You could remove it. (Although the factory method is still a better idea.)</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T02:06:32.907",
"Id": "45905",
"ParentId": "45777",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "45905",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T21:58:48.057",
"Id": "45777",
"Score": "4",
"Tags": [
"java",
"swing"
],
"Title": "Did I properly encapsulate this package?"
} | 45777 |
<blockquote>
<p><strong>Task:</strong></p>
<p>Given <code>comma_separated.txt</code> file with string:</p>
<blockquote>
<pre><code>1,2,3,4,5,6,7,8,9,10,11,12...,n
</code></pre>
</blockquote>
<p>Calculate the average value.</p>
<p><strong>For example:</strong> 1,2,3 should be equal 2 (float) as result.</p>
</blockquote>
<p>Here is my solution in C:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int element_counter;
float* all_elements;
void mark_element_as_read() {
element_counter += 1;
}
int get_number_of_read_elements() {
return element_counter;
}
float* expand_array_stack_for(float* elements) {
return realloc(elements, get_number_of_read_elements() * sizeof(elements));
}
void append_float(float element) {
all_elements = expand_array_stack_for(all_elements);
all_elements[get_number_of_read_elements()] = element;
}
float* get_collection() {
return all_elements;
}
float* read_from_file(char* filename) {
FILE *file_opened;
file_opened = fopen(filename, "r");
char elements[255];
char * element;
while (fgets(elements, sizeof(elements), file_opened) != NULL) {
element = strtok(elements, ",");
while (element != NULL) {
append_float(strtof(element, NULL));
mark_element_as_read();
element = strtok(NULL, ",");
}
}
free(element);
fclose(file_opened);
return get_collection();
}
int main() {
float sum = 0.0, average;
float *elements = read_from_file("comma_separated.txt");
int i = 0;
for (i = 0; i < get_number_of_read_elements(); i++) {
sum += elements[i];
}
average = sum / get_number_of_read_elements();
printf("average = %f\n", average);
return 0;
}
</code></pre>
<p>This is my very first time coding in C. I used to code in Ruby, Java and PHP, so maybe this code would be a little bit "high leveled".</p>
| [] | [
{
"body": "<h1>Things you can improve</h1>\n\n<h3>Variables/Initialization</h3>\n\n<ul>\n<li><p>Floating-point math is challenging in surprising places. It's easy to write down a reasonable algorithm that introduces 0.01% error on every step, which over 1,000 iteration turns the results into complete slop. You can easily find volumes filled with advice about how to avoid such surprises. Much of it is valid today, but much of it is easy to handle quickly: <strong>use <code>double</code> instead of <code>float</code></strong>, and for intermediate values in calculations, it doesn't hurt to use <code>long double</code>.</p>\n\n<p>The problem is how many bits each type uses to store significant digits. <code>float</code> uses 32 bits, and <code>double</code> uses 64 bits. 64 bits is enough to reliably store 15 significant digit, which is plenty in order to solve all of our floating-point problems for now. All we had to do was throw twice as much space at the problem, and suddenly all sorts of considerations are basically irrelevant. Even if there is a perceptible speed difference between a program written with all <code>double</code>s and one written with all <code>float</code>s, it's worth extra microseconds to be able to ignore so many caveats.</p></li>\n<li><p>Don't use global variables.</p>\n\n<blockquote>\n<pre><code>int element_counter;\nfloat* all_elements;\n</code></pre>\n</blockquote>\n\n<p>The problem with global variables is that since every function has access to these, it becomes increasingly hard to figure out which functions actually read and write these variables.</p>\n\n<p>To understand how the application works, you pretty much have to take into account every function which modifies the global state. That can be done, but as the application grows it will get harder to the point of being virtually impossible (or at least a complete waste of time).</p>\n\n<p>If you don't rely on global variables, you can pass state around between different functions as needed. That way you stand a much better chance of understanding what each function does, as you don't need to take the global state into account.</p>\n\n<p>So instead of using global variables, initialize the variables in <code>main()</code>, and pass them as arguments to functions if necessary.</p></li>\n</ul>\n\n<h3>Standards</h3>\n\n<ul>\n<li><p><code>strtok</code> is limited to tokenizing only one string (with one set of delimiters) at a time, and it can't be used while threading. Therefore, <code>strtok</code> is considered deprecated. </p>\n\n<p>Instead, use <a href=\"http://linux.die.net/man/3/strtok_r\"><code>strtok_r</code></a> or <code>strtok_s</code> which are threading-friendly versions of <code>strtok</code>. The POSIX standard provided <code>strtok_r</code>, and the C11 standard provides <code>strtok_s</code>. The use of either is a little awkward, because the first call is different from the subsequent calls.</p>\n\n<ol>\n<li><p>The first time you call the function, send in the string to be parsed as the first argument.</p></li>\n<li><p>On subsequent calls, send in <code>NULL</code> as the first argument.</p></li>\n<li><p>The last argument is the scratch string. You don't have to initialize it on first use; on subsequent uses it will hold the string as it is parsed so far.</p></li>\n</ol>\n\n<p>To demonstrate its use, I've written a simple line counter (of only non-blank lines) using the POSIX standard one. I'll leave the choice of what version to use and implementation into your program up to you.</p>\n\n<pre><code>#include <string.h> // strtok_r\n\nint countLines(char* instring)\n{\n int counter = 0;\n char *scratch, *txt;\n char *delimiter = \"\\n\";\n for (; (txt = strtok_r((!counter ? instring : NULL), delimiter, &scratch)); counter++);\n return counter;\n}\n</code></pre>\n\n<p>If you implement this, you have your question answered.</p>\n\n<blockquote>\n <p>Also, in my use of <code>strtok()</code>, what should I be doing with the balance\n of the string after the delimiter? Is that hanging out in memory\n somewhere?</p>\n</blockquote>\n\n<p>It's not hanging out in memory, it's in the scratch string you provided.</p></li>\n<li><p>You don't have to return <code>0</code> at the end of <code>main()</code>, just like you wouldn't bother putting <code>return;</code> at the end of a <code>void</code>-returning function. The C standard knows how frequently this is used, and lets you not bother.</p>\n\n<blockquote>\n <p><strong>C99 & C11 §5.1.2.2(3)</strong></p>\n \n <p>...reaching the <code>}</code> that terminates the <code>main()</code> function returns a\n value of <code>0</code>.</p>\n</blockquote></li>\n</ul>\n\n<h3>Syntax/Styling</h3>\n\n<ul>\n<li><p>Put the variable declarations to separate lines. </p>\n\n<blockquote>\n<pre><code>float sum = 0.0, average;\n</code></pre>\n</blockquote>\n\n<p>From <em>Code Complete, 2d Edition</em>, p. 759:</p>\n\n<blockquote>\n <p>With statements on their own lines, the code reads from top to bottom,\n instead of top to bottom and left to right. When you’re looking for a\n specific line of code, your eye should be able to follow the left\n margin of the code. It shouldn’t have to dip into each and every line\n just because a single line might contain two statements.</p>\n</blockquote></li>\n<li><p>Use <a href=\"http://www.cplusplus.com/reference/cstdlib/strtod/\"><code>strtod()</code></a> instead of <code>strtof()</code>. (This goes with my point about <code>double</code> vs. <code>float</code>).</p></li>\n<li><p>Declare your parameters as <code>void</code> if you don't take in any arguments in your methods.</p>\n\n<pre><code>int main(void)\n</code></pre></li>\n<li><p>You can simplify your <code>NULL</code> checks.</p>\n\n<pre><code>while(element) // same as while (element != NULL)\n</code></pre></li>\n<li><p>Initialize <code>i</code> inside of your <code>for</code> loops.<sup>(C99)</sup></p>\n\n<pre><code>for (int i = 0; i < get_number_of_read_elements(); i++)\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T22:40:50.020",
"Id": "45782",
"ParentId": "45779",
"Score": "9"
}
},
{
"body": "<h3>Your C solution</h3>\n\n<p>As syb0rg mentioned, <code>strtok()</code> is deprecated. Before jumping to replace it with <code>strtok_r()</code> or <code>strtok_s()</code>, though, consider alternatives such as <code>strsep()</code>, <code>strtod()</code> and the <code>scanf()</code> family of functions.</p>\n\n<p>You shouldn't call <code>free(element)</code>, since <code>strtok()</code> is returning a pointer to a static buffer.</p>\n\n<p>Memory management in C is a hassle. In this problem, memory management can be an issue in two ways:</p>\n\n<ul>\n<li>Whenever you read from a file, you have to provide a buffer. You used <code>fgets()</code> to fill a 255-byte buffer named <code>elements</code>. What if the file size exceeds 255 bytes, and a number straddles the 255-byte boundary? Handling that boundary correctly takes a lot of effort!</li>\n<li>Storing a list of numbers of unbounded size is also problematic. You handle that by calling <code>realloc()</code> before appending each number to the list. While that is correct, it's inefficient, as each call to <code>append_float()</code> could involve copying the entire array each time.</li>\n</ul>\n\n<p>Therefore, C programmers prefer solutions that minimize the memory-management headaches.</p>\n\n<h3>A natural C solution</h3>\n\n<p>Fortunately, such a solution exists. I would consider this a natural way to solve the problem in C.</p>\n\n<pre><code>#include <stdio.h>\n\nint main(void) {\n const char *filename = \"comma_separated.txt\";\n FILE *f = fopen(filename, \"r\");\n if (!f) {\n perror(filename);\n return 1;\n }\n\n double d;\n double sum = 0.0;\n int count;\n while (EOF != fscanf(f, \"%lf,\", &d)) {\n sum += d;\n count++;\n }\n printf(\"average = %lf\\n\", sum / count);\n fclose(f);\n return 0;\n}\n</code></pre>\n\n<p>Of course, it violates the Single Responsibility Principle by lumping everything into <code>main()</code>.</p>\n\n<h3>Ruby analogy</h3>\n\n<p>Since you're familiar with Ruby, let's use it to explore how to comply with the Single Responsibility Principle. This is roughly equivalent to the simple C code above.</p>\n\n<pre><code>def sum_comma_separated_numbers(filename)\n sum, count = 0.0, 0\n open(filename) do |file|\n file.each do |line|\n line.split(',').each do |num|\n sum += num.to_f\n count += 1\n end\n end\n end\n return sum / count\nend\n\nputs(sum_comma_separated_numbers('comma_separated.txt'))\n</code></pre>\n\n<p>To make the code above comply with the Single Responsibility Principle, I'd make an enumerator that yields floats.</p>\n\n<pre><code>class NumberTokenizer\n include Enumerable\n\n def initialize(io, sep=',')\n @io = io\n @sep = sep\n end\n\n def each\n @io.each do |line|\n line.split(@sep).each { |num| yield num.to_f }\n end\n end\nend\n\ndef average(enum)\n sum, count = 0.0, 0\n enum.each do |num|\n sum += num\n count += 1\n end\n return sum / count\nend\n\nopen('comma_separated.txt') do |f|\n puts(average(NumberTokenizer.new(f)))\nend\n</code></pre>\n\n<h3>Translating to C</h3>\n\n<p>Drawing inspiration from the Ruby example, we want to make a tokenizer that produces <code>double</code>s, and an <code>average()</code> function that takes a tokenizer.</p>\n\n<pre><code>#include <stdio.h>\n\ntypedef struct {\n FILE *f;\n} Tokenizer;\n\nTokenizer *tokenizer_init(Tokenizer *t, FILE *f) {\n t->f = f;\n return t;\n}\n\n/* Returns 1 if there is a next comma-separated or\n space-separated number, 0 if there is not. */\nint tokenizer_next(Tokenizer *t, double *d) {\n return 1 == fscanf(t->f, \"%lf,\", d);\n}\n\ndouble average(Tokenizer *t) {\n double sum = 0.0;\n int count = 0;\n double d;\n while (tokenizer_next(t, &d)) {\n sum += d;\n count++;\n }\n return sum / count;\n}\n\nint main(void) {\n const char *filename = \"comma_separated.txt\";\n FILE *f = fopen(filename, \"r\");\n if (!f) {\n perror(filename);\n return 1;\n }\n\n Tokenizer t;\n printf(\"average = %lf\\n\", average(tokenizer_init(&t, f)));\n fclose(f);\n return 0;\n}\n</code></pre>\n\n<p>I would consider that a SRP-compliant solution that does not have any memory management headaches. (Of course, there is sophisticated buffer management going on behind the scenes within <code>fscanf()</code>, but it's nicely hidden from you.)</p>\n\n<p>The tokenizer concept is actually just window dressing around <code>fscanf()</code>. You could simplify things with <code>typedef FILE tokenizer</code>, but I prefer to keep the abstraction there.</p>\n\n<h3>Miscellaneous</h3>\n\n<p>While Ruby uses two spaces per level of indentation, C code generally has 4 or 8 spaces per level.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T01:58:34.940",
"Id": "45791",
"ParentId": "45779",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "45791",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T22:15:22.657",
"Id": "45779",
"Score": "11",
"Tags": [
"beginner",
"c",
"csv"
],
"Title": "Averaging numbers from a file, obeying Single Responsibility Principle"
} | 45779 |
<p>System I'm building has Users and Articles. Users can upvote/downvote Articles and cancel their votes if they want to. Each vote changes article's score. Score equals to sum of all vote values together.</p>
<p>So I created three models: User, Article, ArticleVote. Even though the most natural way for me would be to be able to do <code>user.upvote(article)</code>, for separation of concerns reasons I've put it in ArticleVote model:</p>
<pre><code>class ArticleVote < ActiveRecord::Base
belongs_to :article
belongs_to :user
before_destroy :before_destroy
validates :value, inclusion: {in: [1, -1]}
def self.upvote(user, article)
cast_vote(user, article, 1)
end
def self.downvote(user, article)
cast_vote(user, article, -1)
end
private
def self.cast_vote(user, article, value)
vote = ArticleVote.where(user_id: user.id, article_id: article.id).first_or_initialize
vote.value = value
vote.save!
article.score += value
article.save!
end
def before_destroy
article.score -= value
article.save
end
end
</code></pre>
<p>So now I call upvote via <code>ArticleVote.upvote(user, article)</code> which doesn't look too bad, but because of Rails' behavior, this doesn't work very good.</p>
<p>If I want to cancel an upvote for example:</p>
<pre><code>article = Article.find(528953)
# article.score = 5 at this point (for example)
vote = ArticleVote.where(user: current_user, article: article).first.destroy
# article.score = 5 !!!!
article.reload
# article.score = 4
</code></pre>
<p>So even though I already fetched an Article from database, and used instance of it to find ArticleVote I have to fetch it again to get the actual score value. I would expect ActiveRecord to automatically set <code>vote.article</code> to reference my <code>article</code>, so when I modify it's state, I wouldn't have to fetch it once again.</p>
<p>Is there a way I can avoid this unnecessary <code>article.reload</code> call and still have valid <code>article.score</code> value?</p>
<p>(Using Rails version 4)</p>
| [] | [
{
"body": "<p>Rails just isn't taking chances, so when you call <code>vote.article</code> it's performing a new DB query, and thus creating a new instance rather than grabbing a cache. And that's a good thing! You might run into trouble otherwise, since you call <code>save</code>. If it was the same <code>Article</code> instance everywhere, you'd suddenly be calling <code>save</code> on it from a non-obvious point in the code.</p>\n\n<p>I.e. pretend that Rails <em>does</em> reuse the same <code>Article</code> instance, and that instance has other unsaved changes. Perhaps these changes aren't valid, and in that case, the <code>save</code> call in <code>ArticleVote</code> would fail although you're only trying to change the article's <code>score</code>. It would also update the article's <code>updated_at</code> timestamp, although that may not be relevant; an article receiving or losing a vote doesn't really mean that the article itself was updated.</p>\n\n<p>So, for one I'd recommend using <code>article.update_column(:score, article.score - value)</code> in you <code>before_destroy</code> method. And, yes, you'll still need to call <code>reload</code> elsewhere.</p>\n\n<p>However, the underlying issue is that you're modifying an <code>article</code> \"from the outside\". I'd recommend a different approach altogether, with no <code>articles.score</code> column in the database, and using Rails' caching API instead:</p>\n\n<pre><code>class Article\n has_many :votes, class_name: \"ArticleVotes\"\n\n # score is not part of the DB schema;\n # it's computed and cached as necessary\n def score\n # get or update the cached score\n Rails.cache.fetch(score_cache_key) { votes.sum(:value) }\n end\n\n def flush_score_cache\n Rails.cache.delete(score_cache_key)\n end\n\n # let's not use or override the built-in\n # #cache_key method for this, since that\n # relies on the updated_at timestamp.\n def score_cache_key\n \"article/#{id}/score\" # or something similar with the ID in it\n end\nend\n</code></pre>\n\n<p>(In the above, you may want to handle the possibility of the record being new, and thus having a <code>nil</code> id.)</p>\n\n<p>And in <code>ArticleVote</code>:</p>\n\n<pre><code>class ArticleVote\n after_commit :flush_article_score\n\nprivate\n\n def flush_article_score\n article.flush_score_cache\n end\nend\n</code></pre>\n\n<p>Now whenever a vote is added, removed or updated, the article's score cache will be busted, forcing a <code>article.score</code> to do a proper recount if/when it's called.</p>\n\n<p>This also has the advantage that the article's score remains consistent with the actual votes: It's computed entirely from what's in the database. Alternatively, you can simply increment/decrement the cached value instead of flushing it, and still avoid having a database column.</p>\n\n<p>Of course, there are some drawbacks too. Since it is a cache the usual disclaimers apply (you have to be diligent about busting it when necessary, or you'll hit a stale cache, etc..). And if you've got heavy voting traffic you might end up busting the cache so often it just always does the <code>SUM()</code> query. In that case, you could still go with your current solution of having a database column that you increment and decrement, but I might still want to stick that in a different table to avoid the aforementioned issues with implicitly calling <code>save</code> on an article (or, like now, overwriting an updated score with a older one if you forget to <code>reload</code>). You could also consider a more \"raw SQL\" approach of actually incrementing or decrementing rather than writing the value directly, i.e. <code>UPDATE ... SET score=score + 1 WHERE ...</code>. That would avoid race conditions. Optimally, you might do a bit of both: A database column holding the canonical score of an article on disk, and a memory cache you use most of the time for reads, so you only have to hit the database for writes. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T00:22:39.913",
"Id": "45787",
"ParentId": "45781",
"Score": "5"
}
},
{
"body": "<p>I would start with creating two subclasses of your votes, using rails STI (you need to add one string 'type' column to your model - You can get rid of <code>value</code> though) and use rails counter_cache feature for both subclasses.</p>\n\n<pre><code>class ArticleVote < ActiveRecord::Base\n\n def initialize(*args)\n raise 'This class cannot be initialized' if self.class == ArticleVote\n super\n end\n\n validate :user, presence: true\n\nend\n\nclass UpVote < ArticleVote\n belong_to :article, counter_cache: true\nend\n\nclass DownVote < ArticleVote\n belongs_to: article, counter_cache: true\nend\n</code></pre>\n\n<p>With this in place, I would create three associations on your Article model, and define <code>score</code> method:</p>\n\n<pre><code>class Article < ActiveRecord::Base\n has_many :votes, class_name: 'ArticleVotes'\n has_many :up_votes\n has_many: down_votes\n\n def score\n (up_votes_count || 0) - (down_votes_count || 0) \n end\nend\n</code></pre>\n\n<p>You can create new votes using <code>article.up_votes.create(user_id: user.id)</code> (similar for down_votes).</p>\n\n<p>Counter cache will keep track of a number of down and up votes (including destroying existing votes) and this is extremely cheap to subtract those values. Note that you need two extra columns in you article model (<code>up_votes_count</code> and <code>down_votes_count</code>, no <code>score</code> column needed).</p>\n\n<p>Now the only thing left is to keep track of user changing their votes. To do this, I would add <code>before_create</code> filter on <code>Vote</code> model:</p>\n\n<pre><code>class ArticleVote < ActiveRecord::Base\n belongs_to :article\n\n def initialize(*args)\n raise 'This class cannot be initialized' if self.class == ArticleVote\n super\n end\n\n validate :user, presence: true\n\n before_create(prepend: true) do\n existing_record = article.article_votes.find_by(user_id: user_id)\n return false if existing_record && existing_record.class == self.class\n existing_record && existing_record.destroy\n true\n end\nend\n</code></pre>\n\n<p>This filter will check whether given user already voted on given article. If he did and he is trying to vote again, do nothing (<code>return false</code>) otherwise remove previous vote and create new one.</p>\n\n<p>There is a potential problem here with condition race. The only way to ensure record uniqueness is to create database constraint like unique index. </p>\n\n<p>Note that, while testing it in the console, counters columns behaves as normal column - it is stored in memory and will not checked whether the value changed in a database or not. Hence you need to reload the model to see the changes:</p>\n\n<pre><code>article.score #=> 0\narticle.up_vote.create(user_id: User.first.id)\narticle.score #=> 0 # Counters not updated\narticle.reload.score #=> 1 # But column in a database has been updated\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T02:23:25.427",
"Id": "45794",
"ParentId": "45781",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "45794",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T22:37:04.223",
"Id": "45781",
"Score": "5",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Article voting schema"
} | 45781 |
<p>If I was at an interview, and wrote this code, what would you think? Please be brutal.</p>
<p>Time it took to wrote it: 13 minutes</p>
<p>Problem:</p>
<blockquote>
<p>Write an efficient algorithm that searches for a value in an m x n
matrix. This matrix has the following properties:</p>
<p>Integers in each row are sorted from left to right. The first integer
of each row is greater than the last integer of the previous row. For
example,</p>
<p>Consider the following matrix:</p>
<pre><code>[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
</code></pre>
<p>Given target = 3, return true.</p>
</blockquote>
<hr>
<pre><code> public boolean searchMatrix(int[][] matrix, int target) {
int lastCol = matrix[0].length-1;
int row=0;
while(row!=matrix.length && lastCol>=0){
if(matrix[row][lastCol]==target){
return true;
}
if(matrix[row][lastCol]>target){
lastCol--;
if(binarySearch(matrix[row], 0, lastCol, target)!=-1){
return true;
}
}
row++;
}
return false;
}
public int binarySearch(int[] arr, int low, int high, int target){
while(low<=high){
int mid = (low + high)/2;
if(arr[mid]==target){
return mid;
}
else if(arr[mid]<target){
low = mid+1;
}
else if(arr[mid]>target){
high = mid-1;
}
}
return -1;
}
</code></pre>
<p>Space complexity = O(1)
Time Compexity = O(log(n!))</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T01:55:23.310",
"Id": "79914",
"Score": "1",
"body": "A better way to do this is to treat it like a single dimension sorted array, and perform your binary search on _that_, using modulo and division to extract your values from the 2d array."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T02:05:29.787",
"Id": "79915",
"Score": "0",
"body": "Can you explain how I'd use modulo, a bit weak with that operation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T02:10:21.007",
"Id": "79916",
"Score": "0",
"body": "something like `row = mid/ arr[0].length()` and `col = mid % arr[0].length()`. If no-one else does, I'll post an answer tomorrow, but I need to get some sleep."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-27T09:28:52.683",
"Id": "432072",
"Score": "0",
"body": "O(n!)... are you saying n factorial?"
}
] | [
{
"body": "<p>Your algorithm is not efficient (thats the brutal part of the answer).</p>\n\n<p>Searching in a list of t values is a task that can be accomplished using O(log(t)) comparisons. Here we have t=m*n values so it should be accomplished using O(log(m*n)) = O(log(m))+O(log(n)) comparisons. I suspect your algorithm may execute the while loop about <code>matrix.length</code> times so it is not O(log(m)) (where m is the number of rows). </p>\n\n<p>The algorithm could work in the following way:</p>\n\n<ul>\n<li>if the searched value is smaller then the first column in the first row then the searched value is not contained in the matrix.</li>\n<li>Then do a binary search on the first column of the matrix to find the largest entry smaller or equal to the searchd value</li>\n<li>if the value found macthes you are done. </li>\n<li>otherwise do a binary search on the row found. </li>\n<li>if the value found matches the searched value you are done</li>\n<li>otherwise the searched value is not in the matrix</li>\n</ul>\n\n<p>Annother way is to treat the problem like a single dimension sorted array as it is proposed in the comment of @Azar. </p>\n\n<p>Even a small piece of code can have <a href=\"http://en.wikipedia.org/wiki/Binary_search_algorithm#Implementation_issues\" rel=\"nofollow\">a lot of errors</a> so it does make sense to try to use <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html\" rel=\"nofollow\">library methods</a> to accomplish this task and not implement the binary search by yourself (but I don't know if this is the intention of the poser of the problem).</p>\n\n<p>This blog entry discusses an <a href=\"http://googleresearch.blogspot.co.at/2006/06/extra-extra-read-all-about-it-nearly.html\" rel=\"nofollow\">example of a buggy implementation in Java</a>. It references the following <a href=\"http://bugs.java.com/bugdatabase/view_bug.do?bug_id=5045582\" rel=\"nofollow\">SUN bug report</a> because there was an errornous implementation of the binary search even in the JDK.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T10:17:14.683",
"Id": "79953",
"Score": "0",
"body": "Really not more complicated at all, but yes, it has the same runtime, `O(log(mn))`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T16:06:12.037",
"Id": "80005",
"Score": "0",
"body": "@Azar: If it is not more complicated I am curious about your answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T01:10:41.897",
"Id": "80254",
"Score": "0",
"body": "Sorry, been a little busy lately. Here you go: http://pastebin.com/t59ZnJFQ"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T08:17:08.947",
"Id": "80687",
"Score": "0",
"body": "@Azar: The overhead is insignificant so I will remove the recommendation from my posting. You avoided the mentioned bug. Nevertheless I would recommand to use a library."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T07:37:12.917",
"Id": "45809",
"ParentId": "45783",
"Score": "2"
}
},
{
"body": "<p>I think it is very well done, especially for 12 minutes. </p>\n\n<hr>\n\n<h2>Similar solutions</h2>\n\n<p>That solution is very similar to GeekforGeek solution.</p>\n\n<p><a href=\"https://www.geeksforgeeks.org/search-in-row-wise-and-column-wise-sorted-matrix/\" rel=\"nofollow noreferrer\">https://www.geeksforgeeks.org/search-in-row-wise-and-column-wise-sorted-matrix/</a></p>\n\n<p>The problem is slightly different (more generic). </p>\n\n<p>Compare</p>\n\n<pre><code>class GFG {\n\n/* Searches the element x in mat[][]. If the\nelement is found, then prints its position\nand returns true, otherwise prints \"not found\"\nand returns false */\nprivate static void search(int[][] mat, int n, int x) {\n\n int i = 0, j = n - 1; // set indexes for top right\n // element\n\n while (i < n && j >= 0) {\n if (mat[i][j] == x) {\n System.out.print(\"n Found at \" + i + \" \" + j);\n return;\n }\n if (mat[i][j] > x) {\n j--;\n } else // if mat[i][j] < x\n {\n i++;\n }\n }\n\n System.out.print(\"n Element not found\");\n return; // if ( i==n || j== -1 )\n}\n}\n// This code is contributed by Arnav Kr. Mandal.\n</code></pre>\n\n<hr>\n\n<h2>Complexity analysis.</h2>\n\n<p>Your complexity analysis was wrong.\nLet A matrix n x m. The complexity is O(m log(n)).</p>\n\n<p>Proof:\nFor every movement in the vertical direction, the algorithm performs a new binary search in the horizontal direction. </p>\n\n<p>If the matrix is a columnar matrix... the complexity will be O(m), for example.</p>\n\n<hr>\n\n<h2>Room for improvement</h2>\n\n<p>A better solution would be using the binary search in both directions (what keep working for more generic problems). Complexity is O(log(n) * log(m))</p>\n\n<p>Or take usage of total ordering. More efficient but less generic. Complexity is O(log (n) + log(m))</p>\n\n<p>See:\n <a href=\"https://www.geeksforgeeks.org/search-element-sorted-matrix/\" rel=\"nofollow noreferrer\">https://www.geeksforgeeks.org/search-element-sorted-matrix/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-27T10:20:41.250",
"Id": "223052",
"ParentId": "45783",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "45809",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T22:48:12.753",
"Id": "45783",
"Score": "7",
"Tags": [
"java",
"interview-questions",
"search",
"matrix",
"binary-search"
],
"Title": "Searching in a sorted 2D matrix"
} | 45783 |
<p>I am doing a project for school and had to create a function to check if 2 time ranges overlap. I searched the net a bit but failed to find a simple function to do that. I played around a bit with my code and I think I created a working one.</p>
<p>Note: it works for 24 hour times only & don't forget the 0 in front of AM time e.g "08:15"</p>
<p>If anyone has a better function to do this or finds some bugs in the code below - please post below.</p>
<p><a href="http://writecodeonline.com/php/" rel="nofollow">Here is the code you can test directly on</a>.</p>
<pre><code>$start_time1 = "10:15";
$end_time1 = "12:20";
$start_time2 = "13:15";
$end_time2 = "14:25";
function testRange($start_time1,$end_time1,$start_time2,$end_time2)
{
$timeCheck;
if(($end_time1 < $start_time2))
{
$timeCheck = true;
return $timeCheck;
}
else if(($start_time1 > $start_time2) && ($start_time1 > $end_time2))
{
$timeCheck = true;
return $timeCheck;
}
else
{
$timeCheck = false;
return $timeCheck;
}
}
if(testRange($start_time1,$end_time1,$start_time2,$end_time2))
{
echo "Not In Range";
}
else
{
echo "In Range";
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T01:24:56.463",
"Id": "79912",
"Score": "1",
"body": "I'm not sure why you've created the `$timeCheck` variable. You can just write `return true` or `return false` instead of using that variable. That saves you a few lines of excess code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T12:07:40.400",
"Id": "79959",
"Score": "0",
"body": "Your question isn't as much asking to _review_ the code, but more to show a better approach. Please understand that this may deter people from responding. If I reviewed your code, saying which bits you could improve, and how, I wouldn't give you a full and working example of an alternative, but I would've given you a code-review. Would you regard that as an answer to your question, too? If so, please edit and reformulate your question, if not, please consider posting this question elsewhere"
}
] | [
{
"body": "<ul>\n<li>As <a href=\"https://codereview.stackexchange.com/users/39766/s3rius\">s3rius</a> pointed out, you don't need the <code>$timeCheck</code> variable. You can just use <code>return true;</code> or <code>return false;</code>.</li>\n<li>To parse a time use the <a href=\"http://us2.php.net/manual/en/class.datetime.php\" rel=\"noreferrer\">DateTime</a> class. You can find the <a href=\"http://us2.php.net/manual/en/datetime.formats.time.php\" rel=\"noreferrer\">supported time formats here</a>. The constructor will throw an exception if it cannot parse the string. Consider if you want to handle the exception yourself or let the caller handle it.</li>\n<li>What if the start time is after the end time? You can throw an exception, switch the start and end times, or not handle the error.</li>\n<li>The meaning of the return value is not obvious based on your function name. How does it test the range? Change it to something like rangesNotOverlap or something similar so that it is apparent that true means they don't overlap.</li>\n<li>Are time ranges open or close intervals? If one range ends at 10:00 and the other starts at 10:00, do they overlap?</li>\n<li>Lets consider all cases:</li>\n</ul>\n\n<p>.</p>\n\n<pre><code> 1\nCase 01: |-----|\n |-----|\n 2\n\n 1\nCase 02: |-----|\n |-----|\n 2\n\n 1\nCase 03: |-----|\n |-----|\n 2\n\n 1\nCase 04: |---------|\n |-----|\n 2\n\n 1\nCase 05: |-----|\n |---------|\n 2\n\n 1\nCase 06: |-----|\n |-----|\n 2\n\n 1\nCase 07: |-----|\n |-----|\n 2\n\n 1\nCase 08: |-----|\n |-----|\n 2\n\n 1\nCase 09: |-----|\n |-----|\n 2\n\n 1\nCase 10: |\n |-----|\n 2\n\n 1\nCase 11: |-----|\n |\n 2\n\n 1\nCase 12: |\n |-----|\n 2\n\n 1\nCase 13: |\n |-----|\n 2\n\n 1\nCase 14: |-----|\n |\n 2\n\n 1\nCase 15: |-----|\n |\n 2\n\n 1\nCase 16: |\n |\n 2\n\n | | Operlap | Overlap \n Case | Example | Open Interval | Closed Interval \n--------|-------------------------|---------------|-----------------\nCase 01 | 09:00-11:00 09:00-11:00 | Yes | Yes\nCase 02 | 09:00-11:00 10:00-12:00 | Yes | Yes\nCase 03 | 10:00-12:00 09:00-11:00 | Yes | Yes\nCase 04 | 09:00-12:00 10:00-11:00 | Yes | Yes\nCase 05 | 10:00-11:00 09:00-12:00 | Yes | Yes\nCase 06 | 09:00-10:00 11:00-12:00 | No | No\nCase 07 | 11:00-12:00 09:00-10:00 | No | No\nCase 08 | 09:00-10:00 10:00-11:00 | No | Yes\nCase 09 | 10:00-11:00 09:00-10:00 | No | Yes\nCase 10 | 10:00-10:00 09:00-11:00 | Yes | Yes\nCase 11 | 09:00-11:00 10:00-10:00 | Yes | Yes\nCase 12 | 09:00-09:00 09:00-10:00 | No | Yes\nCase 13 | 10:00-10:00 09:00-10:00 | No | Yes\nCase 14 | 09:00-10:00 09:00-09:00 | No | Yes\nCase 15 | 09:00-10:00 10:00-10:00 | No | Yes\nCase 16 | 09:00-09:00 09:00-09:00 | No | Yes\n</code></pre>\n\n<p>Your function returns the correct result on the closed interval for all cases.</p>\n\n<ul>\n<li>We can make your code simpler by noticing that we only have to check for two cases. The ranges don't overlap only if <code>end1 < start2</code>, (the same as your first if), or if <code>end2 < start1</code> (which is included in your second if). The other check you do <code>start1 > start2</code> is redundant, because it is always true if <code>end2 < start1</code>.</li>\n</ul>\n\n<p>Put it all together:</p>\n\n<pre><code>function rangesNotOverlapClosed($start_time1,$end_time1,$start_time2,$end_time2)\n{\n $utc = new DateTimeZone('UTC');\n\n $start1 = new DateTime($start_time1,$utc);\n $end1 = new DateTime($end_time1,$utc);\n if($end1 < $start1)\n throw new Exception('Range is negative.');\n\n $start2 = new DateTime($start_time2,$utc);\n $end2 = new DateTime($end_time2,$utc);\n if($end2 < $start2)\n throw new Exception('Range is negative.');\n\n return ($end1 < $start2) || ($end2 < $start1);\n}\n\nfunction rangesNotOverlapOpen($start_time1,$end_time1,$start_time2,$end_time2)\n{\n $utc = new DateTimeZone('UTC');\n\n $start1 = new DateTime($start_time1,$utc);\n $end1 = new DateTime($end_time1,$utc);\n if($end1 < $start1)\n throw new Exception('Range is negative.');\n\n $start2 = new DateTime($start_time2,$utc);\n $end2 = new DateTime($end_time2,$utc);\n if($end2 < $start2)\n throw new Exception('Range is negative.');\n\n return ($end1 <= $start2) || ($end2 <= $start1);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T05:52:43.530",
"Id": "45804",
"ParentId": "45784",
"Score": "6"
}
},
{
"body": "<p>Or you can make it the easy way... ;-)</p>\n\n<pre><code>function testRange($start_time1,$end_time1,$start_time2,$end_time2)\n{\n return ($start_time1 <= $end_time2 && $start_time2 <= $end_time1);\n}\n</code></pre>\n\n<p>This solution assumpts, that the end time of any interval is never before the start time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T09:17:56.813",
"Id": "204263",
"ParentId": "45784",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T23:20:33.777",
"Id": "45784",
"Score": "4",
"Tags": [
"php",
"interval"
],
"Title": "Test 2 time ranges to see if they overlap"
} | 45784 |
<p>I wrote a package manager in clojure that does 5 things:</p>
<ol>
<li><p>depend a b //creates a and b (if they don't exist) and adds dependency on a</p></li>
<li><p>install a //installs a and its dependencies</p></li>
<li><p>list //prints out the install packages</p></li>
<li><p>sys //prints out all packages</p></li>
<li><p>remove or uninstall packages and dependencies that are no longer needed.</p></li>
</ol>
<p>I did this as an exercise to learn Clojure. I'm not sure if this is idiomatic are not. I tried to avoid typedef since that seems like attempting OOP on Clojure. I'm just wondering if there are any very obvious non idiomatic code or code smells.</p>
<pre><code>(use '[clojure.string :only [split, lower-case]])
(def DEPEND "depend")
(def INSTALL "install")
(def REMOVE "remove")
(def UNINSTALL "uninstall")
(def SYS "sys")
(def LIST "list")
(def INFO "info")
(def EXIT "exit")
(def END "end")
(def all-packages (atom {}))
(def installed-packages (atom (sorted-set)))
(defn in? [seq elm]
(some #(= elm %) seq))
(defn create
"makes a package element with provided name, option list of providers
are packages requried by package, optional list of clients are packages using
package"
([name]
(create name #{} #{}))
([name providers clients]
{:name name, :providers providers, :clients clients}))
(defn add-client
[package client]
(create (:name package) (:providers package) (conj (:clients package) client)))
(defn remove-client
[package client]
(create (:name package) (:providers package) (disj (:clients package) client)))
(defn add-provider
"add a provided to package"
([package] package)
([package provider]
(create (:name package) (conj (:providers package) provider) (:clients package)))
([package provider & more-providers]
(reduce add-provider package (cons provider more-providers))))
(defn get-providers [package]
(get (get @all-packages package) :providers ))
(defn get-clients [package]
(get (get @all-packages package) :clients ))
(defn get-package [package]
(get @all-packages package))
(defn exists? [package]
(contains? @all-packages package))
(defn dependent? [first second]
(if (in? (cons first (get-providers first)) second)
(do (println (str "\t" first) "depends on" second) true)
(some #(dependent? % second) (get-providers first))))
(defn update-sys [package]
(swap! all-packages assoc (:name package) package))
(defn add-sys-package
"adds a package to all-packages"
[package & deps]
(doseq [dep deps]
(if-not (exists? dep) (update-sys (create dep))))
(if (not-any? #(dependent? % package) deps)
(update-sys (apply add-provider (cons (create package) deps)))
(println "Ignoring command")))
(defn print-sys []
(doseq [[k,v] @all-packages] (println "\t" v)))
(defn print-installed []
(doseq [v @installed-packages] (println "\t" v)))
(defn installed? [package]
(contains? @installed-packages package))
(defn install-new [package]
(do (println "\t installing" package)
(swap! installed-packages conj package)))
(defn install
[package self-install]
(if-not (exists? package) (add-sys-package package))
(if-not (installed? package)
(do (doseq [provider (get-providers package)] (if-not (installed? provider) (install provider false)))
(doseq [provider (get-providers package)] (update-sys (add-client (get-package provider) package)))
(install-new package))
(do
(if self-install (update-sys (add-client (get-package package) package)))
(println "\t" package "is already installed."))))
(defn not-needed? [package self-uninstall]
(def clients
(if self-uninstall
(disj (get-clients package) package)
(get-clients package)))
(empty? clients))
(defn uninstall-package [package]
(println "\t uninstalling" package)
(swap! installed-packages disj package))
(defn uninstall
[package self-uninstall]
(if (installed? package)
(if (not-needed? package self-uninstall)
(do (doseq [provider (get-providers package)] (update-sys (remove-client (get-package provider) package)))
(uninstall-package package)
(doseq [provider (filter #(not-needed? % false) (get-providers package))] (uninstall provider false)))
(println "\t" package "is still needed"))
(println "\t" package "is not installed")))
(def run (atom true))
(defn stop-run []
(reset! run false))
(defn exit []
(println "goodbye") (stop-run))
(defn runprog []
(println "starting")
(reset! run true)
(while (true? @run)
(def line (read-line))
(def command (first (split line #" +")))
(def args (rest (split line #" +")))
(condp = (lower-case command)
DEPEND (apply add-sys-package args)
LIST (print-installed)
INSTALL (install (first args) true)
INFO (println (get-package (first args)))
[REMOVE UNINSTALL] (uninstall (first args) true)
UNINSTALL (uninstall (first args) true)
SYS (print-sys)
EXIT (exit)
END (exit)
())))
(runprog)
</code></pre>
<p>Edit: After incorporating almost all suggestions <a href="https://gist.github.com/debetimi/9908652" rel="nofollow">github gist</a></p>
| [] | [
{
"body": "<p>You can use clojure sets to group like outcomes in a condp.</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(condp get (lower-case command)\n #{DEPEND} (apply add-sys-package args)\n #{LIST} (print-installed)\n #{INSTALL} (install (first args) true)\n #{INFO} (println (get-package (first args)))\n #{REMOVE UNINSTALL} (uninstall (first args) true)\n #{SYS} (print-sys)\n #{EXIT END} (exit)\n nil)\n</code></pre>\n\n<p>In the case of the cond you have written, a case statement is probabaly the best bet. Not only do you get better performance (constant time), but you can group common values. Watch out though, like in Java, you can only have constants in the case statement. This means that using symbols in the case (as you have written in your condp) will make the statement look for the actual symbol, not the value assigned to the symbol. A common practice is to use keywords when comparing in case statements.</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(case (-> command lower-case keyword)\n :depend (apply add-sys-package args)\n :list (print-installed)\n :install (install (first args) true)\n :info (println (get-package (first args)))\n (:remove :uninstall) (uninstall (first args) true)\n :sys (print-sys)\n (:exit :end) (exit)\n nil)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T16:51:11.353",
"Id": "80017",
"Score": "0",
"body": "Thanks. Coming from Java, `case` was the first thing I tried, but I ran into the problem that you mentioned about it only matching symbols. In my code `DEPEND`, `LIST`, etc are all \"def-ed\" at the beginning of the file to reference their corresponding string so `condp` matches the value of the reference. How could I get a user input from `read-line` to match the symbol?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T19:18:14.223",
"Id": "80047",
"Score": "0",
"body": "I see, the keyword argument. Thanks. I somehow glossed over that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T13:32:51.970",
"Id": "45823",
"ParentId": "45788",
"Score": "6"
}
},
{
"body": "<p>OK, bear with me. I got really into this, so I hope you don't mind that this is super long! :) Here are my thoughts.</p>\n\n<h3>Major things:</h3>\n\n<ol>\n<li><p>I would consider using refs instead of atoms to represent your package list. The difference is that refs are used for <strong>coordinated</strong> access to multiple entities, whereas atoms provide uncoordinated access to a single entity. Because you're working with two related lists, <code>all-packages</code> and <code>installed-packages</code>, it would be safer to use refs to represent them.</p></li>\n<li><p>A simpler way to create a command-line utility like this is to make use of a CLI library. Clojure has a few good ones. See <a href=\"https://stackoverflow.com/questions/1341154/building-a-clojure-app-with-a-command-line-interface\">this question on Stack Overflow</a> for a few good methods.</p></li>\n<li><p>You used <code>def</code> inside of two function definitions, which is generally considered incorrect in Clojure. Usually you will only use <code>def</code>, <code>defn</code>, etc. on the top level of your program. When you're inside of a <code>def</code>, <code>defn</code>, etc., you should use <code>let</code> instead to do what you're trying to do. See below:</p>\n\n<pre><code>(defn not-needed? [package self-uninstall]\n (let [clients (if self-uninstall\n (disj (get-clients package) package)\n (get-clients package))]\n (empty? clients)))\n</code></pre>\n\n<p> </p>\n\n<pre><code>(defn runprog []\n (println \"starting\")\n (reset! run true)\n (while (true? @run))\n (let [line (read-line)\n [command & args] (split line #\"\\s+\")]\n ...\n</code></pre>\n\n<p>Notice, also, how I used destructuring to simplify <code>command (first (split line #\" +\")), args (rest (split line #\" +\"))</code> to just <code>[command & args] (split line #\"\\s+\")</code>. Destructuring is a very powerful tool that can make your code more concise and easier to read.</p></li>\n</ol>\n\n<h3>Minor things:</h3>\n\n<ol>\n<li><p>For your <code>in?</code> function, you can simplify <code>(some #(= elm %) seq)</code> to <code>(some #{elm} seq)</code>. The <code>#{}</code> reader is a shorthand notation for a set, and a set in Clojure can be used as a function that looks up its argument in the set and returns either the argument if it is found, or <code>nil</code> if it's not. Because any value that isn't <code>false</code> or <code>nil</code> is considered \"truthy\" in Clojure, that means you can use a set as a function that tells you whether or not an element is contained in a collection. By the way, I would name the argument in this function <code>coll</code> rather than <code>seq</code>, as <code>seq</code> already refers to the <code>clojure.core/seq</code> function.</p></li>\n<li><p>You can simplify the <code>(get (get ...</code> form in your <code>get-providers</code> and <code>get-clients</code> functions by using <a href=\"http://clojuredocs.org/clojure_core/clojure.core/get-in\" rel=\"nofollow noreferrer\">get-in</a>:</p>\n\n<pre><code>(defn get-providers [package]\n (get-in @all-packages [package :providers]))\n\n(defn get-clients [package]\n (get-in @all-packages [package :clients]))\n</code></pre></li>\n<li><p>You can omit the <code>do</code> in your <code>install-new</code> function definition. Any time you're doing something like defining a function using <code>defn</code>, there is already an \"implicit <code>do</code>\":</p>\n\n<pre><code>(defn install-new [package]\n (println \"\\t installing\" package)\n (swap! installed-packages conj package))\n</code></pre></li>\n<li><p>You have a few functions (<code>install</code>, <code>not-needed?</code> and <code>uninstall</code>) that take a parameter called either <code>self-install</code> or <code>self-uninstall</code>, which is expected to be either <code>true</code> or <code>false</code>. It would be more idiomatic to make these <a href=\"http://clojurefun.wordpress.com/2012/08/13/keyword-arguments-in-clojure/comment-page-1\" rel=\"nofollow noreferrer\">keyword arguments</a>, like this:</p>\n\n<pre><code>(defn install [package & {:keys [self-install]}]\n ; the rest of the function would still be the same\n\n(defn not-needed? [package & {:keys [self-uninstall]}]\n ; etc.\n</code></pre>\n\n<p>Then you would call the functions like this, for example:</p>\n\n<pre><code>(install \"clementine\" :self-install true)\n</code></pre>\n\n<p>It is a little more verbose, but I think it's more elegant and it makes it clearer what your code is doing.</p></li>\n<li><p>Your <code>uninstall</code> function smells of OOP practices, in particular in the way that you have nested <code>if</code> structures. These aren't always bad form in Clojure, but generally it's better to find a more functional way of expressing the flow of your program. Consider using <code>cond</code> as an alternative:</p>\n\n<pre><code>(defn uninstall [package & {:keys [self-uninstall]}]\n (cond \n (not (installed? package))\n (println \"\\t\" package \"is not installed.\")\n\n (and (installed? package)\n (not (not-needed? package :self-uninstall self-uninstall)))\n (println \"\\t\" package \"is still needed.\")\n\n :else\n (do\n (doseq [provider (get-providers package)]\n (update-sys (remove-client (get-package provider) package)))\n (uninstall-package package)\n (doseq [provider (filter #(not-needed? % :self-uninstall false)\n (get-providers package))]\n (uninstall provider :self-uninstall false)))))\n</code></pre>\n\n<p>This is also longer than your code, but I find it clearer and easier to read.</p></li>\n</ol>\n\n<h3>Nitpicky things:</h3>\n\n<ol>\n<li><p>I would consider renaming your <code>create</code> function to <code>package</code>, simply because <code>create</code> sounds like a function that would <em>change</em> the state of something, like perhaps it would create a package within one of your package lists. I understand that that's not what your function does, but I feel like if you called it <code>package</code> instead, it would make it clearer that <code>(package \"foo\" bar baz)</code> just <em>represents</em> a package named <code>\"foo\"</code> with providers <code>bar</code> and clients <code>baz</code>. You do have a handful of functions that change the state of your package lists, so I think it pays to be careful about what you name your functions, so you can make it easier to know which functions will mutate the state of your lists, and which ones are pure functions.</p></li>\n<li><p>While you're at it, you might consider making your <code>package</code> (a.k.a. <code>create</code>) function use keyword args too:</p>\n\n<pre><code>(defn package\n \"makes a package element with provided name, option list of providers\n are packages requried by package, optional list of clients are packages using\n package\"\n [name & {:keys [providers clients] \n :or {:providers #{} :clients #{}}]\n {:name name, :providers providers, :clients clients})\n</code></pre>\n\n<p>You could then use it either like this: <code>(package \"foo\")</code><br>\nwhich returns <code>{:name \"foo\" :providers #{} :clients #{}}</code></p>\n\n<p>or like this: <code>(package \"foo\" :providers #{\"bar\"} :clients #{\"baz\"})</code><br>\nwhich returns <code>{:name \"foo\" :providers #{\"bar\"} :clients #{\"baz\"}}</code>. </p>\n\n<p>You can even leave out <code>:providers</code> or <code>:clients</code> at will without having to worry about the order of arguments in your function call. This is another thing that is more verbose, but more readable if you don't mind the extra typing every time you call the function.</p></li>\n<li><p>I mentioned in #1 the idea of carefully naming your functions so that you can tell which ones are mutating state vs. which ones are just pure functions. I would consider naming your non-pure functions (i.e. the ones that are changing the value of refs/atoms) with a <code>!</code> at the end. This is idiomatic in Clojure. I would do that with the following functions: <code>update-sys! add-sys-package! install-new! install! uninstall-package!</code> and <code>uninstall!</code>.</p>\n\n<p>I would do the same thing with your <code>stop!</code> and <code>exit!</code> functions, and would also consider renaming <code>run</code> to <code>run?</code> since it represents a boolean value.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T20:58:32.260",
"Id": "80060",
"Score": "0",
"body": "Dave, thanks for your detailed analysis. These are exactly the sort of idiomatic best practices I was looking for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T18:59:01.933",
"Id": "80197",
"Score": "0",
"body": "You're quite welcome! Hope you're enjoying learning Clojure!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T19:44:58.093",
"Id": "45878",
"ParentId": "45788",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "45878",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T00:29:23.067",
"Id": "45788",
"Score": "8",
"Tags": [
"functional-programming",
"clojure"
],
"Title": "Package manager in Clojure"
} | 45788 |
<p>This is all in one methods but I would like to see it in individual separate methods. The code works fine but all of the code is in the <code>canvasApp()</code> methods and I would like to see it all in individual methods so that I could call them as below.</p>
<p>Question: How to make all of the code into separate function?</p>
<pre><code>canvasApp();
gameloop();
</code></pre>
<p>Code:</p>
<pre><code>function canvasApp() {
if (!canvasSupport()) {
return;
}
function drawScreen () {
context.fillStyle = '#EEEEEE';
context.fillRect(0, 0, theCanvas.width, theCanvas.height);
//Box
context.strokeStyle = '#000000';
context.strokeRect(1, 1, theCanvas.width-2, theCanvas.height-2);
// Create ball
y += speed;
context.fillStyle = "#000000";
context.beginPath();
context.arc(x,y,15,0,Math.PI*2,true);
context.closePath();
context.fill();
}
theCanvas = document.getElementById('canvasOne');
context = theCanvas.getContext('2d');
var speed = 5;
var y = 10;
var x = 250;
function gameLoop() {
window.setTimeout(gameLoop, 20);
drawScreen();
}
gameLoop();
}
</code></pre>
| [] | [
{
"body": "<p>From a Code Review perspective, what you are asking for, is worse.</p>\n\n<p>Currently, you only need to call <code>canvasApp()</code> and that function does all the work. Inside you have <code>drawScreen</code> which is periodically called, starting in <code>gameLoop</code>.</p>\n\n<p>Still,</p>\n\n<ul>\n<li>I would put all the <code>var</code> statements on top for readability</li>\n<li>I would put <code>var</code> in front of <code>context</code> and <code>theCanvas</code> (!)</li>\n<li>I would assign your colors (<code>'#EEEEEE'</code>) to meaningfully named variables</li>\n<li>I would assign <code>Math.PI*2</code> to a <code>var doublePi = Math.PI*2</code> for speed</li>\n<li>I would consider dropping the curly braces from the guard clause</li>\n<li><code>//Box</code> is not really a meaningful naming, <code>//border</code> and <code>//background</code> would make more sense`</li>\n</ul>\n\n<p>That would give this:</p>\n\n<pre><code>function canvasApp() {\n\n if (!canvasSupport())\n return;\n\n var canvas = document.getElementById('canvasOne'),\n context = canvas.getContext('2d'), \n borderColor = '#EEEEEE',\n backgroundColor = '#000000',\n ballColor = '#000000',\n speed = 5,\n y = 10,\n x = 250,\n doublePi = Math.PI*2,\n ballSize = 15,\n refreshInterval = 20; //In milliseconds\n\n function drawScreen () {\n //Background + Border\n context.fillStyle = borderColor;\n context.fillRect(0, 0, canvas.width, canvas.height);\n //Background\n context.strokeStyle = backgroundColor; \n context.strokeRect(1, 1, canvas.width-2, canvas.height-2);\n // Create ball\n y += speed;\n context.fillStyle = ballColor;\n context.beginPath();\n context.arc(x,y,ballSize,0,doublePi,true);\n context.closePath();\n context.fill();\n }\n\n function gameLoop() {\n window.setTimeout(gameLoop, refreshInterval);\n drawScreen(); \n }\n\n gameLoop();\n}\n</code></pre>\n\n<p>I am still not too excited by redrawing every 20 milliseconds 2 large boxes, but I will leave the research on further optimization to you.</p>\n\n<p>Update: after playing the code and reading it more closely, the code only redraws a square once, and then the border, so that should be fine.</p>\n\n<p>A working jsbin version is here: the animation is fast enough, though disappointing as there is no bouncing..\n<a href=\"http://jsbin.com/lidil/2\" rel=\"nofollow\">http://jsbin.com/lidil/2</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T16:19:22.337",
"Id": "80014",
"Score": "0",
"body": "Could i just draw the boxes once which do not need to be drawn on every refresh of the screen they really are only the borders of the Canvas."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T17:08:08.797",
"Id": "80021",
"Score": "0",
"body": "I am not sure, I think you draw a square ( well, 2 really ) to wipe out the prior ball drawing. If you create a jsfiddle then I will look into that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T17:22:19.973",
"Id": "80025",
"Score": "0",
"body": "The code is at home and I do have jsfiddle account I will post all of the html code to night. Thank you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T22:36:06.003",
"Id": "80075",
"Score": "0",
"body": "http://jsfiddle.net/cC3zU/1/ -- here is the fiddle (I think). I am not sure how to save them and it actually was not displaying in the result window so I am not certain it is created correctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T10:55:21.490",
"Id": "80291",
"Score": "0",
"body": "I added a fiddle where I applied my changes, click the link in my answer, if you move the mouse you will see the edit button appear in the top left corner, if you click that button you will see the source."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T15:06:20.790",
"Id": "45840",
"ParentId": "45790",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T01:51:53.520",
"Id": "45790",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Splitting canvas app into separate functions"
} | 45790 |
<p>Solution to bounded knapsack 01 problem. Once again comprehensive description is difficult in this space, refer <a href="http://en.wikipedia.org/wiki/Knapsack_problem#0.2F1_Knapsack_Problem" rel="nofollow">here</a>. Looking for code review. optimizations and best practices.</p>
<pre><code>final class Item {
private final int value;
private final int weight;
public Item (int value, int weight) {
if (value == 0) {
throw new IllegalArgumentException("The value " + value + " should be positive.");
}
if (weight == 0) {
throw new IllegalArgumentException("The weight " + weight + " should be positive.");
}
this.value = value;
this.weight = weight;
}
public int getValue() {
return value;
}
public int getWeight() {
return weight;
}
}
public final class Knapsack01 {
private Knapsack01() { }
/**
* Returns the maximum value, given set of items and maxweight
*
* @param items the set of items.
* @param maxWeight the max weight
* @return the max value obeying the constraints
*/
public static int getMaxValue (Item[] items, int maxWeight) {
if (maxWeight <= 0) {
throw new IllegalArgumentException("the maxweight: " + maxWeight + " should be positive");
}
int[][] knapsack = new int[items.length + 1][maxWeight + 1];
for (int item = 0; item <=items.length; item++) {
for (int weight = 0; weight <= maxWeight; weight++) {
if (item == 0 || weight == 0) {
continue;
}
int itemWeight = items[item - 1].getWeight();
if (weight >= itemWeight) {
int remainingWeight = weight - itemWeight;
// check the max value upto remainingWieght, the we might have computed before.
int valueUptoRemainingWeight = knapsack[item - 1][remainingWeight];
// how about trying currentItem + remainingItem ?
int tentativeValue = items[item - 1].getValue() + valueUptoRemainingWeight;
// compare this against previously calculated max-value
int previousMaxValue = knapsack[item - 1][weight];
knapsack[item][weight] = Math.max(tentativeValue, previousMaxValue);
} else {
knapsack[item][weight] = knapsack[item - 1][weight];
}
}
}
return knapsack[items.length][maxWeight];
}
public static void main(String[] args) {
Item i1 = new Item( 60, 10);
Item i2 = new Item(100, 20);
Item i3 = new Item(120, 30);
Item[] items = new Item[3];
items[0] = i1;
items[1] = i2;
items[2] = i3;
assertEquals(180, getMaxValue(items, 40));
assertEquals(220, getMaxValue(items, 50));
assertEquals(280, getMaxValue(items, 60));
assertEquals(280, getMaxValue(items, 60));
}
}
</code></pre>
| [] | [
{
"body": "<p>Just a few comments :</p>\n\n<hr>\n\n<p>Your <code>if (value == 0)</code> and <code>if (weight == 0)</code> should probably be <code>if (value <= 0)</code> and <code>if (weight <= 0)</code>.</p>\n\n<hr>\n\n<p><a href=\"http://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow\">Keep It Simple</a> : because <code>value</code> and <code>weight</code> are <code>final</code>, you could probably make them public, removing the need for getters.</p>\n\n<p>Also, you could make this an <a href=\"http://en.wikipedia.org/wiki/Inner_class\" rel=\"nofollow\">inner class/nested class</a> if you don't plan to use it for anything else.</p>\n\n<hr>\n\n<p>Purely personal but I'd rather avoid <code>continue</code> whenever it can be easily avoided. If your case, it's quite easy to put the whole block behind a <code>if (item != 0 && weight != 0)</code> (or even better : <code>if (item > 0 && weight > 0)</code>). </p>\n\n<p>However, things could be even more straightforward : <code>for (int item = 0; item <=items.length; item++)</code> and <code>for (int weight = 0; weight <= maxWeight; weight++)</code> could start at <code>1</code> because first iteration won't do anything anyway because condition <code>if (item == 0 || weight == 0)</code> will be true. Then, as far as I can tell, the guard is not needed anymore.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T16:47:44.903",
"Id": "80016",
"Score": "0",
"body": "simple yet meaningful :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T08:41:33.640",
"Id": "45811",
"ParentId": "45793",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T02:05:58.233",
"Id": "45793",
"Score": "1",
"Tags": [
"java",
"algorithm",
"dynamic-programming",
"knapsack-problem"
],
"Title": "Knapsack 01 solution"
} | 45793 |
<p>Counterfactual Regret Minimization is an algorithm that can be used to find the Nash Equilibrium for games of incomplete information. I have tried to adapt the exercise from <a href="http://cs.gettysburg.edu/~tneller/modelai/2013/cfr/index.html" rel="nofollow">here</a> to Clojure. You can see the original RPSTrainer.java, my first functional version of the algorithm rps.clj and finally a version that I tried to tweak for performance rps_tweak.clj all <a href="https://gist.github.com/luxbock/da22767ef16af6ebc5dc" rel="nofollow">here</a>.</p>
<p>Here is the tweaked version:</p>
<pre class="lang-clj prettyprint-override"><code>(ns cfr.rps-tweak
(:require [clojure.core.matrix :as m]
[primitive-math :as pm]))
(set! *warn-on-reflection* true)
(m/set-current-implementation :vectorz)
(defn create-utility-fn
"Given a payoff-matrix creates a utility function for the game. The utility
function accepts two strategy vectors as its arguments and returns the utility
for the first player in question."
[m]
(fn ^double [sa sb]
(let [prob-m
(m/compute-matrix
(map m/ecount [sa sb])
#(pm/* ^double (m/mget sa %1) ^double (m/mget sb %2)))]
(m/ereduce + (m/mul prob-m m)))))
(defn regret
"Given a utility function and three strategy vectors, returns the regret for
player having played his strategy `sa' instead of `sb' against his opponents `so'"
[uf sa sb so]
(pm/- ^double (uf sb so) ^double (uf sa so)))
(defn action-profile [n]
"An action profile is the list of pure strategies available to a player."
(map #(m/mset (repeat n 0) % 1) (range n)))
(defn regret-profile
"Given a utility function and strategies for both players, this function
returns the regret for all the pure-strategies the first player could have
played, including the strategy he did play."
[uf sa so]
(map #(regret uf sa % so) (action-profile (m/ecount sa))))
(defn normalise-strategies
[nsum strat]
(if (pm/> ^double nsum 0.0)
(map #(pm/div ^double % ^double nsum) strat)
(repeat (m/ecount strat) (pm/div (m/ecount strat)))))
(defn new-strategy
"Creates a new strategy based on the regrets experienced by the player."
[rgr]
(let [n (m/ecount rgr)
strat (map #(if (pos? (m/mget rgr %)) (m/mget rgr %) 0) (range n))
nsum (reduce + strat)]
(normalise-strategies nsum strat)))
(defn cumulative-probabilities
"Takes a collection of probabilities (that sum up to one) and turns it into a
sequence of cumulative probabilities."
[coll]
(reduce #(conj %1 (+ %2 (last %1))) [0] coll))
(defn choose-action
"Given a strategy vector, chooses an action to play based on its probability."
[^doubles strat]
(let [cp (cumulative-probabilities strat)
r (rand)
index (pm/dec ^long (m/ecount (take-while #(pm/> ^double r ^double %) cp)))]
(m/mset (repeat (m/ecount strat) 0) index 1)))
(defn avarage-strategy
"Given a vector where each index maps to how often a certain strategy has been
played, returns the frequency of each strategy as a part of the total."
[ssum]
(let [nsum (reduce + ssum)]
(normalise-strategies nsum ssum)))
(defn cfrm-be
"Given a utility function, number of iterations and a strategy for the
opponent, performs the Counterfactual Regret Minimization algorithm to find
the best response to the strategy in question."
[uf n sb]
(let [n (int n)]
(loop [i (int 0)
reg-a (m/array [0 0 0])
ssum (m/array [0 0 0])]
(if (pm/== i n)
(avarage-strategy ssum)
(let [strat-a (choose-action (new-strategy reg-a))
strat-b sb]
(recur (pm/inc i)
(m/add reg-a (regret-profile uf strat-a strat-b))
(m/add ssum strat-a)))))))
(defn cfrm-ne
"Given a utility function and a number of iterations to perform, performs the
Counterfactual Regret Minimization algorithm to find an approximation of the
Nash Equilibrium for the game."
[uf n]
(let [n (int n)]
(loop [i (int 0)
reg-a (m/array [0 0 0])
reg-b (m/array [0 0 0])
ssum (m/array [0 0 0])]
(if (pm/== i n)
(avarage-strategy ssum)
(let [strat-a (choose-action (new-strategy reg-a))
strat-b (choose-action (new-strategy reg-b))]
(recur (pm/inc i)
(m/add reg-a (regret-profile uf strat-a strat-b))
(m/add reg-b (regret-profile uf strat-b strat-a))
(m/add ssum strat-a)))))))
(comment
(def rps
(create-utility-fn [[0, -1, 1]
[1, 0, -1]
[-1, 1, 0]]))
(cfrm-ne rps 100000)
)
</code></pre>
<p>The tweaked version performs about 3.5x faster than rps.clj, but it's still two orders of magnitude away from the original Java implementation. This is not that surprising given that the two versions are doing very different things. Still I wonder are there any other improvements I could make for speed without having to write Java in Clojure, in which case I would probably just write Java in Java and call it from Clojure? If I were to build an application that relied on the performance of an algorithm such as the one above, would I be better off doing the performance critical things in Java and then just using Clojure as glue code for the rest?</p>
<p>I made two significant improvements at some cost to the flexibility of the program:</p>
<ol>
<li>The utility function is now a simple lookup from the payoff matrix, which works because <code>choose-action</code> always returns a pure strategy. Creating a probability matrix is therefore unnecessary.</li>
<li>As a result the arguments to the utility-function can simply be indices of the payoff matrix instead of arrays. </li>
</ol>
<p>These two changes gave me a speedup roughly by a factor of 10x. </p>
<p>Using mutable arrays to store the regrets and strategy-sum in the main loop also performs just a tiny bit faster, but the difference is surprisingly minuscule:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>cfr.rps-moar> (bench (cfrm-ne rps 100000))
WARNING: Final GC required 2.974887513309308 % of runtime
Evaluation count : 60 in 60 samples of 1 calls.
Execution time mean : 1.285734 sec
Execution time std-deviation : 16.892914 ms
Execution time lower quantile : 1.263259 sec ( 2.5%)
Execution time upper quantile : 1.321674 sec (97.5%)
Overhead used : 1.982317 ns
Found 1 outliers in 60 samples (1.6667 %)
low-severe 1 (1.6667 %)
Variance from outliers : 1.6389 % Variance is slightly inflated by outliers
</code></pre>
</blockquote>
<p>vs.</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>cfr.rps-muta> (bench (cfrm-ne rps 100000))
WARNING: Final GC required 3.27423659048163 % of runtime
Evaluation count : 60 in 60 samples of 1 calls.
Execution time mean : 1.217206 sec
Execution time std-deviation : 7.875121 ms
Execution time lower quantile : 1.203429 sec ( 2.5%)
Execution time upper quantile : 1.236352 sec (97.5%)
Overhead used : 1.968409 ns
Found 4 outliers in 60 samples (6.6667 %)
low-severe 4 (6.6667 %)
Variance from outliers : 1.6389 % Variance is slightly inflated by outliers
</code></pre>
</blockquote>
<p>Here is the mutable version:</p>
<pre class="lang-clojure prettyprint-override"><code>(ns cfr.rps-muta
(:require [clojure.core.matrix :as m]
[primitive-math :as pm]))
(set! *warn-on-reflection* true)
(m/set-current-implementation :vectorz)
(defn create-utility-fn
"Given a payoff-matrix creates a utility function for the game. The utility
function accepts two strategy vectors as its arguments and returns the utility
for the first player in question."
[m]
(fn ^double [sa sb]
(m/mget m sa sb)))
(defn regret
"Given a utility function and three strategy vectors, returns the regret for
player having played his strategy `sa' instead of `sb' against his opponents `so'"
[uf sa sb so]
(pm/- ^double (uf sb so) ^double (uf sa so)))
(defn regret-profile
"Given a utility function and strategies for both players, this function
returns the regret for all the pure-strategies the first player could have
played, including the strategy he did play."
[uf sa so ns]
(map #(regret uf sa % so) (range ns)))
(defn normalise-strategies
[nsum strat]
(if (pm/> ^double nsum 0.0)
(map #(pm/div ^double % ^double nsum) strat)
(repeat (m/ecount strat) (pm/div (m/ecount strat)))))
(defn new-strategy
"Creates a new strategy based on the regrets experienced by the player."
[rgr]
(let [n (m/ecount rgr)
strat (map #(if (pos? (m/mget rgr %)) (m/mget rgr %) 0) (range n))
nsum (reduce + strat)]
(normalise-strategies nsum strat)))
(defn cumulative-probabilities
"Takes a collection of probabilities (that sum up to one) and turns it into a
sequence of cumulative probabilities."
[coll]
(reduce #(conj %1 (+ %2 (last %1))) [0] coll))
(defn choose-action
"Given a strategy vector, chooses an action to play based on its probability."
[^doubles strat]
(let [cp (cumulative-probabilities strat)
r (rand)]
(pm/dec ^long (m/ecount (take-while #(pm/> ^double r ^double %) cp)))))
(defn avarage-strategy
"Given a vector where each index maps to how often a certain strategy has been
played, returns the frequency of each strategy as a part of the total."
[ssum]
(let [nsum (reduce + ssum)]
(normalise-strategies nsum ssum)))
(defn cfrm-be
"Given a utility function, number of iterations and a strategy for the
opponent, performs the Counterfactual Regret Minimization algorithm to find
the best response to the strategy in question."
[m n sb]
(let [n (int n)
uf (create-utility-fn m)
reg-a (m/array [0.0 0.0 0.0])
ssum (m/array [0.0 0.0 0.0])
[sca scb] (m/shape m)]
(loop [i (int 0)]
(if (pm/== i n)
(avarage-strategy ssum)
(let [strat-a (choose-action (new-strategy reg-a))
strat-b sb]
(m/add! reg-a (regret-profile uf strat-a strat-b sca))
(m/add! ssum strat-a)
(recur (pm/inc i)))))))
(defn cfrm-ne
"Given a utility function and a number of iterations to perform, performs the
Counterfactual Regret Minimization algorithm to find an approximation of the
Nash Equilibrium for the game."
[m n]
(let [n (int n)
uf (create-utility-fn m)
reg-a (m/array [0.0 0.0 0.0])
reg-b (m/array [0.0 0.0 0.0])
ssum (m/array [0.0 0.0 0.0])
[sca scb] (m/shape m)]
(loop [i (int 0)]
(if (pm/== i n)
(avarage-strategy ssum)
(let [strat-a (choose-action (new-strategy reg-a))
strat-b (choose-action (new-strategy reg-b))]
(m/add! reg-a (regret-profile uf strat-a strat-b sca))
(m/add! reg-b (regret-profile uf strat-b strat-a scb))
(m/add! ssum strat-a)
(recur (pm/inc i)))))))
(comment
(def rps
[[0, -1, 1]
[1, 0, -1]
[-1, 1, 0]])
(cfrm-ne rps 100000)
)
</code></pre>
<p>I can't think of anything more I could do. It still runs about 10x slower than the original Java implementation, but I think my version is more general and nicer to read.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T03:16:47.090",
"Id": "45796",
"Score": "6",
"Tags": [
"performance",
"algorithm",
"clojure"
],
"Title": "Translating CFRM algorithm from Java to Clojure and improving performance"
} | 45796 |
<p>I have a modal window that needs to be closed, obviously. I've created this piece of code that works okay. But is there a way to optimize it?</p>
<pre><code>// close the modal window
$('.modal-close').click(function(e) {
$('#modal').hide();
$('#modal-overlay').hide();
e.preventDefault();
});
$(document).keydown(function(e) {
if (e.keyCode == 27) { // if Esc key is pressed
$('#modal').hide();
$('#modal-overlay').hide();
}
if (e.keyCode == 9) { // cancel the Tab key
return false;
}
});
</code></pre>
| [] | [
{
"body": "<p>You can combine a couple of things: The close functionality can be function, and jQuery can operate on several elements at once:</p>\n\n<pre><code>function closeModal(event) { // passing in an event obj is optional\n $(\"#modal, #modal-overlay\").hide();\n if(event) {\n event.preventDefault();\n }\n}\n\n$(\".modal-close\").click(closeModal);\n\n$(document).keydown(function(event) {\n switch(event.keyCode) {\n case 27: // esc\n closeModal();\n break;\n case 9: // tab\n event.preventDefault();\n break;\n default: // everything else\n break;\n }\n}\n</code></pre>\n\n<p>I've switched the <code>keydown</code> handler to use a <code>switch</code> statement, but that's not critically important. The point is just that since the keycode will be <em>either</em> one number or the other, there's no need for multiple <code>if</code>s, and a <code>switch</code> is simple to extend if you need to handle more keycodes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T04:03:43.573",
"Id": "45799",
"ParentId": "45797",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "45799",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T03:39:20.177",
"Id": "45797",
"Score": "2",
"Tags": [
"javascript",
"optimization",
"jquery"
],
"Title": "Am I optimally closing this modal window?"
} | 45797 |
<p>I am trying to solve this <a href="http://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/" rel="nofollow">Binary tree lever order traversal</a>:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7]
[9,20],
[3],
]
</code></pre>
</blockquote>
<p>How can I improve the speed of the code below? It always gives me a time exceed error.</p>
<pre class="lang-java prettyprint-override"><code>/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<ArrayList<Integer>> tree = new ArrayList<ArrayList<Integer>>();
Stack<Integer> stack = new Stack<Integer>();
ArrayList<Integer> node = new ArrayList<Integer>();
this.iterateAll(root, stack);
while (!stack.empty()) {
if (stack.peek() != null) {
node.add(stack.pop());
if (!stack.isEmpty()) {
if (stack.peek() != null) {
tree.add(node);
node = new ArrayList<Integer>();
} else {
stack.pop();
if (!stack.isEmpty()) {
if (stack.peek() != null) {
tree.add(node);
node = new ArrayList<Integer>();
}
}
}
} else {
tree.add(node);
}
} else {
stack.pop();
}
}
return tree;
}
public Stack<Integer> iterateAll(TreeNode root, Stack<Integer> stack) {
if (root != null) {
stack.push(root.val);
if (root.right != null) {
iterateAll(root.right, stack);
} else {
stack.push(null);
}
if (root.left != null) {
iterateAll(root.left, stack);
} else {
stack.push(null);
}
}
return stack;
}
}
</code></pre>
| [] | [
{
"body": "<p>Depending on number of nodes in your tree, recursive post-order traversal of the tree, might let you run into problems on the stack. If the number of nodes is huge, you might need to consider a non-recursive post-order traversal.</p>\n\n<p>Have a look at <a href=\"http://leetcode.com/2010/10/binary-tree-post-order-traversal.html\" rel=\"nofollow\">http://leetcode.com/2010/10/binary-tree-post-order-traversal.html</a>, which describes multiple solutions, both iterative and non-recursive.</p>\n\n<p>On think to keep in mind is that the non-recursive algorithms use more memory, as it need to push nodes to a stack.</p>\n\n<p>You might also consider doing a post-order tree traversal enumerator, but that might be for another day.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T10:17:21.197",
"Id": "79954",
"Score": "0",
"body": "you might want to write a little sum up of your link, in case it goes down, I think some pseudocode or even just a short explanation of the algorithm would be enough."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T05:52:40.270",
"Id": "45803",
"ParentId": "45798",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T03:46:20.817",
"Id": "45798",
"Score": "5",
"Tags": [
"java",
"programming-challenge",
"tree",
"breadth-first-search",
"time-limit-exceeded"
],
"Title": "Binary tree level order traversal algoritm"
} | 45798 |
<p>I have datalayer code as below which is implementing an interface as:
<strong>Note:</strong> I have hand written this code on Notepad so it may contain some typo errors, which you can gracefully ignore. I am searching for an approach here.</p>
<pre><code>public interface ISimpleInterface{
void DosSomething(long someValue);
}
public class ConcreteImplementation: ISimpleInterface
{
public void DosSomething(long someValue){
//add code for creating new command, connection objects here
using(var connection=new NpgsqlConnection(ConnectionString)){
connection.Open();
long ID=GetNextValueFromSeq1(connection);
using(var command=new NpgsqlCommand()){
command.Connection=connection;
command.CommandText="Insert INTO testTable(col1, col2) VALUES (:pcol1, :pcol2)";
command.Parameters.AddRange(
new NpgsqlParameters{ ParameterName="pcol1", ParameterType=NpgsqlDbType.BigInt, Value=ID},
new NpgsqlParameters{ ParameterName="pcol1", ParameterType=NpgsqlDbType.BigInt, Value=someValue}
);
}
}
}
long GetNextValueFromSeq1(NpgsqlConnection connection){
//code to get next value from Sequence1 goes here
}
}
</code></pre>
<p>A typical Unit Test class might be: </p>
<pre><code>public class ConcreteImplementationTests{
public void DoSomething_SimpleInsert_InsertsRecord(long someValue){
//code for deleting or truncating table testTable goes here
var sut=new ConcreteImplementation();
sut.DoSomething(13);
//write a select command to check whether a record has been inserted in testTable
//If there is one record in table then test passes, else it fails.
}
}
</code></pre>
<p><strong>Note:</strong> My concerns are that how I can assert that <code>Dosomething</code> method correctly takes value from sequence and inserts in table, because in real life, a developer might even forget to get value from <code>GetNextValueFromSeq1</code> method. He/she might not know this thing unless/until at a later stage when running the application they get a run time exception.</p>
<p>I am also open to any suggestions in improving my code so as long as it provides greater testability, test maintainability.</p>
<p>In real life, the <code>DosSomething</code> method might even have a list of long values.</p>
| [] | [
{
"body": "<p>I think this ID should be generated at database level (autoincrement). But let's ignore this, for testing you have to make sure your methods do not have a dependency on eachother. </p>\n\n<p>It would be better if you write it like this</p>\n\n<pre><code>public void DoSomething(long someValue, long id) \n{\n // Insert new value\n}\n\npublic long GetInsertId() \n{\n // Return ID\n}\n</code></pre>\n\n<p>Now you can test these methods independently</p>\n\n<pre><code>public void GetInsert_ShouldReturnNewId()\n{\n // Your requirements for a new ID should be tested here\n}\n\npublic void DoSomething_ShouldInsertNewRecord()\n{\n var sut=new ConcreteImplementation();\n var id = sut.GetInsertId();\n\n sut.DoSomething(13, id);\n}\n</code></pre>\n\n<p>By using this approach the developer <strong><em>MUST</em></strong> provide an ID. The developer can obtain an ID by calling your new method. Just keep in mind that if you want to make your code more testable you have to make your methods independant. They must work on there own.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T16:12:08.967",
"Id": "80009",
"Score": "0",
"body": "In my real project I have around 20 sequencies. So, if I leave this decision on developer using the api, he/she might mistakenly get value from other Sequence."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T07:54:03.533",
"Id": "45810",
"ParentId": "45800",
"Score": "2"
}
},
{
"body": "<p>I would use constructor injection to get a class that can provide you with an ID. \nThat way you can easily mock it in your unittests and you can change the implementations at a later stage if you want to or need to.</p>\n\n<pre><code> public class ConcreteImplementation: ISimpleInterface\n{\n\n private IIdentityProvider _identityProvider;\n public ConcreteImplementation(IIdentifierProvider identityProvider)\n {\n\n _identityProvider = identityProvider;\n }\n\n public void DosSomething(long someValue){\n ...\n using(var connection=new NpgsqlConnection(ConnectionString)){\n ...\n var ID = _identityProvider.GetNextValueFromSeq1(connection);\n ...\n );\n }\n }\n }\n\n}\n\npublic interface IIdentityProvider {\n long GetNextValueFromSeq1(NpgsqlConnection connection);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T10:42:11.847",
"Id": "45815",
"ParentId": "45800",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T04:13:47.203",
"Id": "45800",
"Score": "0",
"Tags": [
"c#",
"unit-testing"
],
"Title": "Unit Testing Datalayer written in ADO.net"
} | 45800 |
<p>Could someone help me on how to eliminate some nested blocks or improve this code? I am concerned this will slow down my site dramatically.</p>
<pre><code>function dispalyEvent($weekNr, $week, $year){
echo "<p>";
$gendate = new DateTime();
$gendate->setISODate($year,$week,$weekNr);
$event_query = mysql_query("SELECT * FROM calendar ORDER BY starttime");
//Go through all event in the database
while($event = mysql_fetch_array($event_query)) {
//Create a range for starting date and ending date
$date1 = new DateTime($event['startyear'].$event['startmonth'].$event['startdate']);
$date2 = new DateTime($event['endyear'].$event['endmonth'].$event['enddate']);
$date2->modify('+1 day');
$period = new DatePeriod($date1, new DateInterval('P1D'), $date2);
$title = $event['title'];
$name = $event['name'];
$recur_query = mysql_query("SELECT * FROM recur WHERE title = '$title' AND name = '$name'");
$recur = mysql_fetch_array($recur_query);
$recurring = $recur['type'];
//Find day of starting recurring event and ending day
if (!$recurring == "None"){
$starttime = explode("/",$recur['startdate']);
$startdate = new DateTime();
$startdate->setDate($starttime[2], $starttime[0], $starttime[0]);
$endtime = explode("/",$recur['enddate']);
$enddate = new DateTime();
$enddate->setDate($endtime[2], $endtime[0], $endtime[0]);
}
else {
$startdate = new DateTime();
$enddate = new DateTime();
}
//Put the dates in integer to find if it is out of range
$displaydate = intval($gendate->format("Ymd"));
$startdate = intval($startdate->format("Ymd"));
$enddate = intval($enddate->format("Ymd"));
settype($displaydate, "integer");
settype($startdate, "integer");
settype($enddate, "integer");
//Go through each date in the range
foreach ($period as $savedDate) {
//Check if the Item is Approved
if ($event['Approved'] == "Approved"){
switch($recurring){
Case 'None':
//If the date in the range is the same as the displaydate
if ($gendate->format("Y-m-d") == $savedDate->format('Y-m-d')){
//Create event
renderEvent($event['ad'], $event['starttime'], $event['title'], $event['endtime'], $event['location'], $event['address'], $event['price'], $event['description']);
}
break 1;
Case 'Daily':
//Check margin between start and end date of recurring event
if ($displaydate > $startdate and !$displaydate < $enddate){
//Check if the day number is the same
if ($recur['day']-1 == $gendate->format("w")){
//Create event
renderEvent($event['ad'], $event['starttime'], $event['title'], $event['endtime'], $event['location'], $event['address'], $event['price'], $event['description']);
}
}
break 1;
Case 'Weekly':
//Check margin between start and end date of recurring event
if ($displaydate > $startdate and !$displaydate < $enddate){
//Find the amount of weeks between two dates
$weekRange = datediffInWeeks($recur['startdate'], $recur['enddate']);
//Round down to the possible amount to display
$weeks = ceil($weekRange / $recur['day']);
//Returns the week cuurent week to display
$currentWeek = $gendate->format("W");
//Loop for every #(1, 2, 3, 4) of weeks
for ($n=0; $n<$weeks; $n++) {
//Display event if weeks are the same
if ($n == $currentWeek) {
//Put days in array
$days = explode(",",$recur['weekday']);
//If number day of the week is the same display event
foreach ($days as $day) {
//Check if the day number is the same
if ($day == $gendate->format("w")) {
//Create event
renderEvent($event['ad'], $event['starttime'], $event['title'], $event['endtime'], $event['location'], $event['address'], $event['price'], $event['description']);
}
}
}
}
}
break 1;
}
}
}
}
echo "</p>";
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T08:24:15.523",
"Id": "79943",
"Score": "0",
"body": "Explain the purpose of this function. Is it called for each day on the calendar to render events for that day?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T06:39:19.850",
"Id": "96333",
"Score": "0",
"body": "Try to avoid nested if block and use ternary operator. Move code in functions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T11:47:19.200",
"Id": "96334",
"Score": "0",
"body": "While I agree with the functions part of your comment, I don't agree with using ternaries to avoid nesting blocks. `if-else` branches don't introduce a new block-scope, and the PHP ternary is fundamentally flawed. Besides, the OP's code is messy as it is, and there are issues with operator precedence all over. Ternaries will only add confusion and be a new source of bugs at this point. That's just bad advice in this case..."
}
] | [
{
"body": "<p>Here are a few quick tips:</p>\n\n<ul>\n<li><p>Your indentation seems mostly consistent, but there are a few lines off by a space. Most editors have a format feature if you find it too tedious to maintain it manually.</p></li>\n<li><p>Other whitespace is inconsistent as well. Compare these two lines:</p>\n\n<pre><code>foreach ($period as $savedDate) { // perfect\n</code></pre>\n\n<p>and</p>\n\n<pre><code>switch($recurring){ // allergic to spaces?\n</code></pre></li>\n<li><p>Pick a naming convention and stick with it: <code>$startdate</code> versus <code>$savedDate</code>. I recommend camelCase.</p></li>\n<li><p><code>break</code> statements don't need the default <code>1</code> argument. Inside <code>switch</code> blocks especially it looks very strange and makes you stop and think when there's no reason.</p></li>\n<li><p>Indent the <code>break</code> statements one level below their matching <code>case</code> statements, at the same level as the code before them. Some people keep the <code>case</code> lines at the same level as the <code>switch</code> since they go hand-in-hand to keep the lines from shifting so far to the right.</p></li>\n</ul>\n\n<p><strong>Bug</strong></p>\n\n<p>Be very careful when negating boolean expressions. <code>if (!$recurring == \"None\")</code> will never pass because no value equals the string <code>\"None\"</code> when it's negated. This should be <code>if (!($recurring == \"None\"))</code> to correct the operator precedence, but <code>if ($recurring !== \"None\")</code> is clearer.</p>\n\n<p>Finally, the best way to see how it performs is to time it repeatedly and take the average.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T09:15:16.647",
"Id": "79948",
"Score": "0",
"body": "White space use is largely a personal taste (as long as it is not on the level of `for(int i=0,int j=3;i<2*j+1,j>=34;i+=2,j/=2*3+c)` ) and I find both of the given examples acceptable. Although OP would benefit from being consistent."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T11:36:29.023",
"Id": "79956",
"Score": "0",
"body": "The operator precedence bug is present all over.. most notably `if ($displaydate > $startdate and !$displaydate < $enddate)`: using `and` is preventing this to be evaluated in the wackiest of ways, but it doesn't betray much awareness of operator precedence at all..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T06:49:46.350",
"Id": "45808",
"ParentId": "45801",
"Score": "1"
}
},
{
"body": "<p>Ok, the following review may seem blunt or harsh, but please, try to keep in mind that this is in order to <em>help</em>. I'm not trying to hurt or mock anyone, but in order for code-review to be as effective as it ought to be, I'll have to be brutal.</p>\n\n<p>If you haven't read it already, the <em>help-section</em> asks you post <em>working</em> code. bug-riddled code isn't subject to review yet, it has to be debugged first.<br>\nIt is possible you aren't aware of it, and that you may <em>think</em> your code works, when really it doesn't. Well, not as you expect it to, at least. I know it feels banal and tedious, closely looking at <a href=\"http://www.php.net/manual/en/language.operators.precedence.php\" rel=\"nofollow noreferrer\">the operator precedence table</a> doesn't do any harm. Quite the opposite, in fact. You'll soon find out why Both David Harkness and myself mention potenial bugs or unexpected behaviour with expressions like:</p>\n\n<pre><code>if (!$recurring == \"None\")\n//and\nif ($displaydate > $startdate and !$displaydate < $enddate)\n</code></pre>\n\n<p>And as a last point in this foreword to what is already a hefty answer, I would like to strongly suggest you change your <code>php.ini</code> settings for the <code>error_reporting</code> and set <code>display_errors</code> to true, one, or <code>stdout</code>, depending on your PHP version.<br>\nThe <code>error_reporting</code>'s default value is likely to be <code>E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED</code>, while debugging, it's best to set it to <code>E_ALL | E_STRICT</code>, or call <code>error_reporting(-1);</code> in your script.</p>\n\n<p>As I have done before, I'll walk through your code line by line, offering advice and the reasoning behind my criticism. At the end, I'll add an example of code you could end up with if you decide to take my recommendations to heart.<br>\n<em>Update</em>: I did not add a code example as there are simply too many unknowns to deal with, and that any example would basically end up being a total re-write of your code, which isn't my job, and is of little educational use to you. Instead, just to make it 100% clear, however blunt or harsh this answer may seem <a href=\"https://codereview.meta.stackexchange.com/questions/810/guidelines-for-new-users-proposal-tag\">here's a meta-post on why I consider it necessary for code-review to be tough</a><br>\nNow, without further ado, let's get too it:</p>\n\n<pre><code>function dispalyEvent($weekNr, $week, $year){\n</code></pre>\n\n<p>Yes, I have some criticisms about the very first line of code you posted already. Ok, a function <code>displayEvent</code>, that expects 3 arguments. All three have to do with time. But if you need variables that tell you something about time, why not ask of the user (caller) to pass a <code>DateTime</code> class from the off?</p>\n\n<pre><code>function displayEvent(DateTime $date)\n{\n</code></pre>\n\n<p>Now this tells the user of your code that he's expected to pass a <code>DateTime</code> instance as an argument. It reduces the number of arguments from 3 to 1, and allows for type-hints. As we'll see in a second, this also saves you the bother of creating the <code>DateTime</code> instances inside the function. The advantage of that is that, if the caller already <em>has</em> a <code>DateTime</code> instance, he can simply pass that object, and not call methods to get the year, week and weekNr values, which are only being used to re-construct the same <code>DateTime</code> instance all over.</p>\n\n<p>Onwards:</p>\n\n<pre><code> echo \"<p>\";\n</code></pre>\n\n<p>Don't <code>echo</code> in a function. A function <em>returns</em>. The caller of your function may then <em>choose</em> to echo the return value, or may store it somewhere else. Having a function <code>echo</code> something puts the user of your code in a tight spot: calling this function means he can't set the headers, can't use this function to retrieve data and present it in a way he wants to. Just create a variable <code>$outString = '';</code>, and return that at the end.</p>\n\n<pre><code> $gendate = new DateTime();\n $gendate->setISODate($year,$week,$weekNr);\n</code></pre>\n\n<p>As I said before: this code can be made redundant simply by changing the function's signature to expect a <code>DateTime</code> instance from the off</p>\n\n<pre><code> $event_query = mysql_query(\"SELECT * FROM calendar ORDER BY starttime\");\n\n //Go through all event in the database\n while($event = mysql_fetch_array($event_query)) {\n</code></pre>\n\n<p>Please, <em>please</em>, <strong><em>please</em></strong> stop using the <strong><em>deprecated</em></strong> <code>mysql_*</code> extension. Switch to <code>PDO</code> or <code>mysqli_*</code> instead. Henceforth I'll be using <code>PDO</code>.<br>\nAnd as a rule of thumb, or even personal mantra: Avoid <code>SELECT *</code> queries whenever you can. Select <em>what</em> you need, and <em>how</em> you need it. You haven't done that last bit at all, judging by the next snippet of code:</p>\n\n<pre><code> //Create a range for starting date and ending date\n $date1 = new DateTime($event['startyear'].$event['startmonth'].$event['startdate']);\n $date2 = new DateTime($event['endyear'].$event['endmonth'].$event['enddate']);\n $date2->modify('+1 day');\n</code></pre>\n\n<p>Why not select these dates like so:</p>\n\n<pre><code>SELECT CONCAT_WS('-', startyear, startmonth, startdate) AS date1\n</code></pre>\n\n<p>That way, you'll be able to write:</p>\n\n<pre><code>$date1 = new DateTime($event['date1']);\n</code></pre>\n\n<p>That's just, I think you'll agree, a hell of a lot cleaner. Anyway, back to the code:</p>\n\n<pre><code> $period = new DatePeriod($date1, new DateInterval('P1D'), $date2);\n\n $title = $event['title'];\n $name = $event['name'];\n</code></pre>\n\n<p>Why bother assigning individual variables, you have an associative array, what's wrong with that? An assoc array is a data structure that holds together all related data anyway. This data clearly belongs together, why not keep it together in that array?<br>\nWe'll get to the <code>DatePeriod</code> business in a moment, for now, let's carry on:</p>\n\n<pre><code>$recur_query = mysql_query(\"SELECT * FROM recur WHERE title = '$title' AND name = '$name'\");\n$recur = mysql_fetch_array($recur_query);\n$recurring = $recur['type'];\n//Find day of starting recurring event and ending day \nif (!$recurring == \"None\"){\n $starttime = explode(\"/\",$recur['startdate']); \n $startdate = new DateTime();\n $startdate->setDate($starttime[2], $starttime[0], $starttime[0]);\n $endtime = explode(\"/\",$recur['enddate']); \n $enddate = new DateTime();\n $enddate->setDate($endtime[2], $endtime[0], $endtime[0]);\n}\nelse {\n $startdate = new DateTime();\n $enddate = new DateTime();\n}\n</code></pre>\n\n<p>Ok, you may have noticed I fixed the indentation. Seriously, indentation is important. For your sake and ours. Stay consistent and try to adhere to <a href=\"http://www.php-fig.org\" rel=\"nofollow noreferrer\">the standard as much as you can</a>.<br>\nAnyway: This code basically queries the same DB for, pretty much, the same data over and over again. Of course, the where clause is different every time, but what you're doing is sending a string to MySQL, who then parses and compiles the query and <em>then</em> fetches the data.</p>\n\n<p>A prepared statement can be sent to the DB once, to be compiled, optimized (and in many cases, a lot of the data is even pre-fetched), and you can then send the values that are to be placed in the <code>WHERE</code> clause whenever you need that query to be executed. This saves the DB server a lot of work, saves time and <em>is more secure</em>. You're just stringing <code>$name</code> and <code>$title</code> in the query, for example. Completely oblivious to the fact that There <em>could</em> be a name like <em>\"O'Connor\"</em> assigned to <code>$name</code>. Resulting in the Query:</p>\n\n<pre><code>SELECT * FROM recur WHERE title = 'foobar' AND name = 'O'Connor'\n</code></pre>\n\n<p>Which will cause problems. And what if <a href=\"http://bobby-tables.com/\" rel=\"nofollow noreferrer\">Bobby Tables</a> pays a visit?<br>\nOn the <code>DateTime</code> things, I can only say: Why <code>explode</code>? Why not simply write:</p>\n\n<pre><code>$recur['startdate'] = new DateTime($recur['startdate']);\n</code></pre>\n\n<p><code>DateTime</code> does a great job at <em>\"guessing\"</em> the format, but if you wish not to rely on this, you can always choose to specify the format yourself:</p>\n\n<pre><code>$recur['startdate'] = DateTime::createFromFormat(\n 'd/m/Y',\n $recur['startdate']\n);\n</code></pre>\n\n<p>Anyway, let's continue:</p>\n\n<pre><code>//Put the dates in integer to find if it is out of range\n$displaydate = intval($gendate->format(\"Ymd\"));\n$startdate = intval($startdate->format(\"Ymd\"));\n$enddate = intval($enddate->format(\"Ymd\"));\nsettype($displaydate, \"integer\");\nsettype($startdate, \"integer\");\nsettype($enddate, \"integer\");\n</code></pre>\n\n<p>DRY, Don't Repeat Yourself. You are calling the <code>intval</code> function. Look at the return type:</p>\n\n<pre><code>int intval ( mixed $var [, int $base = 10 ] )\n// \\---> returns an INT\n</code></pre>\n\n<p>Why, then are you calling <code>settype</code>? It's pretty safe to say you're calling <code>settype</code> on an int already. Even if you're not, why not <em>cast</em>? A cast saves the overhead of a function call:</p>\n\n<pre><code>$displaydate = (int) $gendate->format(\"Ymd\");\n</code></pre>\n\n<p>That's all there is too it, and you've saved yourself the bother of 2 function calls.<br>\nMoving on:</p>\n\n<pre><code>//Go through each date in the range\nforeach ($period as $savedDate) { \n //Check if the Item is Approved\n if ($event['Approved'] == \"Approved\"){\n switch($recurring){\n</code></pre>\n\n<p>Ok, think about what you're doing here. For each date in the <code>DatePeriod</code>, you're evaluating, basically, what the results of the initial query told you. Why do you need to check those more than once? You <em>know</em> the <code>$event['Approved']</code> and <code>$recurring</code> values aren't going to change. Determine which <code>case</code> is going to be true beforehand. Then you can significantly shorten the loop body.<Br>\nYou're only processing those events that have been <em>approved</em>! Why not add that to the <code>WHERE</code> clause in your query????</p>\n\n<pre><code>SELECT * FROM calendar WHERE Approved = 'Approved' ORDER BY starttime;\n</code></pre>\n\n<p>That way, you don't have to check the value of <code>$event['Approved']</code> to begin with. Also: <code>break;</code> is the same as writing <code>break 1;</code>. The latter just looks weird here. Anyway, consider writing separate functions for various event-types: <code>renderNonRecurring</code>, <code>renderDailyEvent</code> and (but there's a lot to be said about this case still) <code>renderWeeklyEvent</code>.<Br>\nYou can then write something as simple as:</p>\n\n<pre><code>foreach ($period as $savedDate)\n{\n switch ($recurring)\n {\n case 'None':\n if ($gendate == $savedDate)\n {//DateTime instances can be compared like so, no format needed\n renderNonRecurringEvent($event);\n }\n break;\n }\n}\n</code></pre>\n\n<p>Notice how I don't pass every individual key of the array to the render function, but instead just pass <em>all of the event-related data</em>. Doesn't that make sense to you?<br>\nOf course, looking at this function's tendency to <code>echo</code>, I take it your <code>render*</code> functions echo, too. Just have them <em>return</em> the output string and concatenate it to the <code>$outString</code> I mentioned in the beginning of my answer:</p>\n\n<pre><code>$outString .= renderEvent($event);\n</code></pre>\n\n<p>Now, for the big one:</p>\n\n<pre><code>Case 'Weekly':\n //Check margin between start and end date of recurring event\n if ($displaydate > $startdate and !$displaydate < $enddate){\n</code></pre>\n\n<p>Operator precedence... this condition is just terribly unreliable. <code>and</code> has a low precedence. Use <code>&&</code>. Always. Unless you know what you're doing.<br>\nAlso think about what you're trying to check when you write</p>\n\n<pre><code>!$displaydate < $enddate\n</code></pre>\n\n<p>Are you saying</p>\n\n<pre><code>(!$displaydate) < $enddate\n//if inverse boolean value of $displaydate < $enddate\n//ie: if $displaydate truthy, then this would evalute to:\n// if (!true) < $enddate -> false < $enddate --> 0 < $enddate\n</code></pre>\n\n<p>Or are you trying to check for:</p>\n\n<pre><code>$displaydate >= $enddate //makes a lot more sense, no?\n</code></pre>\n\n<p>For some reason, you've created a function to get the diff in weeks. What is odd is that you insist on passing the date <em>string</em> to this function, when you've already constructed a <code>DateTime</code> instance for these dates. At least pass that to the function, because I'm prepared to take a punt that this <code>datediffInWeeks</code> function creates those same instances all over. But to be honest, I'd just not bother, and write this in-line, there's not a lot too it anyway. Here's the code you have:</p>\n\n<pre><code> //Find the amount of weeks between two dates\n $weekRange = datediffInWeeks($recur['startdate'], $recur['enddate']);\n //Round down to the possible amount to display\n $weeks = ceil($weekRange / $recur['day']);\n</code></pre>\n\n<p>And this is what I'd write:</p>\n\n<pre><code>$weekRange = $recur['startdate']->diff($recur['enddate']);\n$weeks = range(0, ceil($weekRange->d/7));//d property is number of days, as int\n//to get range of number of weeks:\n$weeks = range(\n (int)$recur['startdate']->format('W'),//start from current week\n $recur['startdate']->format('W') + ceil($weekRange->d/7)\n);\n</code></pre>\n\n<p>Now once you have that, there is no point in looping over the array, is there? a simple <code>in_array</code> call, or even <code>if (min($weeks) <= $gendate->format(\"W\") && max($weeks) >= $gendate->format(\"W\"))</code> would do the trick.<br>\nThe same logic applies to the days business. That way, you can do away with all those nested loops, because that's just an unholy, slow, messy and unmaintainable mess.</p>\n\n<p><strong>PDO: Reusing prepared statements:</strong><br>\nHere's an example of how I'd query the data using PDO, re-using prepared statements:</p>\n\n<pre><code>//outside the loop, call prepare\n$stmt = $pdo->prepare('SELECT * FROM recur WHERE title = :title AND name = :name');\n//note no quotes, just :title and :name\n$events = $pdo->query('SELECT * FROM calendar WHERE Allowed = \"Allowed\" ORDER BY starttime ASC');//order by <field> ASC/DESC\nwhile ($event = $events->fetch(PDO::FETCH_ASSOC))\n{//inside call execute as much as you want\n $stmt->execute(\n array(\n ':name' => $event['name'],\n ':title' => $event['title']\n )\n );\n $recur = $stmt->fetch(PDO::FETCH_ASSOC);\n}\n</code></pre>\n\n<p><strong>General recommendations</strong><br>\nRefactor this code ASAP. Learn about more modern MySQL extensions, <code>PDO</code> or <code>mysqli_*</code>. Both are more powerful than <code>mysql_*</code>, but <code>mysqli_*</code> is the most powerful of the lot. However, its API is messy (alowing both OO and procedural style programming), and has a lot more pitfalls owing to its complexity.<br>\nI haven't touched on this in my answer, but <em>never assume all is going well</em>. Check what functions return. They could return <code>false</code>, <code>0</code> or <code>null</code>, or they could throw an <code>Exception</code>, to let you know all is not well. Don't ignore those situations, deal with them.<br>\nWrite a couple of one-liners down as guide lines, for example:</p>\n\n<ul>\n<li>Prepare queries that use variables in the WHERE clause, by using prepared statements</li>\n<li>If you have to scroll to read through a function, you're doing too much in one function. Split the logic over several functions.</li>\n<li>DRY</li>\n<li>Only <code>SELECT</code> what you need</li>\n<li>Functions don't <code>echo</code>, they return. Think of them as books. They contain information, you read it, and can then relay that information to others. A book doesn't read itself out loud to other people. That's not its function.</li>\n<li>errors happen. That's a fact. Check the return values of functions (<code>false</code>, <code>0</code>, <code>null</code> or wrap them in a <code>try-catch</code> block). Check the manual, to see what each function returns in case something goes wrong.</li>\n<li>Learn about prepared statements and injection. This implies changing the MySQL extension you use, <a href=\"http://www.php.net/manual/en/mysqlinfo.api.choosing.php\" rel=\"nofollow noreferrer\">this page helps you with that</a></li>\n<li>Debugging implies <em>seeing the bugs</em>. Therefore <code>E_STRICT | E_ALL</code> + <code>display_errors</code> are a must.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T18:03:16.130",
"Id": "80034",
"Score": "0",
"body": "Thank you so much for the hard work. I am new to php but I understand what you are saying and I will post my new code. Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T07:24:24.387",
"Id": "80109",
"Score": "0",
"body": "@PieterdeVries: It's all in a day's work for [bicycle repair man](http://chinahands.files.wordpress.com/2010/05/bicycle-repair-man.jpg) ;) Do let me know when and where you've posted your updated code, in case you want it reviewed"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:18:47.433",
"Id": "80389",
"Score": "0",
"body": "Well I have some issues with figuring out some of the things. I am still perfecting it and just so you know the case clause is for repeated events. You may see the form at http://logicalwebhost.com/goats/calendar/calendar_entry.php BTW the reason I used mysql instead of opd or MySQLi is because the project was started in that by another user but I did know about the change in php."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T02:59:48.870",
"Id": "80476",
"Score": "0",
"body": "Here is my new code: http://codereview.stackexchange.com/questions/46133/too-many-nested-blocks-fixed-but-not-sure-if-this-way-is-right"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T10:27:11.023",
"Id": "45814",
"ParentId": "45801",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "45814",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T05:17:57.210",
"Id": "45801",
"Score": "4",
"Tags": [
"php",
"beginner"
],
"Title": "I have a huge function filled with nested blocks"
} | 45801 |
<p>I am using using the following code to choose the transport layer security protocol while issuing a request to server. Could someone please review it.
This is in reference to the following question:
<a href="https://stackoverflow.com/questions/22657498/i-want-to-choose-the-transport-layer-security-protocol-in-urllib2">https://stackoverflow.com/questions/22657498/i-want-to-choose-the-transport-layer-security-protocol-in-urllib2</a></p>
<pre><code>import ssl
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager
class MyAdapter(HTTPAdapter):
def init_poolmanager(self, connections, maxsize, block=False):
self.poolmanager = PoolManager(num_pools=connections,
maxsize=maxsize,
block=block,
ssl_version=ssl.PROTOCOL_SSLv3)
s = requests.Session()
myAdp = MyAdapter()
myAdp.init_poolmanager(5, 100)
s.mount('https://', myAdp)
try:
url = "https://www.google.com"
feed = s.get(url, verify = True)
print feed.text
except Exception as e:
print "Exception:", e
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T09:09:42.397",
"Id": "45812",
"Score": "4",
"Tags": [
"python",
"https"
],
"Title": "Choose the Transport Layer Security protocol - requests python"
} | 45812 |
<p>In an effort to teach myself some python and programming in general I made a Sudoku Solver (as many others have done before me from what I can tell). The one thing that bugs me a little is my use of deepcopy which I think I can avoid by implementing __eq__ in my classes.</p>
<p>My questions:</p>
<ol>
<li>Is this understanable?</li>
<li>How Pythonic is this?</li>
<li>Are there any glaring bugs / convention mistakes / missuses of structures?</li>
<li>How can I introduce unit testing?</li>
</ol>
<p>Full code (400 lines) can be found <a href="https://github.com/overdetermined/SodokuSolver/blob/master/SudokuCell.py" rel="nofollow">here</a>.</p>
<pre><code>class SudokuCell:
"""Most Basic Sudoku Cell
-Contains 9 Possible values, initialized at true
-Can return the possible cases
"""
def __init__(self):
self.values = {1: True,2:True,3:True,4:True,5:True,6:True,7:True,8:True,9:True}
def check_cell(self):
"""return all values still possible"""
out = []
for k,d in self.values.items():
if d==True:
out.append(k)
return out
def set_cell(self, val):
"""set all values to False except val"""
for k,d in self.values.items():
if k != val:
self.values[k] = False
self.values[val]=True
def reset_cell(self):
self.values = {1: True,2:True,3:True,4:True,5:True,6:True,7:True,8:True,9:True}
class SudokuGrid:
def __init__(self):
self.Cells = []
for x in range(0,81):
Cell = SudokuCell()
self.Cells.append(Cell)
self.groups = self.__define_groups__()
def __eq__(self, other):
return self.Cells == other.Cells
def print_Grid(self):
"""print Sudoku Grid"""
values=self.__str_fill__()
print '-------------------'
for x in range (0,3):
print '|'+values[x*9] +' '+ values[x*9+1] +' ' + values [x*9+2] + '|'+values[x*9+3] +' '+ values[x*9+4] +' ' + values [x*9+5] + '|'+values[x*9+6] +' '+ values[x*9+7] +' ' + values [x*9+8] + '|'
print '*-----*-----*-----*'
for x in range (3,6):
print '|'+values[x*9] +' '+ values[x*9+1] +' ' + values [x*9+2] + '|'+values[x*9+3] +' '+ values[x*9+4] +' ' + values [x*9+5] + '|'+values[x*9+6] +' '+ values[x*9+7] +' ' + values [x*9+8] + '|'
print '*-----*-----*-----*'
for x in range (6,9):
print '|'+values[x*9] +' '+ values[x*9+1] +' ' + values [x*9+2] + '|'+values[x*9+3] +' '+ values[x*9+4] +' ' + values [x*9+5] + '|'+values[x*9+6] +' '+ values[x*9+7] +' ' + values [x*9+8] + '|'
print '-------------------'
def check_gridsolved(self):
for x in self.Cells:
if len(x.check_cell())!=1:
return False
return True
def __define_groups__(self):
"""we need to know how the grid is formed"""
groups=[]
#rows
for x in range(0,9):
groups.append([x*9,x*9+1,x*9+2,x*9+3,x*9+4,x*9+5,x*9+6,x*9+7,x*9+8])
#collumns
for x in range(0,9):
groups.append([x,x+9,x+18,x+27,x+36,x+45,x+54,x+63,x+72])
#squares 1
for x in range(0,3):
groups.append([x*3,x*3+1,x*3+2,x*3+9,x*3+10,x*3+11,x*3+18,x*3+19,x*3+20])
#squares 2
for x in range(9,12):
groups.append([x*3,x*3+1,x*3+2,x*3+9,x*3+10,x*3+11,x*3+18,x*3+19,x*3+20])
#squares 3
for x in range(18,21):
groups.append([x*3,x*3+1,x*3+2,x*3+9,x*3+10,x*3+11,x*3+18,x*3+19,x*3+20])
return groups
def __str_fill__(self):
"""get Row for Print"""
out =[]
i=0
for x in self.Cells:
out.append('*')
if len(x.check_cell())==1:
out[i]=str(x.check_cell()[0])
i+=1
return out
class Sudoku_Solver():
'''This class is an iterative non-exhaustive search algorithm for the SudokuGrid'''
def __init__(self):
self.Branch = collections.OrderedDict() #{} #stores the Branch info
self.inputGrid = SudokuGrid()
self.workingGrid = SudokuGrid()
self.solved = False
self.unsolvable = False
self.solutionGrids = []
def load(self,SudokuGrid):
self.inputGrid = copy.deepcopy(SudokuGrid)
self.workingGrid = copy.deepcopy(SudokuGrid)
def simple_solver(self):
iteration = 1
laststate = SudokuGrid()
while ((laststate == self.workingGrid)==False): #
laststate = copy.deepcopy(self.workingGrid) #want to get rid of deepcopy...
iteration += 1
if 0==self.__slv_iterate_truncation__():
#print 'er'
return 0 #cannot solve
if 0==self.__slv_iterate_singlefind__():
#print 'bad eval'
return 0 #cannot solve
if iteration > 30:
print 'ERROR too many iterations'
break
return iteration
def solve(self):
iteration = 0
simple_iteration = self.simple_solver()
if (simple_iteration)==0:
self.unsolvable = True
if (self.workingGrid.check_gridsolved()==False): #start branching
self.workingGrid.print_Grid()
print len(Solver.Branch)
self.Branch.update(self.__slv_find_firstchoice__()) #seed
self.__slv_iterate_over_branch()
self.solutionGrids.append(self.workingGrid)
self.workingGrid.print_Grid()
'''MORE CODE'''
</code></pre>
<p>Functionality: basic block is a <code>SudokuCell</code> which can be a value from 1 to 9. A <code>SudokuGrid</code> contains 81 cells as the traditional puzzle. Groups signify the rules of the game (i.e Groups in which a number can only occur once). I have a simple solver which iterates through the groups and checks for inconsistencies (values in a cell that shouldn't be elsewhere) and single values (only one cell has this). After that it is just continuing guesswork. The solver works on all the sudokus I have tried (maybe 5).</p>
<p>I also wanted to learn about unit testing unfortunately had so many implementation questions and too little time to really consider it, but I am thinking of introducing that next.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T12:18:50.317",
"Id": "79961",
"Score": "2",
"body": "New style classes should be derived from `object`. i.e. `class SudokuGrid:` should be `class SudokuGrid(object):`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T14:02:56.730",
"Id": "79967",
"Score": "0",
"body": "Use `__str__` instead of `print_Grid` for `SudokuGrid`. https://docs.python.org/2/reference/datamodel.html#special-method-names"
}
] | [
{
"body": "<p>in your class SudokuCell()</p>\n\n<p>add a function that sets all the values to a boolean, e.g. ...</p>\n\n<pre><code>def reset_all_values(self, new_value):\n self.values = {}\n for i in range(1, 10):\n self.values[i] = new_value\n</code></pre>\n\n<p>Then, <strong>init</strong> can call this with True and it can replace reset_cell(). Also, in set_cell, you can just call reset_all_values(False) and then do </p>\n\n<pre><code>self.values[val] = True\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T13:16:48.773",
"Id": "45821",
"ParentId": "45817",
"Score": "1"
}
},
{
"body": "<p>First : the comments about aesthetic.</p>\n\n<p>You can use <strong>List/set/dict comprehension</strong> more than you do :</p>\n\n<hr>\n\n<pre><code>self.values = {1: True,2:True,3:True,4:True,5:True,6:True,7:True,8:True,9:True}\n</code></pre>\n\n<p>becomes :</p>\n\n<pre><code>self.values = {n:True for n in range(10)}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>self.values = dict.fromkeys(range(10), True)\n</code></pre>\n\n<hr>\n\n<pre><code> out = []\n for k,d in self.values.items():\n if d==True:\n out.append(k) \n</code></pre>\n\n<p>becomes :</p>\n\n<pre><code> out = [k for k,d in self.values.items() if d]\n</code></pre>\n\n<p>From <a href=\"http://legacy.python.org/dev/peps/pep-0008/#id40\" rel=\"nofollow noreferrer\">PEP 8</a> :</p>\n\n<blockquote>\n <p>Don't compare boolean values to True or False using ==.</p>\n</blockquote>\n\n<hr>\n\n<pre><code>print '|'+values[x*9] +' '+ values[x*9+1] +' ' + values [x*9+2] + '|'+values[x*9+3] +' '+ values[x*9+4] +' ' + values [x*9+5] + '|'+values[x*9+6] +' '+ values[x*9+7] +' ' + values [x*9+8] + '|'\n</code></pre>\n\n<p>becomes :</p>\n\n<pre><code>print '|'+ ' '.join(values[x*9+i] for i in range(9)) + '|'\n</code></pre>\n\n<p>From <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> :</p>\n\n<blockquote>\n <p>For example, do not rely on CPython's efficient implementation of\n in-place string concatenation for statements in the form a += b or a =\n a + b. This optimization is fragile even in CPython (it only works for\n some types) and isn't present at all in implementations that don't use\n refcounting. In performance sensitive parts of the library, the\n ''.join() form should be used instead. This will ensure that\n concatenation occurs in linear time across various implementations.</p>\n</blockquote>\n\n<hr>\n\n<pre><code> for x in self.Cells:\n if len(x.check_cell())!=1:\n return False\n return True\n</code></pre>\n\n<p>becomes :</p>\n\n<pre><code> return all(len(x.check_cell()) == 1 for x in self.Cells)\n</code></pre>\n\n<hr>\n\n<pre><code>groups.append([x*9,x*9+1,x*9+2,x*9+3,x*9+4,x*9+5,x*9+6,x*9+7,x*9+8])\n</code></pre>\n\n<p>becomes : </p>\n\n<pre><code>groups.append([x*9+i for i in range(9)])\n</code></pre>\n\n<p>. </p>\n\n<pre><code>groups.append([x,x+9,x+18,x+27,x+36,x+45,x+54,x+63,x+72])\n</code></pre>\n\n<p>becomes :</p>\n\n<pre><code>groups.append([x+9*i for i in range(9)])\n</code></pre>\n\n<p>.</p>\n\n<pre><code>groups.append([x*3,x*3+1,x*3+2,x*3+9,x*3+10,x*3+11,x*3+18,x*3+19,x*3+20])\n</code></pre>\n\n<p>becomes :</p>\n\n<pre><code>groups.append([x*3+i*9+j for i in range(3) for j in range(3)])\n</code></pre>\n\n<p>.</p>\n\n<hr>\n\n<pre><code> out =[]\n i=0\n for x in self.Cells:\n out.append('*')\n if len(x.check_cell())==1:\n out[i]=str(x.check_cell()[0])\n i+=1\n</code></pre>\n\n<p>becomes first using <a href=\"https://docs.python.org/2.7/library/functions.html#enumerate\" rel=\"nofollow noreferrer\">enumerate</a> :</p>\n\n<pre><code> out =[]\n for i,x in enumerate(self.Cells):\n out.append('*')\n if len(x.check_cell())==1:\n out[i]=str(x.check_cell()[0])\n</code></pre>\n\n<p>then, with ternary operator</p>\n\n<pre><code> out =[]\n for x in self.Cells:\n out.append(str(x.check_cell()[0]) if len(x.check_cell())==1 else '*')\n</code></pre>\n\n<p>finally with list comprehension :</p>\n\n<pre><code> out =[str(x.check_cell()[0]) if len(x.check_cell())==1 else '*' for x in self.Cells]\n</code></pre>\n\n<h2>----------</h2>\n\n<p><strong>Underscore</strong> is a conventional variable name for a value that we don't use (more info <a href=\"https://stackoverflow.com/questions/2745018/python-is-there-a-dont-care-symbol-for-tuple-assignments\">here</a>).</p>\n\n<pre><code> for x in range(81):\n Cell = SudokuCell()\n self.Cells.append(Cell)\n</code></pre>\n\n<p>becomes :</p>\n\n<pre><code> for _ in range(81):\n Cell = SudokuCell()\n self.Cells.append(Cell)\n</code></pre>\n\n<h2>----------</h2>\n\n<p>Now, more relevant comments :</p>\n\n<p><strong>Data structure</strong> : at the moment, you are representing cells with dictionnary mapping values to whether they are possible or not. A dictionnary is likely to be a bit overkill here : you might as well use :</p>\n\n<ul>\n<li>a simple list to perform exactly the same mapping (reindexing your 1 to 9 range to a 0 to 8 range would be a good option).</li>\n<li>a set to convey the same information : a value is possible if and only if it is in the set.</li>\n</ul>\n\n<hr>\n\n<p>Whenever you are using this kind of logic, you should try to keep your structure as small as possible for performance reasons but also because it will make things harder to get wrong. In your case, there probably no need to store the result of <code>__define_groups__()</code> in each instance of the class because the value returned is always the same, you could compute this one and for all and use it for all instances.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T15:39:07.940",
"Id": "79993",
"Score": "1",
"body": "And `self.values = {n:True for n in range(0,10)}` becomes: `self.values = dict.fromkeys(range(0,10), True)`. You can also drop the `[` and `]` in the `join` call and avoid building a useless `list`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T17:51:17.543",
"Id": "80032",
"Score": "0",
"body": "I'm am overwhelmed by the thoroughness of your answer. Thank you. Inefficiencies in the declarations was one thing I worried about. I will try to implement these in the coming week."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T22:19:53.903",
"Id": "80073",
"Score": "1",
"body": "Is there a reason for using `range(0,10)` instead of `range(10)`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T08:27:39.127",
"Id": "80111",
"Score": "0",
"body": "No good reason : I have updated my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T13:41:58.957",
"Id": "80140",
"Score": "0",
"body": "Hmm.. that underscore notation is pretty neat! What would be the convention for a nested loop with another don't-care? Double underscore?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T14:02:18.097",
"Id": "80144",
"Score": "0",
"body": "This is going out of my field of knowledge but I reckon using the same variable name for nested loop is not a real issue with `for` loops (in the sense that it will perform the number of iteration you'd expect). You can reuse underscore everywhere and it should work : `len([0 for _ in range(10) for _ in range(10)]) == 100`. I am not sure what the usage is in that case."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T13:39:48.313",
"Id": "45824",
"ParentId": "45817",
"Score": "15"
}
},
{
"body": "<p>Instead of having lots of numbers, replace them with constants ...</p>\n\n<pre><code>ROW_STARTS = range(0, 73, 9)\nCOLUMN_STARTS = range(9)\nCOLUMN_INCREMENTS = range(0, 73, 9)\nSQUARE_STARTS = [0, 3, 6, 27, 30, 33, 54, 57, 60]\nSQUARE_INCREMENTS = [0, 1, 2, 9, 10, 11, 18, 19, 20]\n\nROWS = [[x+y for y in range(9)] for x in ROW_STARTS]\nCOLUMNS = [[x+y for y in COLUMN_INCREMENTS] for x in COLUMN_STARTS]\nSQUARES = [[x+y for y in SQUARE_INCREMENTS] for x in SQUARE_STARTS]\n</code></pre>\n\n<p>Then, in your define_groups function, you would ...</p>\n\n<pre><code>groups = []\ngroups.append([x[:] for x in ROWS])\ngroups.append([x[:] for x in COLUMNS])\ngroups.append([x[:] for x in SQUARES])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T17:52:20.977",
"Id": "80033",
"Score": "0",
"body": "Thank you for the prompt answers. These are things I can easily implement."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T14:25:30.840",
"Id": "45833",
"ParentId": "45817",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T12:14:46.377",
"Id": "45817",
"Score": "12",
"Tags": [
"python",
"unit-testing",
"sudoku"
],
"Title": "Deepcopy usage in a Sudoku solver"
} | 45817 |
<p>I have implemented a HTML table sorting. I actually implemented a sort first using jQuery and then modified it based on the answer to <a href="https://codereview.stackexchange.com/questions/37632/how-should-i-sort-an-html-table-with-javascript-in-a-more-efficient-manner?newreg=4b372a7633204fa09a28b55a6443b687">this question</a> for performance as I had done the same mistake. My question is how to make sure if the code I have written is stable or not?</p>
<p>I know that the stability of sorting depends on the sort method's algorithm and that changes with the browser, and according to <a href="http://mdn.beonex.com/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/sort.html" rel="nofollow noreferrer">this page</a>, mozilla's implementation of sorting is stable, but when I checked with my code, it doesn't seem to be stable. Could someone have a look at my code and let me know how to determine whether the sort performed is stable or not?</p>
<pre><code><html><head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
asc = new Array();
for (var a=0;a<$("tbody tr:eq(0) td").length;a++) asc[a] = 1;
$("th").click(
function(){
c = $(this).index();
var rows = $("tbody tr");
var rlen = rows.length;
var arr = new Array();
var cols;
for(var i=0;i<rlen;i++){
cols = $("tbody tr:eq("+i+") td");
var clen = cols.length;
arr[i] = new Array();
for (var j=0;j<clen;j++){
arr[i][j] = $("tbody tr:eq("+i+") td:eq("+j+")").html();
}
}
arr.sort(function(a,b){
if (a[c]==b[c]) return 0;
else if(a[c]<b[c]) return -1 * asc[c];
else return asc[c];
});
for (var i=0;i<rlen;i++){
arr[i] = "<td>" + arr[i].join("</td><td>") + "</td>"
}
$("tbody").html("<tr>"+arr.join("</tr><tr>")+"</tr>");
asc[c] = (asc[c]==1)?-1:1;
});});
</script>
<style type="text/css">
table { border-collapse: collapse; border: none;}
th,
td {
border: 1px solid black;
padding: 4px 16px;
font-family: Times New Roman;
font-size: 24px;
text-align: left;
}
th {
background-color: #D8D8D8;
cursor: pointer;
}
</style>
</head><body>
<table>
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tbody>
<tr>
<td>March</td>
<td>180</td>
</tr>
<tr>
<td>January</td>
<td>100</td>
</tr>
<tr>
<td>February</td>
<td>80</td>
</tr>
<tr>
<td>Januray</td>
<td>40</td>
</tr>
<tr>
<td>March</td>
<td>200</td>
</tr>
<tr>
<td>February</td>
<td>90</td>
</tr>
</tbody>
</table>
</body></html>
</code></pre>
<p>And if there can be any improvements for efficiency, can anyone point that out as well?</p>
| [] | [
{
"body": "<p>From a once over;</p>\n\n<ul>\n<li>The easiest way to be sure that you sort algorithm is stable, is to write you own sort algorithm.</li>\n<li>The second easiest way to be sure is to pass in each array entry object it's position in the array ( you could set this after your <code>arr[i][j]</code> assignment ). If <code>(a[c]==b[c])</code> then you would not return <code>0</code>, but you would return <code>-1</code> or <code>+1</code> based on their original position in the array</li>\n<li>You did not declare <code>c</code> and <code>asc</code> with <code>var</code></li>\n<li><code>var arr = [];</code> is preferred to <code>var arr = new Array();</code></li>\n<li>One single comma separated <code>var</code> statement is preferred over many <code>var</code> statements</li>\n<li>You declare <code>var i</code> twice, since <code>var i</code> declares <code>i</code> for the scope of the function, you do not need to declare it again.</li>\n<li>Your indenting is off, you should look into that</li>\n<li>Assigning a function to <code>document.ready</code> is old skool, you should look into using <a href=\"https://stackoverflow.com/questions/6902033/element-onload-vs-element-addeventlistenerload-callbak-false\">addEventListener</a> or simple using <a href=\"http://api.jquery.com/ready/\" rel=\"nofollow noreferrer\">$( handler )</a>;.</li>\n<li><p>You should cache the value of <code>a<$(\"tbody tr:eq(0) td\").length</code></p>\n\n<pre><code> for (var a = 0, count = $(\"tbody tr:eq(0) td\").length; a < count ; a++)\n</code></pre></li>\n<li><p>On my second point, imagine you are sorting people by their age, in a stable manner:</p></li>\n</ul>\n\n<p>Bob, 23 years\nJohn, 12 years\nTricia, 23 years</p>\n\n<p>becomes</p>\n\n<p>Bob, 23 years\nTricia, 23 years\nJohn, 12 years</p>\n\n<p>it would be unstable if the order was</p>\n\n<p>Tricia, 23 years\nBob, 23 years\nJohn, 12 years</p>\n\n<p>because Tricia was initially below Bob, she should stay below Bob. \nYou can accomplish this by comparing the original position of the 2 records and making sure that if the age is the same, you make sure the original order is respected.</p>\n\n<p>I hope this example made it clearer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T07:53:12.227",
"Id": "80110",
"Score": "0",
"body": "Thanks for the answer konijn, I implement my own sorting algorithm to ensure stability, but I did not understand your second point. Could you please explain that a bit more?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T15:41:02.750",
"Id": "80157",
"Score": "0",
"body": "Thanks again for the explanation, it definitely made it a lot clearer..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T14:09:43.070",
"Id": "45829",
"ParentId": "45818",
"Score": "3"
}
},
{
"body": "<p>Additionally to what @konijn wrote:</p>\n\n<p>Instead of \"reselecting\" the rows/cells in your first loop, use the already selected items. Also use the child selector (<code>></code>)</p>\n\n<pre><code>var rows = $(\"tbody > tr\"),\n rlen = rows.length,\n arr = [];\nfor (var i = 0; i < rlen; i++){\n var cols = rows.eq(i).find(\"> td\");\n var clen = cols.length;\n arr[i] = [];\n for (var j = 0; j < clen; j++){\n arr[i][j] = cols.eq(j).html();\n }\n}\n</code></pre>\n\n<p>Also instead of rebuilding the whole table, consider storing references to each row with the data and just re-append all existing rows in the correct order.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T14:53:58.067",
"Id": "45837",
"ParentId": "45818",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "45829",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T12:21:14.353",
"Id": "45818",
"Score": "5",
"Tags": [
"javascript",
"jquery",
"performance",
"sorting"
],
"Title": "How to verify if HTML table sort is stable or not?"
} | 45818 |
<p>This snippet from a downloader callable handles HTTP status codes. I need critique on both the style (<code>for</code> or <code>do-while</code> loop better here?) and functionality. Should I manage the delay differently? Do I need to handle <code>InterruptedException</code> specifically?</p>
<pre><code>HttpURLConnection connection = null;
boolean connected=false;
outer:
for(int retry=0;retry<=RETRIES&&!connected;retry++)
{
if(retry>0) {log.warning("retry "+retry+"/"+RETRIES);Thread.sleep(RETRY_DELAY_MS);}
connection = (HttpURLConnection)entries.openConnection();
connection.connect();
switch(connection.getResponseCode())
{
case HttpURLConnection.HTTP_OK: log.fine(entries +" **OK**");connected=true;break; // fine, go on
case HttpURLConnection.HTTP_GATEWAY_TIMEOUT: log.warning(entries+" **gateway timeout**");break;// retry
case HttpURLConnection.HTTP_UNAVAILABLE: System.out.println(entries+ "**unavailable**");break;// retry, server is unstable
default: log.severe(entries+" **unknown response code**.");break outer; // abort
}
}
connection.disconnect();
log.severe("Aborting download of dataset.");
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-19T16:35:54.430",
"Id": "277235",
"Score": "1",
"body": "You got labels? Goto style?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-01T15:05:21.573",
"Id": "437555",
"Score": "0",
"body": "@fnc12: I try to refrain using them but sometimes I don't find a better option. That's one of the reasons I put this in code review."
}
] | [
{
"body": "<h2>Readability</h2>\n<p>Let's reformat your code quickly:</p>\n<blockquote>\n<pre><code> HttpURLConnection connection = null;\n boolean connected = false;\n outer: for (int retry = 0; retry <= RETRIES && !connected; retry++) {\n if (retry > 0) {\n log.warning("retry " + retry + "/" + RETRIES);\n Thread.sleep(RETRY_DELAY_MS);\n }\n connection = (HttpURLConnection) entries.openConnection();\n connection.connect();\n switch (connection.getResponseCode()) {\n case HttpURLConnection.HTTP_OK:\n log.fine(entries + " **OK**");\n connected = true;\n break; // fine, go on\n case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:\n log.warning(entries + " **gateway timeout**");\n break;// retry\n case HttpURLConnection.HTTP_UNAVAILABLE:\n System.out.println(entries + "**unavailable**");\n break;// retry, server is unstable\n default:\n log.severe(entries + " **unknown response code**.");\n break outer; // abort\n }\n }\n connection.disconnect();\n log.severe("Aborting download of dataset.");\n</code></pre>\n</blockquote>\n<p>Fixed:</p>\n<ul>\n<li><p>1-liners are hard to read:</p>\n<pre><code> case HttpURLConnection.HTTP_UNAVAILABLE: System.out.println(entries+ "**unavailable**");break;// retry, server is unstable\n</code></pre>\n</li>\n<li><p>spacing inside for-loop conditions:</p>\n<pre><code> for(int retry=0;retry<=RETRIES&&!connected;retry++)\n</code></pre>\n</li>\n<li><p>indentation - 1-space indentation is <em>'just wrong'™</em>.</p>\n</li>\n</ul>\n<h2>Functionality</h2>\n<p>Right, how does this code work? There are a few problems I can (now) see in here:</p>\n<ol>\n<li>On HTTP_OK, it <code>breaks</code> out of the switch, then it exits the loop (because <code>&& !connected</code>), and then immediately disconnects and logs a severe error? This can't be right?</li>\n<li><code>HTTP_GATEWAY_TIMEOUT</code> logs a warning.... great, but <code>HTTP_UNAVAILABLE</code> does a <code>System.out.println</code></li>\n</ol>\n<p>The <code>InterruptedException</code> handling is not shown here. There are articles on how to do this properly. Google up on that.</p>\n<h2>Suggestion</h2>\n<p>I recommend a sub-function, with a do-while loop (the following is a quick hack-up - untested):</p>\n<pre><code>private static final HttpURLConnection getConnection(URL entries) throws InterruptedException{\n int retry = 0;\n boolean delay = false;\n do {\n if (delay) {\n Thread.sleep(RETRY_DELAY_MS);\n }\n HttpURLConnection connection = (HttpURLConnection)entries.openConnection();\n switch (connection.getResponseCode()) {\n case HttpURLConnection.HTTP_OK:\n log.fine(entries + " **OK**");\n return connection; // **EXIT POINT** fine, go on\n case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:\n log.warning(entries + " **gateway timeout**");\n break;// retry\n case HttpURLConnection.HTTP_UNAVAILABLE:\n log.warning(entries + "**unavailable**");\n break;// retry, server is unstable\n default:\n log.severe(entries + " **unknown response code**.");\n break; // abort\n }\n // we did not succeed with connection (or we would have returned the connection).\n connection.disconnect();\n // retry\n retry++;\n log.warning("Failed retry " + retry + "/" + RETRIES);\n delay = true;\n \n } while (retry < RETRIES);\n \n log.severe("Aborting download of dataset.");\n \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T14:33:55.873",
"Id": "79977",
"Score": "1",
"body": "You are right, the last severe log should be conditional on !connected. I didn't even think about creating a subfunction out of it but it is an excellent idea because I need the same functionality elsewhere. The indentation however I changed to fit it into the box, I use tabs normally."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-20T18:42:54.347",
"Id": "241069",
"Score": "0",
"body": "@rolfl I also have question on http client which I posted [here](http://codereview.stackexchange.com/questions/128367/efficiently-using-apache-httpclient-in-multithreaded-environment). Just wanted to see if you can help CR my question. I haven't got any response so thought to check with you since I saw you answered lot of http related questions."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T13:05:21.553",
"Id": "45820",
"ParentId": "45819",
"Score": "11"
}
},
{
"body": "<p>Two things to add:</p>\n\n<ol>\n<li><p>I'd print that response code here to the log:</p>\n\n<blockquote>\n<pre><code>log.severe(entries + \" **unknown response code**.\");\n</code></pre>\n</blockquote>\n\n<p>It would help debugging.</p></li>\n<li><p>Retry seems a good idea first but one of the recent Java Posse episode (<a href=\"http://javaposse.com/java-posse-442\" rel=\"nofollow\">#442 Roundup ‘13 - Big Data Bloopers</a>) has an interesting thought: This might not be that you really want. If there's a problem on the other side it might just makes the thing worse and it probably performs a DoS attack.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T09:02:45.670",
"Id": "80702",
"Score": "0",
"body": "That's why I double the delay after every retry. I hope that is enough to not create a DoS."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T01:23:32.107",
"Id": "45902",
"ParentId": "45819",
"Score": "2"
}
},
{
"body": "<p>Working Solution</p>\n\n<pre><code> public int callAPI() {\n return 1;\n }\n\n\n\n public int retrylogic() throws InterruptedException, IOException{\n int retry = 0;\n int status = -1;\n boolean delay = false;\n do {\n if (delay) {\n Thread.sleep(2000);\n }\n\n try {\n status = callAPI();\n }\n catch (Exception e) {\n System.out.println(\"Error occured\");\n status = -1;\n }\n finally {\n switch (status) {\n case 200:\n System.out.println(\" **OK**\");\n return status; \n default:\n System.out.println(\" **unknown response code**.\");\n break;\n }\n retry++;\n System.out.println(\"Failed retry \" + retry + \"/\" + 3);\n delay = true;\n } \n }while (retry < 3);\n\n return status;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-01T15:22:19.893",
"Id": "437564",
"Score": "3",
"body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read [Why are alternative solutions not welcome?](https://codereview.meta.stackexchange.com/a/8404/120114)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-01T15:03:23.510",
"Id": "225359",
"ParentId": "45819",
"Score": "-1"
}
}
] | {
"AcceptedAnswerId": "45820",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T12:22:46.883",
"Id": "45819",
"Score": "8",
"Tags": [
"java",
"error-handling",
"http"
],
"Title": "HttpURLConnection response code handling"
} | 45819 |
<p>I have a class used to return a single integer, but think there is room for improvement. The class should only return a single row every time and if no row is found it might be a good idea to throw an error from the class rather than from the calling code which will break when the integer comes back as zero.</p>
<p>The function below is called from a sync application that is returning a primary key in order to make an update.</p>
<pre><code> public static int GetCommuteDataID(CommuteData commuteData)
{
int commuteDataID = 0;
using (var db = new CarbonContext())
{
var returnCommuteData = from e in db.CommuteDatas
where e.id == commuteData.id &&
e.SurveyID == commuteData.SurveyID &&
e.SurveyYear == commuteData.SurveyYear
select e.CommuteDataID;
foreach (var item in returnCommuteData)
commuteDataID = Convert.ToInt32(item.ToString());
}
return commuteDataID;
}
</code></pre>
<p>Here is the code that calls GetCommuteDataID:</p>
<pre><code>//Make sure the record does not exist
if (!CommuteDataRepository.CommuteDataExists(localCommuteData))
db.CommuteDatas.Add(localCommuteData);
else
{
localCommuteData.CommuteDataID = CommuteDataRepository.GetCommuteDataID(localCommuteData);
db.Entry(localCommuteData).State = System.Data.EntityState.Modified;
}
</code></pre>
<p>Here is the new function:</p>
<pre><code>public static int GetCommuteDataID(int? id, int surveyID, int surveyYear)
{
using (var db = new CarbonContext())
{
return db.CommuteDatas
.Where(cd => cd.id == id &&
cd.SurveyID == surveyID &&
cd.SurveyYear == surveyYear)
.Select(cd => (int)cd.CommuteDataID)
.SingleOrDefault();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T14:31:03.637",
"Id": "79975",
"Score": "0",
"body": "I don't quite understand your question. Are you looking to add a new implementation to the code ? What it this code suppose to do, retrieve an id or something ? And where is the exception you're talking about ? Could clarify your question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T14:36:58.420",
"Id": "79978",
"Score": "0",
"body": "I don't think you need to get the primary key of an object for any update transaction. If you did things right, you should be able to just call: `context.update({Object} commuteData);`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T14:42:31.977",
"Id": "79981",
"Score": "0",
"body": "The function is for a sync application. I do not get my primary key value from the web service JSON that is returned. So, I see if a row exists based on three other values, then return my primary key to use for the update."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T14:59:31.727",
"Id": "79988",
"Score": "0",
"body": "@AllanHorwitz why not change the JSON then? And doesn't this also mean you are maintaining two data-layers and storages in one application?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T15:00:47.730",
"Id": "79990",
"Score": "0",
"body": "The JSON is coming from a vendor, so I cannot change it."
}
] | [
{
"body": "<p>I see a number of things wrong with this implementation:</p>\n\n<p>First, You already have a <code>CommuteData</code> entity. Why are you using it to go back to the database to retrieve a property that's already on it (ie: <code>commuteData.CommuteDataId</code>)? This makes me very suspicious of any calling code (you may want to post a use case for clarity).</p>\n\n<p>That point aside, if there's a possibility that the method will be unable to return, it should throw an exception if an invalid state is encountered, or not return a number that is invalid (ie: 0).</p>\n\n<p>To combat this, you could go with one of these patterns:</p>\n\n<pre><code>// Throw an exception if there is no applicable CommuteDataId but one\n// is always expected to be available when calling this method:\npublic static int GetCommuteDataId(CommuteData commuteData)\n{\n ...\n // Tell EF that you only expect one and only one result.\n return something.Single()\n}\n\n// Return null if there is no applicable CommuteDataId...\npublic static int? GetCommuteDataId(CommuteData commuteData)\n\n// Return true if commuteDataId contains a valid Id.\npublic static bool TryGetCommuteDataId(CommuteData commuteData, out commuteDataId)\n</code></pre>\n\n<p>The property names you're using are also very confusing. What's the difference between <code>CommuteData.id</code> and <code>CommuteData.CommuteDataID</code>? Furthermore, the casing of your properties are not consistent: <code>id</code>, <code>CommuteDataID</code>, <code>SurveyId</code>.</p>\n\n<p>This code is also very suspicious:</p>\n\n<pre><code>commuteDataID = Convert.ToInt32(item.ToString());\n</code></pre>\n\n<p>It would appear that you are converting an int to a string, then back to an int. If it's not an int, the method should return it in it's true form instead of doing any misleading conversion that the caller has no idea about.</p>\n\n<p>Lastly, you're pulling back too much information from the database. SQL (and thus EF) can return exactly what you want in a single call.</p>\n\n<pre><code>public static int? GetCommuteDataID(int commuteDataId)\n{\n using (var db = new CarbonContext())\n {\n return db.CommuteDatas\n .Where(cd => cd.id == commuteDataId)\n .Select(cd => (int?)cd.CommuteDataID)\n .SingleOrDefault();\n }\n}\n</code></pre>\n\n<p>The updated example above still has several problems with it, but hopefully it illustrates some of the points I was trying to make.</p>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>Your updated function is almost there, but there are still some things wrong/misleading about it:</p>\n\n<pre><code>public static int GetCommuteDataID(int? id, int surveyID, int surveyYear)\n</code></pre>\n\n<p>Why is id nullable here? This implies that either:</p>\n\n<ul>\n<li>If <code>id</code> isn't provided, <code>surveyId</code> and <code>surveyYear</code> are enough to produce a unique result (otherwise you wouldn't be returning a single int).</li>\n<li><code>id</code> can be used along with <code>surveyId</code> and <code>surveyYear</code> to produce a unique result even when it's null (unlikely).</li>\n</ul>\n\n<p>Next: </p>\n\n<pre><code>.Where(cd => cd.id == id &&\n cd.SurveyID == surveyID &&\n cd.SurveyYear == surveyYear)\n</code></pre>\n\n<p>Again, are you sure this is the criteria you want to use to ensure uniqueness? Why would <code>id</code> exist if it wasn't unique?</p>\n\n<pre><code>.Select(cd => (int)cd.CommuteDataID)\n.SingleOrDefault();\n</code></pre>\n\n<p>Lastly, if CommuteDataID is already an int there's no need to cast it to one. <code>SingleOrDefault</code> has three outcomes:</p>\n\n<ol>\n<li>The query produces no result: The default value for the type of query is returned. When you <code>Select</code> an <code>int</code>, the default value is 0 because that's the default value for an <code>int</code>. I was casting to <code>int?</code> in my example so it would return null (the default for <code>int?</code>) when no value was found.</li>\n<li>The query produces one result: The result is used.</li>\n<li>The query produces multiple results: An exception is thrown because it was expected that only 0 or 1 results would be returned based on the filters you provided.</li>\n</ol>\n\n<p>If your inputs should produce one and only one result, then you should use <code>Single()</code>, which will throw an exception if 0 or multiple results are returned by the query. All of this would imply that your method arguments were enough to produce a single result which doesn't seem to be the case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T14:39:18.703",
"Id": "79979",
"Score": "0",
"body": "The CommuteDataID will be zero at the time the function is called, I am using the class to find that value. The \"id\" value is being returned from a web service. That \"id\" is the primary key used by the vendor of the service. CommuteDataID is my primary key."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T14:54:23.580",
"Id": "79984",
"Score": "1",
"body": "I believe using an \"invalid\" entity as a query argument makes the code unclear. If the `id` is what makes it unique, then why also query by `SurveyId` and `SurveyYear`? If those are filter inputs, then I would add them as different function arguments instead of passing the entity itself (or only pass the `id` like my last example shows if it is truly a primary key)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T14:59:51.713",
"Id": "79989",
"Score": "0",
"body": "Thank you for your help. I did originally use three arguments, but I changed it since all the values I need are already in a single argument (the object itself). The id might not be unique, all three arguments are needed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T18:29:55.663",
"Id": "80038",
"Score": "1",
"body": "No problem. I've updated my answer in response to your updated question that now includes more code for review."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T14:22:44.483",
"Id": "45832",
"ParentId": "45826",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "45832",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T13:59:14.370",
"Id": "45826",
"Score": "1",
"Tags": [
"c#",
"entity-framework",
"asp.net-mvc-4"
],
"Title": "Class to Return Single Integer"
} | 45826 |
<p>I wrote a BFS implementation that walks a tile-based field. It takes a function that should return true for walkable tiles and false for walls. It also takes the start and end points. It currently takes about 5 seconds to find the shortest path from (0, 0) to (1000, 1000) which isn't bad, but it really isn't great.</p>
<pre><code>import qualified Data.HashSet as H
import Data.Maybe (mapMaybe, isNothing)
import Data.List (foldl')
bfs ::
(Int -> Int -> Bool) -> -- The field function. Returns True if tile is empty, False if it's a wall
(Int, Int) -> -- Starting position
(Int, Int) -> -- Final position
Int -- Minimal steps
bfs field start end = minSteps H.empty [start] 0
where
minSteps visited queue steps
|end `elem` queue = steps + 1
|otherwise = minSteps newVisited newQueue (steps + 1)
where
(newVisited, newQueue) = foldl' aggr (visited, []) queue
aggr (vis, q) node = if H.member node vis
then (H.insert node vis, neighbors node ++ q)
else (vis, q)
neighbors (nx, ny) = filter (uncurry field) $ map (\(x, y) -> (nx + x, ny + y)) [(1, 0), (0, -1), (-1, 0), (0, 1)]
hugeField x y = x >= 0 && x <= 1000 && y >= 0 && y <= 1000
main = print $ bfs hugeField (0, 0) (1000, 1000)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T20:47:17.810",
"Id": "84233",
"Score": "0",
"body": "it seems you accidentally swapped `then` and `else` parts of the condition"
}
] | [
{
"body": "<p>I managed to make it five times faster but my solution uses some ad-hoc hacks.</p>\n\n<p>First, I replaced queue with a set. This makes checking for solution faster and allows to update <code>visited</code> with single set-union operation.</p>\n\n<pre><code>bfs field start end = minSteps H.empty (H.singleton start) 0\n where \n minSteps visited queue steps\n |end `H.member` queue = steps + 1\n |otherwise = minSteps newVisited newQueue (steps + 1)\n where\n -- add whole frontier to visited set\n newVisited = queue `H.union` visited\n -- make next frontier from non-visited neighbors\n newQueue\n = H.fromList (concatMap neighbors $ H.toList queue)\n `H.difference` newVisited\n</code></pre>\n\n<p>This change makes the program slightly slower but it allows further optimizations.</p>\n\n<p>Now to the ugly hack. Assuming you are on 64-bit machine and coordinates of empty tiles are in the range [0..2^31), it is possible to pack pair of coordinates into single <code>Int</code>. This will reduce memory footprint, improve cache locality and simplify hash calculation.</p>\n\n<p>Here are two functions to pack/unpack coordinates:</p>\n\n<pre><code>enc :: (Int,Int) -> Int\nenc (x,y) = shiftL (x .&. 0xFFFFFFFF) 32 .|. (y .&. 0xFFFFFFFF)\n\ndec :: Int -> (Int, Int)\ndec z = (shiftR z 32, z .&. 0xFFFFFFFF)\n</code></pre>\n\n<p>Use them to store packed coordinates in <code>visited</code> and <code>queue</code> and this will give you small improvement over the original code.</p>\n\n<p>So, we made some ugly changes but gained very small speedup. Now it's time for magic. Changing single line of code will make the code 5 times faster.</p>\n\n<p>Just import <code>Data.IntSet</code> instead of <code>Data.HashSet</code>.<br>\nHere is full code:</p>\n\n<pre><code>import qualified Data.IntSet as H\nimport Data.Bits\n\nbfs field start end = minSteps H.empty (H.singleton $ enc start) 0\n where\n minSteps visited queue steps\n |enc end `H.member` queue = steps + 1\n |otherwise = minSteps newVisited newQueue (steps + 1)\n where\n newVisited = queue `H.union` visited\n newQueue\n = H.fromList (concatMap (map enc.neighbors.dec) $ H.toList queue)\n `H.difference` newVisited\n\n neighbors (nx, ny)\n = filter (uncurry field)\n $ map (\\(x, y) -> (nx + x, ny + y))\n [(1, 0), (0, -1), (-1, 0), (0, 1)]\n\nenc :: (Int,Int) -> Int\nenc (x,y) = shiftL (x .&. 0xFFFFFFFF) 32 .|. (y .&. 0xFFFFFFFF)\n\ndec :: Int -> (Int, Int)\ndec z = (shiftR z 32, z .&. 0xFFFFFFFF)\n\nhugeField x y = x >= 0 && x <= 1000 && y >= 0 && y <= 1000\n\nmain = print $ bfs hugeField (0, 0) (1000, 1000)\n</code></pre>\n\n<p>The reason of such a speedup is that <code>IntSet</code> represents dense sets in much more compact form than <code>HashSet</code>. And this makes <code>union</code> and <code>difference</code> faster.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T21:38:54.223",
"Id": "48013",
"ParentId": "45828",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48013",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T14:06:07.977",
"Id": "45828",
"Score": "5",
"Tags": [
"optimization",
"haskell",
"breadth-first-search"
],
"Title": "BFS implementation that walks a tile-based field"
} | 45828 |
<p>We have an entity data model (database first) for a legacy product we are migrating to .Net from Delphi. We recently deployed to a server where some of the tables had been modified and columns deleted. The results were catastrophic. I'm working on a way of validating the EDM schema against the live SQL server database.</p>
<pre><code>public Validation(ADbContext db)
{
_connectionString = db.Database.Connection.ConnectionString;
}
private readonly string _connectionString;
public ILookup<string, List<string>> Run()
{
// A tolerance to deal with Entity Framework renaming
var modelValidation = GetModelProperties<ADbContext>(tolerance);
var isValid = !modelValidation.Any(v => v.Any(x => x.Count > 0));
if (!isValid)
Logger.Activity(BuildMessage(modelValidation));
return modelValidation;
}
public string BuildMessage(ILookup<string, List<string>> modelValidation)
{
// build a message to be logged
}
public List<string> GetMissingColumns(IEnumerable<string> props, IEnumerable<string> columns, int tolerance)
{
// compare whether the entity properties have corresponding columns in the database
var missing = props.Where(p => !columns.Any(c => p.StartsWith(c) && Math.Abs(c.Length - p.Length) <= tolerance)).ToList();
return missing;
}
public string[] GetSQLColumnNames(Type t)
{
SqlConnection connection = new SqlConnection(_connectionString);
var table = t.Name;
DynamicParameters dparams = new DynamicParameters();
dparams.Add("Table", table);
var query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @Table ";
// Using dapper to retrieve list of columns from that table
List<string> columns = connection.Query<string>(query, dparams).ToList();
return columns.ToArray();
}
static string[] GetEntityPropertyNames(Type t)
{
var properties = t.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(p => p.CanRead && !p.PropertyType.FullName.Contains("My.Namespace") && !p.PropertyType.FullName.Contains("Collection"))
.Select(p => p.Name)
.ToArray();
// these conditions excludes navigation properties: !p.PropertyType.FullName.Contains("My.Namespace") && !p.PropertyType.FullName.Contains("Collection")
return properties;
}
ILookup<string, List<string>> GetModelProperties<T>(int tolerance, T source = default(T))
{
var properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(p => p.PropertyType.IsGenericType)
.Select(p => p.PropertyType.GetGenericArguments()[0])
.Select(p => new
{
Entity = p.Name,
Properties = GetEntityPropertyNames(p),
Columns = GetSQLColumnNames(p),
})
.ToArray();
return properties.ToLookup(p => p.Entity, p => GetMissingColumns(p.Properties, p.Columns, tolerance));
}
</code></pre>
<ol>
<li>Is there a better way?</li>
<li>Does Entity Framework already provide a mechanism for achieving this?</li>
<li>Would this be better in the data layer or in another assembly?</li>
<li>Is adding Dapper (just for this purpose) overkill, does it add unnecessary complexity to the project?</li>
</ol>
<p><strong>Update</strong>
I've created a <a href="https://github.com/reckface/EntityFramework.Verify" rel="nofollow">Github repository</a> with a library I've been using that implements this. To minimise dependencies, I've used reflection in favour of Entity specific features.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T17:32:15.127",
"Id": "80179",
"Score": "0",
"body": "I think question 2 is probably best asked on StackOveflow. Also, Dapper would only work if you don't have any non-conventional mappings or implicit many to manys"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-30T07:03:40.603",
"Id": "330860",
"Score": "1",
"body": "great work with the EntityFramework.Verify repo. The only changes I need for my purposes was in the `EntityFrameworkTypeRepository.GetColumns` method, I added `!p.GetGetMethod().IsVirtual && !p.GetCustomAttributes(typeof(NotMappedAttribute), true).Any()` to the clauses - this then skipped my navigation and unmapped properties."
}
] | [
{
"body": "<blockquote>\n <p>Is there a better way?<br>\n Does Entity Framework already provide a mechanism for achieving this?</p>\n</blockquote>\n\n<p>In fact this is one question. If EF would provide a mechanism, undoubtedly that would be better, because you'd know for sure it yields something that EF is happy with. Unfortunately, no, EF hasn't got such a mechanism.</p>\n\n<p>As far as EF checks the consistency of the database with an existing model, it only compares a previously stored model hash in the database with the current model hash. It never compares actual database objects. That would take far too much time in checking whether a migration should be applied. And then, all these methods are internal.</p>\n\n<p>There is however a shorter and more reliable way to get entity and property names from a context. More reliable, because you'll only get the mapped entities and properties without having to jump through hoops to exclude non-mapped ones. I'll give you the heart of it, so you can fit it in appropriately.</p>\n\n<pre><code>var oc = ((IObjectContextAdapter)dbcontext).ObjectContext;\n\nvar items = oc.MetadataWorkspace.GetItems(DataSpace.CSpace).OfType<EntityType>();\nforeach (var entityType in items)\n{\n var props = string.Join(\",\", entityType.Properties);\n Debug.WriteLine(string.Format(\"{0}: {1}\", entityType.Name, props));\n}\n</code></pre>\n\n<blockquote>\n <p>Would this be better in the data layer or in another assembly?</p>\n</blockquote>\n\n<p>I would make the part that provides table and column names part of the data layer, because there you have all required references. I would not include the part that queries the database, because it's done with Dapper, and...</p>\n\n<blockquote>\n <p>Is adding Dapper (just for this purpose) overkill, does it add unnecessary complexity to the project?</p>\n</blockquote>\n\n<p>No, Dapper is great. But since this is a third-party dependency I would use it in a separate assembly that has a reference to your DAL (to obtain the database object names), so your DAL doesn't have this dependency.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T14:41:07.117",
"Id": "46278",
"ParentId": "45831",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46278",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T14:20:49.823",
"Id": "45831",
"Score": "10",
"Tags": [
"c#",
"entity-framework"
],
"Title": "Verifying the Entity Data Model schema against a production database"
} | 45831 |
<p>I'm writing a program that will perform a long-running computation, gradually improving a solution. On top of that, there's a simple UI that basically allows the user to stop the computation (letting the worker finish a step it's working on) and shows the best solution.
Here's a simplified version of what I have, I'm using async/await for the first time. Is there anything you would improve, or any other comments?</p>
<p><strong>Worker code</strong></p>
<pre><code>public class SearchEngine
{
//...
public async Task<IProblemSolution> Search(CancellationTokenSource cts)
{
await Task.Factory.StartNew(() => {
BestSolution = Problem.RandomSolution();
while (!cts.IsCancellationRequested)
{
IProblemSolution s = Problem.RandomSolution(); // for simplification
if (s.ObjectiveValue() < BestSolution.ObjectiveValue())
BestSolution = s;
}
});
return BestSolution;
}
}
</code></pre>
<p><strong>UI</strong></p>
<pre><code> private async void StartButton_Click(object sender, RoutedEventArgs e)
{
if (CancelTokenSrc != null)
return;
CancelTokenSrc = new CancellationTokenSource();
Engine = new SearchEngine(new SampleProblem());
StopButton.IsEnabled = true;
StartButton.IsEnabled = false;
Task<IProblemSolution> t = Engine.Search(CancelTokenSrc);
await t;
ResultLabel.Content = t.Result.ObjectiveValue().ToString();
StopButton.IsEnabled = false;
StartButton.IsEnabled = true;
CancelTokenSrc = null;
}
private void StopButton_Click(object sender, RoutedEventArgs e)
{
if (CancelTokenSrc != null)
CancelTokenSrc.Cancel();
}
</code></pre>
| [] | [
{
"body": "<h3>Task-based Asynchronous Pattern (<a href=\"http://msdn.microsoft.com/en-us/library/hh873175.aspx\" rel=\"nofollow noreferrer\">MSDN</a>)</h3>\n<blockquote>\n<pre><code>public async Task<IProblemSolution> Search(CancellationTokenSource cts)\n</code></pre>\n</blockquote>\n<p>As I explain in <a href=\"https://codereview.stackexchange.com/a/46004/23788\">this answer</a>, one would rightfully expect the signature of that method to read like this:</p>\n<pre><code>public async Task<IProblemSolution> SearchAsync(CancellationTokenSource cts)\n</code></pre>\n<p>The pattern for <code>async</code> methods is quite simple: use the <code>async</code> keyword, return <code>Task</code> or <code>Task<T></code>, and put an "Async" suffix to the method's name.</p>\n<hr />\n<p>I haven't written much <code>async</code> code (read: never wrote a line of C# that leverages features of .net 4.5), but from previous reviews of such code I think this:</p>\n<pre><code> Task<IProblemSolution> t = Engine.Search(CancelTokenSrc);\n await t;\n\n ResultLabel.Content = t.Result.ObjectiveValue().ToString();\n</code></pre>\n<p>Could be written like this:</p>\n<pre><code> var searchResult = await Engine.SearchAsync(CancelTokenSrc);\n ResultLabel.Content = searchResult.ObjectiveValue().ToString();\n //...\n</code></pre>\n<p>My understanding is that <code>await</code> somehow deals with <code>Task.Result</code> and so the type of <code>searchResult</code> would be <code>IProblemSolution</code> - I might be wrong here though.</p>\n<p>Other than that, I find you could give <code>var</code> some lovin', and change this:</p>\n<pre><code>IProblemSolution s = Problem.RandomSolution();\n</code></pre>\n<p>To this:</p>\n<pre><code>var s = Problem.RandomSolution();\n</code></pre>\n<p>Lastly, I might be biased because I use ReSharper and with that tool IntelliSense/auto-complete is much "smarter", but I don't like names like <code>cts</code> - I'd rather call it <code>cancelTokenSource</code> and then I can type <kbd>c</kbd><kbd>t</kbd><kbd>s</kbd><kbd>Tab</kbd> and poof I'm referring to a readable identifier with a pronounceable name.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T20:09:49.733",
"Id": "80894",
"Score": "0",
"body": "“I don't think the Click handler for your StartButton is called asynchronously, you can drop the async keyword in that signature.” That's not how `async` works. It's required if you use `await`, which this method does. And since it's an event handler, `async void` is the right signature."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T20:11:17.650",
"Id": "80897",
"Score": "0",
"body": "But you're right about the part of using `await` instead of `Result`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T20:13:28.073",
"Id": "80898",
"Score": "0",
"body": "@svick right, [just found out](http://stackoverflow.com/q/14455293/1188513) - I'll edit to correct. Thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T17:45:04.200",
"Id": "46079",
"ParentId": "45838",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T14:54:17.367",
"Id": "45838",
"Score": "3",
"Tags": [
"c#",
"async-await"
],
"Title": "Stopping a long-running asynchronous computation"
} | 45838 |
<p>How can I make the following code shorter or efficient (maybe with other loops or other nice ideas), and keep the current functionality?</p>
<pre><code>my $examine = shift; my $detect = 0;
foreach my $ProteinDB (@DB) {
my $Set = $ProteinDB->{'ID'};
if($Set =~ /$examine/) {
$detect = 1;
my @Pointer = keys(%$ProteinDB);
foreach my $key (@Pointer) {
if($key ne "ID" && $key ne "SQ") {
print "$key " . $ProteinDB->{$key} . "\n";
print "\n";
}
}
print "SQ " . $ProteinDB->{"SQ"} . "\n";
print "//\n";
}
}
if($detect == 0) {
print "Error : For the ID $examine NO-Entry could be Found !\n";
}
</code></pre>
<p>It's nice code and easy to understand, but I don't have that experience that I can tell what I can do more with this code. I am gonna keep trying to change it until it's shorter.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T14:46:24.770",
"Id": "79987",
"Score": "0",
"body": "the Code is fast enough but its too long thats my problem i am trying to use another things(loops, regex,.. to make it shorter, but have the same functionality"
}
] | [
{
"body": "<p>This is nice, well-formatted code. Let's see what we can improve:</p>\n\n<ul>\n<li><p>Only use one statement per line:</p>\n\n<pre><code>my $examine = shift;\nmy $detect = 0;\n</code></pre></li>\n<li><p>I assume this code is from the body of a subroutine. I'd recommend not using <code>shift</code> to unpack arguments, but rather list assignment. This at least looks like a formal parameter list:</p>\n\n<pre><code>sub foo {\n my ($examine) = @_;\n ...\n}\n</code></pre>\n\n<p>Otherwise, you can also use syntax extensions like <code>signatures</code>: <code>sub ($examine) { ... }</code>.</p></li>\n<li><p>Where does <code>@DB</code> come from? Quite likely, a reference to that array should be passed as one parameter.</p></li>\n<li><p>The Perl community has no single unifying coding style, but there are a few conventions that are shared by a large part of that community. For example, variables should use <code>$snake_case</code>, and not <code>$CamelCase</code>. But whatever you choose, just be consistent. Either all variables start with an uppercase letter, or none.</p></li>\n<li><p>I'd rather use the shorter <code>for</code> instead of <code>foreach</code>. The two keywords are absolutely interchangeable.</p></li>\n<li><p>Builtin operators like <code>keys</code> are commonly used without parens around the arguments: <code>keys %$ProteinDB</code> instead of <code>keys(%$ProteinDB)</code></p></li>\n<li><p>Don't introduce unnecessary variables like <code>$Set</code> or <code>@Pointer</code>.</p>\n\n<ul>\n<li><p>For example,</p>\n\n<pre><code>my $Set = $ProteinDB->{'ID'};\nif($Set =~ /$examine/) {\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>if($ProteinDB->{'ID'} =~ /$examine/) {\n</code></pre></li>\n<li><p>and this</p>\n\n<pre><code>my @Pointer = keys(%$ProteinDB);\nforeach my $key (@Pointer) {\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>for my $key (keys %$ProteinDB) {\n</code></pre></li>\n</ul></li>\n<li><p>There is often no need to concatenate strings when you can directly interpolate:</p>\n\n<pre><code>print \"$key \" . $ProteinDB->{$key} . \"\\n\";\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>print \"$key $ProteinDB->{$key}\\n\";\n</code></pre></li>\n<li><p>Starting with Perl 5.10, you can use the <code>say</code> feature. The <code>say</code> function behaves exactly like <code>print</code> except that it always appends a newline.</p></li>\n<li><p>A construct like <code>for my $item (@list) { if (condition($item)) { ... } }</code> can be simplified using the <code>grep</code> builtin:</p>\n\n<pre><code>for my $item (grep { condition($_) } @list) {\n ....\n}\n</code></pre>\n\n<p>Alternatively, you can quickly jump to the next loop iteration if the condition fails, which avoids a level of indentation:</p>\n\n<pre><code>for my $item (@list) {\n next if not condition($item);\n ...\n}\n</code></pre></li>\n<li><p>Your <code>$detect</code> variable just has a boolean value. In that case, only test whether it's truthy or falsey, not whether it's equal to <code>0</code>:</p>\n\n<pre><code>if (not $detect) {\n</code></pre></li>\n<li><p>The wording of your error message isn't exactly clear.</p></li>\n</ul>\n\n<p>Wrapping all that together, I'd rewrite your code to this:</p>\n\n<pre><code>use feature 'say';\n\nsub foo {\n my ($id_regex, $db) = @_;\n\n my $detected = 0;\n for my $protein (@$db) {\n next if not $protein->{ID} =~ /$id_regex/;\n\n $detected = 1;\n\n for my $key (keys %$protein) {\n next if $key eq 'ID' or $key eq 'SQ';\n\n say \"$key $protein->{$key}\";\n say \"\";\n }\n\n say \"SQ $protein->{SQ}\";\n say \"//\";\n }\n\n if (not $detected) {\n say \"Error: No entry for ID =~ /$id_regex/ could be found!\";\n }\n}\n</code></pre>\n\n<p>Notice the strategically placed empty lines to emphasize what belongs together, and what is unrelated.</p>\n\n<p>Further observations, not all of which will be applicable to your case:</p>\n\n<ul>\n<li><p>You are testing that <code>$protein->{ID}</code> <em>matches</em> some regex. For example, when you have the IDs <code>1</code>, <code>42</code>, and <code>123</code>, then asking for <code>1</code> would return both <code>1</code> and <code>123</code>. The way you've written it you could also ask for matches of arbitrary regexes, e.g. <code>foo(qr/\\A1.*1\\z/, \\@DB)</code> (any ID that starts and ends with a <code>1</code>). Is this what you intendted? Or do you only want those proteins where the ID is actually equal? Then use the <code>eq</code> string comparision instead of a regex match.</p></li>\n<li><p>If that is the case, you could also index your proteins in a hash. That takes as much time as looping through all elements, but once you are done a lookup is very fast. Do this if you make multiple lookups:</p>\n\n<pre><code>my %proteins_by_id;\nfor my $protein (@DB) {\n $proteins_by_id{$protein->{ID}} = $protein;\n}\n</code></pre>\n\n<p>or abbreviated:</p>\n\n<pre><code>my %proteins_by_id;\n@proteins_by_id{ map { $_->{ID} } @DB } = @DB;\n</code></pre>\n\n<p>which uses a <em>hash slice</em> <code>@hash{@keys}</code>, and the <code>map</code> functions which is like a <code>foreach</code> but returns a list of results.</p>\n\n<p>Then: <code>my $detected = exists $proteins_by_id{$expected_id}</code></p>\n\n<p>This of course only works if each ID is unique, otherwise we need a hash of arrays:</p>\n\n<pre><code>my %proteins_by_id;\nfor my $protein (@DB) {\n push @{ $proteins_by_id{$protein->{ID}} }, $protein;\n}\n</code></pre></li>\n<li><p>When looping over all <code>keys</code>, they will be in an unspecified order. If you want the output to stay the same between runs, you must <code>sort</code> them:</p>\n\n<pre><code>for my $key (sort keys %$protein) {\n</code></pre></li>\n<li><p>When looping over all <code>keys</code>, you skip the <code>SQ</code> entry but then print it out anyway. Is this really necessary? Or do you just want to make sure that it's printed last? If there is no real need, remove this.</p></li>\n<li><p>You simply <code>print</code> your error. But unless this is some simple one-off script, it is usually better to <code>return</code> a value indicating whether your subroutine has completed successfully. Even better: <code>die</code> with an error. This will abort normal control flow of your script. The error will be passed upwards through the call stack. If it isn't handled, it will terminate the script. Exceptions are often caught via <code>eval { ... }</code>, but the <code>Try::Tiny</code> module is better:</p>\n\n<pre><code>try {\n ... # something that can `die`\n} catch {\n warn \"I caught: $_\"; # do something with the error\n}; # this ';' is not optional\n</code></pre></li>\n<li><p>It is considered a bad practice to print out stuff from a subroutine that actually does something different (like searching for matching entries). If it has to be, return a string that the caller can print out. This is important in larger projects where you need to write tests that check that your program behaves correctly – it's easier to check a return value than to capture everything you print.</p></li>\n</ul>\n\n<p>Assuming I've read your mind correctly, then this code would be better:</p>\n\n<pre><code>use strict;\nuse warnings;\nuse feature 'say';\nuse Try::Tiny;\n\n# index the @DB by ID:\nmy %proteins_by_id;\nfor my $protein (@DB) {\n push @{ $proteins_by_id{$protein->{ID}} }, $protein;\n}\n\nfor my $id (1234, 5678) {\n # print out the report or the error message\n say try { report_matching_id($id, \\%proteins_by_id) } catch { \"Error: $_\" };\n}\n\nsub report_matching_id {\n my ($id, $protein_db) = @_;\n my $matching_proteins = $protein_db->{$id};\n\n # return early if we can see that there are no matches\n # (either the entry doesn't exist, or the array is empty)\n if (not $matching_proteins or not @$matching_proteins) {\n die \"No matching proteins for ID=$id found\";\n }\n\n my $output = \"\";\n for my $protein (@$matching_proteins) {\n # dump each %$protein\n for my $key (sort keys %$protein) {\n next if $key eq 'ID';\n $output .= \"$key $protein->{$key}\\n\\n\";\n }\n $output .= \"//\\n\\n\";\n }\n\n return $output;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T16:24:10.540",
"Id": "80015",
"Score": "0",
"body": "note that snake_case is *literally* shorter than CamelCase :) (though often wider)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T16:05:42.837",
"Id": "45856",
"ParentId": "45839",
"Score": "1"
}
},
{
"body": "<p>This is shorter, but not necessarily more efficient,</p>\n\n<pre><code>my $examine = shift; my $detect = 0;\nfor my $ProteinDB (@DB) {\n next if $ProteinDB->{'ID'} !~ /$examine/;\n $detect = 1;\n print \"$_ $ProteinDB->{$_}\\n\\n\"\n for grep $_ ne \"ID\" && $_ ne \"SQ\", keys %$ProteinDB;\n print \"SQ $ProteinDB->{SQ}\\n//\\n\";\n}\n$detect or print \"Error : For the ID $examine NO-Entry could be Found !\\n\";\n</code></pre>\n\n<p>and if you push it little more,</p>\n\n<pre><code>my $examine = shift; my $detect = 0;\nprint map {\n $detect = 1;\n my $ProteinDB = $_;\n (\n (map \"$_ $ProteinDB->{$_}\\n\\n\", grep $_ ne \"ID\" && $_ ne \"SQ\", keys %$ProteinDB),\n \"SQ $ProteinDB->{SQ}\\n//\\n\"\n );\n }\n grep $_->{ID} =~ /$examine/, @DB;\n$detect or print \"Error : For the ID $examine NO-Entry could be Found !\\n\";\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T16:27:52.983",
"Id": "45861",
"ParentId": "45839",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "45861",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T14:39:32.337",
"Id": "45839",
"Score": "6",
"Tags": [
"perl",
"bioinformatics"
],
"Title": "Foreach-loop for and print commands"
} | 45839 |
<p>To solve a polynomial equation I have written following program, is there any way to optimize this program.</p>
<p>Following code is working code:</p>
<p>Program takes input n,x where n is the deg of polynomial and x is the point at which the polynomial is to be evaluated.</p>
<pre><code> #include<stdio.h>
int power(int x, int y);
int main()
{
// n is the deg of polynomial
// x is the value of polynomial for which it is to be evaluated
int x=0,n=0,A[10],sum=0,i=0,M=0,y=0;
printf("Enter value of n,x \n");
scanf("%d %d",&n,&x);
printf("Enter the coeficients\n");
for(i=0;i<=n;i++) //Taking coefiecent values
{
scanf("%d",&A[i]);
}
y=n;
for(i=0;i<=n;i++)
{
M=power(x,y);
sum=sum+(A[i]*M);
y--;
}
printf("\nSum of polynomial is %d",sum);
return 0;
}
int power(int x, int y)
{
int result = x;
int i;
if(y == 0) return 1;
if(x < 0 || y < 0) return 0;
for(i = 1; i < y; ++i)
result *= x;
return result;
}
</code></pre>
| [] | [
{
"body": "<p>By following <a href=\"http://en.wikipedia.org/wiki/Horner%27s_method\" rel=\"nofollow\">Horner's Method</a> only n multiplications are needed.</p>\n\n<pre><code>#include <stdio.h>\n\nint main()\n{\n // n is the deg of polynomial\n // x is the value of polynomial for which it is to be evaluated\n int x=0,n=0,A[10],b,i;\n\n printf(\"Enter value of n,x \\n\");\n scanf(\"%d %d\",&n,&x);\n\n //Taking coefficient values\n printf(\"Enter the coeficients\\n\");\n\n for(i=0;i<=n;i++) scanf(\"%d\",&A[i]);\n\n for(i = n - 1,b = A[n];i >= 0;i--) b = b*x + A[i];\n\n printf(\"\\nSum of polynomial is %d\\n\",b);\n\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T15:54:31.047",
"Id": "45843",
"ParentId": "45841",
"Score": "2"
}
},
{
"body": "<p>If user enters the coefficients in <code>A[n], A[n-1], ... A[1], A[0]</code> order, code gets nice and tight. No need to save all the coefficients and no need to limit them to 10. Calculate the sum as you go.</p>\n\n<p>BTW: Always good to check the results of <code>scanf()</code>.</p>\n\n<pre><code>#include<stdio.h>\n\nint main() {\n // n is the deg of polynomial\n // x is the value of polynomial for which it is to be evaluated\n int x, n, A;\n long sum = 0; // or use long long\n\n printf(\"Enter value of n,x \\n\");\n if (scanf(\"%d %d\", &n, &x) != 2) {\n return 1; // bad input\n }\n\n printf(\"Enter the coefficients\\n\"); // spelling change\n while (n-- >= 0) {\n if (scanf(\"%d\", &A) != 1) {\n return 1; // bad input\n }\n sum *= x;\n sum += A;\n }\n printf(\"\\nSum of polynomial is %ld\", sum);\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T20:53:56.337",
"Id": "45844",
"ParentId": "45841",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T15:05:23.360",
"Id": "45841",
"Score": "3",
"Tags": [
"c"
],
"Title": "Evaluating a polynomial at a given value of x and n"
} | 45841 |
<p>I am trying to step to the next level from student to amateur web developer, and I would like to make sure I am not making any web-development no-no's, that's all. What caused me to want to ask SO this question is that I had to make some tweaks to make my responsive design work.</p>
<p>For instance, I had to make a lot of my positions "absolute" and had to do some hacking in my HTML, making a different nav bar if it's mobile, desktop or tablet (you'll see I haven't done anything with tablet) design. I'm also pretty new to jQuery, although I'm a programmer so I think that code is okay, but I'll post it anyways. Some other stuff as well, would really appreciate ANY feedback, and I really want some good criticism so I can become better. </p>
<p><a href="http://iam.colum.edu/students/jordan.max/algorerhythm/index.php#" rel="nofollow">live demo</a></p>
<p>HTML</p>
<pre><code><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('nav').hide();
$('.maDown').hide();
$('.assignmentsDown').click(function() {
$('nav.aDown').slideDown(2000);
if($('.wDown').is(":visible"))
{
$('nav.wDown').slideToggle(300);
}
if($('.pDown').is(":visible"))
{
$('nav.pDown').slideToggle(300);
}
$('nav.aDown').slideDown(2000);
});
$('.MassignmentsDown').click(function() {
$('.maDown').show();
});
$('.writingDown').click(function() {
$('nav.wDown').slideDown(2000);
if($('.aDown').is(":visible"))
{
$('nav.aDown').slideToggle(300);
}
if($('.pDown').is(":visible"))
{
$('nav.pDown').slideToggle(300);
}
});
$('.presentationDown').click(function() {
$('nav.pDown').slideDown(2000);
if($('.wDown').is(":visible"))
{
$('nav.wDown').slideToggle(300);
}
if($('.aDown').is(":visible"))
{
$('nav.aDown').slideToggle(300);
}
});
}); //closes ready
</script>
</head>
<figure>
<img src="downwardmonkey.png" alt="down" class="head">
</figure>
<body>
<div id="navContainer">
<h1 class="mainT"> Al Gore Rhythm Labs </h1>
<h2 class="subT"> Chicago, IL </h2>
<div class="topNav">
<ul>
<li> <a href="#" class="assignmentsDown"> Assignments </a></li>
<li> <a href="#" class="writingDown"> Writings </a> </li>
<li> <a href="#" class="presentationDown"> Presentations </a></li>
</ul>
</div>
<div class="mNav">
<p> <a href="#" class="MassignmentsDown"> Assignments |</a></p>
<p> <a href="#" class="MwritingDown"> Writings |</a> </p>
<p> <a href="#" class="MpresentationDown"> Presentations </a></p>
</div>
<div class="maDown">
<ul>
<li class="assignments"><a href="origindex.html" class="a"> First Class Page (A1) </a></li>
<li class="assignments"><a href="#" class="a"> Responsive Class Page (A2) </a></li>
<li class="assignments"><a href="A3.html" class="a"> CSS Engagement (A3) </a></li>
<li class="assignments"><a href="A4.html" class="a"> Transitions and Animations (A4) </a></li>
<li class="assignments"><a href="A5.php" class="a"> jQuery (A5) </a></li>
<li class="assignments"><a href="A6.html" class="a"> jQuery Usability (A6) </a></li>
<li class="assignments"><a href="A7.html" class="a"> HTML5 Form (A7) </a></li>
</ul>
</div>
</div>
<nav class="aDown">
<ul>
<li class="assignments"><a href="origindex.html" class="a"> First Class Page (A1) </a></li>
<li class="assignments"><a href="#" class="a"> Responsive Class Page (A2) </a></li>
<li class="assignments"><a href="A3.html" class="a"> CSS Engagement (A3) </a></li>
<li class="assignments"><a href="A4.html" class="a"> Transitions and Animations (A4) </a></li>
<li class="assignments"><a href="A5.php" class="a"> jQuery (A5) </a></li>
<li class="assignments"><a href="A6.html" class="a"> jQuery Usability (A6) </a></li>
<li class="assignments"><a href="A7.html" class="a"> HTML5 Form (A7) </a></li>
</ul>
</nav>
<nav class="wDown">
<ul>
<li class="writings"><a href="#" class="Writing1.html"> How HTML Will Kill The Native App (W1) </a></li>
<li class="writings"><a href="#" class="Writing2.html"> Ubiquitous Computing (W2) </a></li>
<li class="writings"><a href="#" class="Writing3.html"> Re-examining Interactivity (W3) </a></li>
</ul>
</nav>
<nav class="pDown">
<ul>
<li class="presentations"><a href="PresOne.html" class="p"> Interactive Interests (P1) </a></li>
<li class="presentations"><a href="P2.html" class="p"> Experimental Interactive Artifacts (P2) </a></li>
<li class="presentations"><a href="P3.html" class="p"> Research Assets (P3) </a></li>
</ul>
</nav>
</body>
<figure>
<div class="grassImageDiv"></div>
</figure>
<footer>
<p><a href="http://www.jdmdev.net"> Jordan Max 2014 </a></p>
</footer>
</html>
</code></pre>
<p>CSS3</p>
<pre><code>/********************* DEFAULT QUERIES *********************/
body
{
background-image: url("bg.gif");
}
/******************** MOBILE QUERIES ********************/
@media all and (max-width: 600px) {
a.assignmentsDown, a.writingDown, a.presentationDown, div.topNav
{
display: none;
}
h1, h2
{
text-align: center;
width: 100%;
color: #9aa49a;
}
h1.mainT
{
font-family: 'Montserrat', sans-serif;
font-size: 1.5em;
}
h2.subT
{
font-family: 'Open Sans Condensed', sans-serif;
margin-top: -17px;
}
div#navContainer
{
background: #FCFCFC;
height: 80px;
width: 100%;
}
img.head
{
display: none;
}
a
{
color: #8B8B83;
text-decoration: none;
}
footer
{
color: #9aa49a;
font-family: 'Montserrat', sans-serif;
background-color: #FCFCFC;
width: 100%;
height: 38px;
font-size: .85em;
text-align: center;
padding: 5px;
position: absolute;
bottom: 0;
}
.grassImageDiv
{
display: inline-block;
background-image: url("grass3.png");
position: absolute;
height: 107px;
width: 108%;
bottom: 44px;
margin-left:-61px;
overflow-x: hidden;
}
.mNav
{
text-align: center;
background-color: #FCFCFC;
box-shadow: 10px 10px 5px #888888;
top: 96px;
width: 100%;
position: absolute;
}
div.mNav>p
{
font-family: 'Open Sans Condensed', sans-serif;
font-size: 1.2em;
height: 70%;
list-style-type: none;
display: inline;
}
ul li.assignments, li.writings, li.presentations
{
line-height: 250%;
list-style-type: none;
font-family: 'Montserrat', sans-serif;
}
div.maDown
{
background: #FCFCFC;
width: 300px;
box-shadow: 2px 3px 10px #333;
}
} /******************** end media query ********************/
/******************** TABLET QUERIES ********************/
@media all and (min-width: 600px) {
aside
{
}
} /******************** end media query ********************/
/******************** Desktop Queries ********************/
@media all and (min-width: 1240px){
}
/******************** Large Desktop Queries ********************/
@media all and (min-width: 1240px){
div.mNav
{
display: none;
}
div.maDown
{
display: none;
}
h1
{
}
h2
{
margin-top: -40px;
margin-left: 120px;
}
h1.mainT
{
width: 590px;
font-family: 'Montserrat', sans-serif;
margin-left: 10px;
font-size: 2.5em;
}
h2.subT
{
width: 130px;
font-family: 'Open Sans Condensed', sans-serif;
}
nav
{
font-family: 'Open Sans Condensed', sans-serif;
font-size: 1.2em;
width: 500;
height: 70%;
background-color: #FCFCFC;
padding: 5px;
margin: 10px auto 30px 42%;
box-shadow: 2px 3px 10px #333;
position: fixed;
margin-left: 42%;
top: 15%;
left: -100px;
}
div.topNav>ul>li
{
display: inline-block;
font-family: 'Open Sans Condensed', sans-serif;
font-size: 1.2em;
list-style-type: none;
}
div.topNav
{
word-spacing: 75px;
margin-top: -60px;
margin-left: 650px;
}
a
{
color: #8B8B83;
text-decoration: none;
}
footer
{
color: #9aa49a;
font-family: 'Montserrat', sans-serif;
background-color: #FCFCFC;
width: 100%;
font-size: .85em;
position: fixed;
left: 0px;
bottom: 0px;
text-align: center;
z-index: 1;
}
div#navContainer
{
height: 100px;
background: #FCFCFC; /* grey99*/
box-shadow: 2px 3px 5px #333;
position: fixed;
width:100%;
z-index: 1;
}
ul li.assignments, li.writings, li.presentations
{
width: 400px;
line-height: 250%;
margin-left: -25px;
margin-right:27px;
padding: 20px;
list-style-type: none;
font-family: 'Montserrat', sans-serif;
text-align: center;
z-index: 1;
}
div.temp
{
z-index:1;
}
a:hover.a,:hover.w,:hover.p
{
color: #C1CDC1;
}
figure img.head
{
position: fixed;
top:117px;
margin-left: 58px;
}
p.clickHere
{
position: fixed;
top: 450px;
left: 77%;
font-family: 'Open Sans Condensed', sans-serif;
font-size: 1.6em;
color: #EDEFED;
}
.grassImageDiv
{
display: inline-block;
background-image: url("Grass2.png");
width: 120%;
height: 216px;
position: fixed;
margin-left:-96px;
bottom: 42px;
z-index: -1;
}
/******************** end media query ********************/
</code></pre>
| [] | [
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li><code>$(document).ready(function () {</code> <- old skool, you should use <a href=\"http://api.jquery.com/ready/\" rel=\"nofollow\"><code>$( handler )</code></a></li>\n<li>Indenting, you are not doing it consistently</li>\n<li><code>$('.assignmentsDown').click(function() {</code> and <br>\n<code>$('.writingDown').click(function() {</code> and <br>\n<code>$('.presentationDown').click(function() {</code> all use copy pasted code, you should consider a generic function that can be used for all 3 situations</li>\n<li>It is consider better form nowadays to have your JavaScript in a separate .js file</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T15:49:28.910",
"Id": "45849",
"ParentId": "45846",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "45849",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T15:27:22.843",
"Id": "45846",
"Score": "5",
"Tags": [
"javascript",
"jquery",
"html",
"css",
"html5"
],
"Title": "Expandable navigation menu"
} | 45846 |
<blockquote>
<p><strong>Problem Statement</strong></p>
<p>Generate as many distinct primes P such that reverse (P) is also prime
and is not equal to P.</p>
<p>Output:<br>
Print per line one integer( ≤ 10<sup>15</sup> ). Don't print more than
10<sup>6</sup> integers in all.</p>
<p>Scoring:<br>
Let N = correct outputs. M= incorrect outputs. Your score
will be max(0,N-M).</p>
<p>Note: Only one of P and reverse(P) will be counted as correct. If both
are in the file, one will be counted as incorrect.</p>
<p>Sample Output<br>
107 13 31 17 2</p>
<p>Explanation<br>
Score will be 1. Since 13,107,17 are correct. 31 is
incorrect because 13 is already there. 2 is incorrect.</p>
<p>Time Limit<br>
<strong>2 sec(s)</strong> (Time limit is for each input file.)</p>
<p>Memory Limit<br>
256 MB</p>
<p>Source Limit<br>
25 KB</p>
</blockquote>
<p><strong>My Problem</strong></p>
<p>I have tried quite hard to optimize the solution, but the min possible time this program took was : <strong>16.452 secs</strong></p>
<p><strong>My question</strong> is, is it possible to optimize the following code further, is it possible to reduce execution time to 2 secs, if we are given that we have to use the Python language. </p>
<pre><code>from time import time
start = time()
lsta=[] # empty list used to hold prime numbers created by primes function
LIMIT = pow(10,6)
# binary search function
def Bsearch(lsta,low,high,search):
if low>high:
return False
else:
mid=int((low+high)/2)
if search<lsta[mid]:
return(Bsearch(lsta,low,mid-1,search))
elif search>lsta[mid]:
return(Bsearch(lsta,mid+1,high,search))
elif search==lsta[mid]:
return True
else:
return False
# prime number creating function using sieve of Eras** algorithm
def primes(LIMIT):
dicta = {}
for i in range(2,LIMIT):
dicta[i]=1
for i in range(2,LIMIT):
for j in range(i,LIMIT):
if i*j>LIMIT:
break
dicta[i*j]=0
for i in range(2,LIMIT):
if(dicta[i]==1):
lsta.append(i)
final = [] # used to hold the final output values
primes(LIMIT)
for i in range(len(lsta)):
# prime number compared with reversed counterpart
if(int(str(lsta[i])[::-1])<=lsta[len(lsta)-1]):
if Bsearch(lsta,i+1,len(lsta)-1,int(str(lsta[i])[::-1])):
if not(int(str(lsta[i])[::-1])==lsta[i]):
final.append(str(lsta[i]))
for i in range(len(final)-1,0,-1):
print(final[i])
print(13)
end=time()
print("Time Taken : ",end-start)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T17:04:44.113",
"Id": "80020",
"Score": "0",
"body": "For generating primes, see [Sieve of Eratosthenes - Python](http://codereview.stackexchange.com/q/42420/10916)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T19:20:42.583",
"Id": "80048",
"Score": "0",
"body": "Why wait until you've compiled the entire list to start outputting?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T20:55:52.897",
"Id": "80058",
"Score": "0",
"body": "In what crazy world is 2 *not* a prime number?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T22:10:50.650",
"Id": "80072",
"Score": "2",
"body": "@DavidHarkness: The condition is P is a prime, its reverse is a prime, and its reverse is not equal to P. 2 meets the first two conditions but not the third."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T00:04:06.060",
"Id": "80082",
"Score": "0",
"body": "@EricLippert Okay, I should have added a smiley, but I was just pointing out that the problem description is not entirely clear: \"Only one of P and reverse(P) will be counted as correct\" and \"31 is incorrect because 13 is already there. 2 is incorrect\" seem to imply that 2 is simply incorrect because it is not a prime. Me: \"Everything Bob says is false.\" Bob: \"This statement is false.\" :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T11:30:12.037",
"Id": "80127",
"Score": "0",
"body": "@david-harkness: Yes, so true. It's simply a matter of definition. It seems there are two definitions going around, one of which mandates primes to be odd, which rules out `2`. There are also many sources that state that 2 is in fact a prime... No idea who would be the authority to decide it once and for all... Interestingly, `1` is also not a prime number. However `1` is an even more fundamental class of numbers: A [unit](http://en.wikipedia.org/wiki/Unity_(mathematics))."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T15:42:04.397",
"Id": "80158",
"Score": "2",
"body": "@StijndeWitt: No, there is no (widely-understood) definition of [prime number](http://en.wikipedia.org/wiki/Prime_number) that requires that mandates primes to be odd. That seems to be a misunderstanding."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T19:32:59.977",
"Id": "80211",
"Score": "1",
"body": "@Oddthinking: Interesting because I remember thinking it was really silly that 2 was not a prime... Seems my first instinct was right after all... However I also had this same feeling about one but there I am definitelt wrong. BTW, your username is very suitable now :)"
}
] | [
{
"body": "<p>There are a few things you could optimize:</p>\n\n<ul>\n<li>If you (or the grading server?) are running this on Python 2.x, you should definitely use <code>xrange</code> instead of <code>range</code> (about 2 seconds on my system)</li>\n<li>In your prime sieve, you have to check the multiples only if the current number is a prime (down to 1s); also, instead of multiplying, count by multiples of <code>i</code>s</li>\n<li>use a regular array instead of a dictionary in the sieve (0.8s)</li>\n<li>don't do that string-conversion and reversing more often than necessary; also instead of implementing your own binary search, just use <code>set</code>s for quick lookup (0.4s)</li>\n</ul>\n\n<p>My version (updated):</p>\n\n<pre><code>def primes(limit):\n numbers = [0, 0] + [1] * (limit-2)\n for i in xrange(2, limit):\n if numbers[i]:\n for k in xrange(i**2, limit, i):\n numbers[k] = 0\n return set(i for i, e in enumerate(numbers) if e)\n\nps = primes(LIMIT)\nfinal = set()\nfor p in ps:\n q = int(str(p)[::-1])\n if p != q and q in ps and q not in final:\n final.add(p)\n</code></pre>\n\n<p>Not sure whether this get's the running time down from 16s to 2s in your case, but it might be a start. As a desperate measure, you could decrease <code>LIMIT</code> -- better to find not quite as many than to timeout.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T17:17:07.273",
"Id": "80023",
"Score": "0",
"body": "Thank you for your suggestions, Yeah I am now convinced it cannot be reduced less than what you added here, maybe I should write this program in C or C++ I guess.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T17:27:01.357",
"Id": "80027",
"Score": "0",
"body": "Your basic approach seems to me th eright one, but that's not the best of implementations of the Sieve of Erathostenes. And checking for `p > 9` is redundant with `p != q` and is slowing things down for most numbers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T18:27:48.700",
"Id": "80036",
"Score": "0",
"body": "@Jaime Thanks for the pointers! I improved my sieve a bit using the three-parameters-(x)range instead of multiplying, but left the only-odd-numbers trick out -- for readability, and to not entirely copy your answer (+1). Cut down the time by another 20% (with yours even 40%)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T18:46:01.380",
"Id": "80041",
"Score": "0",
"body": "When `i` is a prime, the first non-prime to remove from the sieve is `i*i`, not `i*2`. I suppose you where trying to write `i**2`? That should cut your time bit quite a bit more, as it avoids a lot of redundant sieving."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-19T10:28:58.230",
"Id": "369645",
"Score": "0",
"body": "`if p != q and q in ps and q not in final:` can save an `in` test if you rewrite as `if p < q and q in ps:`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T16:56:15.283",
"Id": "45863",
"ParentId": "45857",
"Score": "13"
}
},
{
"body": "<p>With an efficient implementation of the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">sieve of Eratosthenes</a> and the general approach outlined by @tobias_k, I have it running in 0.5 seconds, including the printing. Try with this:</p>\n\n<pre><code>def primes(limit):\n # Keep only odd numbers in sieve, mapping from index to number is\n # num = 2 * idx + 3\n # The square of the number corresponding to idx then corresponds to:\n # idx2 = 2*idx*idx + 6*idx + 3\n sieve = [True] * (limit // 2)\n prime_numbers = set([2])\n for j in range(len(sieve)):\n if sieve[j]:\n new_prime = 2*j + 3\n prime_numbers.add(new_prime)\n for k in range((2*j+6)*j+3, len(sieve), new_prime):\n sieve[k] = False\n return prime_numbers\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-19T10:42:36.277",
"Id": "369651",
"Score": "0",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] it to explain your reasoning (how your solution works and how it improves upon the original) so that everyone can learn from your thought process."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T17:28:58.477",
"Id": "45869",
"ParentId": "45857",
"Score": "8"
}
},
{
"body": "<h1>Use a fast prime generator</h1>\n\n<p>See below the best pure python prime generator from <a href=\"https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python\">this thread</a> (python 3):</p>\n\n<pre><code>def primes(n):\n sieve = [True] * (n//2)\n for i in range(3, int(n**0.5) + 1, 2):\n if sieve[i//2]:\n sieve[i*i//2::i] = [False] * ((n-i*i-1)//(2*i)+1)\n return [2] + [2*i+1 for i in range(1, n//2) if sieve[i]]\n</code></pre>\n\n<h1>Constant time lookups using a python set</h1>\n\n<p>You could use the native python module <a href=\"https://docs.python.org/2/library/bisect.html\" rel=\"nofollow noreferrer\">bisect</a> to perform the binary search. But it is simpler and faster to use a <a href=\"https://docs.python.org/2/library/stdtypes.html#set\" rel=\"nofollow noreferrer\">set</a> of primes. See this page about <a href=\"https://wiki.python.org/moin/TimeComplexity\" rel=\"nofollow noreferrer\">time complexity</a>:</p>\n\n<pre><code>prime_set = set(primes(upper_bound))\n</code></pre>\n\n<h1>Keep the main loop simple</h1>\n\n<p>Loop over the primes, reverse the prime, check that its value is over the original prime (to avoid duplicates) and then look for it in the primes set:</p>\n\n<pre><code>def palindromic_primes(upper_bound):\n prime_set = set(primes(upper_bound))\n for p in prime_set:\n r = int(str(p)[::-1])\n if r > p and r in prime_set:\n yield p\n</code></pre>\n\n<h1>Separate the running logic from the solving logic</h1>\n\n<p>It makes it easier to parametrize and test your program (python 3):</p>\n\n<pre><code>if __name__ == '__main__':\n t = time.time()\n upper_bound = int(eval(sys.argv[1]))\n generator = palindromic_primes(upper_bound)\n for score, x in enumerate(generator, 1):\n print(x)\n delta = time.time() - t\n status = \"Score = {} in {:.3f} s\".format(score, delta)\n print(status, file=sys.stderr)\n</code></pre>\n\n<h1>Results for several upper bounds</h1>\n\n<pre><code>$ python3 palindromic_primes 1e6 > /dev/null\nScore = 5592 in 0.077 s\n$ python3 palindromic_primes 1e7 > /dev/null\nScore = 40829 in 0.836 s\n$ python3 palindromic_primes 2e7 > /dev/null\nScore = 59525 in 1.722 s\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-20T13:03:07.900",
"Id": "369898",
"Score": "0",
"body": "I wonder whether reversing numbers using the int → str → int conversion is a limitation. Would the obvious arithmetic approach be faster?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-20T14:31:00.443",
"Id": "369918",
"Score": "1",
"body": "@TobySpeight I just [benchmarked it](https://gist.github.com/vxgmichel/1e39a6c5b2c6f27e295f0a774cb544a4), the string approach is about 3 times faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-20T14:34:06.950",
"Id": "369919",
"Score": "0",
"body": "That was a surprise to me - thanks for demonstrating that!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T17:55:33.820",
"Id": "45873",
"ParentId": "45857",
"Score": "6"
}
},
{
"body": "<p>Using <code>numba</code> you can even run this code in less than one second.</p>\n\n<pre><code>('Time Taken : ', 0.7115190029144287)\n</code></pre>\n\n<p>The code, slightly based on the version of @jaime, should be rewritten with <code>numpy.arrays</code>. See <a href=\"https://stackoverflow.com/questions/22768709/numba-slowing-code\">here</a></p>\n\n<pre><code>import numpy as np\nimport numba\nfrom time import time\nstart = time()\n\nLIMIT = pow(10,6)\n# binary search function\ndef Bsearch(lsta,low,high,search):\n if low>high:\n return False\n else:\n mid=int((low+high)/2)\n if search<lsta[mid]:\n return(Bsearch(lsta,low,mid-1,search))\n elif search>lsta[mid]:\n return(Bsearch(lsta,mid+1,high,search))\n elif search==lsta[mid]:\n return True\n else:\n return False\n\n\ndef primes(limit):\n # Keep only odd numbers in sieve, mapping from index to number is\n # num = 2 * idx + 3\n # The square of the number corresponding to idx then corresponds to:\n # idx2 = 2*idx*idx + 6*idx + 3\n sieve = [True] * (limit // 2)\n prime_numbers = set([2])\n for j in range(len(sieve)):\n if sieve[j]:\n new_prime = 2*j + 3\n prime_numbers.add(new_prime)\n for k in range((2*j+6)*j+3, len(sieve), new_prime):\n sieve[k] = False\n return list(prime_numbers)\n\n\n\n@numba.jit('void(uint8[:])', nopython=True)\ndef primes_util(sieve):\n ssz = sieve.shape[0]\n for j in xrange(ssz):\n if sieve[j]:\n new_prime = 2*j + 3\n for k in xrange((2*j+6)*j+3, ssz, new_prime):\n sieve[k] = False\n\ndef primes_numba(limit):\n sieve = np.ones(limit // 2, dtype=np.uint8)\n primes_util(sieve)\n\n return [2] + (np.nonzero(sieve)[0]*2 + 3).tolist()\n\n\n\nfinal = [] # used to hold the final output values\n\nlsta = primes_numba(LIMIT)\n\nfor i in xrange(len(lsta)):\n # prime number compared with reversed counterpart\n if(int(str(lsta[i])[::-1])<=lsta[len(lsta)-1]):\n if Bsearch(lsta,i+1,len(lsta)-1,int(str(lsta[i])[::-1])):\n if not(int(str(lsta[i])[::-1])==lsta[i]):\n final.append(str(lsta[i]))\n\nfor i in xrange(len(final)-1,0,-1):\n print(final[i])\nprint(13)\n\nend=time()\nprint(\"Time Taken : \",end-start)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-19T10:43:01.160",
"Id": "369652",
"Score": "0",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] it to explain your reasoning (how your solution works and how it improves upon the original) so that everyone can learn from your thought process."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T20:34:30.040",
"Id": "45881",
"ParentId": "45857",
"Score": "2"
}
},
{
"body": "<p>This got around <strong>11000</strong> points using a limit of 13.5 million, in roughly 2 seconds </p>\n\n<p>Basically my strategy is to create a lookup list out made of bools, where at the end of each cycle in my main loop, the next true value with a higher index than the current indexed value is guaranteed to be prime.</p>\n\n<p>The first thing i do when I evaluate a new prime, is to eliminate its multiples from the rest of the list.</p>\n\n<p>After that I get the reverse of my current prime value and perform:</p>\n\n<ul>\n<li><strong>Case1</strong> If the reversed value is lower than the non reversed, I check to see if it is also a prime using my lookup list. If its also a prime value I only add the original value.</li>\n<li><strong>Case2</strong> if reversed value is higher than my overall limit I perform a simple check on it using a common prime evaluating function. If it is prime I add the non reversed prime</li>\n<li><p><strong>Case3</strong> If the reversed value higher than the non reversed prime and lower than the limit I will ignore it seeing as it will be found again under Case1</p>\n\n<pre><code>from time import time\ndef is_prime(n):\n for i in xrange(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\ndef DoMath(limit):\n start = time()\n lkup = [True,True,True] +[ bool(ii%2) for ii in xrange(3,limit)]\n with open(\"text.txt\", 'w') as file:\n index = 3\n r_index = 0\n str_index = ''\n while index < limit:\n if lkup[index]:\n for ii in xrange(index*2, limit, index):\n lkup[ii] = False\n str_index = str(index)\n r_index = int(str_index[::-1])\n if r_index >= limit and is_prime(r_index):\n file.write(str_index+'\\n')\n elif r_index < index and lkup[r_index]:\n file.write(str_index+'\\n')\n index += 1\n end=time()\n print(\"Time Taken : \",end-start)\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-19T10:43:15.647",
"Id": "369653",
"Score": "0",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] it to explain your reasoning (how your solution works and how it improves upon the original) so that everyone can learn from your thought process."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T03:04:30.900",
"Id": "45906",
"ParentId": "45857",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "45869",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T16:05:44.043",
"Id": "45857",
"Score": "25",
"Tags": [
"python",
"performance",
"primes",
"programming-challenge",
"palindrome"
],
"Title": "Count distinct primes, discarding palindromes, in under 2 seconds"
} | 45857 |
<p>I used a standard calculator design from Java. I wanted to expand it so I created a class to create buttons for different operations, like <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>. The original program didn't do this, they just made them individually without a template method. Do you think I should do it like this?</p>
<pre><code>//The java Template Calculator TODO
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Container;
public class JavaCalculator implements ActionListener{
JFrame guiFrame;
JPanel buttonPanel;
JTextField numberCalc;
int calcOperation = 0;
int currentCalc;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable()
{
public void run()
{
new JavaCalculator();
}
});
}
public JavaCalculator()
{
guiFrame = new JFrame();
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Simple Calculator");
guiFrame.setSize(300,300);
guiFrame.setLocationRelativeTo(null);
numberCalc = new JTextField();
numberCalc.setHorizontalAlignment(JTextField.RIGHT);
numberCalc.setEditable(false);
guiFrame.add(numberCalc, BorderLayout.NORTH);
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4,4));
guiFrame.add(buttonPanel, BorderLayout.CENTER);
for (int i=0;i<10;i++)
{
addNumberButton(buttonPanel, String.valueOf(i));
}
addActionButton(buttonPanel, 1, "+");
addActionButton(buttonPanel, 2, "-");
addActionButton(buttonPanel, 3, "*");
addActionButton(buttonPanel, 4, "/");
addActionButton(buttonPanel, 5, "^2");
JButton equalsButton = new JButton("=");
equalsButton.setActionCommand("=");
equalsButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if (!numberCalc.getText().isEmpty())
{
int number = Integer.parseInt(numberCalc.getText());
if (calcOperation == 1)
{
int calculate = currentCalc + number;
numberCalc.setText(Integer.toString(calculate));
}
else if (calcOperation == 2)
{
int calculate = currentCalc - number;
numberCalc.setText(Integer.toString(calculate));
}
else if (calcOperation == 3)
{
int calculate = currentCalc * number;
numberCalc.setText(Integer.toString(calculate));
}
else if (calcOperation == 4)
{
int calculate = currentCalc / number;
numberCalc.setText(Integer.toString(calculate));
}
else if (calcOperation == 5)
{
int calculate = currentCalc * currentCalc;
numberCalc.setText(Integer.toString(calculate));
}
}
}
});
buttonPanel.add(equalsButton);
guiFrame.setVisible(true);
}
private void addNumberButton(Container parent, String name)
{
JButton but = new JButton(name);
but.setActionCommand(name);
but.addActionListener(this);
parent.add(but);
}
private void addActionButton(Container parent, int action, String text)
{
JButton but = new JButton(text);
but.setActionCommand(text);
OperatorAction addAction = new OperatorAction(1);
but.addActionListener(addAction);
parent.add(but);
}
public void actionPerformed(ActionEvent event)
{
String action = event.getActionCommand();
numberCalc.setText(action);
}
private class OperatorAction implements ActionListener
{
private int operator;
public OperatorAction(int operation)
{
operator = operation;
}
public void actionPerformed(ActionEvent event)
{
currentCalc = Integer.parseInt(numberCalc.getText());
calcOperation = operator;
}
}
}
</code></pre>
| [] | [
{
"body": "<h1>Bug!</h1>\n<p>In your program, it's impossible to use any operator besides addition. As Code Review is not meant to be a code-bug-fixing site, I think you should try to fix this yourself. <em>Hint: The bug is in your <code>addActionButton</code> method</em></p>\n<h2>Now, about your question</h2>\n<p>Yes, the template method is a good choice. Removing code duplication is always a good idea, which is I have to inform you about some other improvements you can make as well.</p>\n<h3>Some things you should think about first</h3>\n<ul>\n<li>Java coding convention is to put the <code>{</code> on the same line as before, not on it's own line.</li>\n<li>It is good practice to use <code>private final</code> on as many class-variables ("fields") as possible.</li>\n<li>It is an even better practice to reduce the scope of variables when possible, <code>buttonPanel</code> and <code>guiFrame</code> can be declared as local variables in the constructor.</li>\n</ul>\n<h3>Reducing duplication</h3>\n<ul>\n<li><code>numberCalc.setText(Integer.toString(calculate));</code> is done on every if-case, put it after all the if-else statements instead.</li>\n<li>Instead of using several if-else, you can use a <a href=\"http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html\" rel=\"noreferrer\"><code>switch</code> statement</a>.</li>\n<li>An <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html\" rel=\"noreferrer\">enum</a> is a better choice than using an int to store the current calcOperation.</li>\n</ul>\n<hr />\n<h3>Java 8</h3>\n<p>If you are not allowed or unable to use Java 8, skip this section :)</p>\n<p>If you can use Java 8, there's a way to do this very smoothly. It may be a bit advanced if you are new to the Java language, but if you are willing to learn I suggest you check out <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/function/IntBinaryOperator.html\" rel=\"noreferrer\">IntBinaryOperator</a>.</p>\n<p>Your <code>int calcOperation</code> can be replaced with <code>IntBinaryOperator operator;</code>. Operations can be declared like this:</p>\n<pre><code>IntBinaryOperator add = (a, b) -> a + b;\nIntBinaryOperator substract = (a, b) -> a - b;\nIntBinaryOperator multiply = (a, b) -> a * b;\nIntBinaryOperator divide = (a, b) -> a / b;\n</code></pre>\n<p>Your add action button can then become <code>private void addActionButton(Container parent, IntBinaryOperator action, String text) {</code>. This would <strong>greatly</strong> reduce code duplication for you, but as I said. This is only if you're using Java 8. If you're interested, add a comment and I'll explain more.</p>\n<hr />\n<p>Regarding the user friendliness of your program, it's not layouted as a typical calculator. This is just a nitpick really. It would also be nice to use the keyboard for the program, but that's just a feature-request :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T16:36:02.597",
"Id": "80172",
"Score": "0",
"body": "I updated the code, I replaced the if else statements with switch, I created the JFrame guiFrame and JPanel buttonPanel within the class. I also fixed the bug, I already had it fixed in my compiler, it was probably an old version. { and } are now on the same line\n numberCalc.setText(Integer.toString(calculate));\nnow is outside the switch statement.\n\nI don't know what you meant with enum, or how to do it.\nMy computer says it has Java 8 installed, but when I replace\n int calcOperation = 0;\nwith\n IntBinaryOperator operator;\nit says it is an undefined variable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T20:30:06.847",
"Id": "80220",
"Score": "0",
"body": "I also replaced the for loop to generate numbers for the number buttons with simply: addNumberButton(\"number\"); otherwise i wouldn't be able to put the number in a logical order, or would I?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T20:33:09.640",
"Id": "80222",
"Score": "1",
"body": "@TheWombatGuru If you read the enum tutorial link in my post you should be able to use an enum. You can make one like `public enum Calculation { ADDITION, SUBTRACTION, MULTIPLICATION, DIVISION; }` and then you can declare a `private Calculation activeCalculation;` which you can set to one of those values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T20:33:43.277",
"Id": "80223",
"Score": "1",
"body": "@TheWombatGuru For information on how to develop with Java 8, see https://wiki.eclipse.org/JDT/Eclipse_Java_8_Support_For_Kepler"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T19:55:31.853",
"Id": "80415",
"Score": "0",
"body": "@Simon_André_Forsberg, I made a class for the enum, but I don't know how to implement it into the calculator, I changed the cases in the switch statement to the capital words, but I don't know how I can give actions to the words."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T21:52:09.407",
"Id": "45884",
"ParentId": "45864",
"Score": "11"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T16:56:16.280",
"Id": "45864",
"Score": "12",
"Tags": [
"java",
"swing",
"calculator"
],
"Title": "Basic Calculator in Java with Swing"
} | 45864 |
<pre><code>if($row['best']){
$id = $row['best'];
} elseif($row['average']){
$id = $row['average'];
} elseif($row['bad']){
$id = $row['bad'];
}
</code></pre>
<p>If <code>row['best']</code> is <code>null</code>, I need <code>$id</code> to equal the 2nd best. If 2nd best is null, <code>$id</code> is equal to the next best.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T17:10:36.790",
"Id": "80022",
"Score": "10",
"body": "Can you add a bit of the surrounding context to your question? Where does the `$row` variable come from? I can imagine that there might be a possible solution where the problem can be fixed elsewhere in your code."
}
] | [
{
"body": "<p>There are some different approaches possible here, one of them is to use an array:</p>\n\n<pre><code>$arr = array($row['best'], $row['average'], $row['bad']);\nfor ($arr as $value) {\n if ($value) {\n $id = $value;\n break;\n }\n}\n</code></pre>\n\n<p>If you consider this as a better way or not to do what you are trying to accomplish, is really up to you. I can imagine that if the possible options will be extended, then this would be really helpful. But for only three items, your current way is not that bad.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T17:09:40.627",
"Id": "45866",
"ParentId": "45865",
"Score": "4"
}
},
{
"body": "<p>From <a href=\"https://stackoverflow.com/a/1539479/7602\">here</a>:</p>\n\n<p>If there are only 3 possibilities, you could do this:</p>\n\n<pre><code>$id = $row['best'] or $id = $row['average'] or $id = $row['bad'];\n</code></pre>\n\n<p>This is the closest that PHP can come to JS short circuit assignments.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T17:41:38.887",
"Id": "80029",
"Score": "0",
"body": "I have up to 8 possibilities. For readability, I would rather use if-then-else. No?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T17:44:53.720",
"Id": "80030",
"Score": "0",
"body": "Actually, this could still work with 8, but you would need some newlines, or, you could use @Flambino's approach which is still better than if-then-else"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T01:59:49.390",
"Id": "80665",
"Score": "0",
"body": "@Bastien Oh, with 8 possibilities I would definitely use one of the iteration methods. You should update your question to reflect this requirement. Programmers tend to be literal creatures at heart. :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T17:13:32.793",
"Id": "45867",
"ParentId": "45865",
"Score": "4"
}
},
{
"body": "<p>Simon <a href=\"https://codereview.stackexchange.com/a/45866/14370\">has already answered</a> while I was writing something similar:</p>\n\n<pre><code>foreach(array('best', 'average', 'bad') as $rank) {\n if($row[$rank]) {\n $id = $row[$rank];\n break;\n }\n}\n</code></pre>\n\n<p>Note however, that in both this and Simon's answer, there is a possibility of <code>$id</code> never being assigned a value. <a href=\"https://codereview.stackexchange.com/a/45867/14370\">Konijn's answer</a> avoids that (although <code>$id</code> might still end up false'y)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T02:03:55.780",
"Id": "80666",
"Score": "0",
"body": "Just assign `$id` the desired no-match value before the loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T08:18:58.440",
"Id": "80688",
"Score": "0",
"body": "@DavidHarkness Oh sure, it's easy to handle. Just wanted to keep the code 1:1 with OP's question"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T17:15:47.807",
"Id": "45868",
"ParentId": "45865",
"Score": "10"
}
},
{
"body": "<p>You may want to write the first_in($arr, $keys) function, and rewrite your code as:</p>\n\n<pre><code>$id = first_in($row, array('best', 'average', 'bad'));\n</code></pre>\n\n<p>Or more common firstof($arr) function:</p>\n\n<pre><code>$id = firstof(array($row['best'], $row['average'], $row['bad'));\n</code></pre>\n\n<p>for example, the firstof function:</p>\n\n<pre><code>function firstof($arr) {\n foreach ($arr as $key=>$val)\n if ($val)\n return $val;\n return $arr[count($arr)-1];\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T00:18:08.400",
"Id": "45895",
"ParentId": "45865",
"Score": "5"
}
},
{
"body": "<p>How has <em>no one</em> mentioned the Elvis operator?!</p>\n\n<pre><code>$id = $row['best'] ?: $row['average'] ?: $row['bad'] ?: null;\n</code></pre>\n\n<p>Substitute your desired \"not present\" value of choice for <code>null</code>.</p>\n\n<p><strong>Edit:</strong> This is the short form of the ternary operator which evaluates to the first expression if truthy or the second expression if not. This is similar to how the <code>||</code> operator is often used in JavaScript.</p>\n\n<pre><code>var options = options || {};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T11:15:04.203",
"Id": "80300",
"Score": "0",
"body": "\"Elvis operator\"? Never seen that one before, seems to be some ternary-operator-magic there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T21:42:10.040",
"Id": "80446",
"Score": "1",
"body": "Careful. If $row[xxx] doesn't exist you'll get nasty error notices."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T08:38:32.110",
"Id": "80519",
"Score": "0",
"body": "@mAsT3RpEE Correct, same for all of the code on this page."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T01:37:57.040",
"Id": "45904",
"ParentId": "45865",
"Score": "10"
}
},
{
"body": "<p>Maybe use array functions a bit?</p>\n\n<pre><code>$keys = array_keys($row, TRUE); // returns all keys for which value is boolean TRUE\n$id = $keys[0]; // takes first one as ID\n</code></pre>\n\n<p>Note that this assume only one of the values is set to true or that keys are ordered from the one you want to get the most to one you want the least. It's often a safe assumption, but assumption none the less. Thus, my code is not an universal replacement of your original code, but in many real-life situations it would be pretty good - and it frees you from duplicating lists of possible keys in different parts of the script.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T11:42:39.283",
"Id": "45934",
"ParentId": "45865",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T17:00:50.950",
"Id": "45865",
"Score": "7",
"Tags": [
"php"
],
"Title": "Shorter way to write multiple if-then-else-if"
} | 45865 |
<p>This is my function returning matrices from Matlab. This code run very slowly.
I was trying to use <code>Parallel.For</code> in-order to run it in parallel threads but I got different results than running it on one thread. </p>
<p>Am I iterating the matrix in a wrong order? Row, col vs col, row?
Can you please review this code any suggest some performance boost tips?</p>
<pre><code>public static SerializableMatrix ParseNumericMatrix(MWNumericArray matrix)
{
SerializableMatrix resultMatrix;
int[] dimensions = matrix.Dimensions;
if (dimensions.Length > 3 || dimensions.Length < 2)
{
throw new ArgumentException("Input matrix dimensions are too long", "Three is the max dimensions");
}
var height = dimensions[0];
var width = dimensions[1];
resultMatrix = new SerializableMatrix() { Width = width, Height = height, Data = new List<double[]>() };
if (dimensions.Length == 2)
{
var dataArray = new double[width * height];
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
dataArray[i * width + j] = (double)matrix[i, j];
}
}
resultMatrix.Data.Add(dataArray);
return resultMatrix;
}
if (dimensions.Length == 3)
{
int depth = dimensions[2];
for (int depthIndex = 0; depthIndex < depth; depthIndex++)
{
var dataArray = new double[width * height];
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
// matlab indices start at 1 , not 0!!!
dataArray[i * width + j] = (double)matrix[i + 1, j + 1, depthIndex + 1];
}
}
resultMatrix.Data.Add(dataArray);
}
}
return resultMatrix;
}
</code></pre>
| [] | [
{
"body": "<p>As usual with performance problems the only way of knowing for sure is to use a profiler and check which piece of code is taking the longest time. However looking at the code you are copying the matrix element by element which is typically the slowest way to go. Often there is a method which can do that as a bulk operation for you.</p>\n\n<p>I don't know much about the Matlab stuff as I've never used it but I found <a href=\"https://stackoverflow.com/questions/20020026/how-to-convert-a-matrix-in-matlab-to-a-double-array-in-c-net\">this question on Stackoverflow</a> which has a couple of answers showing a single line statement of copying it. Based on one of these answers your code for the 2D case could look like this:</p>\n\n<pre><code>double[,] data = (double[,])matrix.ToArray(MWArrayComponent.Real);\n</code></pre>\n\n<p>I assume in the 3D case you'll get a <code>double[,,]</code> back which you might have to take apart afterwards so it fits your <code>List<double[]></code> type.</p>\n\n<p>Apart from that:</p>\n\n<p>This exception has a misleading message in case the dimensions are less than 2</p>\n\n<blockquote>\n<pre><code>if (dimensions.Length > 3 || dimensions.Length < 2)\n{\n throw new ArgumentException(\"Input matrix dimensions are too long\", \"Three is the max dimensions\");\n}\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T22:48:10.593",
"Id": "45890",
"ParentId": "45875",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "45890",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T18:39:53.317",
"Id": "45875",
"Score": "2",
"Tags": [
"c#",
"performance",
".net",
"matrix",
"matlab"
],
"Title": "Parsing MWNumericArray to C# code optimization"
} | 45875 |
<p>I recently added a feature to my application to serve arbitrary markdown documents from a directory. This is designed to allow authors to populate a folder full of help documents, and be able to view them without any code changes. However, because this is an MVC application, I needed a few extra features. Straight to it, here's my controller:</p>
<pre><code>public class DocumentationController : Controller
{
private const string DefaultDocPage = "Overview";
public ActionResult Index(string id = null)
{
ViewBag.HomeLinkPage = string.IsNullOrEmpty(id) || id == DefaultDocPage ? string.Empty : DefaultDocPage;
if (string.IsNullOrEmpty(ViewBag.HomeLinkPage))
{
id = DefaultDocPage;
}
var filePath = Server.MapPath(Url.Content("~/Content/Documentation/" + id.Trim("/".ToCharArray()) + ".md"));
if(!System.IO.File.Exists(filePath))
{
Response.StatusCode = (int)HttpStatusCode.NotFound;
return null;
}
var contents = new StringBuilder(System.IO.File.ReadAllText(filePath));
contents.Replace("{{AppRoot}}/", Url.Content("~"));
contents.Replace("{{Documentation}}", Url.Content("~/Documentation"));
contents.Replace("{{DocumentationImages}}", Url.Content("~/Content/Documentation/images"));
contents.Replace("{{SupportLink}}", ConfigurationManager.AppSettings["SupportLink"]);
return View("Index", (object)contents.ToString());
}
}
</code></pre>
<p>In short, it allows passing a file name (without ".md") called "id" (poor name is my fault for lazy routing), assigns a default document if a file name was not passed, sets a ViewBag link to the homepage if we're not on the default document, maps the file name to a markdown document in the directory, replaces some preprocessed keywords, and returns the view with the contents of the document.</p>
<p>My view renders the homepage link, if applicable, then the document using MarkdownSharp. I haven't seen my idea of "preprocessed keywords" in markdown before, so I was wandering what others think. It's really useful for resolving links in documents, without worrying about them while writing. It allows document writers to write:</p>
<blockquote>
<p><code>To view your user page [click here]({{AppRoot}}/User/Me) and here's an image: </code></p>
</blockquote>
<p>Which is transformed to this, on localhost, without the author worrying about the actual path to the application, or the content directory:</p>
<blockquote>
<p><code>To view your user page [click here](http://localhost/MyApp/User/Me) and here's an image: </code></p>
</blockquote>
<p>I also added one for the support link, so I could pull in that setting from <code>ConfigurationManager.AppSettings</code>.</p>
<p>My questions, succinctly: </p>
<ul>
<li>Are there any realistic cases that I may not be anticipating?</li>
<li>Is there a best practice that I'm not aware of, for having pre-processed text replaced in markdown?</li>
<li>Is there a better way than <code>StringBuilder.Replace</code> for processing each of my keywords?</li>
</ul>
| [] | [
{
"body": "<p>A few minor nit-picks:</p>\n\n<ol>\n<li><p>I'd change the id checking code around a bit to avoid some redundant checks by first sanitizing the input:</p>\n\n<pre><code>id = string.IsNullOrEmpty(id) ? DefaultDocPage : id;\nViewBag.HomeLinkPage = id == DefaultDocPage ? string.Empty : DefaultDocPage;\n</code></pre></li>\n<li><p>Consider making <code>DefaultDocPage</code> a configurable property so you don't have to change the code <strike>if</strike> when someone asks to have a different name</p></li>\n<li><p><a href=\"https://msdn.microsoft.com/en-us/library/d4tt83f9%28v=vs.90%29.aspx\" rel=\"nofollow\"><code>Trim</code> takes a <code>params</code> array</a> so there is no need to do the <code>ToCharArray</code>, you can just pass in all the trim characters directly like this:</p>\n\n<pre><code>id.Trim('/')\n</code></pre></li>\n<li><p>Replacing</p>\n\n<blockquote>\n<pre><code>var filePath = Server.MapPath(Url.Content(\"~/Content/Documentation/\" + id.Trim(\"/\".ToCharArray()) + \".md\"));\n</code></pre>\n</blockquote>\n\n<p>with <code>string.format</code> makes it a bit easier to read:</p>\n\n<pre><code>var filePath = Server.MapPath(Url.Content(string.format(\"~/Content/Documentation/{0}.md\", id.Trim('/'))));\n</code></pre></li>\n</ol>\n\n<p><strike>1. There is no need to cast to <code>object</code> here:</p>\n\n<blockquote>\n<pre><code>return View(\"Index\", (object)contents.ToString());\n</code></pre>\n \n <p></strike></p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T21:11:09.070",
"Id": "80063",
"Score": "1",
"body": "Thanks! For #4 the cast to object is actually necessary when passing a string here, otherwise MVC tries to use a different overload that uses \"Index\" as the view name and the passed string as the Master view name. There are [other ways](http://stackoverflow.com/questions/9802546/mvc-3-cant-pass-string-as-a-views-model) to solve that though, that may be more readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T21:12:07.780",
"Id": "80065",
"Score": "0",
"body": "Ah, alright, I'm not doing much MVC so I'm not aware"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T21:07:10.607",
"Id": "45882",
"ParentId": "45877",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T19:01:44.900",
"Id": "45877",
"Score": "5",
"Tags": [
"c#",
"strings",
"url-routing",
"markdown"
],
"Title": "Preprocessing Markdown Documents for Keywords"
} | 45877 |
<p>I need to create variable-length strings of dots/periods/full-stops to add to some text content, in a way that is similar to a formatted table-of-contents:</p>
<pre><code>Chapter 1 .................................... 1
Section 1.1 ................................ 1
Subsection 1.1.2 .......................... 12
</code></pre>
<p>I know that things like <code>String.format</code> exist, but that is not suitable for formatting periods this way.</p>
<p>The code is complicated by the need for there to be many threads doing similar work at the same time.</p>
<p>I have written this utility class that caches a 'base' string in a Thread-local, and uses that to supply the required data.</p>
<p>Are there any alternatives, improvements, or other recommendations you have?</p>
<pre><code>public final class DotPadding {
private static final ThreadLocal<String> PAD_BASE = new ThreadLocal<String>() {
@Override
protected String initialValue() {
return "................";
}
};
public static final String getPadding(final int length) {
if (length <= 0) {
return "";
}
String base = PAD_BASE.get();
if (base.length() >= length) {
return base.substring(0, length);
}
while (base.length() < length) {
base = base.concat(base);
}
PAD_BASE.set(base);
return base.substring(0, length);
}
}
</code></pre>
<p>As an example usage, this is one of the ways that the above code is used. There are other places too:</p>
<pre><code>String description = getFormattedDescription(title);
String index = getFormattedIndex(page);
String line = description
+ " "
+ DotPadding.getPadding(width - (2 + description.length() + index.length()))
+ " "
+ index;
System.out.println(line);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T22:01:55.503",
"Id": "80069",
"Score": "0",
"body": "Shouldn't you have some sort of helper method like `DotPadding.getPaddedString(String left, String right)`? Or is that what the last code block is about?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T22:07:33.893",
"Id": "80070",
"Score": "0",
"body": "The way this code works is to just have a single length of dots: input value `3` will return `...` and 5 will return `.....`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T22:10:23.270",
"Id": "80071",
"Score": "1",
"body": "No, what I meant is you're calculating the amount of dots needed for between `description` and `index` in the last code block, shouldn't that be wrapped in a helper method?"
}
] | [
{
"body": "<ol>\n<li><p>Naive approach: use <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#repeat%28char,%20int%29\" rel=\"nofollow noreferrer\"><code>StringUtils.repeat</code></a> (<a href=\"http://commons.apache.org/proper/commons-lang/apidocs/src-html/org/apache/commons/lang3/StringUtils.html#line.5209\" rel=\"nofollow noreferrer\">source</a>) without the <code>ThreadLocal</code>:</p>\n\n<blockquote>\n<pre><code>public static String repeat(final char ch, final int repeat) {\n final char[] buf = new char[repeat];\n for (int i = repeat - 1; i >= 0; i--) {\n buf[i] = ch;\n }\n return new String(buf);\n}\n</code></pre>\n</blockquote>\n\n<p>Anyway, I suppose you did some profiling and it turned out that this is a bottleneck. Otherwise I'd really not complicate it with the <code>ThreadLocal</code> nor the doubling/concatenation logic.</p></li>\n<li><p><code>substring</code> in Java 6 used the same character array as the original <code>String</code> instance but <a href=\"https://stackoverflow.com/q/16123446/843804\">it was changed in Java 7</a>. So, <code>substring</code> calls copies the character array anyway, therefore string doubling and calling substring does not seem beneficial to me. (Anyway, it should be measured.)</p>\n\n<p>There is one exception (according to the source which Eclipse brings up for Java 8) when <code>beginIndex</code> is zero and <code>endIndex</code> is the length of the original string. In this case <code>substring</code> returns the same <code>String</code> instance without copying. This case seems unlikely here, I guess there's a little chance that <code>PAD_BASE.lenght</code> will be the same as the <code>length</code> parameter since the while loop doubles the size of the padding string on every iteration.</p>\n\n<p>So, in an average case the naive approach would create less new <code>String</code> (and underlying <code>char[]</code>) objects here than the one with substring.</p></li>\n<li><p>Another idea is storing an array of strings in the <code>ThreadLocal</code> and extending the array on demand if the required lenght is longer than <code>paddings.lenght</code>:</p>\n\n<pre><code>String paddings[] = new String[max];\nfor (int i = 0; i < max; i++) {\n paddings[i] = StringUtils.repeat('.', i);\n}\n</code></pre></li>\n<li><p><code>2</code> could be a named constant.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T23:41:50.383",
"Id": "45894",
"ParentId": "45885",
"Score": "4"
}
},
{
"body": "<p>I find it amusing that you go to a lot of effort to make the dot generator efficient, with thread-local storage for caching. Then, when you actually need to use this string, you just concatenate strings the simple and inefficient way. You don't really gain any performance by caching the string of dots, since you'll be copying it anyway during the concatenation.</p>\n\n<p>It would be nice to have a purpose-built object so that you could write:</p>\n\n<pre><code>Padding p = new Padding(48);\nSystem.out.println(p.format(\"Chapter 1\", \"1\"));\nSystem.out.println(p.format(\" Section 1.1\", \"1\"));\nSystem.out.println(p.format(\" Subsection 1.1.2\", \"12\"));\n</code></pre>\n\n<p>It would all be accomplished with one <code>char[]</code> array, and you should be able to use it normally without threading issues.</p>\n\n<pre><code>public class Padding {\n private char[] buf;\n private char leader, space;\n\n public Padding(int width) {\n this(width, '.');\n }\n\n public Padding(int width, char leader) {\n this(width, leader, ' ');\n }\n\n public Padding(int width, char leader, char space) {\n this.buf = new char[width];\n this.leader = leader;\n this.space = space;\n }\n\n public String format(String left, String right) {\n int lLen = left.length();\n int rLen = right.length();\n\n // Left and right text\n left.getChars(0, lLen, this.buf, 0);\n right.getChars(0, rLen, this.buf, this.buf.length - rLen);\n\n // Dot leader\n for (int i = lLen + 1; i < this.buf.length - rLen - 1; i++) {\n this.buf[i] = this.leader;\n }\n\n // Space padding\n this.buf[lLen] = this.buf[this.buf.length - rLen - 1] = this.space;\n\n return new String(this.buf);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T03:55:26.363",
"Id": "45908",
"ParentId": "45885",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "45908",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T21:54:40.943",
"Id": "45885",
"Score": "10",
"Tags": [
"java",
"strings",
"concurrency"
],
"Title": "Poke-a-Dot (Provider)"
} | 45885 |
<p>I'm looking for some feedback on my implementation of the algorithm. How can I improve it? I ran into problems when calculating the larger prime numbers > 46349 due to integer overflow, but fixed that by using <code>sqrt</code> instead of <code>pow</code>.</p>
<pre><code>#include<iostream>
#include<math.h>
using namespace std;
int main(){
int number;
cin >> number;
const int CAP = number;
bool * prime = new bool[CAP];
for(int i = 0; i < CAP; i++){ //sets all to true for the marking
prime[i] = true;
}
for(int i = 2; i < number; i++){
if(i <= sqrt(number) && prime[i] == true){
for(int j = i*i; j < number; j++){ //if %i == 0 mark false
if(j % i == 0){ //haven't tried another way
prime[j] = false;
}
}
}
}
for(int i = 2; i < number; i++){
if(prime[i] == true){
cout << i << endl;
}
}
return 0;
}
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p><code><math.h></code> is a C header. Use the C++ header <code><cmath></code>.</p></li>\n<li><p>If you have a dynamically-allocated array with <code>new</code>, you <em>must</em> use <code>delete</code> at some point afterwards, otherwise you'll get a memory leak:</p>\n\n<pre><code>delete [] prime;\n</code></pre></li>\n<li><p>When comparing something with a <code>bool</code>, you don't need to explicitly use <code>true</code> or <code>false</code>.</p>\n\n<p>For <code>true</code>:</p>\n\n<pre><code>if (someBool) {}\n</code></pre>\n\n<p>For <code>false</code>:</p>\n\n<pre><code>if (!someBool) {}\n</code></pre></li>\n<li><p>Do you really need <code>CAP</code>? It's set to the same value as <code>number</code>, except it's <code>const</code>.</p></li>\n<li><p>You don't need <code>std::endl</code> in the loop. This also flushes the buffer, which is slower. Instead, use <code>\"\\n\"</code> to produce just a newline.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T22:47:24.293",
"Id": "80077",
"Score": "0",
"body": "Interesting. I had no idea `std::endl` was that much slower. When should I use `std::endl`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T22:49:32.030",
"Id": "80079",
"Score": "2",
"body": "@Lanyard: You would usually use at the end of a large output, or if you need to flush the buffer immediately. More info can be found [here](http://stackoverflow.com/questions/213907/c-stdendl-vs-n)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T04:00:50.167",
"Id": "80094",
"Score": "1",
"body": "@Lanyard: My advice would be to *never* use `endl`. If you want a new-line, use `\\n`. If you want to flush the stream, I think it's better to pass `std:flush` to make that intent clear."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T22:18:57.963",
"Id": "45888",
"ParentId": "45886",
"Score": "5"
}
},
{
"body": "<p>The title of your post says that you want to implement the Sieve of Eratosthenes. However, your code also performs trial division, and has a <code>sqrt()</code> operation that is typically used as a limit when performing trial division. You should be able to implement the Sieve without doing any division or modulo operation at all. As for the <code>sqrt()</code> limit check, it is superfluous, as the inner loop checks that <code>i * i < number</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T22:46:13.290",
"Id": "80076",
"Score": "0",
"body": "You're right. I checked the wiki for Sieve of Eratosthenes and it states that it is often confused for trial division. Time to start over again."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T22:38:06.950",
"Id": "45889",
"ParentId": "45886",
"Score": "8"
}
},
{
"body": "<p>As 200_success pointed out, you have not implemented a sieve. See Wikipedia's pseudo code for the Sieve of Eratosthenes.</p>\n\n<hr>\n\n<p>You need to check if reading in a number was actually successful:</p>\n\n<pre><code>if (!(std::cin >> number)) {\n std::cerr << \"Invalid number provided\" << std::endl;\n return EXIT_FAILURE;\n}\n</code></pre>\n\n<p>(Note that you would need <code>cstdlib</code> for <code>EXIT_FAILURE</code>.)</p>\n\n<hr>\n\n<p><code>number</code> is a bad name. It's an int--of course it's a number. What is it's meaning? Get rid of <code>CAP</code>, and name <code>number</code> something more meaningful like <code>maxNumber</code> (or ideally something better -- I'm having a naming mental block).</p>\n\n<hr>\n\n<p>You should only ever use bare dynamic arrays if you are implementing a container or some other low level structure. They are non-exception safe, and you have to remember to clean up the memory. Just use a pre-allocated vector, and you can retain the same performance (or maybe even better in this relatively rare circumstance).</p>\n\n<pre><code>std::vector<bool> prime(CAP, true);\n</code></pre>\n\n<p>Note that <code>std::vector<bool></code> has a specialization that uses packing to save space at the cost of a few extra cycles and some rather odd semantics (you actually get a proxy object from the vector rather than a direct reference to the element). </p>\n\n<p>As Jerry Coffin noted, this task is almost certainly memory constrained rather than CPU, so the higher throughput of bit-based bools should actually provide faster performance.</p>\n\n<p>Also, note that as a bonus on top of automatic memory management, you get to remove your initializing loop.</p>\n\n<hr>\n\n<p>Though in toy programs it doesn't matter, using <code>namespace std;</code> is <a href=\"https://stackoverflow.com/q/1452721/567864\">considered harmful</a>, and it's a bad habit to form. Instead, use <code>using std::cout;</code>, <code>using std::endl;</code>, etc to only import certain symbols (and do it inside of a function, not at the global level).</p>\n\n<hr>\n\n<p>It's not technically wrong, but it's much, much more common to use a space between #include and the file:</p>\n\n<pre><code>#include <iostream>\n</code></pre>\n\n<hr>\n\n<p><code>//if %i == 0 mark false</code> this comment says the exact same thing the code does. Either make it much more meaningful (<code>// mark the number non-prime if it is divisible by i</code>), or--better in this situation--just remove it.</p>\n\n<hr>\n\n<p>Interactive programs should be avoided if at all possible. They cannot be chained with other commands in a scripted fashion, and they are prone to user error. Instead, when you're only accepting one or a few simple user inputs, just use arguments to the program (i.e. use <code>argv</code> to get the maximum number rather than using <code>std::cin</code>).</p>\n\n<hr>\n\n<p>In C++, if a return value is not specified in main, it is assumed to be <code>EXIT_SUCCESS</code> (0). Because of this, I like to omit return values in main when it's not possible for the program to result in a non successful return. Seeing a <code>return</code> in main makes me immediately wonder if it can fail. (Your program actually should be able to fail, so I would keep the return, you just should also have some error checking on the input reading).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T03:51:43.190",
"Id": "80093",
"Score": "0",
"body": "For this task, `vector<bool>` will often be faster than other containers. You lose a little CPU time to isolate one bit of storage, but in exchange you reduce the memory bandwidth by about 8:1. It's normally limited by memory bandwidth, not CPU speed, so (for this task) that typically ends up a win."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T04:34:46.677",
"Id": "80096",
"Score": "0",
"body": "@JerryCoffin Ah, makes sense I suppose since basically every loop iteration is going to have to pull new data into the cache. Will update accordingly in a moment."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T22:52:44.780",
"Id": "45891",
"ParentId": "45886",
"Score": "12"
}
},
{
"body": "<p>Here's a function that returns a <code>vector<int></code> of all the primes up to the given limit. I kept with the dynamic bool array since even a vector seemed to be 4 times slower. There are a number of optimizations that I haven't really seen covered before:</p>\n\n<p>Edit: It appears compiler optimization helps quite a bit. with full optimization the vector is faster. without it's slower.</p>\n\n<pre><code>vector<int> MakePrimes2(int upperlimit)\n{\n int bound = (int) floor(sqrt(upperlimit));\n vector<bool> primes(upperlimit, true);\n vector<int> outval; \n primes[0] = false;\n primes[1] = false;\n //Since 2 is a special case if we do it separately we can optimize the rest since \n //they will all be odd\n for(int i = 4; i < upperlimit; i += 2)\n {\n primes[i] = false;\n }\n outval.push_back(2);\n //Since the only ones we need to look at are odd we can step by 2\n for (int i = 3; i <= bound; i += 2)\n {\n if (primes[i]) \n {\n //Since we are looping already we might as well start filling the \n //outval vector\n outval.push_back(i);\n //Since all the even multiples are already accounted for we start \n //at the square of the number \n //and since it is odd skip to every other multiple\n for (int j = i*i; j < upperlimit; j += i * 2)\n {\n primes[j] = false;\n }\n }\n }\n //Fill the rest of the vector starting one past the square root of the upperlimit\n for(int i = bound+1;i < upperlimit; i++)\n {\n if(primes[i])\n outval.push_back(i);\n }\n return outval;\n}\n</code></pre>\n\n<p>Returning a vector like this instead of the bool array simplifies your loop to display the list of primes, and is a very minor hit on speed</p>\n\n<p>Update: Did some more tests and using a loop to compare vectors made with my code and with standard code found them to be identical with my method approximately 35% faster finding all the primes up to 1,000,000,000.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T04:43:47.920",
"Id": "80098",
"Score": "0",
"body": "Can you post your code that used a vector (perhaps a pastebin or gist)? I'm quite surprised that it was slower if your compiler's optimizations were cranked up. Was the vector sized from creation, or grown?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T04:49:31.460",
"Id": "80099",
"Score": "0",
"body": "Same code just replaced the declaration for primes to a vector, `vector<bool> primes(upperlimit, true);`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T04:57:37.143",
"Id": "80100",
"Score": "0",
"body": "On closer look, this has a lot of dubious code in it. It's implied that you're using `using namespace std` which is fine in implementation files, but without noting that, it's a bit odd. Also, I don't think this function is correct. Have you checked it's output with something like `MakePrimes2(1000000)`? Also, depending on undefined behavior (\"on my compiler...\") is questionable. Edit: just realized the bug is likely actually due to the use of undefined behavior."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T05:04:48.320",
"Id": "80101",
"Score": "0",
"body": "I've checked the output against slower but established code and saw nothing wrong and went as high as 100,000,000. I've even used 2 different compiler/ide's and got comparable results."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T05:57:01.880",
"Id": "80104",
"Score": "0",
"body": "Seems the vector version is correct (once the extraneous delete[] is removed). The array based version was bugged for compilers (e.g. all of them when optimizations are enabled) that don't zero the array."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T06:00:42.067",
"Id": "80105",
"Score": "0",
"body": "Yep found the same thing. I added some notes about my speed tests."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T04:25:40.117",
"Id": "45913",
"ParentId": "45886",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T22:02:28.193",
"Id": "45886",
"Score": "14",
"Tags": [
"c++",
"primes",
"sieve-of-eratosthenes"
],
"Title": "Sieve of Eratosthenes in C++"
} | 45886 |
<p>I have been using this code for a while for a project at work. Actually I got it from a friends who got it from a book. But either way it worked for my demonstration.</p>
<p>But the other night I decided to sit down and see if I could make it into all functions and then to see about moving the variables up to the top of each function. It would be normal for simple programming and everything should work, but when I did this, the code crashed and burned (didn't show anything in the canvas). It should show bouncing balls.</p>
<pre><code><!doctype html>
<html>
<head>
<title>Bounding Balls</title>
<script src="modernizr.js"></script>
<script type="text/javascript">
window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded() {
canvasApp();
}
function canvasSupport () {
return Modernizr.canvas;
}
function canvasApp() {
if (!canvasSupport()) {
return;
}
function drawScreen () {
context.fillStyle = '#EEEEEE';
context.fillRect(0, 0, theCanvas.width, theCanvas.height);
//Box
context.strokeStyle = '#000000';
context.strokeRect(1, 1, theCanvas.width-2, theCanvas.height-2);
//Place balls
context.fillStyle = "#00AA00";
var ball;//object
for (var i =0; i <balls.length; i++) {
ball = balls[i];
ball.x += ball.xunits;
ball.y += ball.yunits;
context.beginPath();
context.arc(ball.x,ball.y,ball.radius,0,Math.PI*2,true);
context.closePath();
context.fill();
if (ball.x > theCanvas.width || ball.x < 0 ) {
ball.angle = 180 - ball.angle;
updateBall(ball);
} else if (ball.y > theCanvas.height || ball.y < 0) {
ball.angle = 360 - ball.angle;
updateBall(ball);
}
}
}
function updateBall(ball) {
ball.radians = ball.angle * Math.PI/ 180;
ball.xunits = Math.cos(ball.radians) * ball.speed;
ball.yunits = Math.sin(ball.radians) * ball.speed;
}
var numBalls = 100 ;
var maxSize = 8;
var minSize = 5;
var maxSpeed = maxSize+5;
var balls = new Array();
var tempBall;
var tempX;
var tempY;
var tempSpeed;
var tempAngle;
var tempRadius;
var tempRadians;
var tempXunits;
var tempYunits;
theCanvas = document.getElementById('canvasOne'); // <-- Code will not work if this is moved to the top of the method ---
context = theCanvas.getContext('2d');
for (var i = 0; i < numBalls; i++) {
tempRadius = Math.floor(Math.random()*maxSize)+minSize;
tempX = tempRadius*2 + (Math.floor(Math.random()*theCanvas.width)-tempRadius*2);
tempY = tempRadius*2 + (Math.floor(Math.random()*theCanvas.height)-tempRadius*2);
tempSpeed = maxSpeed-tempRadius;
tempAngle = Math.floor(Math.random()*360);
tempRadians = tempAngle * Math.PI/ 180;
tempXunits = Math.cos(tempRadians) * tempSpeed;
tempYunits = Math.sin(tempRadians) * tempSpeed;
tempBall = {x:tempX,y:tempY,radius:tempRadius, speed:tempSpeed, angle:tempAngle, xunits:tempXunits, yunits:tempYunits}
balls.push(tempBall);
}
function gameLoop() {
window.setTimeout(gameLoop, 20);
drawScreen()
}
gameLoop();
}
</script>
</head>
<body>
<div style="position: absolute; top: 50px; left: 50px;">
<canvas id="canvasOne" width="500" height="500">
Your browser does not support the HTML 5 Canvas.
</canvas>
</div>
</body>
</html>
</code></pre>
<p>The code is similar to another post which I posted but in this cases I was wondering why these two lines of code could not be moved to the top of the function.</p>
<p>Code here that does not seem to work at the top of the function.</p>
<pre><code> theCanvas = document.getElementById('canvasOne');
context = theCanvas.getContext('2d');
</code></pre>
<p>My canvas will not see any of the code that is drawn two it if this code is at the top of the function.</p>
<p>How can this become more efficient?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T23:41:28.460",
"Id": "80081",
"Score": "0",
"body": "Duplicate of http://codereview.stackexchange.com/questions/45790/splitting-canvas-app-into-separate-functions ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T00:09:06.133",
"Id": "80083",
"Score": "0",
"body": "Asking to debug non-working code is off-topic for Code Review. However, after [adding `//` before a stray remark](http://codereview.stackexchange.com/revisions/45892/2), I got it to work for me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T00:13:20.897",
"Id": "80084",
"Score": "0",
"body": "It's more of a follow-up question than a duplicate. In the future, please link follow-up questions to their predecessors as a courtesy to other users."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T00:22:07.733",
"Id": "80085",
"Score": "0",
"body": "This code works fine and I was the one that posted a similar example. Both of these are me, and if I need to I can remove this one if everyone wants me to. Just let me know."
}
] | [
{
"body": "<p>I don't see any problem when I move the two lines you mentioned to an earlier position (directly after the check for canvas support).</p>\n\n<ul>\n<li><p>You need to clean up the indention.</p></li>\n<li><p>Use one <code>var</code> statement with the variables separater with commas instead of multiple statements.</p></li>\n<li><p>No need to prefix all those variables with <code>temp...</code>. Also declare them inside the loop. That makes it clear that you only are using them in there.</p></li>\n<li><p>Your code to generate random integers between two limits is wrong. <code>tempRadius</code> will be between 5 and 12, but the <code>maxSize</code> is 8.</p></li>\n<li><p><code>tempX</code>/<code>tempY</code> calculation adds <code>2*tempRadius</code>, but then you subtract it again, so it has no effect. This is basiclly the same mistake as with the calculation of the radius (see next point). Also it seems to be the attempt to have the balls bounce when their size touch the walls instead of their center, but you fail to include this when calculating the bouncing.</p></li>\n<li><p>Considering both your attempts to get a random integer between to limits are wrong, you should write a simple function that does that (correctly). Test it.</p></li>\n<li><p>Apropos bouncing: The balls don't bounce off the walls any way. Currently they bounce when they happen to have passed the wall.</p></li>\n<li><p>There is no need to floor <code>tempAngle</code>.</p></li>\n<li><p>You can simplify the calculation of <code>tempRadians</code> to <code>tempRadians = Math.random() * 2 * Math.PI</code> .</p></li>\n<li><p>There is no need to recalculate <code>xunits</code>/<code>yunits</code> of the ball from the angle. When a ball bounces off the left or right walls, then <code>ball.xunits</code> simply becomes <code>-ball.xunits</code>. (Equivalently the top and bottom walls and <code>yunit</code>)</p></li>\n<li><p>You should use a <a href=\"http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html\" rel=\"nofollow\">module pattern</a> to wrap your code, so you don't need to use global variables (`context´).</p></li>\n</ul>\n\n<p>EDIT: Here's my version: <a href=\"http://jsfiddle.net/jjM3V/\" rel=\"nofollow\">http://jsfiddle.net/jjM3V/</a> (Not quite perfect, as it has some duplicate code in the bounce calculation, that I don't like).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T13:05:50.773",
"Id": "80134",
"Score": "0",
"body": "Nice this is so much better. How long have you been working in Javascript. What is the best way in your opinion to declare and object in Javascript. I have seen many different ways. I assume on the fiddle page that the script has to be wrapped in a (function to make it work)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T13:10:12.813",
"Id": "80135",
"Score": "0",
"body": "I am reading up on the module pattern part, that was why the code was wrapped in a function declaration on the fiddle page."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T13:42:54.287",
"Id": "80141",
"Score": "1",
"body": "I've been working with JavaScript for far too long :) There is no best way for classes (not objects). I use the method that seems appropriate to the given task. Most of the time I stay away from classes (e.g. the `new` keyword) anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T13:48:41.837",
"Id": "80143",
"Score": "0",
"body": "The doesn't \"have to be\" wrapped in a function, however this makes all enclosed functions and variables defined with `var` local to that function, so there are no global variables."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T14:05:40.717",
"Id": "80145",
"Score": "0",
"body": "From what I read in Javascript there should be no global variables used at all. Or how does this work? What if by changed you had one variable that you needed to use globaly but I guess if you had all of your code in a function wrapper there would be no really need for a global variable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T14:06:46.290",
"Id": "80146",
"Score": "0",
"body": "To respond to the question above with objects. Can you show a simple example of how you would declare one. You can put up a JSFiddle if you want."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T14:15:27.877",
"Id": "80147",
"Score": "0",
"body": "Exactly. Global variables always have the danger, that they will collide (be overwritten) by another script in the same page. The module pattern makes sure that a given script only has one global variable (\"the module\"), so that developers only need to make sure that multiple scripts use their own single, unique variable name. And you only need that global variable in the first place, if other scripts are supposed to access/call/use that module. In this example no external access is needed, so you don't need a global variable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T14:16:19.833",
"Id": "80148",
"Score": "0",
"body": "This isn't really the place fro a tutorial. Have a look for example at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript to learn how classes/objects work in JS."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T10:17:29.090",
"Id": "45932",
"ParentId": "45892",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T23:32:39.070",
"Id": "45892",
"Score": "5",
"Tags": [
"javascript",
"canvas",
"animation"
],
"Title": "Bouncing ball in JavaScript"
} | 45892 |
<p>Please let me know your thoughts on the code below, please be brutal. Here is the question I solved:</p>
<p>Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).</p>
<p>For example:
Given binary tree {3,9,20,#,#,15,7},</p>
<pre><code> 3
/ \
9 20
/ \
15 7
</code></pre>
<p>return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]</p>
<pre><code> public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
if(root==null){
return res;
}
ArrayList<Integer> level = new ArrayList<Integer>();
level.add(root.val);
res.add(level);
int depth=1;
queue.add(root);
TreeNode empty = new TreeNode(2);
queue.add(null);
level = new ArrayList<Integer>();
while(!queue.isEmpty()){
TreeNode curr = queue.poll();
if(curr==null){
if(!queue.isEmpty()){
queue.add(null);
}
else{
break;
}
res.add(level);
level = new ArrayList<Integer>();
depth++;
}
else{
if(depth%2==0){
if(curr.left!=null){
level.add(curr.left.val);
queue.add(curr.left);
}
if(curr.right!=null){
level.add(curr.right.val);
queue.add(curr.right);
}
}
else{
if(curr.right!=null){
level.add(curr.right.val);
queue.add(curr.right);
}
if(curr.left!=null){
level.add(curr.left.val);
queue.add(curr.left);
}
}
}
}
return res;
}
</code></pre>
| [] | [
{
"body": "<p>Just the first few steps of refactoring:</p>\n\n<ol>\n<li><p><code>ArrayList<...></code> reference types should be simply <code>List<...></code>:</p>\n\n<pre><code>List<List<Integer>> res = new ArrayList<>();\n</code></pre>\n\n<p>See: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p></li>\n<li><p>This variable is never used, remove it:</p>\n\n<blockquote>\n<pre><code>TreeNode empty = new TreeNode(2);\n</code></pre>\n</blockquote></li>\n<li><p>I would avoid abbreviations like <code>res</code>, <code>curr</code> and <code>val</code>. They are not too readable and I suppose you have autocomplete (if not, use an IDE, it helps a lot), so using longer names does not mean more typing but it would help readers and maintainers a lot since they don't have to remember the purpose of each variable - the name would express the programmers intent and would not force readers to decode the abbreviations every time they read/maintain the code.</p>\n\n<p>Furthermore, if you type <code>resu</code> and press Ctrl+Space for autocomplete in Eclipse it founds nothing which is rather disturbing.</p></li>\n<li><p>These two lines are duplicated:</p>\n\n<blockquote>\n<pre><code>level.add(curr.left.val);\nqueue.add(curr.left);\n</code></pre>\n</blockquote>\n\n<p>You could extract out a method for that:</p>\n\n<pre><code> private void visit(List<Integer> level, Queue<TreeNode> queue, TreeNode left) {\n level.add(left.val);\n queue.add(left);\n}\n</code></pre></li>\n<li><p>After that you might notice the similarity between the method above and the body of the following <code>if</code> statement:</p>\n\n<blockquote>\n<pre><code>if(curr.right!=null){\n level.add(curr.right.val);\n queue.add(curr.right);\n}\n</code></pre>\n</blockquote>\n\n<p>You could use the same method here too:</p>\n\n<pre><code>if (curr.right != null) {\n visit(level, queue, curr.right);\n}\n</code></pre>\n\n<p>Of course, renaming the method's parameter will increase clarity:</p>\n\n<pre><code>private void visit(List<Integer> level, Queue<TreeNode> queue, TreeNode node) {\n level.add(node.val);\n queue.add(node);\n}\n</code></pre></li>\n<li><p>So, currently the end of the original method looks like the following:</p>\n\n<pre><code>if (depth % 2 == 0) {\n if (curr.left != null) {\n visit(level, queue, curr.left);\n }\n if (curr.right != null) {\n visit(level, queue, curr.right);\n\n }\n} else {\n if (curr.right != null) {\n visit(level, queue, curr.right);\n }\n if (curr.left != null) {\n visit(level, queue, curr.left);\n }\n}\n</code></pre>\n\n<p>You could remove some more duplication by moving the null check into the <code>visit</code> method:</p>\n\n<pre><code>private void visit(List<Integer> level, Queue<TreeNode> queue, TreeNode node) {\n if (node == null) {\n return;\n }\n level.add(node.val);\n queue.add(node);\n}\n</code></pre>\n\n<p>(I've used a <a href=\"http://blog.codinghorror.com/flattening-arrow-code/\" rel=\"nofollow\">guard clause here to make the code flatten</a>.)</p>\n\n<p>Usage:</p>\n\n<pre><code>if (depth % 2 == 0) {\n visit(level, queue, currentNode.left);\n visit(level, queue, currentNode.right);\n} else {\n visit(level, queue, currentNode.right);\n visit(level, queue, currentNode.left);\n}\n</code></pre></li>\n<li><p>I would also invert the condition here to get a guard clause:</p>\n\n<blockquote>\n<pre><code>if(!queue.isEmpty()){\n queue.add(null);\n}\nelse{\n break;\n}\n</code></pre>\n</blockquote>\n\n<p>Result:</p>\n\n<pre><code>if (queue.isEmpty()) {\n break;\n}\nqueue.add(null);\n</code></pre></li>\n<li><p>There are seven lines between the declaration of the queue and its first usage:</p>\n\n<blockquote>\n<pre><code>Queue<TreeNode> queue = new LinkedList<>();\nif (root == null) {\n return result;\n}\nList<Integer> level = new ArrayList<Integer>();\nlevel.add(root.val);\nresult.add(level);\nint depth = 1;\nqueue.add(root);\n</code></pre>\n</blockquote>\n\n<p>It could have smaller scope and could be closer to its first usage:</p>\n\n<pre><code>if (root == null) {\n return result;\n}\nList<Integer> level = new ArrayList<Integer>();\nlevel.add(root.val);\nresult.add(level);\nint depth = 1;\nQueue<TreeNode> queue = new LinkedList<>();\nqueue.add(root);\n</code></pre>\n\n<p>(<em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T22:50:53.863",
"Id": "80242",
"Score": "0",
"body": "I like how you refer to Effective Java, do you think I should read that book?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T04:58:48.103",
"Id": "80265",
"Score": "0",
"body": "@bazang: It was an eye-opener for me with great tips, highly recommended. You can find another good books here: http://codereview.stackexchange.com/q/31/7076"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T18:33:55.553",
"Id": "45965",
"ParentId": "45893",
"Score": "1"
}
},
{
"body": "<p>Branching to change behavior is a code smell. A cleaner design would be to use the State pattern, and let the state toggle each time you descend to the next layer of the tree.</p>\n\n<p>Also, I think you've made things less clear by tangling your traversal logic, with your output logic. Which is to say, instead of doing something with the child, and something with the child values, instead of working with the parent value and adding the children to the traversal tree.</p>\n\n<p>In pseudo code, I would expect the logic to look like</p>\n\n<pre><code>currentNodes = [ root ]\nwhile( currentNodes.notEmpty ) {\n state = state.switch\n valueList = report.nextValues\n\n nextNodes = []\n\n for ( node : currentNodes ) {\n valueList.add(node.value)\n\n nextNodes.add( state.order(node.left, node.right) )\n }\n currentNodes = nextNodes.reverse;\n}\n\nreturn report\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T18:38:51.453",
"Id": "45966",
"ParentId": "45893",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "45965",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T23:36:24.450",
"Id": "45893",
"Score": "3",
"Tags": [
"java",
"algorithm",
"interview-questions"
],
"Title": "ZigZag order of a tree traversal"
} | 45893 |
<p>A brief background:</p>
<p>I'm working on a game prototype for a simple strategy game. After I created a number of possible jobs I wanted to create something to manage them. This is the first time I've attempted something like this so code review would be helpful. </p>
<p>I created a set of methods that adds Jobs to a Job Queue and assigns them to Dwarves if they don't currently have a job. That way, the player can add a number of jobs, and as long as the job is valid, it will be added to the Queue.</p>
<p>First the relevant enum:</p>
<pre><code>typedef enum {
MiningJob = 0,
LadderJob,
BottomBuildJob,
WallBuildJob,
RoomBuildJob
}JobType;
</code></pre>
<p>Here is the main code for the Job Queue:</p>
<pre><code>#pragma mark - Job Queue
-(void) addJobToQueueOfType:(int)jobType forFloor:(int)floorNumber {
if ([self checkIfFloor:floorNumber isValidForJob:jobType]) {
DTJob *tempJob = [[DTJob alloc]init];
tempJob.jobType = jobType;
tempJob.floorNumber = floorNumber;
[_jobQueue insertObject:tempJob atIndex:0];
}
}
-(BOOL) checkIfFloor:(int)floorNumber isValidForJob:(int)jobType {
NSNumber *floorNum = [NSNumber numberWithInt:floorNumber];
DTTowerFloor *tempFloor = [self.gameTower.towerDict objectForKey:floorNum];
switch (jobType) {
case MiningJob:
if (tempFloor.hasLadder && tempFloor.isRevealed && tempFloor.blockPercentageRemaining > 0) {
return YES;
}
break;
case LadderJob:
if (!tempFloor.hasLadder && tempFloor.isRevealed && self.currentCommonResources >= _ladderCost && !tempFloor.hasActiveWorker) {
return YES;
}
break;
case BottomBuildJob:
if (tempFloor.isRevealed && tempFloor.hasLadder && tempFloor.blockPercentageRemaining <= 0 && !tempFloor.hasBottom && self.currentCommonResources >= _bottomCost && !tempFloor.hasActiveWorker) {
return YES;
}
break;
case WallBuildJob:
if (tempFloor.isRevealed && tempFloor.hasBottom && !tempFloor.hasWalls && self.currentCommonResources >= _wallCost && !tempFloor.hasActiveWorker) {
return YES;
}
break;
case RoomBuildJob:
if (tempFloor.isRevealed && tempFloor.hasBottom && tempFloor.hasWalls && self.currentCommonResources >= _roomCost && !tempFloor.hasActiveWorker) {
return YES;
}
break;
default:
break;
}
return NO;
}
-(void) assignJob:(DTJob *)job toDwarf:(DTDwarf *)dwarf {
switch (job.jobType) {
case MiningJob:
[self assignMiningJobToDwarf:dwarf forFloor:job.floorNumber];
break;
case LadderJob:
[self assignLadderJobToDwarf:dwarf forFloor:job.floorNumber];
break;
case BottomBuildJob:
[self assignBottomBuildJobToDwarf:dwarf forFloor:job.floorNumber];
break;
case WallBuildJob:
[self assignWallBuildJobToDwarf:dwarf forFloor:job.floorNumber];
break;
case RoomBuildJob:
[self assignRoomBuildJobToDwarf:dwarf forFloor:job.floorNumber];
break;
default:
break;
}
}
//this is called from the update loop
-(BOOL) isDwarfAvailable {
for (DTDwarf *tempDwarf in self.dwarves) {
if (!tempDwarf.hasJobAssigned && !tempDwarf.isMoving) {
_nextDwarf = tempDwarf;
return YES;
}
}
return NO;
}
</code></pre>
<p>Here is the call from the Update loop which runs every 0.25 seconds according to the time step of the SKScene:</p>
<pre><code>-(void) checkAssignJobToDwarfFromQueue {
if ([self isDwarfAvailable] && _jobQueue.count > 0) {
DTJob *tempJob = [_jobQueue lastObject];
[_jobQueue removeLastObject];
if (_nextDwarf != nil && !_nextDwarf.hasJobAssigned) {
[self assignJob:tempJob toDwarf:_nextDwarf];
}
}
}
</code></pre>
<p>Forgot to post the last part. This is how the SKScene sends the Job to the Queue. There are two different menus, so I couldn't see how to use the enum for the names here.</p>
<pre><code>#pragma mark - Interaction with the Game
-(void) doSimpleJob:(int)jobNumber forFloor:(int)floorNumber {
switch (jobNumber) {
case 0:
//mining job
[_game addJobToQueueOfType:MiningJob forFloor:floorNumber];
break;
case 1:
//ladder job
[_game addJobToQueueOfType:LadderJob forFloor:floorNumber];
break;
case 2:
[self buildBuildingSelectionBoxForFloor:floorNumber];
_buildingSelectionBoxIsOpen = YES;
break;
default:
break;
}
}
-(void) doBuildJob:(int)jobNumber{
switch (jobNumber) {
case 0:
//bottom build job
[_game addJobToQueueOfType:BottomBuildJob forFloor:_selectedFloor];
break;
case 1:
//wall build job
[_game addJobToQueueOfType:WallBuildJob forFloor:_selectedFloor];
break;
case 2:
//room build job
[_game addJobToQueueOfType:RoomBuildJob forFloor:_selectedFloor];
break;
default:
break;
}
}
</code></pre>
| [] | [
{
"body": "<p>Let's make your relevant enum more relevant:</p>\n<pre><code>typedef NS_ENUM(NSInteger, JobType) {\n MiningJob = 0,\n LadderJob,\n BottomBuildJob,\n WallBuildJob,\n RoomBuildJob\n};\n</code></pre>\n<p>Now let's change the argument type of all the methods where we want to send a job type:</p>\n<p>As example, get rid of this:</p>\n<pre><code>- (void)doBuildJob:(int)jobNumber...\n</code></pre>\n<p>And use this:</p>\n<pre><code>- (void)doBuildJob:(JobType)jobType {\n switch (jobType) {\n case BottomBuildJob: \n // stuff\n break;\n case WallBuildJob: \n // stuff\n break;\n case RoomBuildJob:\n // stuff\n break;\n case MiningJob:\n case LadderJob:\n default:\n break;\n}\n</code></pre>\n<p>There's very little point in <code>typedef</code>ing an <code>enum</code> if you're not going to use it as a type. But with that said, <code>typedef</code>ing an <code>enum</code> is definitely the right path. We want to make our code more clear, and <code>enum</code>s are a great way to do that. <code>typedef</code>ing them means we can use them as a type for method arguments.</p>\n<p>Also, when <code>switch</code>ing an a <code>typedef enum</code>, Xcode will help us autocomplete all the types, and warn us if we're missing one. This is why we have the empty cases. Partly to stop Xcode from crying, but mostly to make it explicitly clear that we intend to do nothing in these cases.</p>\n<p>This also eliminates the need for comments in some places.</p>\n<p>Isn't <code>case MiningJob:</code> much better than <code>case 0: // mining job</code>?</p>\n<p>And that's good Objective-C style. Use class, typedef, method, and variable names that help reduce the need for comments. Objective-C is the pinnacle of self-documenting code, so let's be sure we're using its tools to make our code self-documenting.</p>\n<hr />\n<p>The <code>checkIfFloor:isValidForJob:</code> could be refactored as such:</p>\n<pre><code>-(BOOL) checkIfFloor:(int)floorNumber isValidForJob:(int)jobType {\n NSNumber *floorNum = [NSNumber numberWithInt:floorNumber];\n DTTowerFloor *tempFloor = [self.gameTower.towerDict objectForKey:floorNum];\n switch (jobType) {\n case MiningJob:\n return (tempFloor.hasLadder && tempFloor.isRevealed && tempFloor.blockPercentageRemaining > 0);\n case LadderJob:\n return (!tempFloor.hasLadder && tempFloor.isRevealed && self.currentCommonResources >= _ladderCost && !tempFloor.hasActiveWorker);\n case BottomBuildJob:\n return (tempFloor.isRevealed && tempFloor.hasLadder && tempFloor.blockPercentageRemaining <= 0 && !tempFloor.hasBottom && self.currentCommonResources >= _bottomCost && !tempFloor.hasActiveWorker);\n case WallBuildJob:\n return (tempFloor.isRevealed && tempFloor.hasBottom && !tempFloor.hasWalls && self.currentCommonResources >= _wallCost && !tempFloor.hasActiveWorker);\n case RoomBuildJob:\n return (tempFloor.isRevealed && tempFloor.hasBottom && tempFloor.hasWalls && self.currentCommonResources >= _roomCost && !tempFloor.hasActiveWorker);\n default:\n return NO;\n }\n}\n</code></pre>\n<p>And that's a good start... but these conditionals are really complicated. What might be best is an individual method for each of these conditions. Where, <code>MiningJob</code> as an example might look like this:</p>\n<pre><code>- (BOOL)canDoMiningJob {\n return (self.hasLadder &&\n self.isRevealed &&\n self.blockPercentageRemainig > 0);\n}\n</code></pre>\n<p>This would be an instance method on <code>DTTowerFloor</code>.</p>\n<p>And then in the above switch statement I mentioned refactoring, we can now just do this...</p>\n<pre><code>switch (jobType) {\n case MiningJob: return [tempFloor canDoMiningJob];\n case LadderJob: return [tempFloor canDoLadderJob];\n case BottomBuildJob: return [tempFloor canDoBottomBuildJob];\n case WallBuildJob: return [tempFloor canDoWallBuildJob];\n case RoomBuildJob: return [tempFloor canDoRoomBuildJob]; \n default: return NO;\n}\n</code></pre>\n<hr />\n<p>Now, beyond this, it's hard to make too many comments. You haven't shown us what kind of object <code>_jobQueue</code> is, or how you're using it beyond putting objects into the queue.</p>\n<p>For now, I'll assume it's just an <code>NSArray</code>. I'm curious as to why you're inserting new tasks at the beginning of the array. Inserting to the beginning of an array is a particularly expensive operation. Even in Objective-C, where our array simple holds pointers to objects (and pointers are significantly smaller than entire objects and much easier to move around), when we insert at the beginning, every other pointer in the array has to be shifted to the right by 1.</p>\n<p>Now, from a gameplay perspective, you can only be handling the queue in one of two ways. It's either first in first out, or first in last out. If it's the former, then tasks are popped out of the queue and completed in the order they were inserted. If it's the latter, then tasks are continually stacked on the queue, and the first task put on the queue isn't completed until every other object put on the queue after it has been completed.</p>\n<p>Either way, going with the assumption that your queue is simply an <code>NSArray</code>, I'm going to make the argument that you shouldn't be inserting at the front of the array.</p>\n<hr />\n<h1>Situation One - First In, First Out</h1>\n<p>In this situation, when tasks are completed, we remove the one that's been in the queue the longest. So, doing it your way and inserting at the front, this is as simple as popping <code>[_jobQueue lastObject]</code> out of the array and performing that task. Modifying the back-end of an array is highly efficient relative to the front end--especially when removing objects.</p>\n<p>But, I'm going to make the assumption that players will be able to CANCEL tasks they've put in the queue, and I'm going to make the assumption that modifying the queue is an action that will generally speaking go a lot faster than the game actually completing the tasks. Are these fair assumptions?</p>\n<p>If the assumptions are fair, then we want to be adding to the back end of the queue. We can still remove the first object when that task is completed. We can remove any object at any index, just as we can insert any object at any index. And it's not particularly efficient to remove from the front end (it's the same efficiency as inserting at the front end though)... but if player-controlled modification of the queue is likely to happen at a higher frequency (because they can insert/remove all they want) than game-controlled removal from the queue, then we need to put the one that happens less frequently at the less efficient end.</p>\n<p>So, insert at the back (simply <code>addOjbect:</code>) and remove from the front when tasks are completed (or from the specific point when a player cancels a tasks).</p>\n<hr />\n<h1>Situation Two - First In, Last Out</h1>\n<p>I think this might be the less likely scenario, but if this IS the scenario, it makes the decision far easier. If you insert at the front, you also have to remove from the front. If you insert at the back, you remove from the back. Inserting & removing to the front are both highly inefficient (relative to the back) and you're guaranteed to be mostly modifying the front end as this is the end you're inserting to and definitely popping off from. So just use the back end.</p>\n<hr />\n<p>Ultimately though, the most efficient way to handle the queue though, would be with a doubly-linked list with a head and a tail. But that's a whole different topic. I highly recommend you implement a doubly-linked list to handle the queue, but I feel that is way outside the scope of this QA.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T14:22:35.283",
"Id": "80779",
"Score": "0",
"body": "This was extremely helpful. You were right that it was an NSArray. Thanks for writing this up! I'm sure it will help other people as well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T11:44:15.877",
"Id": "45935",
"ParentId": "45897",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "45935",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T00:48:17.747",
"Id": "45897",
"Score": "2",
"Tags": [
"game",
"objective-c",
"queue"
],
"Title": "Job queue that performs actions"
} | 45897 |
<p>This question is a follow-up to a <a href="https://codereview.stackexchange.com/q/40119/31982">previous version</a> of this program, which I wrote because I found it annoying that <a href="https://www.videolan.org/vlc/index.html" rel="nofollow noreferrer">VLC Media Player</a> (which I love) prevents the screensaver from starting after playback of media has ended on my Ubuntu 12.04 system.</p>
<p>There have been several changes which are listed in the comments at the top of the code.</p>
<p>I'm not trying to play code golf, but I'm looking for ways to shorten the code or do things more efficiently. General suggestions for any other improvements or ways to make this code more portable are welcome.</p>
<pre><code>/* VLC-Watchdog v6
* by Jeremy B. Beck
*
* A fix for stopped VLC Media Player inhibiting the power management
* daemon and preventing screen saver and/or monitor power off on my Ubuntu
* 12.04 system using the DBus low level API.
*
* Takes start | stop as command line argument.
*
* Checks if VLC Media Player is running by searching for the interface in
* the DBus list of interface names. If VLC is found to be running,
* queries the playback status through the DBus Get method. If the
* playback status is found to be stopped, calls the Quit() method via
* DBus. If VLC is found not to be running, VLC-Watchdog sleeps for 30
* seconds then repeats all of the above. When VLC-Watchdog receives
* the stop signal (eg. "VLC-Watchdog stop" from the command line) it exits.
*
* Changed in v6:
* + Check if VLC is running by looking for the interface name via DBus
* instead of using pgrep.
* + Cleaned up code to connect to session bus. Connect to bus in main()
* and pass the connection pointer to the methods that need it instead of
* creating a new connection in every method.
*
* Changed in v5:
* + double check if VLC is stopped after 10 sec delay to prevent quitting
* VLC while it is starting up or loading media
* Changed in v4:
* + cleaned up error logging
* + time stamped error log entries
*/
#include <stdio.h>
#include <stdlib.h>
#include <dbus/dbus.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
static void skeleton_daemon();
int vlc_running(DBusConnection *conn);
int vlc_stopped(DBusConnection *conn, int pid);
int quit_vlc(DBusConnection *conn, int pid);
void usage(char *pname);
void sig_handler(int signo);
void log_error(const char *format, ...);
extern int running = 1;
extern int err_count = 0;
int main(int argc, char *argv[]) {
FILE *fp;
int pid, status;
DBusConnection *conn;
DBusError err;
//check command line arguments for validity
if ((argc != 2) || (
(strcmp(argv[1], "start") != 0) &&
(strcmp(argv[1], "stop") != 0)))
usage(argv[0]);
//start / run actions
if (strcmp(argv[1], "start") == 0) {
skeleton_daemon(); //daemonize
//check if DBus is loaded
if (getenv("DBUS_SESSION_BUS_ADDRESS") == NULL) {
log_error("DBus session bus address == NULL\n");
log_error("stopping VLC-Watchdog\n");
exit(1);
}
//write the PID to a file for future reference
fp = fopen("/tmp/vlcwatchdog.pid", "w");
fprintf(fp, "%d\n", getpid());
fclose(fp);
//register signal handler
if (signal(SIGUSR1, sig_handler) == SIG_ERR) {
log_error("error while setting signal handler\n");
exit(1);
}
/* when first started and every 30 seconds thereafter, check if
* VLC is running, check if it is stopped, ask it to Quit() if it
* is stopped. Stop and exit when SIGUSR1 is received */
dbus_error_init(&err); // init DBus error
conn = dbus_bus_get(DBUS_BUS_SESSION, &err); //connect to session bus
if (conn == NULL) {
log_error(err.message);
return 1;
}
while (running) {
if ((pid = vlc_running(conn))) {
/* if VLC is stopped wait 10 sec then check if it is still
* stopped in an attempt to prevent quitting VLC while it is
* starting up or loading media */
if (vlc_stopped(conn, pid)) {
sleep(10);
if (vlc_stopped(conn, pid)) {
if((status = quit_vlc(conn, pid)) == 1) {
log_error("quit_vlc() returned 1. exiting\n");
break;
}
}
}
}
if (err_count >= 10) {
log_error("error count exceeded. exiting\n");
break;
}
sleep(30);
}
//remove temporary file
if (remove("/tmp/vlcwatchdog.pid") == -1) {
log_error("error removing temporary file /tmp/vlcwatchdog.pid");
exit(1);
}
}
//stop actions
if (strcmp(argv[1], "stop") == 0) {
//retrieve PID from file
if (access("/tmp/vlcwatchdog.pid", R_OK) != -1) {
fp = fopen("/tmp/vlcwatchdog.pid", "r");
if (fscanf(fp, "%d", &pid) != 1) {
log_error("fscanf failed to read PID from file while stopping\n");
}
fclose(fp);
}
//if unable to read PID from file, try pgrep
else {
char whatsmyname[256], s[32];
sprintf(whatsmyname, "%s%s", "pgrep ", argv[0]);
fp = popen(whatsmyname, "r");
if (fp != NULL) {
if (fgets(s, 32, fp) != NULL) {
sscanf(s, "%d", &pid);
fclose(fp);
}
else {
fclose(fp);
fprintf(stderr, "daemon does not appear to be running\n");
exit(1);
}
}
else {
fclose(fp);
log_error("popen failed while stopping\n");
exit(1);
}
}
//issue stop signal to VLC-Watchdog daemon
kill(pid, SIGUSR1);
}
exit(0);
}
/* deamonize the process */
static void skeleton_daemon() {
pid_t pid;
/* Fork off the parent process */
pid = fork();
/* An error occurred */
if (pid < 0)
exit(EXIT_FAILURE);
/* Success: Let the parent terminate */
if (pid > 0)
exit(EXIT_SUCCESS);
/* On success: The child process becomes session leader */
if (setsid() < 0)
exit(EXIT_FAILURE);
/* Fork off for the second time*/
pid = fork();
/* An error occurred */
if (pid < 0)
exit(EXIT_FAILURE);
/* Success: Let the parent terminate */
if (pid > 0)
exit(EXIT_SUCCESS);
/* Set new file permissions */
umask(0);
/* Change the working directory to the root directory */
/* or another appropriated directory */
if (chdir("/") != 0) {
log_error("chdir failed in skeleton_daemon\n");
exit(1);
}
/* Close all open file descriptors */
int x;
for (x = sysconf(_SC_OPEN_MAX); x>0; x--)
{
close (x);
}
}
/* check if VLC is stopped, if so, return 1, return 0 otherwise */
int vlc_stopped(DBusConnection *conn, int pid) {
DBusError err;
DBusMessage *method_call, *reply;
DBusMessageIter iter, sub_iter;
int arg_type = 0;
const char *prop_iface = "org.mpris.MediaPlayer2.Player";
const char *prop_iface_method_name = "PlaybackStatus";
const char *pb_stat;
char name[80];
//append the pid to the name of the destination
sprintf (name, "%s%d", "org.mpris.MediaPlayer2.vlc-", pid);
dbus_error_init(&err); // init DBus error
//create the method call to be used to get playback status of VLC
method_call = dbus_message_new_method_call(name,
"/org/mpris/MediaPlayer2", "org.freedesktop.DBus.Properties",
"Get");
if (method_call == NULL) {
log_error("Get() method call is NULL after creation\n");
return 1;
}
//put the method arguments on the message
if (!dbus_message_append_args(method_call, DBUS_TYPE_STRING,
&prop_iface, DBUS_TYPE_STRING, &prop_iface_method_name,
DBUS_TYPE_INVALID)) {
log_error("failed to append args to message\n");
return 1;
}
//call the method, get the reply, check for error
reply = dbus_connection_send_with_reply_and_block (conn,
method_call, -1, &err);
//this error can be recovered from
if (reply == NULL) {
log_error("null reply \n %s \n", err.message);
dbus_error_free(&err);
err_count++;
return 0;
}
//initialize an iterator pointing to arguments in reply message
if (!dbus_message_iter_init (reply, &iter)) {
log_error("reply message has no arguments\n");
return 1;
}
//check the type of the first argument (should be variant)
arg_type = dbus_message_iter_get_arg_type(&iter);
if (arg_type != DBUS_TYPE_VARIANT) {
log_error("Expected variant, got %d\n", arg_type);
return 1;
}
//recurse into the variant container to get an iter to the string
dbus_message_iter_recurse(&iter, &sub_iter);
//check the type of the value in the variant (should be string)
arg_type = dbus_message_iter_get_arg_type(&sub_iter);
if (arg_type != DBUS_TYPE_STRING) {
log_error("Expected string, got %d\n", arg_type);
return 1;
}
//extract the value of the string from sub_iter
dbus_message_iter_get_basic(&sub_iter, &pb_stat);
//if VLC is stopped, return 1, otherwise 0
if (strcmp("Stopped", pb_stat) == 0)
return 1;
else
return 0;
}
/* call the VLC Quit() method via DBus return 0 on success, 1 otherwise */
int quit_vlc(DBusConnection *conn, int pid) {
DBusMessage *method_call;
char name[80];
//append the pid to the name of the destination
sprintf (name, "%s%d", "org.mpris.MediaPlayer2.vlc-", pid);
//initialize the Quit() method call message
method_call = dbus_message_new_method_call(name,
"/org/mpris/MediaPlayer2", "org.mpris.MediaPlayer2", "Quit");
if (method_call == NULL) {
log_error("Quit() method call NULL after creation");
return 1;
}
//send the Quit() message, report error if any
if (!dbus_connection_send(conn, method_call, NULL)) {
log_error("Send of Quit() call message failed\n");
return 1;
}
return 0;
}
/* return PID of VLC if it is running, 0 otherwise */
int vlc_running(DBusConnection *conn) {
DBusError err;
DBusMessage *method_call, *reply;
DBusMessageIter iter, sub_iter;
int arg_type = 0, pid = 0;
const char *string;
dbus_error_init(&err); // init DBus error
method_call = dbus_message_new_method_call("org.freedesktop.DBus",
"/org/freedesktop/DBus", "org.freedesktop.DBus", "ListNames");
//call the method, get the reply, check for error
reply = dbus_connection_send_with_reply_and_block (conn,
method_call, -1, &err);
//initialize an iterator pointing to arguments in reply message
if (!dbus_message_iter_init (reply, &iter)) {
log_error("reply message has no arguments\n");
return 1;
}
//check the type of the first argument (should be array)
arg_type = dbus_message_iter_get_arg_type(&iter);
if (arg_type != DBUS_TYPE_ARRAY) {
log_error("Expected array, got %d\n", arg_type);
return 1;
}
//recurse into the array container to get an iter to the string
dbus_message_iter_recurse(&iter, &sub_iter);
//check the type of the value in the array (should be string)
arg_type = dbus_message_iter_get_arg_type(&sub_iter);
if (arg_type != DBUS_TYPE_STRING) {
log_error("Expected string, got %d\n", arg_type);
return 1;
}
//extract the values of the strings from sub_iter
while (dbus_message_iter_has_next(&sub_iter)) {
dbus_message_iter_get_basic(&sub_iter, &string);
if (strstr(string, "org.mpris.MediaPlayer2.vlc-") != NULL) {
//extract the PID from the string
sscanf(string, "org.mpris.MediaPlayer2.vlc-%d", &pid);
return pid;
}
else //go to the next array element
dbus_message_iter_next(&sub_iter);
}
//VLC interface was not found. Assume VLC is not running.
return 0;
}
/* Print the usage help then exit */
void usage(char *pname) {
fprintf(stderr, "usage: %s start | stop\n", pname);
exit(1);
}
/* Signal handler function */
void sig_handler(int signo) {
if (signo == SIGUSR1)
running = 0;
return;
}
/* Write errors to a log file */
void log_error(const char *format, ...)
{
va_list args;
FILE *errlog;
time_t t = time(NULL);
errlog = fopen("/tmp/vlcwderr.log", "a");
fprintf(errlog, "%s ", asctime(localtime(&t)));
va_start(args, format);
vfprintf(errlog, format, args);
va_end(args);
fclose(errlog);
return;
}
</code></pre>
| [] | [
{
"body": "<p>Define your variable in the smallest possible scope as it make things easier to understand.</p>\n\n<hr>\n\n<p>Avoid hardcoded strings and magic numbers in your code. In you do need them, make sure you define them in a single place ( <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\">Don't Repeat Yourself</a> ) .</p>\n\n<hr>\n\n<p>Split your logic into smaller functions. In your case, one can easily see that <code>start</code> and <code>stop</code> are good candidates.</p>\n\n<hr>\n\n<p>Re-opening and closing the file every time you need to log something does not seem like an efficient solution. In your case, it might do the trick.</p>\n\n<hr>\n\n<p>You don't need to have <code>return;</code> at the end of a function.</p>\n\n<hr>\n\n<p>You should try to use <code>return</code> to let the calling functions (try to) handle the errors instead of <code>exit</code>-ing from everywhere in the code.</p>\n\n<hr>\n\n<p>Here's a non tested version of your code after taking into account these simple comments : </p>\n\n<pre><code>/* VLC-Watchdog v6\n * by Jeremy B. Beck\n *\n * A fix for stopped VLC Media Player inhibiting the power management\n * daemon and preventing screen saver and/or monitor power off on my Ubuntu\n * 12.04 system using the DBus low level API.\n *\n * Takes start | stop as command line argument.\n *\n * Checks if VLC Media Player is running by searching for the interface in\n * the DBus list of interface names. If VLC is found to be running,\n * queries the playback status through the DBus Get method. If the\n * playback status is found to be stopped, calls the Quit() method via\n * DBus. If VLC is found not to be running, VLC-Watchdog sleeps for 30\n * seconds then repeats all of the above. When VLC-Watchdog receives\n * the stop signal (eg. \"VLC-Watchdog stop\" from the command line) it exits.\n *\n * Changed in v6:\n * + Check if VLC is running by looking for the interface name via DBus\n * instead of using pgrep.\n * + Cleaned up code to connect to session bus. Connect to bus in main()\n * and pass the connection pointer to the methods that need it instead of\n * creating a new connection in every method.\n *\n * Changed in v5:\n * + double check if VLC is stopped after 10 sec delay to prevent quitting\n * VLC while it is starting up or loading media\n * Changed in v4:\n * + cleaned up error logging\n * + time stamped error log entries\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <dbus/dbus.h>\n#include <unistd.h>\n#include <string.h>\n#include <signal.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <time.h>\n\nstatic void skeleton_daemon();\nint vlc_running(DBusConnection *conn);\nint vlc_stopped(DBusConnection *conn, int pid);\nint quit_vlc(DBusConnection *conn, int pid);\nvoid usage(char *pname);\nvoid sig_handler(int signo);\nvoid log_error(const char *format, ...);\n\nextern int running = 1;\nextern int err_count = 0;\n\n#define PATH_TO_VLCWATCHDOG_PID \"/tmp/vlcwatchdog.pid\"\n#define PATH_TO_MEDIAPLAYER \"/org/mpris/MediaPlayer2\"\n\nint main(int argc, char *argv[]) {\n if (argc==2)\n {\n //start / run actions\n if (strcmp(argv[1], \"start\") == 0) {\n return do_start();\n }\n //stop actions\n else if (strcmp(argv[1], \"stop\") == 0) {\n return do_stop();\n }\n }\n\n //check command line arguments are not valid \n usage(argv[0]);\n exit(1);\n}\n\nint do_start()\n{\n skeleton_daemon(); //daemonize\n //check if DBus is loaded\n if (getenv(\"DBUS_SESSION_BUS_ADDRESS\") == NULL) {\n log_error(\"DBus session bus address == NULL\\n\");\n log_error(\"stopping VLC-Watchdog\\n\");\n return(1);\n }\n //write the PID to a file for future reference\n FILE * fp = fopen(PATH_TO_VLCWATCHDOG_PID, \"w\");\n fprintf(fp, \"%d\\n\", getpid());\n fclose(fp);\n //register signal handler\n if (signal(SIGUSR1, sig_handler) == SIG_ERR) {\n log_error(\"error while setting signal handler\\n\");\n return(1);\n }\n /* when first started and every 30 seconds thereafter, check if\n * VLC is running, check if it is stopped, ask it to Quit() if it\n * is stopped. Stop and exit when SIGUSR1 is received */\n DBusError err;\n dbus_error_init(&err); // init DBus error\n DBusConnection *conn = dbus_bus_get(DBUS_BUS_SESSION, &err); //connect to session bus\n if (conn == NULL) {\n log_error(err.message);\n return 1;\n }\n while (running) {\n if (int pid = vlc_running(conn)) {\n /* if VLC is stopped wait 10 sec then check if it is still\n * stopped in an attempt to prevent quitting VLC while it is\n * starting up or loading media */\n if (vlc_stopped(conn, pid)) {\n sleep(10);\n if (vlc_stopped(conn, pid)) {\n if((quit_vlc(conn, pid)) == 1) {\n log_error(\"quit_vlc() returned 1. exiting\\n\");\n break;\n }\n }\n }\n }\n if (err_count >= 10) {\n log_error(\"error count exceeded. exiting\\n\");\n break;\n }\n sleep(30);\n }\n //remove temporary file\n if (remove(PATH_TO_VLCWATCHDOG_PID) == -1) {\n log_error(\"error removing temporary file %s\",PATH_TO_VLCWATCHDOG_PID);\n return(1);\n }\n return 0;\n}\n\nint do_stop()\n{\n //retrieve PID from file\n int pid;\n if (access(PATH_TO_VLCWATCHDOG_PID, R_OK) != -1) {\n FILE * fp = fopen(PATH_TO_VLCWATCHDOG_PID, \"r\");\n if (fscanf(fp, \"%d\", &pid) != 1) {\n log_error(\"fscanf failed to read PID from file while stopping\\n\");\n }\n fclose(fp);\n }\n //if unable to read PID from file, try pgrep\n else {\n char whatsmyname[256], s[32];\n sprintf(whatsmyname, \"%s%s\", \"pgrep \", argv[0]);\n FILE * fp = popen(whatsmyname, \"r\");\n if (fp != NULL) {\n if (fgets(s, 32, fp) != NULL) {\n sscanf(s, \"%d\", &pid);\n fclose(fp);\n }\n else {\n fclose(fp);\n fprintf(stderr, \"daemon does not appear to be running\\n\");\n return(1);\n }\n }\n else {\n fclose(fp);\n log_error(\"popen failed while stopping\\n\");\n return(1);\n }\n }\n //issue stop signal to VLC-Watchdog daemon\n kill(pid, SIGUSR1);\n return 0;\n}\n\n\n\n/* deamonize the process */\nstatic void skeleton_daemon() {\n /* Fork off the parent process */\n pid_t pid = fork();\n\n /* An error occurred */\n if (pid < 0)\n exit(EXIT_FAILURE);\n\n /* Success: Let the parent terminate */\n if (pid > 0)\n exit(EXIT_SUCCESS);\n\n /* On success: The child process becomes session leader */\n if (setsid() < 0)\n exit(EXIT_FAILURE);\n\n /* Fork off for the second time*/\n pid = fork();\n\n /* An error occurred */\n if (pid < 0)\n exit(EXIT_FAILURE);\n\n /* Success: Let the parent terminate */\n if (pid > 0)\n exit(EXIT_SUCCESS);\n\n /* Set new file permissions */\n umask(0);\n\n /* Change the working directory to the root directory */\n /* or another appropriated directory */\n if (chdir(\"/\") != 0) {\n log_error(\"chdir failed in skeleton_daemon\\n\");\n exit(1);\n }\n\n /* Close all open file descriptors */\n for (int x = sysconf(_SC_OPEN_MAX); x>0; x--)\n {\n close (x);\n }\n\n}\n\n/* check if VLC is stopped, if so, return 1, return 0 otherwise */\nint vlc_stopped(DBusConnection *conn, int pid) {\n DBusError err;\n DBusMessageIter iter, sub_iter;\n const char *prop_iface = \"org.mpris.MediaPlayer2.Player\";\n const char *prop_iface_method_name = \"PlaybackStatus\";\n const char *pb_stat;\n char name[80];\n\n //append the pid to the name of the destination\n sprintf (name, \"%s%d\", \"org.mpris.MediaPlayer2.vlc-\", pid);\n dbus_error_init(&err); // init DBus error\n //create the method call to be used to get playback status of VLC\n DBusMessage * method_call = dbus_message_new_method_call(name,\n PATH_TO_MEDIAPLAYER, \"org.freedesktop.DBus.Properties\",\n \"Get\");\n if (method_call == NULL) {\n log_error(\"Get() method call is NULL after creation\\n\");\n return 1;\n }\n //put the method arguments on the message\n if (!dbus_message_append_args(method_call, DBUS_TYPE_STRING,\n &prop_iface, DBUS_TYPE_STRING, &prop_iface_method_name,\n DBUS_TYPE_INVALID)) {\n log_error(\"failed to append args to message\\n\");\n return 1;\n }\n //call the method, get the reply, check for error\n DBusMessage * reply = dbus_connection_send_with_reply_and_block (conn,\n method_call, -1, &err);\n //this error can be recovered from\n if (reply == NULL) {\n log_error(\"null reply \\n %s \\n\", err.message);\n dbus_error_free(&err);\n err_count++;\n return 0;\n }\n //initialize an iterator pointing to arguments in reply message\n if (!dbus_message_iter_init (reply, &iter)) {\n log_error(\"reply message has no arguments\\n\");\n return 1;\n }\n //check the type of the first argument (should be variant)\n int arg_type = dbus_message_iter_get_arg_type(&iter);\n if (arg_type != DBUS_TYPE_VARIANT) {\n log_error(\"Expected variant, got %d\\n\", arg_type);\n return 1;\n }\n //recurse into the variant container to get an iter to the string\n dbus_message_iter_recurse(&iter, &sub_iter);\n //check the type of the value in the variant (should be string)\n arg_type = dbus_message_iter_get_arg_type(&sub_iter);\n if (arg_type != DBUS_TYPE_STRING) {\n log_error(\"Expected string, got %d\\n\", arg_type);\n return 1;\n }\n //extract the value of the string from sub_iter\n dbus_message_iter_get_basic(&sub_iter, &pb_stat);\n //if VLC is stopped, return 1, otherwise 0\n return (strcmp(\"Stopped\", pb_stat) == 0)\n}\n\n/* call the VLC Quit() method via DBus return 0 on success, 1 otherwise */\nint quit_vlc(DBusConnection *conn, int pid) {\n char name[80];\n\n //append the pid to the name of the destination\n sprintf (name, \"%s%d\", \"org.mpris.MediaPlayer2.vlc-\", pid);\n //initialize the Quit() method call message\n DBusMessage *method_call = dbus_message_new_method_call(name,\n PATH_TO_MEDIAPLAYER, \"org.mpris.MediaPlayer2\", \"Quit\");\n if (method_call == NULL) {\n log_error(\"Quit() method call NULL after creation\");\n return 1;\n }\n //send the Quit() message, report error if any\n if (!dbus_connection_send(conn, method_call, NULL)) {\n log_error(\"Send of Quit() call message failed\\n\");\n return 1;\n }\n return 0;\n}\n\n/* return PID of VLC if it is running, 0 otherwise */\nint vlc_running(DBusConnection *conn) {\n DBusError err;\n DBusMessageIter iter, sub_iter;\n\n dbus_error_init(&err); // init DBus error\n DBusMessage *method_call = dbus_message_new_method_call(\"org.freedesktop.DBus\",\n \"/org/freedesktop/DBus\", \"org.freedesktop.DBus\", \"ListNames\");\n //call the method, get the reply, check for error\n DBusMessage * reply = dbus_connection_send_with_reply_and_block (conn,\n method_call, -1, &err);\n //initialize an iterator pointing to arguments in reply message\n if (!dbus_message_iter_init (reply, &iter)) {\n log_error(\"reply message has no arguments\\n\");\n return 1;\n }\n //check the type of the first argument (should be array)\n int arg_type = dbus_message_iter_get_arg_type(&iter);\n if (arg_type != DBUS_TYPE_ARRAY) {\n log_error(\"Expected array, got %d\\n\", arg_type);\n return 1;\n }\n //recurse into the array container to get an iter to the string\n dbus_message_iter_recurse(&iter, &sub_iter);\n //check the type of the value in the array (should be string)\n arg_type = dbus_message_iter_get_arg_type(&sub_iter);\n if (arg_type != DBUS_TYPE_STRING) {\n log_error(\"Expected string, got %d\\n\", arg_type);\n return 1;\n }\n //extract the values of the strings from sub_iter\n while (dbus_message_iter_has_next(&sub_iter)) {\n const char *string;\n dbus_message_iter_get_basic(&sub_iter, &string);\n if (strstr(string, \"org.mpris.MediaPlayer2.vlc-\") != NULL) {\n //extract the PID from the string\n int pid;\n sscanf(string, \"org.mpris.MediaPlayer2.vlc-%d\", &pid);\n return pid;\n }\n else //go to the next array element\n dbus_message_iter_next(&sub_iter);\n }\n //VLC interface was not found. Assume VLC is not running.\n return 0;\n}\n\n/* Print the usage help then exit */\nvoid usage(char *pname) {\n fprintf(stderr, \"usage: %s start | stop\\n\", pname);\n}\n\n/* Signal handler function */\nvoid sig_handler(int signo) {\n if (signo == SIGUSR1)\n running = 0;\n}\n\n/* Write errors to a log file */\nvoid log_error(const char *format, ...)\n{\n va_list args;\n time_t t = time(NULL);\n\n FILE *errlog = fopen(\"/tmp/vlcwderr.log\", \"a\");\n fprintf(errlog, \"%s \", asctime(localtime(&t)));\n va_start(args, format);\n vfprintf(errlog, format, args);\n va_end(args);\n\n fclose(errlog);\n return;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T17:53:18.993",
"Id": "80183",
"Score": "3",
"body": "You should not use `sprint` because it's unsafe and easy to fall in buffer overflows, _especially_ when user's activity is included. Rather go for `snprintf`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T17:54:12.087",
"Id": "80185",
"Score": "0",
"body": "This is probably worth an answer on its own."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T17:57:42.777",
"Id": "80186",
"Score": "1",
"body": "There are some other things I want to point out, I'll post an answer later."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T15:52:22.277",
"Id": "45952",
"ParentId": "45900",
"Score": "5"
}
},
{
"body": "<p>Other things that should be considered are:</p>\n\n<ul>\n<li>In <code>main()</code> exit(1); why not just <code>return 1</code>?</li>\n<li>When dealing with command line options, you should <em>generally</em> make use of <code>getopt</code> and <code>getopt_long</code>, although in this case is not that useful.</li>\n<li>In the C standard library, there are a lot of unsafe functions and you should avoid them, of course. You can find some <a href=\"https://stackoverflow.com/questions/167165/what-c-c-functions-are-most-often-used-incorrectly-and-can-lead-to-buffer-over\">here</a>.<br>\nIn your case, avoid using <code>sprintf</code> and <code>sscanf</code>*, especially when user's input is involved. That <em>easily</em> leads to buffer overflows.</li>\n<li><code>fopen</code> might fail and you want to know that. If you don't want, you'll likely get a nice SIGSEGV.</li>\n<li>Sometimes you use macros for string literals, sometimes <code>const char*</code>. I'd personally prefer just one choise, the last one precisely.</li>\n</ul>\n\n<p>*there is no <code>snscanf</code>, because <code>*scanf</code> lets you specify buffer's size in the format string. For example:</p>\n\n<pre><code>printf(\"Enter a string: \");\nchar s[128];\nscanf(\"%128s\", s);\n</code></pre>\n\n<p>but for strings, use <code>fgets</code>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T18:32:44.367",
"Id": "45964",
"ParentId": "45900",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T01:10:17.517",
"Id": "45900",
"Score": "5",
"Tags": [
"c",
"linux",
"portability"
],
"Title": "VLC media player watchdog daemon v6"
} | 45900 |
<p>When a user presses a key in my game, their avatar can move down, left, right or up. By move, I mean their avatar animates while various other things move around them on the screen. This is accomplished by raising an event from the <code>InputHandler</code> class.</p>
<pre><code>public class InputHandler
{
public delegate void ActionListener(Actions action);
public event ActionListener ActionRequested;
public void ProcessKeyboard(KeyboardState keyboardState)
{
var keys = keyboardState.GetPressedKeys().ToList();
if (!keys.Any())
{
ActionRequested(Actions.Idle);
return;
}
foreach (var action in keys.Select(GetAction))
{
ActionRequested(action);
}
}
}
</code></pre>
<p>The <code>Player</code> class listens for the <code>ActionRequested</code> event:</p>
<pre><code>public class Player
{
private readonly IEnumerable<Sprite> sprites;
public Player(IEnumerable<Sprite> sprites)
{
this.sprites = sprites;
}
public void Listen(Actions action)
{
switch (action)
{
case Actions.Idle:
Idle();
return;
case Actions.MoveDown:
case Actions.MoveLeft:
case Actions.MoveRight:
case Actions.MoveUp:
Animate(action);
return;
}
}
public void Idle()
{
foreach (var sprite in sprites)
{
sprite.Idle();
}
}
public void Animate(Actions action)
{
foreach (var sprite in sprites)
{
sprite.Animate(action);
}
}
}
</code></pre>
<p>When the <code>Animate</code> method is called on the <code>Sprite</code> class, it gets the <code>Animation</code> for that <code>Action</code> (<code>MoveDown</code>, <code>MoveLeft</code>, etc.), gets the next frame from that <code>Animation</code> and resets the previous animation (so it doesn't start halfway through the next time the button is pressed). The <code>Idle</code> method moves the frame to the left-most position in the sprite sheet (so the avatar is standing still and not frozen mid-animation). Think of the frame as a viewport for the sprite sheet.</p>
<pre><code>public class Sprite
{
private Rectangle frame;
private readonly IDictionary<Actions, Animation> animations;
private Animation prevAnimation;
public Sprite(Rectangle frame, IDictionary<Actions, Animation> animations)
{
this.frame = frame;
this.animations = animations;
}
public void Idle()
{
frame.X = 0;
}
public void Animate(Actions action)
{
Animation animation;
if (!animations.TryGetValue(action, out animation))
{
return;
}
if (!animation.IsReady())
{
return;
}
frame = animation.GetNextFrame();
if (animation == prevAnimation)
{
return;
}
if (prevAnimation != null)
{
prevAnimation.Reset();
}
prevAnimation = animation;
}
}
</code></pre>
<p>The <code>Animation</code> class itself is really just a list of frames (<code>Rectangle</code>s). The <code>IsReady</code> method updates the timer (only one frame can be returned every 100ms or so, so the avatar doesn't act like a cracked out monkey). The <code>GetNextFrame</code> method updates the current frame number and returns the next one in the sequence.</p>
<pre><code>public class Animation
{
private readonly IEnumerable<Rectangle> frames;
private int currentFrame = 1;
private double frameTimer = 0;
private const double frameSpeed = 0.2;
public Animation(IEnumerable<Rectangle> frames)
{
this.frames = frames;
}
public void Reset()
{
currentFrame = 1;
frameTimer = 0;
}
public bool IsReady()
{
if (frameTimer == 0)
{
frameTimer += frameSpeed;
return true;
}
if (frameTimer < frameInterval)
{
frameTimer += frameSpeed;
return false;
}
frameTimer = 0;
return false;
}
public Rectangle GetNextFrame()
{
if (currentFrame == frames.Count())
{
currentFrame = 1;
return frames.FirstOrDefault();
}
currentFrame++;
return frames.ElementAtOrDefault(currentFrame - 1);
}
}
</code></pre>
<p>Finally here's a typical sprite sheet, which I got from <a href="http://lpc.opengameart.org/" rel="nofollow noreferrer">Liberated Pixel Cup</a>. Each row is an animation for one direction (up, left, down right), and the far left column (<code>frame.X = 0</code>) is the standing position. The actual animations don't include this first column because it makes it look all janky.</p>
<p><img src="https://i.stack.imgur.com/xPf2J.png" alt="enter image description here"></p>
<p>This works pretty well and I'm happy with it for the most part. I have a few issues that I'm not sure how to improve:</p>
<ol>
<li><code>InputHandler</code> raises an event for what is essentially a non-action when there is no input detected, which means it is almost constantly telling the Player to Idle.</li>
<li>I don't like that there's a hard-coded requirement in the <code>Idle</code> method of the <code>Sprite</code> class for every sprite sheet to reserve its left-most column for an avatar's standing position. Not every sprite sheet is a humanoid anyways.</li>
<li>I don't like that the <code>Animate</code> method is responsible for resetting the previous animation - I have NO idea how else to do this, since I can't detect when a user stops pressing a key.</li>
<li>I'm not sure if the <code>IsReady</code> method of the <code>Animation</code> class should update <code>frameTimer</code> or just check the value of <code>frameTimer</code> and return true of false.</li>
<li>Similarly, I'm not sure if the <code>GetNextFrame</code> method should update <code>currentFrame</code> or just return the next frame in the sequence.</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T06:14:57.927",
"Id": "80106",
"Score": "0",
"body": "Are you asking how to fix this issues in your current design or how to implement a better design?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T15:02:57.983",
"Id": "80154",
"Score": "5",
"body": "I'm looking for a code review. Whatever that includes is fine."
}
] | [
{
"body": "<p>Looks pretty neat overall, I merely glanced at your code (favorited, I want to look at this more deeply, as I'm [<em>playing with</em> | <em>learning</em>] XNA myself, your XNA posts are very useful!).</p>\n\n<p>One thing I've noticed, I don't think you need this <code>switch</code> block:</p>\n\n<pre><code>public void Listen(Actions action)\n{\n switch (action)\n {\n case Actions.Idle:\n Idle();\n return;\n\n case Actions.MoveDown:\n case Actions.MoveLeft:\n case Actions.MoveRight:\n case Actions.MoveUp:\n Animate(action);\n return;\n }\n}\n</code></pre>\n\n<p>Instead, I'd probably do this:</p>\n\n<pre><code>public void Listen(Actions action)\n{\n Animate(action);\n}\n</code></pre>\n\n<p>...and in <code>Animate(Actions)</code> I'd add the call to <code>Idle()</code> and exit <code>if (action == Actions.Idle)</code>. \"Being idle\" <em>does</em> involve choosing a location on the sprite sheet, I don't see why it would be handled in <code>Listen</code> when everything else is in <code>Animate</code>.</p>\n\n<p>Also in <code>switch</code> blocks you should use <code>break;</code>, and let the function <code>return</code> by itself.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T15:56:10.557",
"Id": "45953",
"ParentId": "45901",
"Score": "10"
}
},
{
"body": "<p>Your <code>GetNextFrame</code> should have fewer <code>if</code> statements. In other words, you should merge some of them together. The ones that return early should especially be in an <code>if ..then .. else if.. then</code> structure, like this. It works either way, but this looks cleaner and is more to the point about what the code does.</p>\n\n<pre><code>public Rectangle GetNextFrame(GameActions gameAction)\n{\n var sequence = GetSequence(gameAction);\n if (gameAction == GameActions.Idle) {\n frameTimer = 0;\n\n prevFrame.X = 0;\n prevGameAction = gameAction;\n\n return prevFrame;\n } else if(frameTimer != 0) {\n UpdateTimer();\n\n return prevFrame;\n } else if (sequence == null) {\n return prevFrame;\n }\n\n UpdateTimer();\n\n Rectangle nextFrame;\n\n if (gameAction != prevGameAction)\n {\n nextFrame = sequence.First();\n }\n else\n {\n nextFrame = sequence.Next(prevFrame);\n }\n\n prevFrame = nextFrame;\n prevGameAction = gameAction;\n\n return nextFrame;\n}\n</code></pre>\n\n<p>Your <code>Animate</code> method has some extra lines in it as well where the <code>if</code> statements can be merged together.</p>\n\n<pre><code>public void Animate(Actions action)\n{\n Animation animation;\n\n if (!animations.TryGetValue(action, out animation) || !animation.IsReady())\n {\n return;\n }\n\n frame = animation.GetNextFrame();\n\n if (animation == prevAnimation)\n {\n return;\n }\n\n if (prevAnimation != null)\n {\n prevAnimation.Reset();\n }\n\n prevAnimation = animation;\n}\n</code></pre>\n\n<p>That one <code>if</code> statement with the OR clause <code>||</code> does the exact same thing that your code did, but with fewer lines and in a cleaner manner.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:15:34.913",
"Id": "80754",
"Score": "0",
"body": "sorry, some of this was from yesterday, I forgot to finish it. I haven't had a chance to read the updates on the question yet either"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:14:15.263",
"Id": "46268",
"ParentId": "45901",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T01:17:32.537",
"Id": "45901",
"Score": "17",
"Tags": [
"c#",
"game",
"animation",
"xna"
],
"Title": "Sprite animation handler"
} | 45901 |
<p>This is my code for a server using EAP (Sockets).</p>
<p>Is <code>AsyncOperation.Post</code> the right way to raise thread safe events?</p>
<p><code>AsyncOperation.Post</code> states: </p>
<blockquote>
<p>Invokes a delegate on the thread or context appropriate for the application model.</p>
</blockquote>
<p>Is there any other mistake in the code (i.e something that can be improved or is a bad thing to do)?</p>
<pre><code>public sealed class Server
{
private Socket _server;
private SocketAsyncEventArgs _acceptArg;
private AsyncOperation _asyncOperation;
public EndPoint LocalEndPoing { get; private set; }
public bool Listening { get; private set; }
public delegate void ErrorOccuredEventHandler(Server sender, Exception e);
public delegate void ClientConnectedEventHandler(Server sender, EndPoint remoteEndpoint);
public event ErrorOccuredEventHandler ErrorOcurred;
public event ClientConnectedEventHandler ClientConnected;
private void OnErrorOccured(Exception e)
{
if(ErrorOcurred!=null)
ErrorOcurred.Invoke(this,e);
}
private void OnClientConnected(EndPoint remoteEndPoint)
{
if(ClientConnected!=null)
ClientConnected.Invoke(this,remoteEndPoint);
}
public Server(EndPoint localEndPoint)
{
LocalEndPoing = localEndPoint;
Listening = false;
_asyncOperation = AsyncOperationManager.CreateOperation(null);
}
public void Start()
{
try
{
if (Listening)
return;
_server = _server ?? new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_server.Bind(LocalEndPoing);
_server.Listen(10);
Listening = true;
_acceptArg = _acceptArg ?? new SocketAsyncEventArgs();
_acceptArg.Completed += _acceptArg_Completed;
if (!_server.AcceptAsync(_acceptArg))
_acceptArg_Completed(null, _acceptArg);
}
catch (Exception exception)
{
_asyncOperation.Post(ex=>OnErrorOccured(ex as Exception),exception);
}
}
public void Stop()
{
try
{
if(!Listening)
return;
_server.Close();
_acceptArg.Dispose();
_server = null;
_acceptArg = null;
Listening = false;
}
catch (Exception exception)
{
_asyncOperation.Post(ex => OnErrorOccured(ex as Exception), exception);
}
}
private void _acceptArg_Completed(object sender, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
_asyncOperation.Post(remoteEndPoint=>OnClientConnected(remoteEndPoint as EndPoint),e.AcceptSocket.RemoteEndPoint);
//Do nasty things with the accepted socket
e.AcceptSocket = null;
if(!_server.AcceptAsync(e))
_acceptArg_Completed(null,e);
}
else
{
_asyncOperation.Post(ex => OnErrorOccured(ex as Exception), new SocketException((int)e.SocketError));
Stop();
}
}
}
</code></pre>
| [] | [
{
"body": "<blockquote>\n<pre><code>public EndPoint LocalEndPoing { get; private set; } \n</code></pre>\n</blockquote>\n\n<p>should be <code>LocalEndPoint</code>. </p>\n\n<hr>\n\n<blockquote>\n<pre><code>public void Start()\n{\n try\n {\n if (Listening)\n return; \n</code></pre>\n</blockquote>\n\n<p>why is this <code>if</code> statement inside the <code>try..catch</code> ? It can be granted that this won't ever throw any exception. As a rule of thumb, only put code inside a <code>try..catch</code> which can throw. </p>\n\n<p>You should always use braces <code>{}</code>, although they might be optional, to make your code less error prone. </p>\n\n<blockquote>\n<pre><code>_server.Listen(10); \n</code></pre>\n</blockquote>\n\n<p>why <code>10</code> and not <code>1000</code>? Using magic numbers should be avoided to make the code easier to read and understand. You should extract magic numbers/strings into meaningful variables/constants so <strong>Sam the maintainer</strong> will see at first glance what this is about. </p>\n\n<hr>\n\n<blockquote>\n<pre><code>_asyncOperation.Post(ex=>OnErrorOccured(ex as Exception),exception); \n</code></pre>\n</blockquote>\n\n<p>Let your variables and operators have some space to breathe, its just making your code more readable like so </p>\n\n<pre><code>_asyncOperation.Post(ex => OnErrorOccured(ex as Exception), exception); \n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>private void _acceptArg_Completed(object sender, SocketAsyncEventArgs e) \n</code></pre>\n</blockquote>\n\n<p>having an underscore prefixed methodname is a <strong>no go</strong>. Underscore prefixing is tolerated for class level variable names only. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-15T06:24:56.767",
"Id": "211196",
"Score": "0",
"body": "Thanks for the advises....really appreciate it. But the actual question is whether `AsyncOperation.Post` is the right way to raise the events...?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-15T06:44:53.450",
"Id": "211198",
"Score": "0",
"body": "As long as the application is not a console application it should be. Take a look at [`Notes to Inheritors`](https://msdn.microsoft.com/en-us/library/system.componentmodel.asyncoperation.post%28v=vs.110%29.aspx#Anchor_2)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-15T18:18:23.117",
"Id": "211304",
"Score": "0",
"body": "what if I'm developing a class library?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-14T14:01:20.507",
"Id": "113912",
"ParentId": "45907",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T03:05:19.160",
"Id": "45907",
"Score": "3",
"Tags": [
"c#",
"asynchronous",
"event-handling"
],
"Title": "Thread Safe Events while utilizing EAP"
} | 45907 |
<p>I'm trying to write a JavaScript library to allow inheritance with knockout.</p>
<p>The fundamental problem when implementing inheritance in Knockout is that each Knockout observable is its own instance, thus if you try this:</p>
<pre><code> x = function () {};
x.prototype.m = ko.observable();
y = function () {};
y.prototype = new x();
z = new y();
//z.m == y.prototype.m == x.prototype.m
</code></pre>
<p>The behavior I'm trying to get goes like this:</p>
<pre><code>//psudo-code, I know this wouldn't work
x = function () {};
x.prototype.a = ko.observable();
y = function () {};
y.prototype = new x();
y.prototype.b = ko.computed(function () { return this.a() });
//enabling this:
z = new y();
z.a(5);
a = new y();
a.a(12);
// z.b() == 5, a.b() == 12
</code></pre>
<p>Here's my proposed solution:</p>
<pre><code>var getParams = function (args, index) {
return args.length > index + 1 ? Array.prototype.slice.apply(index) : Array.prototype.concat.call([], args[index])
};
var Ladder = function () {};
Ladder.prototype.init = function (config) {
var self = this;
if (!(config instanceof dontInit)) {
// Only initialize if config is passed, this allows us to create sub-prototypes
if (this.attachEntity) this.entity = config;
for (var prop in self) {
var extender = self[prop];
if (extender instanceof doAttach) {
self[prop] = extender.extender.apply(self, extender.args); // || ('' + extender.extender); // if the function doesn't return a value perhaps it only performs operations? Leave a tatle tale behind?
}
}
if (this.populateObject) {
for (var prop in config) {
if (config.hasOwnProperty(prop)) {
var val = config[prop];
if (ko && ko.isObservable(self[prop])) self[prop](ko.unwrap(val));
else self[prop] = val;
}
}
}
for (var prop in self) {
var extender = self[prop];
if (extender instanceof doExtend) {
self[prop] = extender.extender.apply(self, extender.args); // || ('' + extender.extender); // if the function doesn't return a value perhaps it only performs operations? Leave a tatle tale behind?
}
}
}
}
Ladder.prototype.attachEntity = true;
Ladder.prototype.populateObject = true;
Ladder.prototype.attach = function (propertyName, extender) {
var args = getParams(arguments, 2);
this.prototype[propertyName] = new doAttach(extender, args);
}
Ladder.prototype.extend = function (propertyName, extender) {
var args = getParams(arguments, 2);
this.prototype[propertyName] = new doExtend(extender, args);
}
Ladder.inherit = Ladder.prototype.inherit = function () {
var ctor = function (config) {
this.init(config);
};
ctor.attach = Ladder.prototype.attach;
ctor.extend = Ladder.prototype.extend;
ctor.inherit = Ladder.prototype.inherit;
ctor.prototype = new this(new dontInit());
return ctor;
};
Ladder.prototype.attachComputed // doComputed
Ladder.createPrototypes = function (prototypes) {
return duplicatePrototypes(prototypes);
}
var dontInit = function () {};
// doAttach is called before config and should attach a computed or observable, though you may attach any value you like.
var doAttach = function (extender, args) {
this.extender = extender;
this.args = args;
};
var doComputed = function (computed) {
return new doExtend(function () {
return ko.computed(computed, this);
}, []);
};
// doExtend is called after config and would normally perform some init work
// naming convention for extenders is _00Name where 00 is a priority (00 will run before 01) and Name is a descriptive name
var doExtend = function (extender, args) {
this.extender = extender;
this.args = args;
};
</code></pre>
<p><strong>My questions are:</strong></p>
<ol>
<li><p><strong>Are there performance issues with this type of inheritance</strong>? i.e. if I use this paradigm to build complex objects with long inheritance chains, will there be a performance hit vs some other 'better' inheritance paradigm?</p></li>
<li><p><strong>Does this make for clear code?</strong> Is it obvious what is going on when I define an object like this:</p>
<pre><code>var myObject = usefullBaseClass.inherit();
myObject.attach("newProperty", ko.observable, 5);
var instanceOfMyObject = new myObject();
// instanceOfMyObjecct is an instance of myObject and has an observable
// property called newProperty which is unique to this instance
</code></pre></li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T23:32:47.743",
"Id": "80247",
"Score": "0",
"body": "I am most curious, what would you be modeling that requires a long inheritance chain ? I have yet to find something that requires more than 3 levels."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T01:58:21.323",
"Id": "80259",
"Score": "0",
"body": "My current use case consists of a set of base classes used to generate a grid, I then create inherited classes for each instance of the grid, the user is then able to extend the classes for grid A without affecting the behavior of those classes in grid B (the goal is for a very customizable grid).\nThe current paradigm would only involve 2-3 deep chains, but that will likely change as I continue adding features. For example the Row class will likely be extended by a sub-class AggRow, when a sub-class AggRow is created for an individual grid it will have an inheritance chain 3 deep."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T02:03:21.933",
"Id": "80261",
"Score": "0",
"body": "I'd also like to plan for deeper inheritance if I can."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T13:05:13.750",
"Id": "80579",
"Score": "0",
"body": "Good enough, can you update the snippet under 'Does this make for clear code', the snippet should include how you created the usefullBaseClass."
}
] | [
{
"body": "<p>Interesting question,</p>\n\n<ul>\n<li><p><em>Are there any performance hits ?</em> I don't see problems, it would not be slower then building the objects in an old skool manner</p></li>\n<li><p><em>Does this make for clear code?</em> Your sample code would not run, you need to provide a sample that would actually run.</p></li>\n</ul>\n\n<p>Furthermore:</p>\n\n<ul>\n<li>You should run you code through JsHint\n<ul>\n<li>You are missing semicolons</li>\n<li>You are declaring some variables more than once in the same function</li>\n</ul></li>\n<li>Your code has <code>Ladder.prototype.attachComputed // doComputed</code> <- Pointless</li>\n<li>Your code has <code>return duplicatePrototypes(prototypes);</code> <- <code>duplicatePrototypes</code> is not provided</li>\n<li><code>dontInit</code> <- <code>doNotInit</code> reads better, also there must be a better way to avoid initialization ;)</li>\n<li><code>doAttach</code> is a constructor, so definitely wrongly named. <code>AttachedValue</code> mayhaps?</li>\n<li>Anonymous functions are a pain in stacktraces, if you are going to create a custom OO approach, then I would avoid avoid anonymous functions like the plague.</li>\n<li><code>// naming convention for extenders is _00Name where 00 is a priority</code> <- I do not believe this works, <code>for (var prop in self) {</code> does not pre-sort property names, at least that is not guaranteed</li>\n<li>The distinction between <code>doAttach</code> and <code>doComputed</code> is unclear, are the comments possibly out of date? <code>// doAttach is called before config and should attach a computed or observable</code> <- It seems from the code that I would attach a computable through <code>doComputed</code> ?</li>\n<li><p>This:</p>\n\n<pre><code>//Note: extender.extender might simply return undefined\nself[prop] = extender.extender.apply(self, extender.args); \n</code></pre>\n\n<p>is better than</p>\n\n<pre><code>self[prop] = extender.extender.apply(self, extender.args); // || ('' + extender.extender); // if the function doesn't return a value perhaps it only performs operations? Leave a tatle tale behind?\n</code></pre></li>\n<li>I guess <code>var self = this;</code> comes from your knockout background. If you are not using closures, then there is no good reason to use this.</li>\n<li><p>Do not drop newlines from <code>if</code> statements;</p>\n\n<pre><code>if (ko && ko.isObservable(self[prop])) \n self[prop](ko.unwrap(val));\nelse \n self[prop] = val;\n</code></pre></li>\n<li><code>if (ko)</code> should be at the very start of your script, there is no point if knockout is not available</li>\n</ul>\n\n<p>All in all, I think I would not use your library until it has matured a bit more.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T13:33:51.447",
"Id": "46188",
"ParentId": "45909",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T04:01:58.097",
"Id": "45909",
"Score": "5",
"Tags": [
"javascript",
"inheritance",
"prototypal-class-design",
"knockout.js"
],
"Title": "Prototype inheritance with Knockout observables"
} | 45909 |
<p>I am working on a project involving the unique partitioning of integers. I.e. I am looking to have all of the partitions of n = x<sub>1</sub> + x<sub>2</sub> + x<sub>3</sub> + ... + x<sub>k</sub>, where x<sub>i</sub> = x<sub>j</sub> implies i = j.</p>
<p>For example, if I give my code input of 10, I want to have as output (in an <code>ArrayList<ArrayList<BigInteger>></code>) the following:</p>
<p>[[1, 2, 3, 4], [2, 3, 5], [1, 4, 5], [1, 3, 6], [4, 6], [1, 2, 7], [3, 7], [2, 8], [1, 9], [10]]</p>
<p>Note that I don't have [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], etc. because these have duplicate entries.</p>
<p>The problem is, once I try to get all of the unique partitions of numbers greater than 70 or so, it starts to take a noticeable amount of time. Further, this shouldn't be a particularly slow algorithm.</p>
<p>The class is below:</p>
<pre><code>import java.math.*;
import java.util.*;
public class UniquePartition {
private BigInteger n;
private ArrayList<ArrayList<BigInteger>> allPartitions;
//Constructs the object with integer. Sets the target and then calculates partitions.
public UniquePartition(int num) {
n = new BigInteger(String.valueOf(num));
allPartitions = new ArrayList<ArrayList<BigInteger>>();
allPartitions = findPartitions();
}
//Constructs the object. Sets the target and then calculates partitions.
public UniquePartition(BigInteger num) {
n = num;
allPartitions = new ArrayList<ArrayList<BigInteger>>();
allPartitions = findPartitions();
}
//Returns partitions without calculating them.
public ArrayList<ArrayList<BigInteger>> getPartitions() {
return allPartitions;
}
//Returns the nth partition without calculating them.
public ArrayList<BigInteger> getPartitionN(int n) {
// ArrayList<ArrayList<BigInteger>> partitions = new ArrayList<ArrayList<BigInteger>>();
return allPartitions.get(n);
}
// Returns an ArrayList containing ArrayLists, each of which is a single partition. Should never be called, otherwise
// will redo calculation.
public ArrayList<ArrayList<BigInteger>> findPartitions() {
ArrayList<String> pS = new ArrayList<String>();
pS = findPartitions(pS,n,n,"");
for(int i=0;i<pS.size();i++) {
ArrayList<BigInteger> partition = new ArrayList<BigInteger>();
String line[] = (pS.get(i)).split(" ");
for (String entry: line) {
BigInteger num = new BigInteger(entry);
partition.add(num);
}
allPartitions.add(partition);
}
return allPartitions;
}
//Stores the partitions in an ArrayList<String>. Never used alone. getAllPartitions() is the driver for this method.
public ArrayList<String> findPartitions(ArrayList<String> p, BigInteger target, BigInteger maxValue, String suffix) {
if (target.equals(BigInteger.ZERO)) {
// System.out.println(suffix);
p.add(suffix);
}
else {
if (maxValue.compareTo(BigInteger.ONE) > 0)
findPartitions(p, target, maxValue.subtract(BigInteger.ONE), suffix);
if (maxValue.compareTo(target)<=0 && !containsInteger(maxValue,suffix))
findPartitions(p, target.subtract(maxValue), maxValue, maxValue + " " + suffix);
}
return p;
}
//Checks if String s contains the BigInteger n. If so, return true, otherwise return false.
public boolean containsInteger(BigInteger n, String s) {
boolean b = false;
String line[] = s.split(" ");
for(String entry: line) {
if(entry == "")
entry = "0";
BigInteger BI = new BigInteger(entry);
if(n.equals(BI))
b = true;
}
return b;
}
//Returns string with all partitions.
public String toString() {
String output = "";
for(int i = 0;i<allPartitions.size();i++) {
for(int j=0; j<(allPartitions.get(i)).size();j++) {
output = output + (allPartitions.get(i)).get(j).toString()+" ";
}
output = output + "\n";
}
return output;
}
//Returns string with kth partition.
public String toString(int k) {
String output = "";
for(int j=0; j<(allPartitions.get(k)).size();j++) {
output = output + (allPartitions.get(k)).get(j).toString()+" ";
}
return output;
}
}
</code></pre>
<p>My driver class is below:</p>
<pre><code>import java.math.*;
import java.util.*;
public class test {
public static void main(String[] args) {
long nanos =0;
int target = TARGET;
System.gc();
nanos = System.nanoTime();
UniquePartition part = new UniquePartition(target);
nanos = System.nanoTime() - nanos;
System.out.println("Time taken to calculate: "+nanos/1000000.0+"ms");
}
}
</code></pre>
<p>So the question is, is there any way that I can improve the speed of this code? I'm looking to be able to search partitions of very large numbers in a reasonable period of time (as you can tell from the BigInteger constructor!). Is that unreasonable to expect? The algorithm itself doesn't seem to be slow... or is it? Any help would be appreciated!</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T05:09:44.927",
"Id": "80102",
"Score": "1",
"body": "The MarkDown interpreter on this site gets confused by tabs; I've replaced them with spaces."
}
] | [
{
"body": "<p>Yes, it is unreasonable to expect this approach to be "fast".</p>\n<p>This answer will focus on... <em>drumroll, please!</em></p>\n<h1>Why your current approach is slow</h1>\n<p>The reason for why it is unreasonable to expect this approach to be fast can be shown simply by adding a <code>private int calls;</code> field to your class and increasing it at the beginning of your <code>findPartitions(ArrayList<String> p, BigInteger target, BigInteger maxValue, String suffix)</code> method. Then log this value for different values in your main method.</p>\n<pre><code>Value 5 Calls: 20\nValue 10 Calls: 103\nValue 15 Calls: 333\nValue 20 Calls: 896\nValue 25 Calls: 2141\nValue 30 Calls: 4735\nValue 35 Calls: 9877\nValue 40 Calls: 19679\nValue 45 Calls: 37729\nValue 50 Calls: 70073\nValue 55 Calls: 126586\nValue 60 Calls: 223195\n</code></pre>\n<p>As you can see, the number of calls to the method increases dramatically, of exponential order.<img src=\"https://i.stack.imgur.com/OTLnF.png\" alt=\"enter image description here\" /></p>\n<p>This is because you are using a recursive approach to the problem that often creates a new "branch".</p>\n<p>So, how to speed this up?</p>\n<p>Let's take a look at <em>some</em> of the output for the value <code>20</code>:</p>\n<pre><code>2 3 7 8 \n1 4 7 8 \n5 7 8 \n2 3 6 9 \n1 4 6 9 \n5 6 9 \n2 3 5 10 \n1 4 5 10 \n2 3 4 11 \n4 5 11 \n2 3 15 \n1 4 15 \n5 15 \n</code></pre>\n<p>What do all these have in common? They all can make the value <code>5</code> in there some where. 11 + 4 (= 15) + <strong>3 + 2</strong> (= 5).</p>\n<p>So, what do I want to say with this?</p>\n<p>Once you have calculated the possible partitions for the value of 5, <strong>reuse them</strong>!</p>\n<p>To accomplish this you can use a <code>Map<Integer, List<Integer>></code> structure. In your <code>findPartitions</code> method, check if the map contains a value for <code>target</code> (<code>map.containsKey</code>) and if it does then reuse it. If it does not, then do something similar to what you are doing there already and use <code>map.put</code> at the end to add the found values to the map.</p>\n<p>I have to warn you though that even adding this reusing-feature, I still expect it to take quite a long time for larger numbers.</p>\n<p>I strongly suggest that you switch back to using <code>int</code> (or <code>Integer</code> for storing them in collections). An int will take you to <code>2 147 483 647</code>, try partitioning that number first before switching to <code>BigInteger</code> (Hint hint: It will still take a tremendous amount of time to partition <code>2 147 483 647</code>, if you don't believe me then try doing it by hand).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T18:59:55.067",
"Id": "80198",
"Score": "0",
"body": "That sounds like a smart idea! But doesn't this method then imply that I need to calculate all of the possible partitions of all numbers below any given number? That may still be more efficient, I'm not sure. I'll edit this post later when I try reimplementing this idea (as well as the ideas in your other answer)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T19:01:25.393",
"Id": "80200",
"Score": "0",
"body": "@user138303 You are currently doing that now anyway, the only difference is that you are currently not remembering anything about what you have previously calculated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T19:02:31.550",
"Id": "80201",
"Score": "0",
"body": "@sam.h.blitz Please don't **edit** your original question, that often causes answers to be invalidated and we don't like that here. **Ask a new** question instead, and a link to this old one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T17:18:10.213",
"Id": "80820",
"Score": "0",
"body": "I'm having trouble implementing the Map structure as you explained. I understand how it works, but because iterative method just changes its input Object, it's difficult to see how to get it to independently calculate the partitions for various values and then add them to other partitions. Sorry for being useless!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T06:39:58.613",
"Id": "45915",
"ParentId": "45910",
"Score": "11"
}
},
{
"body": "<p>This answer will focus on general style of your code.</p>\n\n<ul>\n<li><p>Use constructor chaining. One of your constructors can call the other one, like this:</p>\n\n<pre><code>public StackExchange(int num) {\n this(new BigInteger(String.valueOf(num)));\n}\n</code></pre>\n\n<p>This helps removing a bit of code duplication.</p></li>\n<li><p>Declare by interface, not by implementation. To make it easier to change implementations, you can change this line:</p>\n\n<pre><code> private ArrayList<ArrayList<BigInteger>> allPartitions;\n</code></pre>\n\n<p>into this:</p>\n\n<pre><code> private List<List<BigInteger>> allPartitions;\n</code></pre></li>\n<li><p>Don't do so much work in the constructor. Only initialize <code>n</code> and the <code>allPartitions</code> list in your constructor, don't call <code>findPartitions</code> from the constructor. Let the main method do that. Constructors are supposed to be initial constructors only, not workers that work for a long while to create the object.</p></li>\n<li><p>There's no need to use <code>allPartitions = findPartitions();</code>, <code>findPartitions</code> returns <code>allPartitions</code>. Instead use <code>findPartitions(allPartitions);</code></p></li>\n<li><p>Use JavaDoc to document your methods, like this:</p>\n\n<pre><code> /**\n * Returns partitions without calculating them.\n */\n public ArrayList<ArrayList<BigInteger>> getPartitions() {\n return allPartitions;\n }\n</code></pre></li>\n<li><p>Besides the reasons in my other answer, your <code>containsInteger</code> method takes a tremendous amount of time. Instead of using <strong>strings</strong> to store the result (which really is a bad idea), <strong>use a <code>Set<Integer></code></strong>. Using a <code>Set</code> let's you use <code>set.contains(value)</code> which has a time complexity of <code>O(1)</code>. Your current approach has a time complexity of <code>O(n)</code>. If you aren't familiar of time complexities, <code>O(1)</code> is significantly faster than <code>O(n)</code>. If you are familiar of time complexities, it's still significantly faster.</p></li>\n<li><p>As stated in my other answer, don't expect this algorithm to work well with <code>BigInteger</code>. Stick to using <code>Integer</code> / <code>int</code> instead. Besides the fact that you won't be able to partition <code>Integer.MAX_VALUE</code> (2147483647) that easily, calculations on a regular <code>int</code> is significantly faster than on a <code>BigInteger</code>.</p></li>\n<li><p>Don't call <code>System.gc();</code> in your main method. It is a) totally unnecessary since your program just got started, there's nothing to garbage collect yet. b) Even if it would be something to garbage collect, the method call is just a <em>suggestion</em> to the Java Virtual Machine. In nearly all Java applications, you never need to call this method. The system can take care of this by itself.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T07:01:16.240",
"Id": "45917",
"ParentId": "45910",
"Score": "5"
}
},
{
"body": "<p>@Simon has shown you why the code is slow, that you may have underestimated the enormity of the output. I agree with his points completely, and won't reiterate them.</p>\n\n<p>Instead, I'll suggest an alternative solution, based largely on a <a href=\"https://codereview.stackexchange.com/a/36846/9357\">previous integer partition question on Code Review</a>. That question called for an exhaustive integer partition (<em>x</em><sub><em>i</em></sub> listed in monotonically nondecreasing order), whereas this question calls for a \"unique\" integer partition (<em>x</em><sub><em>i</em></sub> listed in monotonically increasing order). The changes required to the code are minimal, once you figure out the new algorithm.</p>\n\n<p>Running the code below for <em>n</em> = 150, it produces 19406016 partitions in about a minute (not outputting to the console).</p>\n\n<pre><code>import java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\npublic class MonotonicallyIncreasingPartition implements Iterator<int[]> {\n\n private static class IntStack {\n private int[] data;\n private int size;\n\n // sum stores redundant state for performance.\n\n // Sum of all data\n private int sum;\n\n IntStack(int capacity) {\n this.data = new int[capacity];\n }\n\n public void fill(int limit) {\n this.sum = 0;\n this.size = this.data.length;\n int datum = 1;\n for (int i = 0; i < this.size; i++) {\n if (i == this.size - 1) datum = limit - this.sum;\n this.data[i] = datum;\n this.sum += datum++;\n }\n }\n\n public void push(int datum) {\n this.data[this.size++] = datum;\n this.sum += datum;\n }\n\n public int peek() {\n return this.data[this.size - 1];\n }\n\n public int pop() {\n int datum = this.data[--this.size];\n this.sum -= datum;\n return datum;\n }\n\n /**\n * Shortcut for push(i + pop()), peek()\n */\n public int incr(int i) {\n if (i != 0) {\n int datum = this.data[this.size - 1] += i;\n this.sum += i;\n }\n return this.data[this.size - 1];\n }\n\n public boolean isEmpty() {\n return this.size == 0;\n }\n\n public int sum() {\n return this.sum;\n }\n\n public int[] toArray() {\n return Arrays.copyOf(this.data, this.size);\n }\n }\n\n //////////////////////////////////////////////////////////////////////\n\n private final IntStack stack;\n private final int limit;\n\n public MonotonicallyIncreasingPartition(int n) {\n if (n <= 0) throw new IllegalArgumentException();\n this.limit = n;\n int stackSize = (int)Math.floor((-1 + Math.sqrt(1 + 8 * this.limit)) / 2);\n this.stack = new IntStack(stackSize);\n this.stack.fill(this.limit);\n }\n\n @Override\n public boolean hasNext() {\n return !this.stack.isEmpty();\n }\n\n @Override\n public int[] next() {\n if (this.stack.isEmpty()) {\n throw new NoSuchElementException();\n }\n try {\n return this.stack.toArray();\n } finally {\n advance();\n }\n }\n\n private final void advance() {\n if (this.stack.pop() == this.limit) {\n // All the numbers have been gathered into the original\n // number. That's all, folks!\n return;\n }\n\n // Push the smallest possible monotonically increasing numbers\n this.stack.incr(1);\n while (this.stack.peek() + 1 <= this.limit - this.stack.sum()) {\n this.stack.push(this.stack.peek() + 1);\n }\n\n // Increase the last number such that the sum is the limit\n this.stack.incr(this.limit - this.stack.sum());\n\n // Note stack invariant: values are always increasing going from the\n // base to the top.\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n\n public static void main(String[] args) {\n int limit = Integer.parseInt(args[0]);\n Iterator<int[]> part = new MonotonicallyIncreasingPartition(limit);\n while (part.hasNext()) {\n System.out.println(Arrays.toString(part.next()));\n }\n }\n}\n</code></pre>\n\n<p>Note the following speed-enhancing features:</p>\n\n<ul>\n<li>It makes no attempt to store all of the results in one data structure. Instead, it produces an iterator that you can use to fetch one partition at a time.</li>\n<li>There is a simple iterative algorithm to produce the next partition based on the current one.</li>\n<li><p>The data structure being used internally is just a simple <code>int[]</code> array, which I've packaged in an inner class called <code>IntStack</code>. You can tell exactly how large an array you need to allocate based on <em>n</em>. The most you can break it up is as</p>\n\n<p>$$\n \\begin{eqnarray*}\nn & = & 1 + 2 + 3 + \\ldots + x_{max} \\\\\n & = & \\frac{x_{max} (x_{max} + 1)}{2}\n \\end{eqnarray*}\n $$</p>\n\n<p>By the quadratic equation,</p>\n\n<p>$$ x_{max} = \\frac{-1 \\pm \\sqrt{1 + 8 n}}{2} $$</p></li>\n<li><p>No stringification or complicated lookups involved in the partitioning algorithm itself. It merely makes decisions based on the top two numbers on the stack.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T16:20:35.757",
"Id": "80622",
"Score": "0",
"body": "I like the speed of the generation used here, but the iterator seems to make it slower when I need to perform checks on each of the partitions. If I ask both classes to print the output, at around n=60, the code you wrote up takes longer to provide output (or manipulate, or whatever) than the code I originally had. Unfortunately, because I have to do manipulations on each partition, it's not enough to just have a fast generation algorithm. I need fast access to each partition too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T16:28:38.380",
"Id": "80623",
"Score": "0",
"body": "If you need to support `getPartitionN(n)`, then you can still use this algorithm to implement `findAllPartitions()` and cache them in an `ArrayList<int[]>` or something."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T07:57:36.450",
"Id": "45921",
"ParentId": "45910",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "45915",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T04:16:34.463",
"Id": "45910",
"Score": "6",
"Tags": [
"java",
"optimization",
"algorithm",
"combinatorics",
"integer"
],
"Title": "Optimizing unique partitions of integers"
} | 45910 |
<blockquote>
<p>Given an expression string exp, write a program to examine whether the
pairs and the orders of</p>
<pre><code>"{","}","(",")","[","]"
</code></pre>
<p>are correct in exp.</p>
<p>For example, the program should print true for</p>
<pre><code>exp = "[()]{}{[()()]()}"
</code></pre>
<p>and false for</p>
<pre><code>exp = "[(])"
</code></pre>
</blockquote>
<p>Complexity:</p>
<ul>
<li>Time complexity: O(n) where n is length of the string</li>
<li>Space complexity: O(n/2) where n is length of string </li>
</ul>
<p>Looking for code review, optimizations and best practices. </p>
<pre><code>public final class BalancedParanthesis {
private static final Map<Character, Character> brackets = new HashMap<Character, Character>();
static {
brackets.put('[', ']');
brackets.put('{', '}');
brackets.put('(', ')');
}
private BalancedParanthesis() {};
/**
* Returns true is parenthesis match open and close.
* Understands [], {}, () as the brackets
* It is clients responsibility to include only valid paranthesis as input.
* A false could indicate that either parenthesis did not match or input including chars other than valid paranthesis
*
* @param str the input brackets
* @return true if paranthesis match.
*/
public static boolean isBalanced(String str) {
if (str.length() == 0) {
throw new IllegalArgumentException("String length should be greater than 0");
}
// odd number would always result in false
if ((str.length() % 2) != 0) {
return false;
}
final Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < str.length(); i++) {
if (brackets.containsKey(str.charAt(i))) {
stack.push(str.charAt(i));
} else if (stack.empty() || (str.charAt(i) != brackets.get(stack.pop()))) {
return false;
}
}
return true;
}
public static void main(String[] args) {
assertEquals(true, isBalanced("{}([])"));
assertEquals(false,isBalanced("([}])"));
assertEquals(true, isBalanced("([])"));
assertEquals(true, isBalanced("()[]{}[][]"));
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T07:20:30.690",
"Id": "80108",
"Score": "1",
"body": "Best practices: 1) Use Snobol (in which most of the program reduces to `BAL x`, where `x` is the string to check for balance)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T13:14:53.603",
"Id": "80136",
"Score": "1",
"body": "Does your code return `false` for `\"[(])\"` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T15:18:30.100",
"Id": "80156",
"Score": "0",
"body": "@konijn Yes, it does."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T15:21:02.627",
"Id": "80604",
"Score": "0",
"body": "Why wouldn't an empty string be trivially balanced?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-14T00:26:40.553",
"Id": "133745",
"Score": "0",
"body": "I dont know why nobody pointed out but this will fail for input\n(A+B)+(C-D)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-08T11:39:39.540",
"Id": "269390",
"Score": "0",
"body": "Typo: it's one _parenthesis_, two or more _parentheses_, but never _paranthesis_."
}
] | [
{
"body": "<p>I just wanted to write that the code looks completely fine to me, until...</p>\n<pre><code>assertEquals(false, isBalanced("[["));\n</code></pre>\n<p>I''m sure you'll find the error :-)</p>\n<p>Otherwise two small remarks:</p>\n<ul>\n<li><p>Personally I'd have the function return <code>true</code> for an empty string instead of throwing an exception.</p>\n</li>\n<li><p><code>Stack</code> is outdated. I'd use a <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/Deque.html\" rel=\"noreferrer\"><code>Deque</code></a> implementation instead.</p>\n</li>\n</ul>\n<p>EDIT: I'm sorry, but I just realized something else: Your program doesn't fulfill the requirement O(n/2) for space complexity.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T18:34:36.087",
"Id": "80191",
"Score": "0",
"body": "Yes it does. O(n/2) is the same as O(n). Whether it's what the instructor intended is a different question..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T22:51:02.067",
"Id": "80243",
"Score": "0",
"body": "Ah, ok. The O notation isn't my strong suit. But you can modify the code so that it only needs to store n/2+1 chars max."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T13:46:39.137",
"Id": "80343",
"Score": "0",
"body": "@fgrieu: Sorry, it will assert. When calling `isBalanced(\"[[\")`, then the two brackets (`[`) will only pushed on to the stack. The second clause of the `if` statement in the `for` loop (and thus the `pop()`s) are never called, so that it reaches the final `return true`. See http://ideone.com/Ed5eiU (doesn't use assert, but outputs `true` to stdout)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T13:50:34.210",
"Id": "80344",
"Score": "0",
"body": "@RoToRa: I stand corrected."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-03T21:18:01.350",
"Id": "262966",
"Score": "0",
"body": "return stack.isEmpty()"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T08:41:13.870",
"Id": "45926",
"ParentId": "45916",
"Score": "16"
}
},
{
"body": "<p>This code is basically perfect (save for <a href=\"https://codereview.stackexchange.com/a/45926/21609\">that little bug found by RoToRa</a>):</p>\n\n<ul>\n<li>Map initialization in a static initializer block</li>\n<li>constructor is made inaccessible</li>\n<li>the code does what the documentation says</li>\n<li>clever short circuiting</li>\n<li>implementation using explicit stack</li>\n</ul>\n\n<p>However, there are a few points which we can talk about:</p>\n\n<ul>\n<li><p>The JavaDoc doesn't mention that the string must contain at least two characters. I would expect that the string <code>\"\"</code> is indeed balanced. For me, a balanced string would be described by the following EBNF grammar:</p>\n\n<pre><code><Balanced> ::=\n '(' <Balanced> ')'\n| '{' <Balanced> '}'\n| '[' <Balanced> ']'\n| epsilon\n</code></pre>\n\n<p>that is, the empty string is allowed via this recursive definition. Instead, you've implemented a recognizer for the following grammar:</p>\n\n<pre><code><Balanced> ::=\n '(' <InnerBalanced> ')'\n| '{' <InnerBalanced> '}'\n| '[' <InnerBalanced> ']'\n\n<InnerBalanced> ::=\n <Balanced>\n| epsilon\n</code></pre></li>\n<li><p>You forgot to test that <code>str != null</code></p></li>\n<li><p>You could use the diamond operator to invoke inference on generic arguments:</p>\n\n<ul>\n<li><code>Map<Character, Character> brackets = new HashMap<>()</code></li>\n<li><code>Stack<Character> stack = new Stack<>()</code></li>\n</ul></li>\n<li><p>A user of your function can't specify custom parens like <code><…></code>. It would be good to enable some possibility of customization, and default to <code>(…)</code> otherwise.</p></li>\n<li><p>If you enable custom parens, then there may be some ambiguity – each opening paren would be associated with a set of possible closing parens. Note that given an <em>O(1)</em> membership test, this won't affect the algorithmic complexity of your code. Examples: <code>|…|</code> (norm operator/<code>abs</code> from mathematics), <code>|…></code> (Bra-ket notation from quantum physics), <code><…></code> (mean value/expected value from statistics).</p></li>\n<li><p>When checking whether a given string has balanced parens, this string will usually contain non-paren text as well. A function that returns true for <code>q{foo($bar{baz} .= do {my $x = '('; bless \\$x})}</code> given the delimiters <code>{…}</code> would be useful in real-world applications. Unfortunately, this disables your check that the string must be of even length.</p></li>\n<li><p>You only support single “characters” as delimiters. It would be more flexible to allow arbitrary strings. Note that Java's <code>Character</code>s aren't real Unicode characters, but effectively only 16-bit code units. To represent any Unicode code point, we need one or two Java characters (think: “<code>int</code> is the new <code>char</code>”). Note further that this is only sufficient for single code points, whereas one logical character (“grapheme”) may consist of multiple code points.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T19:55:03.680",
"Id": "80215",
"Score": "0",
"body": "\"It would be more flexible to allow arbitrary strings\" But then the problem gets much harder due to possible overlaps. The same problem occurs if you allow custom single-char brackets and a closing bracket coincides with an opening one. Also why would one need to check for `null` explicitly? The documentation doesn't state that null is a valid input, and by default I would not assume it to be, so is a NullPointerException not enough?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T21:12:53.987",
"Id": "80231",
"Score": "0",
"body": "@NiklasB. An explicit NPE with custom error message makes it much easier for a caller to debug. Leaving behaviour unspecified is a cheap cop out. Also, defensive programming is a best practice. Re ambiguity: this is no problem even with the given algorithmic complexity constraints as long as one sets up a few rules that decide how the input is parsed: e.g. overlapping tokens become a non-issue with longest token matching, committing instead of backtracking preserves _O(n)_ behaviour, and we could decide that closing braces are preferred over opening braces. Further questions? :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T21:16:08.700",
"Id": "80232",
"Score": "0",
"body": "Sure, you can specify greedy parsing, but that might go against the intuition of users who would assume that the parser just implements the straightforward context-free grammer given in your answer (which would then be hard to parse). Just wanted to point out that if you go that road you will need to consider a lot of details. W.r.t defensive, would it be just as acceptable to just say \"`null` is never a valid input unless otherwise specified\"? That's usually how I do it (for an entire library, not just for certain methods) and it does not leave anything unspecified"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T21:37:07.880",
"Id": "80235",
"Score": "0",
"body": "@NiklasB. Yes of course, and I only added suggestions on how to make the `isBalanced` more general. I believe that offering more power to “the user” is preferable to offering a restricted “safe” set of operations, even though more power means that more stuff can go wrong. (For some unfathomable reason, I prefer Perl over Python and Scala over Java…) Oh, I forgot to mention another good way to deal with ambiguity etc.: Just throw an exception when ambiguity is encountered (possibly as early as collecting all braces in a data structure)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T08:54:33.073",
"Id": "45927",
"ParentId": "45916",
"Score": "12"
}
},
{
"body": "<p><strong>assertEquals vs assertTrue</strong></p>\n\n<p>I see that you're using :</p>\n\n<blockquote>\n<pre><code> assertEquals(true, isBalanced(\"{}([])\"));\n assertEquals(false,isBalanced(\"([}])\"));\n assertEquals(true, isBalanced(\"([])\"));\n assertEquals(true, isBalanced(\"()[]{}[][]\"));\n</code></pre>\n</blockquote>\n\n<p>This is not the best way to assert boolean values. You should be using : </p>\n\n<pre><code> assertTrue(isBalanced(\"{}([])\"));\n assertFalse(isBalanced(\"([}])\"));\n assertTrue(isBalanced(\"([])\"));\n assertTrue(isBalanced(\"()[]{}[][]\"));\n</code></pre>\n\n<p>This is more clear since it is clear that you are checking for true/false.</p>\n\n<p><strong>Separation</strong></p>\n\n<p>All your tests are still in the main, I will again strongly recommend to extract those tests in a test class, and create a single method for each case. This will help if you give relevant name to your tests to see at first glance what are you testing specifically. Is it an exception, a normal case, etc.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T13:03:35.153",
"Id": "45940",
"ParentId": "45916",
"Score": "13"
}
},
{
"body": "<p>I've only one addition to the other answers</p>\n\n<p>For the stack you use <code>java.util.Stack</code>, this seems like an obvious choice, yet it is a remnant from pre-collection times, and is a subclass of <code>java.util.Vector</code>, and therefore <code>synchronized</code>. You don't need the synchronization overhead, and are better off using <code>java.util.ArrayDeque</code>. That is a double ended queue, but functions perfectly as a stack if only accessed from the top. In fact <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Stack.html\"><code>Stack</code>'s javadoc</a> advises you to use <code>ArrayDeque</code> instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T23:13:53.977",
"Id": "80246",
"Score": "0",
"body": "Wouldn't a `LinkedList` be more appropriate? A linked list is optimised for push and pop operations, which is what is used here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T04:52:30.490",
"Id": "80264",
"Score": "1",
"body": "`ArrayDeque`'s push and pop operations, merely change an int index, only when the array needs to grow, there will be a need to do `System.arrayCopy()`, `LinkedList` will have to create a new `Node` on each push. Since we know the exact maximum needed capacity, we can make sure the `ArrayDeque` never needs to grow, eliminating the one disadvantage for `ArrayDeque`. Even if we don't set a capacity, I think `ArrayDeque` will outperform `LinkedList` in this algorithm."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T17:58:51.133",
"Id": "45962",
"ParentId": "45916",
"Score": "5"
}
},
{
"body": "<p>The class is misnamed: <code>BalancedParanthesis</code> should be <code>BalancedParentheses</code>. \"Paranthesis\" should be spelled \"Parenthesis\", and should be made plural to \"Parentheses\", since you can't balance one parenthesis.</p>\n\n<p>Consider renaming it to <code>BalancedDelimiters</code> to be more general, since you support more than just parentheses.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T18:54:01.243",
"Id": "45973",
"ParentId": "45916",
"Score": "7"
}
},
{
"body": "<p>Even though your <code>brackets</code>is private, it is a good practice to make these kind of key-value holders immutable as well. So your code</p>\n\n<pre><code>private static final Map<Character, Character> brackets = new HashMap<Character, Character>();\n static {\n brackets.put('[', ']');\n brackets.put('{', '}');\n brackets.put('(', ')');\n }\n</code></pre>\n\n<p>could be rewritten as </p>\n\n<pre><code>private static final Map<Character, Character> brackets = Collections.unmodifiableMap(new HashMap<Character, Character>() {{\n put('[', ']');\n put('{', '}');\n put('(', ')');\n }});\n</code></pre>\n\n<p>This is more concise and also serves as good documentation even if your <code>Map</code> is <code>private</code> and even if you don't have a setter.</p>\n\n<p>Another way is to use <a href=\"https://code.google.com/p/guava-libraries/wiki/GuavaExplained\" rel=\"nofollow\">Guava library</a> from Google which claims better performance and real immutability with a more concise syntax</p>\n\n<pre><code>private static final Map<Character, Character> guavaBracket = ImmutableMap.of('[', ']','{', '}','(', ')');\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T13:55:12.903",
"Id": "81141",
"Score": "0",
"body": "The instance initializer block you recommend leads to much confusion in real life, especially when you break the Java Code Style guidelines in the way that you have."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T15:54:02.790",
"Id": "81159",
"Score": "0",
"body": "yeah..only if immutability is bad and more verbose code is less confusing in \"real life\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T15:58:41.943",
"Id": "81160",
"Score": "0",
"body": "The immutability is fine, but the *anonymous subclass with instance initializer block with non-standard code formatting* is what is confusing... which is what my first comment said. More verbose code or correctly formatted readable code.... call it what you want, but what you are recommending is not best practice in any common reference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T16:19:13.627",
"Id": "81164",
"Score": "0",
"body": "You seem to agree about immutability, I do not know whether any best practice recommendation exists for/against anonymous subclassing in such cases. In production code I had reviewed, I have also seen mostly the approach without anon. subclass which you seem to prefer. But lately I have seen the approach I proposed in use increasingly, especially by those who have coded in non Java languages. Code review in general involves some subjective opinion, sometimes matters of preference, style etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T16:23:14.653",
"Id": "81165",
"Score": "0",
"body": "At minimum, [the 'opening' `{{` of the code should be separated by newline](http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html), and correctly indented. The closing `}}` should be split as well. The inner `{}` are a code block, and should be on their own lines just like a method block or any other compound statement...."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T07:47:38.880",
"Id": "46018",
"ParentId": "45916",
"Score": "4"
}
},
{
"body": "<p>Some remarks:</p>\n\n<ol>\n<li>As correctly pointed in the <a href=\"https://codereview.stackexchange.com/a/45926/37580\">accepted answer</a>, the code is plain broken; changing <code>return true</code> into <code>return stack.empty()</code> seems to fix that (disclaimer: I did not run the code).</li>\n<li>I'm not sure that <code>stack.push</code> is truly of complexity O(1), which is necessary to match the \"Time complexity: O(n)\" requirement (think of what happens for an input consisting of a large even number of <code>'{'</code>: the stack is grown at every push). For this reason I would use, rather than a <code>stack</code> object, a single auxiliary <strike>string</strike> <code>char[]</code> array of size <code>str.length()/2</code> used as a stack, and an index into that. It is enough for the job, tends to make the code much simpler, and makes it appreciably faster (especially since <code>stack</code> is <code>synchronized</code>, as I learned from <a href=\"https://codereview.stackexchange.com/a/45962/37580\">this answer</a>).</li>\n<li>The fragment <code>for (int i = 0; i < str.length(); i++)</code> matches the \"Time complexity: O(n)\" requirement, but its straight C equivalent would squarely not, for there <code>strlen()</code> is O(n), thus the statement O(n<sup>2</sup>). I suggest a variable <code>n</code> set to <code>str.length()</code> on entry, that will likely speed up things slightly, clarify and slightly shorten the code, and in any case can't harm much.</li>\n<li>My reading of the problem's statement is that the <em>empty</em> string is perfectly acceptable.</li>\n<li>It is not clear from the problem's statement that any character other than the 6 ones in <code>{}[]()</code> is prohibited, in particular space.</li>\n<li>After that change of 1., the test <code>(str.length() % 2) != 0</code> becomes redundant, and I would say unwanted (independently of the previous item).</li>\n<li>I do <em>not</em> think that it is useful to add a test that <code>str</code> is <code>null</code>, for in that case <code>str.length</code> will throw an exception, and that's fine for me. It would be good style in C, though.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T10:17:52.910",
"Id": "80282",
"Score": "0",
"body": "1) Good point that `Stack.push()` could take longer than O(1) time. It may be prudent to call [`Stack.ensureCapacity()`](http://docs.oracle.com/javase/7/docs/api/java/util/Vector.html#ensureCapacity\\(int\\)) to avoid any possible penalty of having to expand the stack. You could also use a `char[]` array. Strings are immutable in Java, though, and would not be suitable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T10:32:23.833",
"Id": "80284",
"Score": "0",
"body": "@200_success: very right! Fixed it. You guessed it, I'm not truly a Java programmer (I mostly use the Java Card 2 dialect, used in Smart Cards, in the variant where no variable can be `int`, we have only `short`)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:56:48.923",
"Id": "80332",
"Score": "0",
"body": "I would object to the test of the `null` string, since if you know that you will be throwing a `NullPointerException` than make a test that expect an exception. If for any reason something change and the exception is not throw anymore you will know it!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T09:45:10.073",
"Id": "46024",
"ParentId": "45916",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "45926",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T06:55:06.123",
"Id": "45916",
"Score": "32",
"Tags": [
"java",
"algorithm",
"strings",
"stack"
],
"Title": "Check for balanced parentheses"
} | 45916 |
<p>As suggested in <a href="http://chat.stackexchange.com/transcript/message/14590911#14590911">The 2nd Monitor</a>, I'd like a review of this in-place reversal of a singly linked-list:</p>
<pre><code>#include <iostream>
struct node {
int data;
node *next;
};
node *reverse(node *list) {
node *prev = NULL;
node *next;
while (list) {
next = list->next;
list->next = prev;
prev = list;
list = next;
}
return prev;
}
void show_list(node *list) {
while (list != NULL) {
std::cout << list->data << ", ";
list = list->next;
}
}
int main() {
node *list = NULL;
for (int i=0; i<10; i++) {
node *n = new node;
n->next = list;
n->data = i;
list = n;
}
std::cout << "As built: ";
show_list(list);
list = reverse(list);
std::cout << "Reversed: ";
show_list(list);
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T20:35:37.733",
"Id": "80224",
"Score": "2",
"body": "I would use the term one pass reversal rather than in-pace."
}
] | [
{
"body": "<p>Code this valuable shouldn't be limited solely to <code>int</code> data.</p>\n\n<pre><code>template<typename T>\nstruct node { \n T data;\n node *next;\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T07:50:12.997",
"Id": "45920",
"ParentId": "45918",
"Score": "5"
}
},
{
"body": "<ul>\n<li><p>You don't use <code>delete</code> after allocating <code>node</code>s with <code>new</code>, resulting in a memory leak. As a general rule, <code>delete</code> should be used in the same way <code>new</code> was used.</p>\n\n<p>In this case, have an identical <code>for</code> loop and use <code>delete</code> on each node:</p>\n\n<pre><code>for (int i=0; i<10; i++) {\n delete n;\n}\n</code></pre>\n\n<p>With these two loops, you might as well have a constant to hold the number of nodes to use, so that you can make sure the same number is used.</p></li>\n<li><p>You don't need to have <code>return 0</code> at the end of <code>main()</code>. Reaching the end implies successful completion, and the compiler will insert this return for you.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T08:12:04.993",
"Id": "45922",
"ParentId": "45918",
"Score": "8"
}
},
{
"body": "<p>While this a good example of a list reversal algorithm from a purely algorithmic point of view, the finer details with regards to the list and the reverse implementation are in need of some work.</p>\n\n<hr>\n\n<p>The biggest problem here is that the proper tools haven't been used for abstraction and encapsulation of the list. In particular, you should have a <code>list</code> class that manages your sequence of <code>node</code>s rather than managing the <code>node</code>'s bare. This allows you much easier use, and it provides a much cleaner interface. Compare what you're doing to something as simple to use as:</p>\n\n<pre><code>list l;\nl.add(3);\nl.add(5);\n</code></pre>\n\n<p>This also gives the benefit of encapsulating memory management of the <code>node</code>s. Raw memory management with new and delete is extremely error prone and has all kinds of non-obvious caveats (exception safety, flow jumps can cause leaks, etc). Manual memory management should only be used in low level containers. Everything else should hide it behind RAII by either having a container manage it (like <code>list</code> managing <code>node</code>s) or through smart pointers (when a container doesn't make sense).</p>\n\n<p>It should be noted that the higher level of abstraction does come at a cost to you, the developer. By alleviating the consumer's responsibility to manage the nodes, you must do it yourself behind the scenes of a few public methods. Also, in order to allow the consumer to examine the list, you would need to implement some form of iterator. Unfortunately, both of these things coupled together means that a <code>list</code> is going to be much more complicated than a set of <code>node</code>s. If your goal was just to demonstrate a simple reversal algorithm, a <code>list</code> would be overkill. Then again, if you had iterators, you could simply use a reverse iterator and you wouldn't need to actually reverse the list (though this would of course require a doubly linked list for the expected linear performance). </p>\n\n<p>(Oh also, if you do make a <code>list</code>, don't use the name <code>list</code> unless you put it in namespace. Someone would inevitably drag your list and <code>std::list</code> into the global namespace, and it could end badly.)</p>\n\n<hr>\n\n<p>Even if you don't make a full out <code>list</code> class, you should make some effort to abstract away the gritty details. The most obvious and straightforward way to do this is to use functions rather than operating on the list directly (<code>node* list_add(node* head, int data);</code>, <code>list_destroy(node* head);</code>, so on). Not only does this reduce code duplication (and thus the likelihood of fixing one section of code only to leave another broken), but it provides a better experience to use the list.</p>\n\n<hr>\n\n<p>On a more stylistic/technical note, I would give <code>node</code> a constuctor. That allows you to save quite a bit of initialization code when creating nodes:</p>\n\n<pre><code>struct node { \n int data;\n node *next;\n explicit node(int data, node *next = NULL) : data(data), next(next)\n { }\n};\n</code></pre>\n\n<p>This allows much more succinct node creation:</p>\n\n<pre><code>for (int i=0; i<10; i++) {\n list = new node(i, list);\n}\n</code></pre>\n\n<hr>\n\n<p>When there are simple conditions and post-actions, I find <code>for</code> loops easier to immediatley grasp than <code>while</code> loops:</p>\n\n<pre><code>void show_list(node *list) {\n for (; list != NULL; list = list->next) {\n std::cout << list->data << \", \";\n }\n}\n</code></pre>\n\n<hr>\n\n<p>The semantics of your <code>reverse</code> strike me as a bit C. <code>list = reverse(list)</code> makes it look like a new copy of the list is created that is reversed. For example, imagine <code>node* newList = reverse(list)</code>. Without reading the code (as there is no documentation), it is not clear that <code>newList</code> is not copy of <code>list</code>. After this call, <code>list</code> is no longer safe to use, but nothing indicates this. It's just an unexpected side effect.</p>\n\n<p>This usage seems a bit unnatural and prone to error. I would mutate the parameter to <code>reverse</code>. You can even still return it for the <code>list = reverse(list)</code> usage if you want (though I wouldn't since that brings back the ambiguity of whether or not a copy is made).</p>\n\n<pre><code>void reverse(node*& list) {\n node *prev = NULL;\n node *next;\n\n while (list) {\n next = list->next;\n list->next = prev;\n prev = list;\n list = next;\n }\n list = prev;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T19:25:56.723",
"Id": "45977",
"ParentId": "45918",
"Score": "6"
}
},
{
"body": "<p>The code of actual reversal is fine, so like previous answers I only have a some suggestions on general style. As discussed by <a href=\"https://codereview.stackexchange.com/a/45977/39083\">Corbin</a>, raw memory management is very error prone, and you should avoid it at any cost. It is even more dangerous in the presence of exceptions; even if your code is bug-free, you can still have leaks. Without trying to change the logic too much, below are some minimal changes that will help you organize code better. Here's a <a href=\"http://coliru.stacked-crooked.com/a/3a476c336b2bade2\" rel=\"nofollow noreferrer\">live example</a>.</p>\n\n<hr>\n\n<p><strong>Node data structure</strong>:</p>\n\n<pre><code>template<typename T>\nstruct node\n{\n T data;\n node *next;\n\n explicit node(T&& d = T{}, node *n = nullptr) :\n data(std::move(d)), next(n) { }\n\n explicit node(const T& d, node *n = nullptr) :\n data(d), next(n) { }\n};\n</code></pre>\n\n<p>A node is now a class template over the value type <code>T</code>. A couple of constructors make it easier and safer to construct a new node. In case <code>T</code> has move semantics, separate move and copy constructors will be more efficient. Use <code>nullptr</code> instead of <code>NULL</code>.</p>\n\n<hr>\n\n<p><strong>Actual reversal</strong>:</p>\n\n<pre><code>template<typename T, typename N = node<T> >\nN *reverse(node<T> *list)\n{\n N *prev = nullptr;\n\n while(list)\n {\n N *next = list->next;\n list->next = prev;\n prev = list;\n list = next;\n }\n\n return prev;\n}\n</code></pre>\n\n<p>Use type aliases like <code>N</code> to make code more compact. A default template argument is maybe my personal style of saving lines of code. You will probably find this unclear, so use an explicit <code>using N = node<T>;</code> declaration instead. Keeping declarations at first use like <code>N *next</code> make code clearer. Don't worry about efficiency here, leave this to the optimizer.</p>\n\n<hr>\n\n<p><strong>Streaming</strong>:</p>\n\n<pre><code>template<typename S, typename T>\nvoid show_node(S& s, node<T> *&list)\n{\n s << list->data;\n list = list->next;\n}\n\ntemplate<typename S, typename T>\nS& operator<<(S& s, node<T> *list)\n{\n if (list)\n show_node(s, list);\n\n while (list)\n {\n s << \", \";\n show_node(s, list);\n }\n\n return s;\n}\n</code></pre>\n\n<p>Overload <code>operator<<</code> for streaming. Print separators only between elements, not at the end of the sequence. If this leads to code duplication, use an auxiliary function like <code>show_node()</code>.</p>\n\n<hr>\n\n<p><strong>List management</strong>:</p>\n\n<pre><code>template<typename T, typename N = node<T> >\nN *make_list(size_t L)\n{\n N *list = nullptr;\n\n for (size_t i=0; i<L; ++i)\n list = new N{T(i), list};\n\n return list;\n}\n\ntemplate<typename T, typename N = node<T> >\nvoid delete_list(node<T> *list)\n{\n while (list)\n {\n N *next = list->next;\n delete list;\n list = next;\n }\n}\n</code></pre>\n\n<p>As a minimal protection against bugs, define individual functions to generate and to clear a list. See now how convenient is <code>node</code>'s constructor (<code>new N{T(i), list}</code>). Note that <code>T(i)</code> assumes a <code>size_t can be implicitly converted to</code>T`. In more realistic example you should be careful about conversions.</p>\n\n<hr>\n\n<p><strong>Main</strong>:</p>\n\n<pre><code>int main()\n{\n auto list = make_list<int>(10);\n std::cout << \"As built: \" << list << std::endl;\n\n list = reverse(list);\n std::cout << \"Reversed: \" << list << std::endl;\n\n delete_list(list);\n}\n</code></pre>\n\n<p>Using list management functions and streaming operator, <code>main()</code> is now cleaned up. The very next step would be to make sure <code>delete_list</code> is automatically called at end of scope, but as I said I am not changing the logic too much here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T20:54:21.643",
"Id": "80228",
"Score": "0",
"body": "Though there's a lot of good advice in here, I'm afraid this answer is a bit impractical if the question asker weren't a known C++ expert. All kinds of C++11 features are strewn through this with no mention of that (especially since the OP is likely using 03). Also, a default template argument to save a few characters is odd. What in the world is the user supposed to think N is? And why can it vary? That's an inappropriate shortening in my opinion. Use 'using' or typedef if you want to alias a type. Don't expose laziness to the caller."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T21:24:25.040",
"Id": "80234",
"Score": "0",
"body": "Just read that comment back to myself, and it was a bit unclear. To be a bit clearer, the impracticality isn't the C++ features but themselves but the relatively steep learning curve of templates, rvalue references, and move construction thrown at a question that exhibits very little understanding of more advanced features of C++. Then again, I suppose maybe I should stop trying to pretend the knowledge level of the question actually matches the knowledge level of its asker :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T22:04:44.083",
"Id": "80236",
"Score": "0",
"body": "@Corbin Criticism accepted :-) I clarified a bit more the use of a default template argument in the answer. I am usually carried away by uses where it is [really convenient](http://codereview.stackexchange.com/a/45358/39083)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T22:21:19.110",
"Id": "80241",
"Score": "0",
"body": "the issue with the default template argument isn't the lack of clarity. It's the ruining of the public signature that's the issue. An unnecessary template parameter is confusing to the person using the function. A `using` declaration isn't just clearer: I consider it the correct approach in this situation. There are situations like you linked to where you could just wrap it in another function to hide the extraneous template params, but that seems overkill for such a perfect use case for `using`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T22:51:25.597",
"Id": "80244",
"Score": "0",
"body": "@Corbin What can I say, you're right! Feel free to edit if you like."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T20:16:40.413",
"Id": "45978",
"ParentId": "45918",
"Score": "7"
}
},
{
"body": "<p>It might be helpful to have a little more context for this code, to answer questions such as why you don't do something like this:</p>\n\n<pre><code>#include <list>\n...\n std::list<int> my_list;\n ... put something in my_list to make a non-trivial test ...\n show_list(my_list);\n my_list.reverse();\n show_list(my_list);\n</code></pre>\n\n<p>There's also a singly-linked list, <code>slist</code>, if you want to avoid the double-linking of <code>std::list</code>, although I've previously found <code>slist</code> not as portable as <code>std::list</code>. (That is, not everyone's implementation of the STL seemed to provide it.)</p>\n\n<p>If it's really worth creating your own linked list, how about making a class called something like <code>List</code> containing objects of type <code>Node</code>, or implement these as templates <code>List<T></code> and <code>Node<T></code> as others have recommended? Then you can make <code>reverse()</code> be a member function of <code>List<T></code> so that you can write something like:</p>\n\n<pre><code>List<T> my_list;\n... other code ...\nmy_list.reverse();\n</code></pre>\n\n<p>A member function returning void would be my preferred way to modify an object \"in place\"--the function doesn't return anything, and in this case it doesn't even have parameters to play with, so it's clear the ONLY thing it can do is to modify the original list. And notice that that's how list reversal is implemented in STL.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T02:49:15.703",
"Id": "46002",
"ParentId": "45918",
"Score": "2"
}
},
{
"body": "<p>I think there are a few points worth mentioning that I haven't seen in any replies yet.</p>\n\n<pre><code>struct node { \n int data;\n node *next;\n};\n</code></pre>\n\n<p>As @Edward mentioned, this should almost certainly be a template. The <code>next</code> pointer should almost certainly be a <code>unique_ptr</code> instead of a raw pointer.</p>\n\n<pre><code>node *reverse(node *list) { \n node *prev = NULL;\n node *next;\n\n while (list) {\n next = list->next;\n list->next = prev;\n prev = list;\n list = next;\n }\n return prev;\n}\n</code></pre>\n\n<p>Although a couple of people mentioned exceptions, nobody mentioned the fact that this code isn't re-entrant. If an exception is thrown while the list is being reversed, the list will typically be left in a bad state--in particular, part of it may be orphaned. The reversal is done by traversing the list, and manipulating each node's pointer to point to the previous node instead of the next one. While this is being done, the list is basically broken into two pieces. An exception thrown in the middle of that process is likely to \"lose\" one of the pieces.</p>\n\n<p>Likewise, making this thread safe (by almost any reasonable definition of the term) basically requires that the <em>entire</em> reversal process be treated as a single critical section. That is to say, no other thread can be allowed to read part of the list at any point in the reversal process. This is likely to be a serious problem if there is much contention for use of such a collection.</p>\n\n<pre><code>void show_list(node *list) {\n while (list != NULL) {\n std::cout << list->data << \", \";\n list = list->next;\n }\n}\n</code></pre>\n\n<p>This displays a comma and space after the final item in the list. It would be better to provide access to the items in the list via iterators. With iterators, it would be trivial to use something like an <a href=\"https://codereview.stackexchange.com/q/13176/489\">infix_ostream_iterator</a> to display the data more neatly.</p>\n\n<pre><code>node *list = NULL;\n</code></pre>\n\n<p>As @iavr showed, it's better to use <code>nullptr</code> instead of NULL. While <code>NULL</code> works perfectly well to produce a null pointer, it can also be used by accident in places that aren't related to pointers at all (because <code>NULL</code> is simply a macro for the value <code>0</code>). By contrast, <code>nullptr</code> can be assigned to any pointer, but not to other types such as integers.</p>\n\n<p>Overall, this code should clearly be avoided for almost anything except its originally intended use (in-place reversal of a linked list).</p>\n\n<p>Since @David K mentioned the possibility of using <code>std::list</code>, and <code>std::slist</code>, I'll point out yet one more possibility. If you honestly need to a linked list (you probably don't) <em>and</em> need to traverse in both directions, <em>and</em> you really can't afford a doubly-linked list like <code>std::list</code>, there is one other possibility that may be worth considering: a doubly linked list that stores only <em>one</em> link per node.</p>\n\n<p>Although thoroughly crufty in some ways, this structure is just clever enough to be worth mentioning in this context. To store both backward and forward links in only one link field, what we store in the node is actually the exclusive-or of the addresses of the previous and next nodes in the list. The parent linked-list typically stores a dummy node containing pointers to the first and last nodes in the list.</p>\n\n<p>We can then use those pointers to recover the rest of the pointers. We have the address of node A, and the XOR of the addresses of node A and node B. Xoring those two together gives us the address of node B. That node, of course, contains the XOR of the addresses of node B and node C. Since we already have the address of node B, we can XOR it with the value from the node to get the address of node C (and so on for the remaining nodes in the list).</p>\n\n<p>Conversely, if we start with the address of node Z and the XOR of the addresses of node Z and node Y, we can use exactly the same procedure to isolate the address of node Y. That, in turn, is enough to recover the address of node X, and so on through the list in reverse.</p>\n\n<p>This obviously has its own set of strengths and weaknesses. The most obvious weakness is simple obscurity--virtually <em>nobody</em> will simply recognize this structure and understand how it works without at least a little study (and a few probably won't trust it even then). Less obviously, this technique is generally incompatible with automated (tracing-based) garbage collection. A garbage collector detects what memory is still accessible by traversing all accessible pointers. Without special knowledge about how to recover the actual pointers in the list, all but the first and last nodes of this list will appear inaccessible.</p>\n\n<p>Nearly the sole real strength is what was stated up front: this lets you build a linked list that can be traversed in either direction while storing only (bits the same size as) one pointer per node. Since it can be traversed in either direction without modification, it avoids the reentrancy problems inherent in the original code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-04T01:22:24.963",
"Id": "106050",
"Score": "1",
"body": "Clever. I called it :) A doubly linked list would be well-suited. And the XOR trick is one devious trick. Oh, using `unique_ptr<>` in the node is prone to stack-overflow on default destruction. Don't forget to iteratively reset the nodes if you use it!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T05:24:20.973",
"Id": "46008",
"ParentId": "45918",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "45978",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T07:03:55.267",
"Id": "45918",
"Score": "13",
"Tags": [
"c++",
"linked-list"
],
"Title": "In-place reversal of a singly linked list"
} | 45918 |
<p>I've created a linked list class in Python, but I'm not sure how to enforce only passing <code>Node</code> objects into the <code>insert</code> routine.</p>
<pre><code># linked list in Python
class Node:
"""linked list node"""
def __init__(self, data):
self.next = None
self.data = data
def insert(self, n):
n.next = self.next
self.next = n
return n
def showall(self):
print self.data
if self.next != None:
self.next.showall()
ll = Node("one")
ll.insert(Node("two")).insert(Node("three"))
ll.showall()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T08:36:05.393",
"Id": "80112",
"Score": "0",
"body": "Use Python 3.4 `@singledispatch`."
}
] | [
{
"body": "<p>You could delegate the construction of nodes to the <code>insert</code> function :</p>\n\n<pre><code>#!/usr/bin/python\n\n# linked list in Python\n\nclass Node:\n \"\"\"linked list node\"\"\"\n def __init__(self, data):\n self.next = None\n self.data = data\n def insert(self, data):\n n = Node(data)\n n.next = self.next\n self.next = n\n return n\n def showall(self):\n print self.data\n if self.next != None:\n self.next.showall()\n\n\nll = Node(\"one\")\nll.insert(\"two\").insert(\"three\")\nll.showall()\n</code></pre>\n\n<p>You could make this more concise by adding a default argument to your <code>__init__()</code> :</p>\n\n<pre><code>class Node:\n \"\"\"linked list node\"\"\"\n def __init__(self, data, next=None):\n self.next = next\n self.data = data\n def insert(self, data):\n self.next = Node(data, self.next)\n return self.next\n def showall(self):\n print self.data\n if self.next != None:\n self.next.showall()\n\n\nll = Node(\"one\")\nll.insert(\"two\").insert(\"three\")\nll.showall()\n</code></pre>\n\n<hr>\n\n<p>Additional point : from <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> :</p>\n\n<blockquote>\n <p>Comparisons to singletons like None should always be done with <code>is</code> or\n <code>is not</code>, never the equality operators.</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-04-01T09:54:26.107",
"Id": "45930",
"ParentId": "45923",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "45930",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T08:32:16.557",
"Id": "45923",
"Score": "5",
"Tags": [
"python",
"linked-list"
],
"Title": "Passing Node objects into insert routine of linked list"
} | 45923 |
<p>This tag is reserved for <a href="/questions/tagged/linked-list" class="post-tag" title="show questions tagged 'linked-list'" rel="tag">linked-list</a> implementations in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged 'c'" rel="tag">c</a> / <a href="/questions/tagged/c%2b%2b" class="post-tag" title="show questions tagged 'c++'" rel="tag">c++</a> and similar languages.</p>
<p>Please use this tag instead of <a href="/questions/tagged/reinventing-the-wheel" class="post-tag" title="show questions tagged 'reinventing-the-wheel'" rel="tag">reinventing-the-wheel</a> for linked lists.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T08:35:22.773",
"Id": "45924",
"Score": "0",
"Tags": null,
"Title": null
} | 45924 |
Special tag reserved for the countless implementations of linked lists in C and C-derived languages. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T08:35:22.773",
"Id": "45925",
"Score": "0",
"Tags": null,
"Title": null
} | 45925 |
<p>first let me explain what I am trying to achieve here :</p>
<p>I am supposed to compute some results, using data from several tables, filtered by a run_id.
One of these tables has about 500.000 rows per run_id, and 60 columns.
All other tables have only a few thousand rows per run_id.
I also have to write about 500.000 rows of data in a table with only 4 columns.</p>
<p>So, I first tried to load all these tables at once, which failed with an OutOfMemoryError because of the big table (called <code>EPE</code> from now on).</p>
<p>So, I decided to do some batch select to load the data from EPE. However, depending on the 'business' of the database,
the whole process (load, compute, write) can take between 15 and 30 minutes.</p>
<p>Can I improve my code to make it faster ?</p>
<p>Here is my code, slightly reworked, so it might have some typos. Please let me know.</p>
<p>Main class :</p>
<pre><code>@Component
public class Computation {
public static final int MAX_RESULTS = 50000;
public static final String SPECIAL = "207";
Map<String, Curve> dfs;
Map<String, Curve> pds;
Map<String, LegalEntity> les;
@Autowired
@Qualifier("curveDAO")
CurveAccess curveDAO;
@Autowired
@Qualifier("dealDAO")
DealAccess dealDAO;
@Autowired
@Qualifier("entityDAO")
EntityAccess entityDAO;
@Autowired
@Qualifier("resultDAO")
ResultAccess resultDAO;
@Autowired
@Qualifier("traceDAO")
TraceAccess traceDAO;
@Autowired
Runs runs;
public Computation() {
}
public Run initialize(Long runId) {
Run run = runs.getRun(runId);
resultDAO.purge(run);
dfs = curveDAO.getDfs(run);
pds = curveDAO.getPds(run);
ent = entityDAO.getByRun(run);
return run;
}
public Map<Map.Entry<String, String>, Curve> prepareEpe(Run run, int start, int max) {
Map<Map.Entry<String, String>, Curve> epe = new HashMap<Map.Entry<String, String>, Curve>();
epe = dealDAO.getEpe(run, start, max);
return epe;
}
public void calculateResult(Run run, Map<Map.Entry<String, String>, Curve> epes) {
List<Result> results = new ArrayList<Result>();
Curve pdSPECIAL = pds.get(SPECIAL);
for (Entry<Entry<String, String>, Curve> entry : epes.entrySet()) {
Entity ntt = ent.get(entry.getKey().getValue());
if (ntt == null) {
continue;
}
double lgd;
if (ntt.getLgd() == null) {
traceDAO.setTrace(new Trace(0, entry.getKey().getKey(), ntt.getId(), run.getRunId(),
"Missing data", "Missing lgd, no computation", new Date()));
results.add(new Result(entry.getKey().getKey(), ntt.getId(), null, run.getRunId()));
continue;
} else {
lgd = ntt.getLgd();
}
Curve pd = pds.get(ntt.getId());
String currency = ntt.getCurrency();
Curve df;
if (currency == null || currency.isEmpty()) {
traceDAO.setTrace(new Trace(0, entry.getKey().getKey(), ntt.getId(), run.getRunId(), "Forcing",
"No currency found, USD used", new Date()));
df = dfs.get("USD");
} else {
df = dfs.get(currency);
}
if (pd == null) {
traceDAO.setTrace(new Trace(0, entry.getKey().getKey(), ntt.getId(), run.getRunId(),
"Missing data", "Missing pd, no computation", new Date()));
}
if (df == null) {
traceDAO.setTrace(new Trace(0, entry.getKey().getKey(), ntt.getId(), run.getRunId(),
"Missing data", "Missing df, no computation", new Date()));
}
if (pd == null || df == null) {
results.add(new Result(entry.getKey().getKey(), ntt.getId(), null, run.getRunId()));
continue;
}
double result = 0.0;
double probaDownSPECIAL = 0.0;
for (int i = 0; i < Constants.STEPS; i++) {
try {
double epe = entry.getValue().get(i);
double discountFactor = df.get(i);
double probaDown = pd.get(i);
if (i > 0) {
probaDownSPECIAL += pdSPECIAL.get(i - 1);
}
result += epe * discountFactor * probaDown * (1 - probaDownSPECIAL);
} catch (NullPointerException npe) {
npe.printStackTrace();
}
}
result *= lgd;
results.add(new Result(entry.getKey().getKey(), ntt.getId(), result, run.getRunId()));
}
resultDAO.setResult(results);
}
/**
* getters and setters...
*/
public static void main(String[] args) {
Long runId = Long.parseLong(args[0]);
ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:applicationContext.xml");
Computation computer = context.getBean(Computation.class);
Run run = computer.initialize(runId);
Map<Map.Entry<String, String>, Curve> epe = new HashMap<Map.Entry<String, String>, Curve>();
int start = 0;
do {
epe.clear();
epe = computer.prepareEpe(run, start, MAX_RESULTS);
computer.calculateResult(run, epe);
start += MAX_RESULTS;
} while (!(epe.size() < MAX_RESULTS));
}
}
</code></pre>
<p>The ResultDAO (where I write the results) :</p>
<pre><code>@Repository("resultDAO")
@Transactional("resultTxManager")
public class ResultDAO extends EntityAccess implements ResultAccess {
public final static String DELETE_RESULTS = "delete from RESULTS where RUN_ID = ?";
@Autowired
@Qualifier("resultSessionFactory")
private SessionFactory sessionFactory;
private Session session;
@Override
public void setResult(List<Result> results) throws HibernateException {
if (session == null) {
session = sessionFactory.openSession();
}
Transaction tx = session.beginTransaction();
int count = 0;
for (Result row : results) {
session.save(row);
if (count++ % 1000 == 0) {
session.flush();
session.clear();
}
}
tx.commit();
}
@Override
public void purge(Run run) throws HibernateException {
if (session == null) {
session = sessionFactory.openSession();
}
Transaction t = session.beginTransaction();
try {
SQLQuery query = session.createSQLQuery(DELETE_RESULTS);
query.setLong(0, run.getRunId());
query.executeUpdate();
t.commit();
} catch (HibernateException he) {
t.rollback();
throw he;
}
}
}
</code></pre>
<p>Does the session flush frequency have any impact on performance ?</p>
<p>The DealDAO (where I load the EPE table) :</p>
<pre><code>@Repository("dealDAO")
@Transactional("resultTxManager")
public class DealDAO extends EntityAccess implements DealAccess {
public static final String ALL_EPE_QUERY = "select DEAL_ID, NTT_ID, EPE_TS1, EPE_TS2,"
+ " EPE_TS3, EPE_TS4, EPE_TS5, EPE_TS6, EPE_TS7, EPE_TS8, EPE_TS9,"
+ " EPE_TS10, EPE_TS11, EPE_TS12, EPE_TS13, EPE_TS14, EPE_TS15, EPE_TS16,"
+ " EPE_TS17, EPE_TS18, EPE_TS19, EPE_TS20, EPE_TS21, EPE_TS22,"
+ " EPE_TS23, EPE_TS24, EPE_TS25, EPE_TS26, EPE_TS27, EPE_TS28, EPE_TS29,"
+ " EPE_TS30, EPE_TS31, EPE_TS32, EPE_TS33, EPE_TS34, EPE_TS35, EPE_TS36,"
+ " EPE_TS37, EPE_TS38, EPE_TS39, EPE_TS40, EPE_TS41, EPE_TS42, EPE_TS43,"
+ " EPE_TS44, EPE_TS45, EPE_TS46, EPE_TS47, EPE_TS48, EPE_TS49, EPE_TS50,"
+ " EPE_TS51, EPE_TS52, EPE_TS53, EPE_TS54, EPE_TS55, EPE_TS56, EPE_TS57"
+ " from EPE join RUNS on EPE.EPE_CNT_ID = RUNS.EPE_CNT_ID"
+ " where RUN_ID = ? order by DEAL_ID";
@Autowired
@Qualifier("resultSessionFactory")
private SessionFactory sessionFactory;
private Session session;
@Override
public Map<Map.Entry<String, String>, Curve> getEpe(Run run, int start, int max)
throws HibernateException {
if (session == null) {
session = sessionFactory.openSession();
}
SQLQuery select = session.createSQLQuery(ALL_EPE_QUERY);
select.setLong(0, run.getRunId());
select.setFirstResult(start).setMaxResults(max);
@SuppressWarnings("unchecked")
List result = select.list();
Map<Map.Entry<String, String>, Curve> epes = new HashMap<Map.Entry<String, String>, Curve>();
for (Object o : result) {
Object[] objArray = (Object[]) o;
Map.Entry<String, String> entry = new AbstractMap.SimpleEntry<String, String>((String) objArray[0],
(String) objArray[1]);
List valles = new LinkedList(Arrays.asList(objArray));
valles.remove(0);
valles.remove(0);
Object[] values = valles.toArray();
Curve curve = new Curve(values);
epes.put(entry, curve);
}
return epes;
}
}
</code></pre>
<p>OK, the getEpe method is a bit weird, because I am re-using a Curve class instead of creating a new one more suited to my needs. I'll rewrite that part.</p>
<p>Still, how do I choose the size of my batch select (here it is set at 50.000, roughly a tenth of the total number of rows) ?</p>
<p>I didn't include the other DAOs, because I think my question is long enough, and nothing fancy happens in these. I can include them upon request.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T13:23:23.370",
"Id": "80138",
"Score": "0",
"body": "You could probably benefit from threading the application or using something like map/reduce. Sorry this isn't much help, but your data set is large enough that I would say it constitutes re-working it significantly."
}
] | [
{
"body": "<p><strong>Naming, naming, naming...</strong><br>\nYour code is <em>very</em> hard to read - <code>ntt</code>, <code>epe</code>, <code>lgd</code>, <code>SPECIAL = \"207\"</code>(?!?). I understand (hope?) that some of these names are part of your business nomenclature, but, especially when asking strangers to read your code for optimization, giving meaningful names can go a long way. Asking me to figure out how to optimize a loop with <code>result += epe * discountFactor * probaDown * (1 - probaDownSPECIAL)</code> would be hard enough if the names there meant something to me...</p>\n\n<p><strong>Break it down</strong><br>\nYour methods are <em>very</em> long (<code>calculateResult</code> is 67 lines long...) this is a <a href=\"http://sourcemaking.com/refactoring/long-method\" rel=\"nofollow\">code smell</a>, which also makes your code hard to read, as well as hides the structure of your flow, and possible complexity issues.<br>\nRefactor your methods to be shorter, with expressive names, that will make your code more readable, more testable, and more optimizeable.</p>\n\n<p><strong>Distribute the load</strong><br>\nAs @Dan suggested in his comments - you should consider spreading the load on several threads/CPUs/machines...<br>\nAs far as I could see, your calculations are independent of each other, so you could simply arbitrarily split the load on several instances (let's say take over 9 of your friends' machines, and give each machine all the run ids ending with a specific digit...).<br>\nThis should give you linear scale (up to the point where writing to the DB is your bottleneck).</p>\n\n<p><strong>Optimizations for one-time code</strong><br>\nPerhaps I misunderstood your explanation, but it seems that this code is meant to run <em>once</em>. If that is the case, why do you care if it runs 15 minutes, or 8 hours? </p>\n\n<p>Just run it and get on with your life!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T18:39:05.407",
"Id": "45967",
"ParentId": "45933",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T11:04:36.383",
"Id": "45933",
"Score": "3",
"Tags": [
"java",
"performance",
"sql",
"hibernate"
],
"Title": "Loading, computation and writing 500.000 rows in database"
} | 45933 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.