body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>The <a href="https://developers.facebook.com" rel="nofollow noreferrer">Facebook Platform</a> is a software environment provided by the social networking service Facebook for third-party developers to <a href="https://developers.facebook.com/docs/" rel="nofollow noreferrer">create their own applications</a> and services that access data in Facebook. It lets developers integrate their applications directly into the Facebook social networking service.</p>
<p>The platform offers a set of programming interfaces and tools which enable developers to integrate with the "open graph" of personal relations and other things like songs, places, and Facebook pages. Applications on facebook.com, external websites, and devices are all allowed to access the graph. Launched on May 24, 2007, Facebook Platform has evolved from enabling development just on facebook.com to one also supporting integration across the web and devices.</p>
<h3>Documentation</h3>
<ul>
<li><a href="https://developers.facebook.com/docs/" rel="nofollow noreferrer">Facebook Documentation</a></li>
</ul>
<h3>Facebook SDKs</h3>
<ul>
<li><a href="https://developers.facebook.com/docs/reference/javascript/" rel="nofollow noreferrer">JavaScript SDK</a></li>
<li><a href="https://github.com/facebook/facebook-php-sdk" rel="nofollow noreferrer">PHP SDK</a> (<a href="https://developers.facebook.com/docs/reference/php/" rel="nofollow noreferrer">documentation</a>)</li>
<li><strike>[Python SDK]</strike> (deprecated)</li>
<li><a href="https://github.com/pythonforfacebook/facebook-sdk/" rel="nofollow noreferrer">Python SDK</a> (unofficial)</li>
<li><a href="https://github.com/facebook/facebook-ios-sdk/" rel="nofollow noreferrer">iOS SDK</a> (<a href="https://developers.facebook.com/docs/reference/iossdk/" rel="nofollow noreferrer">documentation</a>)</li>
<li><a href="https://github.com/facebook/facebook-android-sdk" rel="nofollow noreferrer">Android SDK</a> (<a href="http://developers.facebook.com/docs/reference/androidsdk/" rel="nofollow noreferrer">documentation</a>)</li>
<li><a href="http://facesharp.codeplex.com/" rel="nofollow noreferrer">FaceSharp .NET Facebook SDK and Starter Kit</a> (unofficial)</li>
<li><a href="https://github.com/facebook-csharp-sdk" rel="nofollow noreferrer">C# SDK</a> (unofficial)</li>
</ul>
<h3>Tools</h3>
<ul>
<li><a href="https://developers.facebook.com/tools/" rel="nofollow noreferrer">Facebook Developer Tools</a></li>
</ul>
<h3>Support</h3>
<ul>
<li><a href="https://developers.facebook.com/support/" rel="nofollow noreferrer">Facebook Developer Support</a></li>
</ul>
<h3>News</h3>
<ul>
<li><a href="https://developers.facebook.com/blog/" rel="nofollow noreferrer">Facebook Developer News</a></li>
</ul>
<h3>Apps</h3>
<ul>
<li><a href="https://developers.facebook.com/apps/" rel="nofollow noreferrer">Facebook Developer Apps</a></li>
</ul>
<h2>Non-developer questions</h2>
<p>For questions from a user perspective, (such as uploading your photos, privacy settings, who can post to your wall, etc.) please refer to our sister site <a href="https://webapps.stackexchange.com/tags/facebook/info">Web Applications</a>. </p>
<h3>More information:</h3>
<ul>
<li><a href="https://en.wikipedia.org/wiki/Facebook" rel="nofollow noreferrer">Facebook Wikipedia Article</a></li>
<li><a href="https://en.wikipedia.org/wiki/Facebook_Platform" rel="nofollow noreferrer">Facebook Developer Platform</a></li>
<li><a href="https://github.com/facebook" rel="nofollow noreferrer">Facebook GitHub</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:01:00.623",
"Id": "42210",
"Score": "0",
"Tags": null,
"Title": null
}
|
42210
|
Facebook Platform lets developers integrate their apps directly into the Facebook social networking service. Use this tag for questions which may arise when developing FOR Facebook. This tag is NOT for support questions about using the Facebook website or the official Facebook app.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:01:00.623",
"Id": "42211",
"Score": "0",
"Tags": null,
"Title": null
}
|
42211
|
<p>The link between dynamic programming and recursion is actually very strong.</p>
<p>Any dynamic programming solution can be transformed into a recursive solution (with memoization), with identical performance characteristics, e.g O(n*n). The difference is primarily one of presentation.</p>
<p>The <a href="http://en.wikipedia.org/wiki/Longest_common_subsequence_problem" rel="nofollow">longest common subsequence problem</a> is a good example of a problem that can be solved with dynamic programming.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:02:14.520",
"Id": "42212",
"Score": "0",
"Tags": null,
"Title": null
}
|
42212
|
Dynamic programming is an algorithmic technique for efficiently solving problems with a recursive structure containing many overlapping subproblems.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:02:14.520",
"Id": "42213",
"Score": "0",
"Tags": null,
"Title": null
}
|
42213
|
<p><a href="http://laravel.com/" rel="nofollow">Laravel</a> is a <a href="/questions/tagged/framework" class="post-tag" title="show questions tagged 'framework'" rel="tag">framework</a> for <a href="/questions/tagged/php" class="post-tag" title="show questions tagged 'php'" rel="tag">php</a> web development released under the <a href="http://mit-license.org/" rel="nofollow">MIT license</a>. Laravel helps you create applications using simple, expressive syntax. Last Laravel's version is 4.1.</p>
<h2>Feature Overview</h2>
<ul>
<li>Simple routing using Closures or controllers</li>
<li>Views and templating</li>
<li>Driver based session and cache handling</li>
<li>Database abstraction with query builder</li>
<li>Eloquent ORM</li>
<li>Reverse Routing</li>
<li>IoC Container</li>
<li>Authentication</li>
<li>Database Migrations</li>
<li>PHPUnit Integration</li>
<li>Automatic Pagination</li>
<li>Bundles</li>
<li>Queue system</li>
<li>Events and Filters</li>
</ul>
<h2>Documentation</h2>
<ul>
<li><a href="http://laravel.com/docs/4-1" rel="nofollow">Laravel 4.1 Documentation</a></li>
<li><a href="http://laravel.com/api/4.1/" rel="nofollow">Laravel 4.1 API</a></li>
<li><a href="http://laravel.com/docs/4-0" rel="nofollow">Laravel 4 Documentation</a></li>
<li><a href="http://laravel.com/api/4.0/" rel="nofollow">Laravel 4 API</a></li>
<li><a href="http://three.laravel.com/docs" rel="nofollow">Laravel 3 Documentation</a></li>
</ul>
<h2>Other notable tags</h2>
<ul>
<li><a href="/questions/tagged/laravel-3" class="post-tag" title="show questions tagged 'laravel-3'" rel="tag">laravel-3</a></li>
<li><a href="/questions/tagged/laravel-4" class="post-tag" title="show questions tagged 'laravel-4'" rel="tag">laravel-4</a></li>
<li><a href="/questions/tagged/eloquent" class="post-tag" title="show questions tagged 'eloquent'" rel="tag">eloquent</a></li>
</ul>
<h2>Community</h2>
<ul>
<li><a href="http://forums.laravel.io/index.php" rel="nofollow">Laravel Forums</a></li>
<li><a href="http://laravel.io/" rel="nofollow">Laravel.io Community</a></li>
<li><a href="http://wiki.laravel.io/" rel="nofollow">Laravel.io Community Wiki</a></li>
</ul>
<h2>Resources and Tutorials</h2>
<ul>
<li><a href="http://daylerees.com/codebright" rel="nofollow">Code Happy: Laravel book by Dayle Rees</a></li>
<li><a href="http://heybigname.com/2012/12/02/we-wrote-a-book/" rel="nofollow">Laravel Starter: Laravel book by Shawn McCool</a></li>
<li><a href="http://maxoffsky.com/code-blog/tutorial-creating-a-blog-in-laravel-from-scratch-part-1-overview/" rel="nofollow">Creating a Blog in Laravel from Scratch</a></li>
<li><a href="http://net.tutsplus.com/tag/laravel/" rel="nofollow">Nettuts+ Tag about Laravel</a></li>
<li><a href="http://fideloper.com/tag/laravel-4" rel="nofollow">Fideloper Laravel Tag</a></li>
<li><a href="http://jasonlewis.me/laravel-tutorials" rel="nofollow">Jason Lewis' Tutorials</a></li>
<li><a href="http://www.codeforest.net/laravel4-simple-website-with-backend-1" rel="nofollow">Laravel 4 – simple website with backend tutorial</a></li>
<li><a href="https://laracasts.com/" rel="nofollow">Laracasts - Laravel Screencasts by Jeffrey Way</a></li>
<li><a href="http://heera.it/tag/laravel-2" rel="nofollow">Heera.IT (Tag - Laravel)</a></li>
<li><a href="http://laravel.sl-creation.org/laravel-4/" rel="nofollow">Laravel.sl - Fast French tutorial</a></li>
<li><a href="http://laravelsnippets.com/" rel="nofollow">Laravel Snippets</a></li>
<li><a href="http://cheats.jesse-obrien.ca/" rel="nofollow">Laravel Cheat Sheet</a></li>
</ul>
<h2>Books</h2>
<ul>
<li><a href="http://wiki.laravel.io/Books" rel="nofollow"><em>Larvel Book List</em></a> via <a href="http://wiki.laravel.io/" rel="nofollow"><em>Laravel Wiki</em></a></li>
</ul>
<h3>Laravel 4</h3>
<ul>
<li><a href="https://leanpub.com/codebright" rel="nofollow"><em>Code Bright</em></a> by Dayle Rees</li>
<li><a href="https://leanpub.com/laravel" rel="nofollow"><em>From Apprentice To Artisan</em></a> by Taylor Otwell</li>
<li><a href="https://leanpub.com/laravel-testing-decoded" rel="nofollow"><em>Laravel Testing Decoded</em></a> by Jeffrey Way</li>
<li><a href="https://leanpub.com/implementinglaravel" rel="nofollow"><em>Implementing Laravel</em></a> by Chris Fidao</li>
<li><a href="http://www.packtpub.com/laravel-application-development-blueprints/book" rel="nofollow"><em>Laravel Application Development Blueprints</em></a> by Arda Kılıçdağı and <a href="http://stackoverflow.com/users/275284/dr-linux">Halil İbrahim Yılmaz</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:02:52.430",
"Id": "42214",
"Score": "0",
"Tags": null,
"Title": null
}
|
42214
|
Laravel is an open-source PHP web development framework created by Taylor Otwell. Laravel helps you create applications using simple, expressive syntax.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:02:52.430",
"Id": "42215",
"Score": "0",
"Tags": null,
"Title": null
}
|
42215
|
<p>Initially released as an add-on to Internet Information Services (IIS) via the Windows NT 4.0 Option Pack, it was subsequently included as a free component of Windows Server (since the initial release of Windows 2000 Server). </p>
<p>ASP 2.0 provided six built-in objects: Application, ASPError, Request, Response, Server, and Session. Session, for example, represents a cookie-based session that maintains the state of variables from page to page. The Active Scripting engine's support of the Component Object Model (COM) enables ASP websites to access functionality in compiled libraries such as DLLs.</p>
<p>ASP supports multiple programming languages, including VBScript, but there are other options. An alternative Active Scripting engine can be selected with the @Language directive or the syntax. JScript (Microsoft's implementation of ECMAScript) is the other language that is built-in. PerlScript (a derivative of Perl) and others are available as third-party installable Active Scripting engines.</p>
<p><a href="/questions/tagged/asp.net" class="post-tag" title="show questions tagged 'asp.net'" rel="tag">asp.net</a> was later introduced by Microsoft, and has replaced 'classic' ASP, and, this has led to the retronym 'ASP classic'</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:03:19.273",
"Id": "42216",
"Score": "0",
"Tags": null,
"Title": null
}
|
42216
|
<p>The 2.0 version of the .NET Framework.</p>
<p>Version Number: 2.0.50727.42<br>
Release Date: 2005-11-07</p>
<p>A listing of the releases of the .NET Framework can be found here:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/List_of_.NET_Framework_versions" rel="nofollow">List of .NET Framework versions</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:04:03.763",
"Id": "42218",
"Score": "0",
"Tags": null,
"Title": null
}
|
42218
|
The 2.0 version of the .NET Framework.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:04:03.763",
"Id": "42219",
"Score": "0",
"Tags": null,
"Title": null
}
|
42219
|
<p><a href="http://en.wikipedia.org/wiki/Base64" rel="nofollow">Base64</a> is a group of similar encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The Base64 term originates from a specific MIME content transfer encoding.</p>
<p>Base64 uses characters <code>0</code> to <code>9</code>, <code>A</code> to <code>Z</code> and <code>a</code> to <code>z</code> to represent digits of 64-decimal numbers. The last two required digits differ between schemas. For instance, MIME (RFC 2045) uses <code>+</code> and <code>/</code> , XML names tokens use <code>-</code> and <code>.</code>, XML identifies use <code>_</code> and <code>:</code> and regular expressions use <code>!</code> and <code>-</code>. </p>
<p>When encoding in Base64 text, 3 bytes are typically encoded into 4 characters. To encode arbitrary lengths, the padding character (<code>=</code>) is used. <code>=</code> at the end of encoded sequence means that only two bytes and <code>==</code> means that only one byte is encoded by the last 4 character group.</p>
<p>Characters outside the discussed alphabet are normally forbidden, except in MIME where they are discarded.</p>
<p>Base64 encoding schemes are commonly used when there is a need to encode binary data that need to be stored and transferred over media that are designed to deal with textual data. This is to ensure that the data remain intact without modification during transport. Base64 is commonly used in a number of applications including email via MIME, and storing complex data in XML.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:04:33.013",
"Id": "42220",
"Score": "0",
"Tags": null,
"Title": null
}
|
42220
|
Base64 is an encoding scheme (with some variations in the presentation) that represents binary data in an ASCII string format.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:04:33.013",
"Id": "42221",
"Score": "0",
"Tags": null,
"Title": null
}
|
42221
|
<p>Code relating to the recording, playback, or manipulation of audio data.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:05:00.330",
"Id": "42222",
"Score": "0",
"Tags": null,
"Title": null
}
|
42222
|
Code relating to sound recording, playback, and manipulation of audio data and hardware.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:05:00.330",
"Id": "42223",
"Score": "0",
"Tags": null,
"Title": null
}
|
42223
|
<p>There are a number of techniques to compress information, with most algorithms working to compress image, speech, music or video. Encoding the same information in lesser bits results in saving some crucial resource such as transmission bandwidth or hard-disk space. Compression algorithms also take advantage of human perception to further reduce the size of information. By encoding the same piece of information with fewer bits in places that the human brain is not accustomed to perceiving as well as other parts, substantial gains in compression ratios can be achieved.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:05:33.690",
"Id": "42224",
"Score": "0",
"Tags": null,
"Title": null
}
|
42224
|
The name given to the process of encoding data such that it uses lesser number of bits as compared to the original representation.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:05:33.690",
"Id": "42225",
"Score": "0",
"Tags": null,
"Title": null
}
|
42225
|
<p>Razor is a template language used by <a href="http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx" rel="nofollow noreferrer">ASP.NET Web Pages</a> and <a href="http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx" rel="nofollow noreferrer">ASP.NET MVC</a> (since version 3). It supports seamless transitions between HTML markup and C# or VB code. Transitions between markup and code are indicated by the "@" sign.</p>
<p>For example, to render a simple HTML list, this C# syntax is used:</p>
<pre><code><ul>
@for (int i = 0; i < 10; i++) {
<li>Item @i</li>
}
</ul>
</code></pre>
<p>To render a simple HTML list in VB, this syntax is used:</p>
<pre><code><ul>
@For i As Integer = 0 To 9
@<li>Item @i</li>
Next
</ul>
</code></pre>
<p>Razor has support for helper templates: </p>
<pre><code>@helper Bold(string text) {
return "<bold>"+text+"<bold>";
}
<p>
This text is @Bold("bold")
<p>
</code></pre>
<p>By default all strings are HTML encoded, if you wish to avoid that, use the <code>Raw</code> helper: </p>
<pre><code><p>@Html.Raw("<bold>hello</bold>")</p>
</code></pre>
<p>Occasionally you may want to include text in an escaped section, to do so use <code><text></code> or <code>@:</code>:</p>
<pre><code>@if(condition) {
@: This is going to be rendered
}
@if(condition) {
<text>
This is a
Multiline text block
</text>
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-02-20T00:08:31.373",
"Id": "42226",
"Score": "0",
"Tags": null,
"Title": null
}
|
42226
|
Razor is a template language used by ASP.NET Web Pages and ASP.NET MVC (since version 3). It supports seamless transitions between HTML markup and C# or VB code. Transitions between markup and code are indicated by the "@" sign.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:08:31.373",
"Id": "42227",
"Score": "0",
"Tags": null,
"Title": null
}
|
42227
|
Locking allows controlled access to specific resources. Exclusive access is the most common requirement, but other variations are possible.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:09:15.050",
"Id": "42229",
"Score": "0",
"Tags": null,
"Title": null
}
|
42229
|
<p>UTF-8 is a character encoding that can describe the set of <a href="/questions/tagged/unicode" class="post-tag" title="show questions tagged 'unicode'" rel="tag">unicode</a> code points in byte sequences of one to six bytes.</p>
<p>UTF-8 is the most widely used character encoding, and is recommended for use on the Internet. It is the standard character encoding on <a href="/questions/tagged/linux" class="post-tag" title="show questions tagged 'linux'" rel="tag">linux</a> and other recent <a href="/questions/tagged/unix" class="post-tag" title="show questions tagged 'unix'" rel="tag">unix</a>-like operating systems. It was designed to be backwards-compatible with <a href="/questions/tagged/ascii" class="post-tag" title="show questions tagged 'ascii'" rel="tag">ascii</a> while still supporting representation of all Unicode code points.</p>
<p>The algorithm for encoding code points in UTF-8 is described in <a href="http://tools.ietf.org/html/rfc3629#section-3" rel="nofollow">RFC 3629</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:09:57.270",
"Id": "42230",
"Score": "0",
"Tags": null,
"Title": null
}
|
42230
|
UTF-8 (Unicode Transformation Format, 8 bits) is a character encoding that describes each Unicode code point using a byte sequence of one to six bytes. It is backwards-compatible with ASCII while still supporting representation of all Unicode code points.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:09:57.270",
"Id": "42231",
"Score": "0",
"Tags": null,
"Title": null
}
|
42231
|
<p>My game uses configuration files in JSON format. One of them is used for setting up control bindings, and it looks like this:</p>
<pre><code>{
"DisplaySettings": {
"IsFullScreen": false,
"PreferredBackBufferWidth": 800,
"PreferredBackBufferHeight": 600
},
"GamePadSettings": {
"Back": "Exit",
"DPadDown": "MoveDown",
"DPadLeft": "MoveLeft",
"DPadRight": "MoveRight",
"DPadUp": "MoveUp"
},
"KeyboardSettings": {
"Escape": "Exit",
"S": "MoveDown",
"A": "MoveLeft",
"D": "MoveRight",
"W": "MoveUp"
}
}
</code></pre>
<p>In the Main method of the Program class (my composition root), I read the file and hand it off to the Input class:</p>
<pre><code>private static class Program
{
private static void Main()
{
IFileHandler fileHandler = new JsonHandler();
var settings = fileHandler.Read<Settings>( "settings.json" );
var level = fileHandler.Read<Level>( "level.json" );
var player = fileHandler.Read<Entity>( "player.json" );
using ( var game = new MyGame( new Graphics( settings.DisplaySettings, level, player),
new Input( settings.GamePadSettings, settings.KeyboardSettings ) ) )
{
game.Run();
fileHandler.Write( "player.json", player );
fileHandler.Write( "level.json", level );
}
}
}
</code></pre>
<p><code>fileHandler.Read<Settings></code> returns one of these (these are default values):</p>
<pre><code>public class Settings
{
public DisplaySettings DisplaySettings = new DisplaySettings();
public GamePadSettings GamePadSettings = new GamePadSettings();
public KeyboardSettings KeyboardSettings = new KeyboardSettings();
}
public class DisplaySettings
{
public bool IsFullScreen = false;
public int PreferredBackBufferWidth = 800;
public int PreferredBackBufferHeight = 600;
}
public class GamePadSettings
{
public string Back = "Exit";
public string DPadDown = "MoveDown";
public string DPadLeft = "MoveLeft";
public string DPadRight = "MoveRight";
public string DPadUp = "MoveUp";
}
public class KeyboardSettings
{
public string Escape = "Exit";
public string S = "MoveDown";
public string A = "MoveLeft";
public string D = "MoveRight";
public string W = "MoveUp";
}
</code></pre>
<p>Obviously this object is injected into the Input class, which is injected into MyGame:</p>
<pre><code>public class MyGame : Game
{
private readonly IGraphics graphics;
private readonly IInput input;
public MyGame( IGraphics graphics, IInput input )
{
if ( graphics == null || input == null )
{
throw new ArgumentNullException();
}
this.graphics = graphics;
this.input = input;
graphics.Setup( this );
input.Setup( this );
Content.RootDirectory = "Content";
}
public void MoveDown()
{
// TODO: Collision detection
graphics.Scroll( new Vector2( 0, 1 ) );
}
public void MoveLeft()
{
graphics.Scroll( new Vector2( -1, 0 ) );
}
public void MoveRight()
{
graphics.Scroll( new Vector2( 1, 0 ) );
}
public void MoveUp()
{
graphics.Scroll( new Vector2( 0, -1 ) );
}
// Other methods...
}
</code></pre>
<p>When MyGame is constructed, it calls the Setup method of the Input class, which creates a dictionary using reflection:</p>
<pre><code>public class Input : IInput
{
private readonly GamePadSettings gamePadSettings;
private readonly KeyboardSettings keyboardSettings;
private IDictionary<Buttons, Action> gamePadBindings;
private IDictionary<Keys, Action> keyboardBindings;
public Input( GamePadSettings gamePadSettings, KeyboardSettings keyboardSettings )
{
if ( gamePadSettings == null || keyboardSettings == null )
{
throw new ArgumentNullException();
}
this.gamePadSettings = gamePadSettings;
this.keyboardSettings = keyboardSettings;
}
public void Setup( Game game )
{
if ( game == null )
{
throw new ArgumentNullException();
}
SetupGamePad( game );
SetupKeyboard( game );
}
private void SetupGamePad( Game game )
{
gamePadBindings = new Dictionary<Buttons, Action>();
AddButtonBinding( game, Buttons.Back, gamePadSettings.Back );
AddButtonBinding( game, Buttons.DPadDown, gamePadSettings.DPadDown );
AddButtonBinding( game, Buttons.DPadLeft, gamePadSettings.DPadLeft );
AddButtonBinding( game, Buttons.DPadRight, gamePadSettings.DPadRight );
AddButtonBinding( game, Buttons.DPadUp, gamePadSettings.DPadUp );
}
private void SetupKeyboard( Game game )
{
keyboardBindings = new Dictionary<Keys, Action>();
AddKeyBinding( game, Keys.Escape, keyboardSettings.Escape );
AddKeyBinding( game, Keys.S, keyboardSettings.S );
AddKeyBinding( game, Keys.A, keyboardSettings.A );
AddKeyBinding( game, Keys.D, keyboardSettings.D );
AddKeyBinding( game, Keys.W, keyboardSettings.W );
}
private void AddButtonBinding( Game game, Buttons button, string methodName )
{
var method = FindMethod( game, methodName );
if ( method == null )
{
return;
}
gamePadBindings.Add( button, () => method.Invoke( game, null ) );
}
private void AddKeyBinding( Game game, Keys key, string methodName )
{
var method = FindMethod( game, methodName );
if ( method == null )
{
return;
}
keyboardBindings.Add( key, () => method.Invoke( game, null ) );
}
// Other methods...
private static MethodInfo FindMethod( object obj, string methodName )
{
return obj.GetType().GetMethod( methodName,
BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public );
}
}
</code></pre>
<p>If you know how reflection works in .Net, then you know it's looking for the methods by name in the MyGame class. The Exit method is actually defined in the Game base class, which I don't control.</p>
<p>What does everyone think of this? I am considering moving the MoveDown, MoveLeft, etc. methods into another class, like IPhysics or something, where I would also do the collision detection. Since I haven't gotten that far yet, these methods live in MyGame for now.</p>
<p>EDIT: Initially I tried to focus this question as much as possible on the Input class, but I would be grateful for any advice.</p>
|
[] |
[
{
"body": "<p>I'm not sure about binding directly to methods based on a configuration file like this, because it means you have to be very careful about what methods does your <code>Game</code> type expose (assuming the player has access to the configuration file, which it probably does).</p>\n\n<p>Consider adding a level of abstraction, either something like <code>PlayerActions</code> class, with methods that would just call the real methods, or maybe a <code>Dictionary<string, Action></code>.</p>\n\n<p>Also, I think player inputs should be handled by some kind of player object, not the game object directly. Otherwise, things like split-screen would be hard to implement.</p>\n\n<p>Some specific notes:</p>\n\n<ol>\n<li><p>Public fields are usually discouraged. But the syntax for properties with default values is quite verbose. And it would be nice to make the types immutable by using private setters and constructors, but that could cause issues with deserialization. So in the end, I think public fields are okay here.</p></li>\n<li><p>Think about using dictionaries for the two input settings. That would allow you to avoid repetition in calling <code>AddXxxBinding</code>. Though it would also make setting the defaults less nice, so I'm not sure this would be actually better.</p></li>\n<li><p>I think it would make sense to save <code>Game</code> into a field of <code>Input</code>. That way, you don't have to pass it as a parameter all the time.</p></li>\n<li><p>There are several changes I would make to the <code>AddButtonBinding()</code> and <code>AddKeyBinding()</code> methods:</p>\n\n<ol>\n<li><p>The methods are almost the same. I would combine them into one generic method.</p></li>\n<li><p>Should bad method name really cause no action? I would at least log it somewhere, if you don't want to crash completely.</p></li>\n<li><p>You can use <a href=\"http://msdn.microsoft.com/en-us/library/74x8f551%28v=vs.110%29.aspx\" rel=\"nofollow\"><code>Delegate.CreateDelegate()</code></a> instead of <code>MethodInfo.Invoke</code> and a lambda.</p></li>\n</ol>\n\n<p>With those changes, the method would look something like:</p>\n\n<pre><code>private void AddBinding<TInput>(\n Game game, Dictionary<TInput, Action> bindings, TInput input, string methodName)\n{\n var method = FindMethod(game, methodName);\n\n if (method == null)\n throw new InvalidOperationException();\n\n bindings.Add(input, (Action)Delegate.CreateDelegate(typeof(Action), game, method));\n}\n</code></pre></li>\n<li><p>Your <code>FindMethod()</code> searches for static methods too, but you're invoking the found method as an instance method. Because of that, I would remove <code>BindingFlags.Static</code>.</p>\n\n<p>Also, <code>FindMethod()</code> doesn't have much to do with input, it probably belongs to a separate class.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T16:09:48.970",
"Id": "72785",
"Score": "0",
"body": "Good advice. I will consider each point carefully. About no. 3: Input is a field in Game - wouldn't adding Game as a field in Input cause a circular reference and/or a memory leak? As for no. 5: FindMethod exists in Input only as a \"helper\" method. Because it's so small, I don't see a real benefit to moving it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T16:20:04.240",
"Id": "72788",
"Score": "0",
"body": "Yes, it would be a circular reference, but that doesn't cause memory leaks in .Net (or other environments with decent GC)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T17:03:24.260",
"Id": "72794",
"Score": "0",
"body": "I hate to get off-topic too much, but actually it would not be a circular reference. If Game had a Game property, or Input had an Input property, that would be circular. (I spent the last 37 minutes wracking my brain over this.) Anyways, you're right that it would make more sense to save Game into a field of Input."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T17:19:59.603",
"Id": "72800",
"Score": "0",
"body": "Circular reference means there is a cycle of references, and that cycle can be of any size, including 1 (`Game` → `Game`) and 2 (`Game` → `Input` → `Game`). [Such cycles are problem for simple reference counting GCs](https://en.wikipedia.org/wiki/Reference_counting#Dealing_with_reference_cycles)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T14:17:37.010",
"Id": "42306",
"ParentId": "42232",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:10:17.650",
"Id": "42232",
"Score": "5",
"Tags": [
"c#",
"game",
"json",
"reflection",
"dependency-injection"
],
"Title": "Setting up keyboard bindings using JSON and reflection"
}
|
42232
|
<p><a href="http://struts.apache.org/2.x/" rel="nofollow">Apache Struts 2</a> is an extensible framework based on model–view–controller (MVC) architecture for creating enterprise-ready Java web applications. The framework is designed to streamline the full development cycle, from building, to deploying, to maintaining applications over time.</p>
<p>Apache Struts 2 was originally known as WebWork 2. After working independently for several years, the WebWork and Struts communities joined forces to create Struts2. This new version of Struts is simpler to use and closer to how Struts was always meant to be.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:12:32.173",
"Id": "42235",
"Score": "0",
"Tags": null,
"Title": null
}
|
42235
|
Apache Struts 2 is an extensible framework based on model–view–controller (MVC) architecture for creating enterprise-ready Java web applications.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:12:32.173",
"Id": "42236",
"Score": "0",
"Tags": null,
"Title": null
}
|
42236
|
A subroutine (e.g. procedure or subprogram) is a portion of code within a larger program, which performs a specific task and can be relatively independent of the remaining code. The syntax of many programming languages includes support for creating self contained subroutines, and for calling and returning from them. They are in many ways similar to functions, but usually have side-effects outside of the simple "return value" that functions return.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:12:53.707",
"Id": "42238",
"Score": "0",
"Tags": null,
"Title": null
}
|
42238
|
<p>The ISO definition of usability:</p>
<blockquote>
<p>The <em>effectiveness, efficiency and
satisfaction</em> with which specified
users achieve specified goals in
particular environments. </p>
<p><strong>Effectiveness</strong>: the accuracy and
completeness with which specified
users can achieve specified goals in
particular environments.<br>
<strong>Efficiency</strong>: the resources expended in relation to
the accuracy and completeness of goals
achieved.
<strong>Satisfaction</strong>: the comfort
and acceptability of the work system
to its users and other people affected
by its use. </p>
</blockquote>
<p><a href="http://en.wikipedia.org/wiki/Usability" rel="nofollow">Wikipedia</a>:</p>
<blockquote>
<p>Usability is the ease of use and
learnability of a human-made object.
The object of use can be a software
application, website, book, tool,
machine, process, or anything a human
interacts with. [...]</p>
</blockquote>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:13:40.320",
"Id": "42239",
"Score": "0",
"Tags": null,
"Title": null
}
|
42239
|
The effectiveness, efficiency and satisfaction with which users achieve specified goals in particular environments. This covers ease of use and learnability of software applications and websites.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:13:40.320",
"Id": "42240",
"Score": "0",
"Tags": null,
"Title": null
}
|
42240
|
<p>I'm making a Backbone-Marionette app with a file structure that matches restful verbs as much as possible. It looks something like this:</p>
<blockquote>
<pre><code>+ backbone
+ apps
+ student
+ show
+ list
+ new
+ lesson
+ show
+ new
+ edit
</code></pre>
</blockquote>
<p>If, for example, the <code>student show</code> controller wanted to display a lesson, I simply execute a command that sends which lesson I want and the region in which it should be inserted like so:</p>
<pre><code>App.execute( "show:lesson", lesson, someRegion );
</code></pre>
<p>This has mostly worked well, but now I need to create an email preview that contains a lesson. This representation of <code>lesson show</code> shouldn't look exactly like the existing <code>lessons show</code> - for example, it doesn't need edit and delete links.</p>
<p>What I'm doing now is adding a config object to my command above that looks like this...</p>
<pre><code>App.execute( "show:lesson", lesson, someRegion, { template: "email" } );
</code></pre>
<p>... then I unpack that object in my Marionette controller and set it on the model. Now that it's piggy backed on the model, I use it to conditionally get the correct template in my view like so:</p>
<pre><code>Show.Lesson = Backbone.Marionette.ItemView.extend({
getTemplate: function() {
if( this.model.get( "config" ).template === "email" ) {
return "lessons/show/lesson_email";
} else {
return "lessons/show/lesson";
}
}
});
</code></pre>
<p>This feels a little weird to me, plus it doesn't quite work when getting templates for Marionette.CompositeViews. Should I be making completely new Marionette views for these email preview versions of my resource representations? Would it make more sense for my file structure to look like this?</p>
<blockquote>
<pre><code>+ backbone
+ apps
+ lesson
+ show
+ show_email
+ new
+ edit
</code></pre>
</blockquote>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T01:55:54.723",
"Id": "42246",
"Score": "3",
"Tags": [
"javascript",
"backbone.js"
],
"Title": "Different templates for various resource representations in Marionette"
}
|
42246
|
<p>Please take a look at this code:</p>
<pre><code>class error_stream: boost::noncopyable
{
public:
template<typename T>
std::ostream& operator<<(T&& arg)
{
return strm() << std::forward<T>(arg);
}
std::string str() { return strm().str(); }
bool empty() const { return !holder_.valid(); }
private:
std::ostringstream& strm() { return holder_; }
struct alignas(std::ostringstream) holder
{
holder(): ptr_{} {}
~holder()
{
if(valid())
ptr_->~basic_ostringstream();
}
operator std::ostringstream&()
{
if(!valid())
ptr_ = new (memory_) std::ostringstream{};
return *ptr_;
}
bool valid() const { return ptr_; }
private:
char memory_[sizeof(std::ostringstream)];
std::ostringstream* ptr_;
} holder_;
};
</code></pre>
<p>Here I want to avoid creating <code>std::ostringstream</code> if there was no output made into it:</p>
<pre><code>error_stream strm;
//strm << "...";
if(!strm.empty())
{
//...get strm.str();
}
</code></pre>
<p>I use placement new/delete when a client outputs something into the stream. Do I need to use alingas for block of memory that will hold instance of <code>std::ostringstream</code>?</p>
<p>UPDATE: To give more context - this is part of THROW wrapper:</p>
<pre><code>...
#define THROW_EX_WITH_LOCATION(EXCEPTION, LOCATION) \
for(error_stream strm;; \
strm.empty()? \
throw_exception<EXCEPTION>(LOCATION): \
throw_exception<EXCEPTION>(LOCATION, strm.str())) \
strm
...
</code></pre>
<p>I don't want to create any stream if ther is no error message but solution should work with minumum overhead over version with just std::ostringstream.</p>
<p>Consider the following cases:</p>
<pre><code>THROW();
</code></pre>
<p>and</p>
<pre><code>THROW() << "some error";
</code></pre>
<p>I agree this looks like nitpicking.</p>
|
[] |
[
{
"body": "<p>This seems overcomplicated to me. Lazy-loading something doesn't require placement-new trickery and mucking around with alignments. Why not simply store a pointer to the stream which is only initialised when the user performs some kind of operation? This is the general way to do lazy-loading:</p>\n\n<pre><code>struct error_stream\n{\nprivate:\n std::unique_ptr<std::ostringstream> stream;\n\n // This should use make_unique, which you can find \n // or write yourself without too much hassle.\n void construct()\n {\n stream = std::unique_ptr<std::ostringstream>(\n new std::ostringstream);\n }\n\npublic:\n\n template <typename T>\n std::ostream& operator<<(T&& arg)\n {\n if(!stream) {\n construct();\n }\n (*stream) << std::forward<T>(arg);\n return *stream;\n }\n\n bool empty() const\n {\n return stream ? false : true;\n }\n\n std::string str() \n {\n if(empty()) {\n construct();\n }\n return stream->str();\n }\n};\n</code></pre>\n\n<p>This seems to have the semantics you want (including being non-copyable due to using a <code>std::unique_ptr</code>) with much less hassle. You don't have to worry about placement new or any alignment requirements, which is going to make the code a -lot- harder to maintain.</p>\n\n<p>Edit: If you really what to avoid the heap, I suppose you can use placement new. You allocate the memory for the stream when you create an <code>error_stream</code>, so I'm curious as to what problem you're trying to solve exactly. That being said, what you want to align is the storage for the <code>ostringstream</code>.</p>\n\n<pre><code>char memory_[sizeof(std::stringstream)];\n</code></pre>\n\n<p>Hence I'd use:</p>\n\n<pre><code>struct holder\n{\n....\nprivate:\n alignas(std::ostringstream) char memory_[sizeof(std::stringstream)];\n ...\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T05:21:46.657",
"Id": "72700",
"Score": "0",
"body": "Yes your solution is cleaner. I'm trying to avoid going to free store if possible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T05:36:03.097",
"Id": "72701",
"Score": "0",
"body": "@AlexT See my edit."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T05:05:59.820",
"Id": "42261",
"ParentId": "42248",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "42261",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T02:17:45.283",
"Id": "42248",
"Score": "10",
"Tags": [
"c++",
"c++11",
"stream",
"wrapper"
],
"Title": "Correct usage of alignas in std::ostringstream wrapper"
}
|
42248
|
<p>How can I optimize the following PHP/JS code?</p>
<p>It works like a charm but I think it is too long and I'm sure it could be optimized. If I have another form, I'll need to copy paste some lines from my PHP code and it'll be quickly overkill.</p>
<hr>
<p>JavaScript:</p>
<pre><code><script>
$(document).ready(function() {
$('#createAccount').on('submit', function() {
var Email = $('#Email').val();
var Password = $('#Password').val();
var PasswordRepeat = $('#PasswordRepeat').val();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
dataType: 'json',
success: function(json) {
$('.alert-message').text(json.reponse).show();
}
});
return false;
});
});
</script>
</code></pre>
<p>PHP:</p>
<pre><code><?php
$reponse="";
if(isset($_POST['Email']) && isset($_POST['Password']) && isset($_POST['PasswordRepeat'])) {
// Si tous les champs ne sont pas renseignés
if($_POST['Email'] == '' || $_POST['Password'] == '' || $_POST['PasswordRepeat'] == '') {
$reponse = "Tous les champs doivent être remplis.";
}
// Si les mots de passe ne sont pas similaires
if($_POST['Password'] != $_POST['PasswordRepeat']) {
$reponse = "Les mots de passe ne sont pas similaires.";
}
// Si ce n'est pas une adresse de courriel
if(!preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['Email'])) {
$reponse = "L'adresse de courriel ne semble pas conforme.";
}
// Si le mot de passe est trop court
if(strlen($_POST['Password']) <= 5) {
$reponse = "Le mot de passe être top court.";
}
// Si tout est ok
if(($_POST['Password'] == $_POST['PasswordRepeat']) && ($_POST['Email'] != '' && $_POST['Password'] != '' && $_POST['PasswordRepeat'] != '') && (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['Email'])) && (strlen($_POST['Password']) >= 6)) {
$reponse = "Nice";
}
}
else {
$reponse = "Une erreur s'est produite.";
}
$array['reponse'] = $reponse;
echo json_encode($array);
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T07:10:51.580",
"Id": "74026",
"Score": "0",
"body": "Consider using PHP's [filter_var()](http://www.php.net/manual/en/filter.examples.validation.php) to check the emails."
}
] |
[
{
"body": "<h3>At least for the PHP part:</h3>\n<p>You should make it into a function where you return status instead of going over every possibility even if you have a <em>fail</em>.</p>\n<pre><code>function validate_post() {\n if ( ... )\n return "no";\n if ( ... )\n return "yes";\n}\n\n$array['reponse'] = validate_post();\n</code></pre>\n<p>By this you would eliminate the last <code>// Si tout est ok</code> part as well, as by the response would be OK.</p>\n<hr />\n<p>If you truly want to eliminate possible steps, you could also negate the <code>isset()</code> checks and use OR instead of AND, as it then will stop on first false.</p>\n<pre><code>if (!isset($_POST['Email']) || !isset($_POST['Password']) ... )\n return "Une erreur s'est produite.";\n</code></pre>\n<p>The length check for password require less resources and as such could be moved above the email check. (Which would be the most expensive.)</p>\n<hr />\n<h3>For the Javascript part</h3>\n<p>it becomes a question on what and if you need to optimize.</p>\n<p>It is likely a process rarely taken. Manual action by user (hopefully) not in a loop ;). When it get submitted you are to have a rather big form for it to have a noticeable effect.</p>\n<p>That said jQuery gives you a overhead, but you might/likely do not want to use pure Javascript.</p>\n<hr />\n<p><em>Edit:</em></p>\n<p>Had another look at this, and also had to check if I was missing something regards to your variables in the Javascript. But, unless you have some omitted code within the <em>"submit"</em> function – you have some unused variables:</p>\n<pre><code>var Email = $('#Email').val();\nvar Password = $('#Password').val();\nvar PasswordRepeat = $('#PasswordRepeat').val();\n</code></pre>\n<p>As you use:</p>\n<pre><code>data : $(this).serialize(),\n</code></pre>\n<p>Which in effect serializes all form fields with a name attribute, and not something like:</p>\n<pre><code>data : $.param({\n Email : Email,\n Password : Email,\n PasswordRepeat : PasswordRepeat\n }),\n</code></pre>\n<p>By which you could also use:</p>\n<pre><code>data : $.param({\n Email : $('#Email').val(),\n Password : $('#Password').val(),\n PasswordRepeat : $('#PasswordRepeat').val()\n}),\n</code></pre>\n<p>It depends on use. If for some reason your form has lot of fields that you do not want to post the latter would be to prefer, though that would also bind it much tighter together and make it a possible spot for bugs in future changes to the code.</p>\n<hr />\n<p>As a side-note you also should most likely have this:</p>\n<pre><code>$('#form').on('submit', function(event) {\n event.preventDefault(); // Prevent form submit.\n ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T03:02:43.190",
"Id": "42251",
"ParentId": "42250",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T02:44:01.697",
"Id": "42250",
"Score": "6",
"Tags": [
"javascript",
"php",
"jquery",
"json",
"form"
],
"Title": "Account-Creation form"
}
|
42250
|
<p>With iOS7, Apple introduced <code>AVCaptureMetadataOutputObjects</code>, which is used for scanning barcodes. If you check out the web for how to scan barcodes in iOS, almost everyone is talking about ZBarSDK. And before iOS7, this was definitely the way to go. But as of iOS7, ZBarSDK has a pretty nasty memory leak, and it's a big library to include when you consider barcode scanning functionality is already built into iOS7. Moreover, I consider Apple's approach to be a slightly easier than ZBarSDK was anyway.</p>
<p>But I decided to make it even easier. I'm working on a wrapper class that will turn several lines of code into just a few lines.</p>
<h1>NHGBarcodeScanner.h</h1>
<pre><code>#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
typedef NS_OPTIONS(unsigned short, BarcodeType) {
CODE_UPCE = 1 << 0,
CODE_CODE39 = 1 << 1,
CODE_CODE39MOD43 = 1 << 2,
CODE_EAN13 = 1 << 3,
CODE_EAN8 = 1 << 4,
CODE_CODE93 = 1 << 5,
CODE_CODE128 = 1 << 6,
CODE_PDF417 = 1 << 7,
CODE_QRCODE = 1 << 8,
CODE_AZTEC = 1 << 9
};
@protocol NHGBarcodeScannerDelegate <NSObject>
@required - (void)barcodeScannerDidScan:(NSString*)result;
@optional - (void)barcodeInitDidFailWithError:(NSError*)error;
@end
@interface NHGBarcodeScanner : UIView
@property (nonatomic,assign) id<NHGBarcodeScannerDelegate> delegate;
- (id)init __attribute__((unavailable()));
- (id)initWithFrame:(CGRect)frame __attribute__((unavailable()));
- (id)initWithFrame:(CGRect)frame barcodeTypes:(BarcodeType)barcodeTypes
delegate:(id<NHGBarcodeScannerDelegate>)delegate;
+ (instancetype)nhgBarcodeScannerWithFrame:(CGRect)frame
barcodeTypes:(BarcodeType)barcodeTypes
delegate:(id<NHGBarcodeScannerDelegate>)delegate;
- (void)startScanning;
@end
</code></pre>
<h1>NHGBarcodeScanner.m</h1>
<pre><code>#import "NHGBarcodeScanner.h"
@interface NHGBarcodeScanner() <AVCaptureMetadataOutputObjectsDelegate>
@end
@implementation NHGBarcodeScanner {
AVCaptureSession *_captureSession;
NSArray *_barcodeTypes;
}
+ (instancetype)nhgBarcodeScannerWithFrame:(CGRect)frame
barcodeTypes:(BarcodeType)barcodeTypes
delegate:(id<NHGBarcodeScannerDelegate>)delegate {
return [[self alloc] initWithFrame:frame barcodeTypes:barcodeTypes delegate:delegate];
}
- (id)initWithFrame:(CGRect)frame
barcodeTypes:(BarcodeType)barcodeTypes
delegate:(id<NHGBarcodeScannerDelegate>)delegate {
self = [super initWithFrame:frame];
if (self) {
_delegate = delegate;
_captureSession = [[AVCaptureSession alloc] init];
AVCaptureDevice *videoCaptureDevice = [AVCaptureDevice
defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error = nil;
AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput
deviceInputWithDevice:videoCaptureDevice error:&error];
if(videoInput) {
[_captureSession addInput:videoInput];
} else {
#if DEBUG
NSLog(@"barcodeInitDidFailWithError: %@", error);
#endif
if ([_delegate respondsToSelector:@selector(barcodeInitDidFailWithError:)]) {
[_delegate barcodeInitDidFailWithError:error];
}
return nil;
}
AVCaptureMetadataOutput *metadataOutput = [[AVCaptureMetadataOutput alloc] init];
[_captureSession addOutput:metadataOutput];
[metadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
_barcodeTypes = [self metadataObjectTypesForOptions:barcodeTypes];
[metadataOutput setMetadataObjectTypes:_barcodeTypes];
[metadataOutput setRectOfInterest:frame];
AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer
alloc] initWithSession:_captureSession];
previewLayer.frame = self.frame;
[self.layer addSublayer:previewLayer];
}
return self;
}
- (NSArray*)metadataObjectTypesForOptions:(BarcodeType)barcodeTypes {
NSMutableArray *metadataObjectTypes = [NSMutableArray array];
if (barcodeTypes & CODE_UPCE) {
[metadataObjectTypes addObject:AVMetadataObjectTypeUPCECode];
}
if (barcodeTypes & CODE_CODE39) {
[metadataObjectTypes addObject:AVMetadataObjectTypeCode39Code];
}
if (barcodeTypes & CODE_CODE39MOD43) {
[metadataObjectTypes addObject:AVMetadataObjectTypeCode39Mod43Code];
}
if (barcodeTypes & CODE_EAN13) {
[metadataObjectTypes addObject:AVMetadataObjectTypeEAN13Code];
}
if (barcodeTypes & CODE_EAN8) {
[metadataObjectTypes addObject:AVMetadataObjectTypeEAN8Code];
}
if (barcodeTypes & CODE_CODE93) {
[metadataObjectTypes addObject:AVMetadataObjectTypeCode93Code];
}
if (barcodeTypes & CODE_CODE128) {
[metadataObjectTypes addObject:AVMetadataObjectTypeCode128Code];
}
if (barcodeTypes & CODE_PDF417) {
[metadataObjectTypes addObject:AVMetadataObjectTypePDF417Code];
}
if (barcodeTypes & CODE_QRCODE) {
[metadataObjectTypes addObject:AVMetadataObjectTypeQRCode];
}
if (barcodeTypes & CODE_AZTEC) {
[metadataObjectTypes addObject:AVMetadataObjectTypeAztecCode];
}
return [NSArray arrayWithArray:metadataObjectTypes];
}
- (void)startScanning {
[_captureSession startRunning];
}
- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputMetadataObjects:(NSArray *)metadataObjects
fromConnection:(AVCaptureConnection *)connection {
[_captureSession stopRunning];
for (AVMetadataObject *metadataObject in metadataObjects) {
AVMetadataMachineReadableCodeObject *readableObject =
(AVMetadataMachineReadableCodeObject *)metadataObject;
for (NSString *barcodeType in _barcodeTypes) {
if ([barcodeType isEqualToString:metadataObject.type]) {
[self.delegate barcodeScannerDidScan:readableObject.stringValue];
return;
}
}
}
}
- (void)removeFromSuperview {
[_captureSession stopRunning];
[super removeFromSuperview];
}
@end
</code></pre>
<hr>
<p>Example usage:</p>
<pre><code>NHGBarcodeScanner *scanner = [NHGBarcodeScanner nhgBarcodeScannerWithFrame:
someFrame barcodeTypes:(CODE_UPCE | CODE_EAN13 | CODE_CODE128) delegate:self];
[someParentView addSubview:scanner];
[scanner startScanning];
</code></pre>
<p>This will add a scanner to <code>someParentView</code> that will scan for UPCE, EAN13, and CODE128 barcodes.</p>
<p>My primary concern with the existing code is the <code>metadataObjectTypesForOptions:</code> method. I don't know if there's a better way to handle this bit mask.</p>
<p>I'm also curious if anyone feels like this class is missing anything.</p>
|
[] |
[
{
"body": "<p>One possible improvement for the sake of convenience could be to add some meta groups to the enum.</p>\n\n<p>For example:</p>\n\n<pre><code>typedef NS_OPTIONS(unsigned short, BarcodeType) {\n CODE_UPCE = 1 << 0,\n CODE_CODE39 = 1 << 1,\n CODE_CODE39MOD43 = 1 << 2,\n CODE_EAN13 = 1 << 3,\n CODE_EAN8 = 1 << 4,\n CODE_CODE93 = 1 << 5,\n CODE_CODE128 = 1 << 6,\n CODE_PDF417 = 1 << 7,\n CODE_QRCODE = 1 << 8,\n CODE_AZTEC = 1 << 9\n}\n\ntypedef NS_OPTIONS(unsigned short, BarcodeGroup) {\n CODEGROUP_1DBarcodes = 1 << 0\n + 1 << 1\n + 1 << 2\n + 1 << 3\n + 1 << 4\n + 1 << 5\n + 1 << 6\n\n CODEGROUP_2DBarcodes = 1 << 7\n + 1 << 8\n + 1 << 9\n\n CODEGROUP_ALLBarcodes = 1 << 0\n + 1 << 1\n + 1 << 2\n + 1 << 3\n + 1 << 4\n + 1 << 5\n + 1 << 6\n + 1 << 7\n + 1 << 8\n + 1 << 9\n};\n</code></pre>\n\n<p>Now instead of combining large groups with the <code>|</code>, a user could instead simply call one of these code groups if they needed all, or just 1d codes or just 2d codes.</p>\n\n<hr>\n\n<p>What's also potentially missing is a way to grab multiple codes in a batch. <code>AVCaptureMetadataOutput</code> will capture as many barcodes as you put in front of it all at once. It puts all these symbols into an array, and then your <code>forin</code> loops in the delegate method grab a single one of these codes.</p>\n\n<p>There are two potential ways of sending the multiple codes.</p>\n\n<ol>\n<li>The delegate method (<code>barcodeScannerDidScan:</code>) could take an <code>NSArray</code> argument, rather than a single <code>NSString</code>. Internally, <code>captureOutput:didOutputMetadataObjects:fromConnection:</code> would then just need a single <code>forin</code> loop to check that the symbol matches the requested symbols, and use this loop to build an array. After the array is built, send it to the delegate.</li>\n<li>The <code>return;</code> can be removed from the nested <code>forin</code> loops. The result is the delegate method will be called once for each barcode that was scanned.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T03:44:11.440",
"Id": "42253",
"ParentId": "42252",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T03:23:28.193",
"Id": "42252",
"Score": "5",
"Tags": [
"objective-c",
"ios"
],
"Title": "AVCaptureMetadataOutputObjects Wrapper"
}
|
42252
|
<p>This project has <a href="https://github.com/patrickmarabeas/ng-FitText.js/blob/49038a2d0857194edfd83ad6fd62f62185f43a26/angularjs-fittext.js" rel="nofollow">evolved a lot</a> since I started learning Angular. I'm pretty happy with it now, and I'm wondering if there's anything I can improve upon, or have forgotten at this point...</p>
<p><strong>HTML</strong></p>
<pre><code><h1 data-fittext>FitText</h1>
<h1 data-fittext=".315" data-fittext-min="12" data-fittext-max="50">ng-FitText</h1>
</code></pre>
<p><strong>Inclusion & Customization</strong></p>
<pre><code>var myApp = angular.module( 'myApp', [ 'ngFitText' ] );
myApp.config( function( fitTextConfigProvider ) {
fitTextConfigProvider.config = {
debounce: true, //default is false
delay: 1000 //default is 250
};
// OR
fitTextConfigProvider.config.debounce = true;
fitTextConfigProvider.config.delay = 1000;
});
</code></pre>
<p><strong>The Module</strong></p>
<pre><code>'use strict';
angular.module( 'ngFitText', [] )
.value( 'config', {
'debounce': false,
'delay': 250
})
.directive( 'fittext', [ 'config', 'fitTextConfig', function( config, fitTextConfig ) {
return {
restrict: 'A',
scope: true,
transclude: true,
replace: true,
template: function( element, attrs ) {
var tag = element[0].nodeName;
return "<"+tag+" data-ng-transclude data-ng-style='{fontSize:fontSize}'></"+tag+">";
},
link: function( scope, element, attrs ) {
angular.extend(config, fitTextConfig.config);
scope.compressor = attrs.fittext || 1;
scope.minFontSize = attrs.fittextMin || Number.NEGATIVE_INFINITY;
scope.maxFontSize = attrs.fittextMax || Number.POSITIVE_INFINITY;
scope.elementWidth = element[0].offsetWidth;
( scope.resizer = function() {
scope.elementWidth = element[0].offsetWidth;
scope.fontSize = Math.max(
Math.min(
scope.elementWidth / ( scope.compressor * 10 ),
parseFloat( scope.maxFontSize )
),
parseFloat( scope.minFontSize )
) + 'px';
if( !scope.$$phase ) scope.$digest();
})();
config.debounce == true
? angular.element( window ).bind( 'resize', debounce( scope.resizer, config.delay ))
: angular.element( window ).bind( 'resize', scope.resizer);
function debounce(a,b,c){var d;return function(){var e=this,f=arguments;clearTimeout(d),d=setTimeout(function(){d=null,c||a.apply(e,f)},b),c&&!d&&a.apply(e,f)}}
}
}
}])
.provider( 'fitTextConfig', function() {
var self = this;
this.config = {};
this.$get = function() {
var extend = {};
extend.config = self.config;
return extend;
};
return this;
});
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>As personal opinion, I wouldn't use <code>config</code> as name for <code>.value</code>, it sounds too generic and can be confused with <code>.config</code> method of the <code>module</code> API.</p></li>\n<li><p>Putting comments like <code>//default is false</code> looks confusing - why are these not default? Also it is easy to change the defaults and forget to adjust comments. Uncle Bob recommends to minimize comments and use expressive code with descriptive names instead.</p></li>\n<li><p><code>function debounce(a,b,c)</code> is great for minimizers but cryptic for code readers</p></li>\n<li><p>In my view, using <code>.provider</code> is possibly an overkill as there is not much configuration logic here. </p></li>\n<li><p>The last two comments <a href=\"https://codereview.stackexchange.com/a/47882/29119\">here</a> also apply. Instead the config JSON can be kept inside <code>.value</code> and decoupled from the provider. </p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T17:00:30.320",
"Id": "84003",
"Score": "0",
"body": "Thanks for your points. The debounce function is taken from Underscore and stated as such in the module comments. Overkill doesn't concern me, but is there another way to *extend* configuration? As far as I'm concerned it's not a configurable module if config settings are blown away upon updating the module..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T07:56:30.387",
"Id": "85088",
"Score": "0",
"body": "Could you explain how `$$phase`, in this context, is an anti-pattern? It seems pretty legitimate to me as `$apply` is already called on load, but is required when the window resizes to apply the updated font size. I've modified the code to remove this anti-pattern, but you essentially end up with something fairly messy in comparison: https://github.com/patrickmarabeas/ng-FitText.js/blob/master/ng-FitText.js#L55 I can understand in a lot of cases its usage means you are probably doing something wrong - but it seems like a more succinct readable solution here?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T14:04:12.100",
"Id": "85113",
"Score": "0",
"body": "I understand that `$$phase` is Angular's internal method, and as such is not intended for regular use. Please see here for more specific details: http://stackoverflow.com/questions/22346990/why-is-using-ifscope-phase-scope-apply-an-anti-pattern."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T14:06:26.580",
"Id": "85114",
"Score": "0",
"body": "Concerning `debounce`, you could take it instead from the non-minimized version with comments, then another reader would better see what it does."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-29T08:40:53.563",
"Id": "136498",
"Score": "0",
"body": "See also http://www.bennadel.com/blog/2605-scope-evalasync-vs-timeout-in-angularjs.htm about `$$phase`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:57:36.533",
"Id": "47895",
"ParentId": "42254",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T03:48:17.143",
"Id": "42254",
"Score": "0",
"Tags": [
"javascript",
"html",
"angular.js"
],
"Title": "Angular version of FitText"
}
|
42254
|
<h2><a href="http://www.tornadoweb.org/" rel="nofollow">Tornado</a></h2>
<p>A web server and a web framework for <a href="http://www.python.org/" rel="nofollow">Python</a>. Originally built to power <a href="http://friendfeed.com/" rel="nofollow">FriendFeed</a> (owned by Facebook), it is now an open source project and used by sites like Quora and Hipmunk. Tornado uses non-blocking IO and asynchronous programming patterns to attain greater scalability and speed. While <a href="http://www.tornadoweb.org/en/stable/" rel="nofollow">documentation</a> is somewhat light, there is an active <a href="http://groups.google.com/group/python-tornado" rel="nofollow">mailing list</a> and a supportive community. The framework is also designed to be fairly simple, along the lines of web.py or bottle, without some of the more complex setup of web frameworks like Django.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T03:48:38.710",
"Id": "42255",
"Score": "0",
"Tags": null,
"Title": null
}
|
42255
|
Tornado is a scalable web server and web framework for Python specializing in handling thousands of simultaneous connections and real-time services.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T03:48:38.710",
"Id": "42256",
"Score": "0",
"Tags": null,
"Title": null
}
|
42256
|
<p>I have code which gets data from a <code>POST</code> request (<code>request.form</code> dict), compares with corresponding attribute in object <code>accident</code> and does some action. The code looks needlessly verbose. How can I optimize it?</p>
<pre><code>if accident.status == 1:
if request.form.get('reason') \
and request.form['reason'] != accident.reason:
accident.set_reason(request.form['reason'], current_user)
if request.form.get('note') \
and request.form['note'] != accident.note:
accident.note = request.form['note']
else:
if request.form.get('priority') \
and int(request.form['priority']) != accident.priority:
accident.set_priority(current_user, int(request.form['priority']))
if request.form.get('status') \
and int(request.form['status']) != accident.status:
accident.set_status(current_user, int(request.form['status']))
if request.form.get('duration') \
and int(request.form['duration']) != accident.duration:
accident.duration = int(request.form['duration'])
if request.form.get('service_status') \
and int(request.form['service_status']) != accident.service_status:
accident.set_service_status(int(request.form['service_status']))
</code></pre>
<p>Below is a stripped down version of <code>Accident</code> class, which is inconsistent because there are many fields, and sometimes setting a field requires many additional actions like logging or checking for user rights. The class derives from <a href="http://docs.mongoengine.org/en/latest/apireference.html">MongoEngine</a> schema class.</p>
<pre><code>class Accident(Document):
priority = IntField(choices=PRIORITIES)
status = IntField(choices=STATUSES, default=0)
duration = IntField()
region = StringField()
service_status = IntField(choices=(0, 1, 2))
reason = StringField(default=u"")
note = StringField(default=u"")
def set_priority(self, user=None, priority=None):
self.priority = priority
# Functions starting with `set_` do some activity that has
# nothing to do with setting and validating a value. That's
# why i don't use @property decorator. `to_history(user)` is
# just an example.
to_history(user)
def set_status(self, user, status):
self.status = status
to_history(user)
def set_reason(self, reason, user):
self.reason = reason
to_history(user)
def set_service_status(self, ss):
self.service_status = ss
to_history(user)
</code></pre>
<p>If this is necessary, how can i improve class structure? It seems like I can't use <code>@property</code> decorator for setters, because my setters accept additional parameters. However I don't like the idea of writing a setter for all possible attributes. I use <code>request.form.get(foo)</code> instead of <code>foo in request.form</code>, because the dictionary may contain <code>foo: None</code> pair, and I don't want to accidentally set an attribute to <code>None</code>.</p>
|
[] |
[
{
"body": "<p>I'm not 100% sure there is a particularly elegant way to write this. If the code did not have a different body for each <code>if</code> statement, one could rewrite it like this</p>\n\n<pre><code>FORM_VALUES = {\n \"priority\": accident.priority,\n \"status\": accident.status,\n \"duration\": accident.duration,\n \"service_status\": accident.service_status\n}\n\nfor key in FORM_VALUES:\n if request.form.get(key) and int(request.form[key]) != FORM_VALUES[key]:\n # As you use different functions for setting the values, this isn't possible\n request.set_value(key, request.form[key])\n</code></pre>\n\n<p>However, that is not the case, so don't get your hopes up. Regardless, there are still improvements to be made:</p>\n\n<ul>\n<li>You're not checking that the header values are valid integers. I'd recommend either checking they are by using <code>string.isdigit()</code> or otherwise wrapping your calls to <code>int()</code> in a try except block.</li>\n<li>You can use <code>'reason' in request.form</code> instead of <code>request.form.get('reason')</code>; they have the same meaning in the places you've used them, but the first is easier to read.</li>\n<li>It might be good if you used an enumeration for the values to <code>Accident.status</code>. As it is, checking that <code>accident.status == 1</code> doesn't tell me anything; using a meaningful identifier might solve this. You can do this quite simply, by just assigning values to each identifier: <code>PENDING, IN_PROGRESS, FINISHED = STATUSES</code>. I've used some random names, and assumed that there are 3 possible statuses, change this to be accurate. Then in your function, instead of <code>if accident.status == 1</code>, we can have <code>if accident.status == PENDING</code>, which is a lot easier to understand without needing to know the meaning of each value of status.</li>\n<li>In general, you should try and be consistent with the ordering of your arguments: your <code>set_reason</code> takes first a <code>reason</code>, then a <code>user</code> argument, while all of your other methods take the <code>user</code> argument first. The <code>set_service_status</code> doesn't take a <code>user</code> argument at all, which is fairly impressive, considering it uses a user variable in the function.</li>\n</ul>\n\n<p>Overall not bad code. I don't agree with your comments on how <code>@property</code> would be inappropriate there, but it's far from the end of the world. In general, I'd try and be more careful to validate user input, but it may be that you do not need to worry about that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T08:19:51.820",
"Id": "42273",
"ParentId": "42259",
"Score": "8"
}
},
{
"body": "<p>Don't forget that <code>dict.get()</code> can also take a default:</p>\n\n<pre><code>if request.form.get('reason', accident.reason) != accident.reason:\n accident.set_reason(request.form['reason'], current_user)\n</code></pre>\n\n<p>...that makes it a little shorter.</p>\n\n<p><strong>EDIT:</strong> or even</p>\n\n<pre><code>def needs_update(name):\n return request.form.get(name, getattr(accident, name)) != getattr(accident, name)\n\nif needs_update('reason'):\n ...\n</code></pre>\n\n<p>Barring @BluePepper's elegant solution, you could probably build a change list and then iterate through the fields that need updating.</p>\n\n<p>This is very cheesy, but you could break the value check and the update in two parts. I did this fast, sorry, but I hope the general idea is clear:</p>\n\n<pre><code>form = {'a': 1, 'b': 2, 'c': 3}\noriginal = {'a': 1, 'b': 20, 'c': 30, 'd': 4}\n\n# build the list of new values as a list of tuples\nupdate = [(k, form.get(k)) for k in form.keys() if form.get(k) != original.get(k, None)]\n\nprint update\n\n# make the updates, making special calls as necessary\nfor k, v in update:\n if k == 'c':\n print \"DO SOMETHING SPECIAL\"\n original['c'] = v\n else:\n original[k] = v\n\nprint original\n</code></pre>\n\n<p>Produces</p>\n\n<pre><code>[('c', 3), ('b', 2)]\nDO SOMETHING SPECIAL\n{'a': 1, 'c': 3, 'b': 2, 'd': 4}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T08:59:58.827",
"Id": "42274",
"ParentId": "42259",
"Score": "7"
}
},
{
"body": "<p>I'd like to see this as my goal:<sup>1</sup></p>\n\n<pre><code>if accident.status == 1:\n transfer_from_form(request.form, accident, [\n ('reason', str),\n ('note', str),\n ])\nelse:\n transfer_from_form(request.form, accident, [\n ('priority', int),\n ('status', int),\n ('duration', int),\n ('service_status', int),\n ])\n</code></pre>\n\n<p>Let's see what it takes to get there! I imagine that <code>transfer_from_form()</code> could look like this:</p>\n\n<pre><code>def transfer_from_form(form, obj, fields):\n for field, conv in fields:\n if form.get(field) and form[field] != getattr(obj, field):\n setattr(obj, field, conv(form[field]))\n</code></pre>\n\n<p>Notionally, that would perform the equivalent of assignments like <code>accident.service_status = int(request.form['service_status'])</code> whenever the form field is set and the attribute on <code>accident</code> doesn't already contain that value.</p>\n\n<p>Then there is the pesky issue of how to pass the <code>user</code> parameter. I would argue that the <code>user</code> should be stored in the session somewhere, and the <code>Accident</code>'s setter method could pluck it out of the session instead of having it passed in explicitly. You didn't specify which web framework you are using, so I can't tell you exactly how to accomplish that.</p>\n\n<p>The <code>Accident</code> class's setters appear to be wrappers around the MongoEngine fields' setters, with some audit logging inserted. Instead of defining methods like <code>set_service_status()</code>, you could hook in the audit logging by <a href=\"https://mail.python.org/pipermail/python-dev/2008-January/076194.html\" rel=\"nofollow\">monkey patching</a> the MongoEngine fields' setters. Not only would the code read more smoothly, you wouldn't be relying on the goodwill of the users of the <code>Accident</code> class to refrain from setting <code>accident.service_status</code> directly instead of going through the approved <code>set_service_status()</code> method.</p>\n\n<hr>\n\n<p><sup>1</sup> There is some redundancy here. Ideally, I shouldn't have to declare that <code>'reason'</code> is a <code>str</code> and <code>'service_status'</code> is an <code>int</code>, because the types should be deducible from the fact that they are a <code>StringField</code> and <code>IntField</code>, respectively. If you can figure out how to accomplish that deduction, that would be even better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T15:47:12.947",
"Id": "72774",
"Score": "0",
"body": "I'm also thinking (broadly) about \"closure\" to handle that pesky user parameter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T15:09:17.343",
"Id": "73408",
"Score": "1",
"body": "Shouldn't `obj.getattr(field)` be `getattr(obj, field)` (similarly `obj.setattr(...)` vs `setattr(obj, ...)`)? Anyway, totally agreed on refactoring that part out, although I would prefer multiple calls over passing a list of parameters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T16:59:48.453",
"Id": "73416",
"Score": "0",
"body": "@MichaelUrman Thanks for spotting the error. Corrected in Rev 2."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T09:41:55.873",
"Id": "42279",
"ParentId": "42259",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T04:31:00.167",
"Id": "42259",
"Score": "11",
"Tags": [
"python",
"form",
"hash-map",
"mongodb"
],
"Title": "Conditionally set attributes in MongoDB based on form fields"
}
|
42259
|
<p>So, I am not sure if I should have <code>Vertex</code> <em>extend</em> <code>Point</code>, because the <code>equals()</code> and <code>compareTo()</code> functions are already parameterized with <code>Point</code>. I guess I don't really need compare to...</p>
<p>Does this structure look good? I used a <code>Map</code> instead of a <code>TreeMap</code> because as3commons and the default flex packages do not have this structure defined. How easy will this be if I were to create it.</p>
<p>Things that I am in the process of working out now:</p>
<ul>
<li>I know I need to add <code>removeVertex()</code> (and <code>removeEdge()</code>?)</li>
<li><p>If I want to create an <code>Edge</code> class, I supposed I would make the following changes:</p>
<pre><code>// Since this is undirected, do I need 2 edges, because I have src and dest?
public class Edge {
public var src:Vertex;
public var dest:Vertex;
public var data:Object;
public function Edge(src:Vertex, dest:Vertex, data:Object=null) {
// Set instance variables
}
}
public class Graph {
public var edges:IMap; // <Object, Edge>
public function addEdge(from:Object, to:Object, data:Object):void {
edges.add(data, new Edge(v, w));
}
}
</code></pre></li>
</ul>
<p>My main gripe would be about juggling all of these data types.</p>
<ul>
<li><code>public var adjList:IMap; // <Vertex, Set></code></li>
<li><code>public var vertices:IMap; // <Object, Vertex></code></li>
<li><code>public var edges:IMap; // <Object, Edge></code></li>
</ul>
<p>This may make if difficult to intelligently traverse the graph.</p>
<hr>
<h2>Reference classes and files:</h2>
<p><strong>Vertex.as</strong></p>
<pre><code>package core {
import flash.geom.Point;
public class Vertex extends Point {
public var data:Object;
public function Vertex(data:Object=null, x:Number=0, y:Number=0) {
super(x, y);
this.data = data;
}
// Implement...
override public function clone():Point {
return new Vertex(data, x, y);
}
override public function toString():String {
return data.toString();
}
// Implement...
override public function equals(toCompare:Point):Boolean {
return super.equals(toCompare) && this.compareTo(toCompare as Vertex) == 0;
}
// Implement...
public function compareTo(other:Vertex):int {
return 0;
}
}
}
</code></pre>
<p><strong>Graph.as</strong></p>
<pre><code>package core {
import org.as3commons.collections.Map;
import org.as3commons.collections.Set;
import org.as3commons.collections.framework.IMap;
import org.as3commons.collections.framework.ISet;
public class Graph {
public var adjList:IMap; // <Vertex, Set>
public var vertices:IMap; // <Object, Vertex>
private static const EMPTY_SET:ISet = new Set();
private var _numVertices:int;
private var _numEdges:int;
public function Graph() {
adjList = new Map();
vertices = new Map();
_numVertices = _numEdges = 0;
}
public function addVertex(data:Object):Vertex {
var v:Vertex = vertices.itemFor(data);
if (v == null) {
v = new Vertex(data);
vertices.add(data, v);
adjList.add(v, new Set());
_numVertices++;
}
return v;
}
public function getVertex(data:Object):Vertex {
return vertices.itemFor(data);
}
public function hasVertex(data:Object):Boolean {
return vertices.hasKey(data);
}
public function hasEdge(from:Object, to:Object):Boolean {
if (!hasVertex(from) || !hasVertex(to))
return false;
return (adjList.itemFor(vertices.itemFor(from)) as Set).has(vertices.itemFor(to));
}
public function addEdge(from:Object, to:Object):void {
var v:Vertex, w:Vertex;
if (hasEdge(from, to))
return;
_numEdges += 1;
if ((v = getVertex(from)) == null)
v = addVertex(from);
if ((w = getVertex(to)) == null)
w = addVertex(to);
(adjList.itemFor(v) as Set).add(w);
(adjList.itemFor(w) as Set).add(v);
}
public function adjacentTo(value:*):ISet {
if (value is Object && hasVertex(value as Object)) {
return adjList.itemFor(getVertex(value as Object)) as Set;
}
if (value is Vertex && adjList.has(value as Vertex)) {
return adjList.itemFor(value as Vertex) as Set;
}
return EMPTY_SET;
}
public function getVertices():ISet {
var set:ISet = new Set();
for each (var v:Vertex in vertices.toArray()) {
set.add(v);
}
return set;
}
public function numVertices():int {
return _numVertices;
}
public function numEdges():int {
return _numEdges;
}
public function toString():String {
var s:String = "";
for each (var v:Vertex in vertices.toArray()) {
s += v + ": ";
var set:ISet = adjList.itemFor(v) as Set;
for each (var w:Vertex in set.toArray()) {
s += (w + " ");
}
s += "\n";
}
return s;
}
}
}
</code></pre>
<p><strong>App.mxml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
creationComplete="onComplete(event)">
<fx:Script>
<![CDATA[
import core.Graph;
import core.Vertex;
import mx.events.FlexEvent;
protected function onComplete(event:FlexEvent):void {
main();
}
public static function main(args:Vector.<String>=null):void {
var G:Graph = new Graph();
G.addEdge("A", "B");
G.addEdge("A", "C");
G.addEdge("C", "D");
G.addEdge("D", "E");
G.addEdge("D", "G");
G.addEdge("E", "G");
G.addVertex("H");
// print out graph
trace(G);
trace('Verticies:', G.numVertices());
trace('Edges :', G.numEdges());
trace();
// print out graph again by iterating over vertices and edges
for each (var v:Vertex in G.getVertices().toArray()) {
var str:String = v + ": ";
for each (var w:Vertex in G.adjacentTo(v.data).toArray()) {
str += w + " ";
}
trace(str);
}
}
]]>
</fx:Script>
</s:Application>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T11:35:32.633",
"Id": "72729",
"Score": "0",
"body": "After doing some research, I found that the best answer for this question: [SO: How do I properly extend the AS3 Point class?](http://stackoverflow.com/a/9015761/1762224) states that the point class should be a delegate of the class that, in theory, **extends** it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-02T15:18:36.033",
"Id": "137361",
"Score": "0",
"body": "Typically graphs are represented by adjacency table. This would save you some place, and would be less surprising for the reader. This also makes `Edge` class unnecessary. You would be only storing vertices. But this may depend on your use case. For graphs with labeled edges it might make sense to actually create such a class, or maybe to extend the adjacency table to have triples rather than tuples."
}
] |
[
{
"body": "<p><code>adjList</code> needs a more descriptive name. Specifically as a class member variable, it deserves the few extra characters it would take to be called <code>adjacencyList</code>.</p>\n\n<p>Additionally, you have extended <code>Point</code>, but do not use any of <code>Point</code>'s functions. Does Point even provide functions? (Yes, it does.)</p>\n\n<p>I'd have gone with a <code>Vertex</code> class that contains a <code>Point</code>, not <code>extends</code> it. You pointed this out yourself in a comment as well.</p>\n\n<hr>\n\n<pre><code> public function adjacentTo(value:*):ISet {\n if (value is Object && hasVertex(value as Object)) {\n return adjList.itemFor(getVertex(value as Object)) as Set;\n }\n\n if (value is Vertex && adjList.has(value as Vertex)) {\n return adjList.itemFor(value as Vertex) as Set;\n }\n\n return EMPTY_SET;\n }\n</code></pre>\n\n<p>This is a nasty bit of code. I wanted to say that you should swap the two checks, as any <code>Vertex</code> is also an <code>Object</code>, and you end up always checking if any of your vertices has <code>value</code> as <code>data</code>. But if you were to have a <code>Vertex</code> which has another <code>Vertex</code> as <code>data</code> then swapping the two would make the function fail to perform properly. A comment along these lines would go a long way towards not shooting yourself in the foot later.</p>\n\n<pre><code> public function addVertex(data:Object):Vertex {\n var v:Vertex = vertices.itemFor(data);\n //codes\n }\n\n public function getVertex(data:Object):Vertex {\n return vertices.itemFor(data);\n }\n</code></pre>\n\n<p>Reuse your functions where you can; like that you allow code to be read at a semantic level, rather than a syntactical level. Logical reasoning likes to work with semantics and not bother so much with the syntax. In this case, you can reuse <code>getVertex</code>:</p>\n\n<pre><code> public function addVertex(data:Object):Vertex {\n var v:Vertex = getVertex(data);\n //codes\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-27T10:51:37.600",
"Id": "142629",
"Score": "0",
"body": "`adjList` == Adjacency List"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-27T11:17:58.463",
"Id": "142637",
"Score": "0",
"body": "@Mr.Polywhirl rephrased the sentence and expanded a bit"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-27T09:27:59.287",
"Id": "78733",
"ParentId": "42262",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T05:15:15.933",
"Id": "42262",
"Score": "3",
"Tags": [
"graph",
"actionscript-3",
"actionscript"
],
"Title": "Actionscript Graph data structure implementation"
}
|
42262
|
<pre><code>char *cat_string(char *to_cat, char *destination) {
char *copy = destination;
while (*copy != '\0') {
*copy++;
}
while (*to_cat != '\0') {
*copy++ = *to_cat++;
}
*copy = '\0';
return destination;
}
</code></pre>
<p>I would like to know if this is an efficient and effective way of writing this function. It seems silly to have to iterate through the whole array just to find the <code>\0</code> character.</p>
<p>Also, should I be returning the pointer to the destination? What's the best practice there? </p>
|
[] |
[
{
"body": "<p>You renamed <code>strcat()</code> to <code>cat_string()</code>, so I suppose it's fitting that you reversed the traditional order of the parameters as well. ☺</p>\n\n<p>I would make three changes:</p>\n\n<ul>\n<li>Changing the first argument to <code>const</code> helps prevent users notice if they call the function with the parameters swapped (but doesn't prevent it in all cases).</li>\n<li>You have a stray pointer dereference. It was misleading, but luckily harmless. (In the first <code>while</code> loop, you just want to advance the <code>copy</code> pointer. You don't care about what value it points to as you advance; you only care when you check for the <kbd>NUL</kbd> terminator.)</li>\n<li><del>You can remove a statement just by changing the loop structure.</del><br>\n<strong>Edit (Rev 3):</strong> Previous recommendation was buggy, and has been retracted. Credit to @MarcvanLeeuwen.</li>\n</ul>\n\n<p>To answer your questions…</p>\n\n<ul>\n<li>The only way to find out where to start appending is to walk the entire <code>destination</code> string to locate where it ends. That's just how C-style strings work.</li>\n<li>Yes, returning <code>destination</code> seems appropriate. It's analogous to what <code>strcat()</code> does.</li>\n</ul>\n\n<p>One final note: two spaces for indentation is too stingy, in my opinion. It's insufficient for readability, and it also encourages inappropriately deep nesting (which would be a symptom of poorly organized code).</p>\n\n<pre><code>char *cat_string(const char *to_cat, char *destination) {\n char *copy = destination;\n while (*copy != '\\0') {\n copy++; /* Removed superfluous dereference. */\n }\n …\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T12:44:29.183",
"Id": "72741",
"Score": "0",
"body": "This \"improvement\" breaks the correct original. Changing `while` to `do`-`while` only changes the start of the loop, not the end: with post-increment in the assignment, the (second while) condition still tests a character yet to be copied, and most of the time the terminating null character of `to_cat` is not copied to `destination`, which then remains unterminated. A null character only gets copied in case `to_cat` originally pointed to a null character (zero length concatenation), but then the loop continues until (if lucky) finding a second null character."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T19:21:38.970",
"Id": "72826",
"Score": "0",
"body": "the real strcpy is `while(*copy++=*to_cat++);` which will end after the final \\0"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T21:27:30.267",
"Id": "72839",
"Score": "0",
"body": "@MarcvanLeeuwen Are you sure?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T07:25:40.563",
"Id": "72933",
"Score": "1",
"body": "@200_success Of course I am sure. In your final do-while loop, you copy a character from `*do_cat++`, then because of the post-increment the `*to_cat` tested in the \"while\" condition is the next character, not yet copied; if it is found to be null it will not have been copied. Compare this to the solution cited by rachet freak, which copies a character and then tests the *same* character for being null. It could somewhat more explicitly be written `while((*copy++=*to_cat**)!='\\0') {}`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T09:15:04.560",
"Id": "72942",
"Score": "0",
"body": "@MarcvanLeeuwen I stand corrected! Thank you for pointing out the error."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T06:05:11.123",
"Id": "42266",
"ParentId": "42264",
"Score": "5"
}
},
{
"body": "<p>1 major issue: undefined behavior when the target doesn't have enough space to hold it all and no way to prevent it with the parameters you ask for</p>\n\n<pre><code>char *cat_string(char *to_cat, char *destination, size_t dest_size) {\n char *copy = destination;\n copy[dest_size-1]=0;//ensure 0 termination\n while (*copy != '\\0') {\n copy++;\n }\n char* end_buffer = destination+dest_size-1;\n while (*to_cat != '\\0' && to_cat!=end_buffer) {\n *copy++ = *to_cat++;\n }\n *copy = '\\0';\n return destination;\n}\n</code></pre>\n\n<p>this changes the semantics a bit but ensures that the buffer doesn't overflow</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T21:29:14.277",
"Id": "72842",
"Score": "2",
"body": "In other words, you recommend implementing `strncat()` instead of `strcat()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T12:46:16.360",
"Id": "72962",
"Score": "1",
"body": "@200_success `strncat` isn't a safe strcat: strncat appends the first n bytes of source, but does nothing to avoid overflowing destination. You may be thinking of [strcat_s](http://msdn.microsoft.com/en-us/library/d45bbxx4.aspx) or similar."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T16:50:59.977",
"Id": "73013",
"Score": "0",
"body": "@ChrisW You're right! I hadn't even heard of `strcat_s()` — it seems to be a Windows-only thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T17:01:59.447",
"Id": "73015",
"Score": "0",
"body": "@200_success The equivalent on Unix seems to be [strlcat](http://www.manpagez.com/man/3/strlcpy/). And maybe there's a version of [strcat_s defined in C11](http://blog.smartbear.com/codereviewer/c11-a-new-c-standard-aiming-at-safer-programming/)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T10:26:25.183",
"Id": "42281",
"ParentId": "42264",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "42266",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T05:30:09.337",
"Id": "42264",
"Score": "5",
"Tags": [
"c",
"beginner",
"strings"
],
"Title": "Writing strcat (string concatenate) in C"
}
|
42264
|
<p>As a follow-up on <a href="https://codereview.stackexchange.com/questions/38619/in-memory-cache-implementation">my earlier question</a>, here is the new implementation. The major change is now that the base class just deals in <code>ICacheValue</code> values which are implemented by the derived classes and generated through implementation of a factory method.</p>
<p>Unfortunately requires some casting in the derived classes but I don't think there is a way around it in C#.</p>
<p>Looking for general review, best practices, design improvements, hidden bugs etc.</p>
<p><strong>Cache base class</strong></p>
<p>It's now abstract and requires the implementation of the <code>CreateCacheValue</code> factory method. It only deals with the basic read/write access of items. All public methods are protected by a lock which call internal unlocked methods which are all virtual so they can get overwritten by the derived cache implementations.</p>
<pre><code>public abstract class Cache<TKey, TValue>
{
protected interface ICacheValue
{
TValue Value { get; set; }
}
protected readonly Dictionary<TKey, ICacheValue> _ValueCache = new Dictionary<TKey, ICacheValue>();
protected object SyncRoot = new object();
protected abstract ICacheValue CreateCacheValue(TValue value);
protected abstract void UpdateElementAccess(TKey key, ICacheValue cacheValue);
protected abstract void CacheValueInvalidated(ICacheValue cacheValue);
public virtual int Count
{
get { return _ValueCache.Count; }
}
public bool TryGetValue(TKey key, out TValue value)
{
ICacheValue v;
value = default(TValue);
lock (SyncRoot)
{
v = GetCacheValueUnlocked(key);
if (v != null)
{
value = v.Value;
UpdateElementAccess(key, v);
return true;
}
}
return false;
}
protected virtual ICacheValue GetCacheValueUnlocked(TKey key)
{
ICacheValue v;
return _ValueCache.TryGetValue(key, out v) ? v : null;
}
public void SetValue(TKey key, TValue value)
{
lock (SyncRoot)
{
SetValueUnlocked(key, value);
}
}
protected virtual ICacheValue SetValueUnlocked(TKey key, TValue value)
{
ICacheValue cacheValue = GetCacheValueUnlocked(key);
if (cacheValue == null)
{
cacheValue = CreateCacheValue(value);
_ValueCache[key] = cacheValue;
}
else
{
cacheValue.Value = value;
}
UpdateElementAccess(key, cacheValue);
return cacheValue;
}
public void Invalidate(TKey key)
{
lock (SyncRoot)
{
InvalidateUnlocked(key);
}
}
protected virtual void InvalidateUnlocked(TKey key)
{
var value = GetCacheValueUnlocked(key);
if (value != null)
{
_ValueCache.Remove(key);
CacheValueInvalidated(value);
}
}
public virtual void Flush()
{
lock (SyncRoot)
{
FlushUnlocked();
}
}
protected virtual void FlushUnlocked()
{
_ValueCache.Clear();
}
public List<TKey> GetKeys()
{
lock (SyncRoot)
{
return new List<TKey>(_ValueCache.Keys);
}
}
}
</code></pre>
<p><strong>Size limited cache</strong></p>
<p>Implements an LRU strategy. Items are invalidated on each cache access (read and write) if required.</p>
<pre><code>public class SizeLimitedCache<TKey, TValue> : Cache<TKey, TValue>
{
protected sealed class CacheValue : ICacheValue
{
public CacheValue(TValue value)
{
Value = value;
}
public LinkedListNode<KeyValuePair<TKey, CacheValue>> IndexRef { get; set; }
public TValue Value { get; set; }
}
private readonly LinkedList<KeyValuePair<TKey, CacheValue>> _IndexList = new LinkedList<KeyValuePair<TKey, CacheValue>>();
public int MaxSize { get; set; }
public SizeLimitedCache(int maxSize)
{
MaxSize = maxSize;
}
protected override void UpdateElementAccess(TKey key, ICacheValue cacheValue)
{
var value = (CacheValue)cacheValue;
// put element at front of the index list
// remove first if already present in list, create new otherwise
var idxRef = value.IndexRef;
if (idxRef != null)
{
_IndexList.Remove(idxRef);
}
else
{
idxRef = new LinkedListNode<KeyValuePair<TKey, CacheValue>>(new KeyValuePair<TKey, CacheValue>(key, value));
value.IndexRef = idxRef;
}
_IndexList.AddFirst(idxRef);
// remove all entries from end of list until max size is satisfied
while (_IndexList.Count > MaxSize)
{
InvalidateUnlocked(_IndexList.Last.Value.Key);
}
}
protected sealed override ICacheValue CreateCacheValue(TValue value)
{
return new CacheValue(value);
}
protected override void CacheValueInvalidated(ICacheValue cacheValue)
{
_IndexList.Remove(((CacheValue)cacheValue).IndexRef);
}
protected override void FlushUnlocked()
{
base.FlushUnlocked();
_IndexList.Clear();
}
}
</code></pre>
<p><strong>Time limited cache</strong></p>
<p>Regularly expires items from the cache. I'm not totally happy with this implementation because technically it makes all operations <code>O(n)</code> due to the expiry timer locking the cache when expiring items. Should probably be based on a similar idea as the size limited cache by checking from the end of the list for expired items (just time based rather than size based).</p>
<pre><code>public class TimeLimitedCache<TKey, TValue> : Cache<TKey, TValue>, IDisposable
{
protected sealed class CacheValue : ICacheValue
{
public CacheValue(TValue value)
{
Value = value;
LastAccess = DateTime.Now;
}
public TValue Value { get; set; }
public DateTime LastAccess { get; set; }
}
private DateTime _LastCacheAccess = DateTime.MinValue;
public TimeSpan MaxEntryAge { get; set; }
private TimeSpan _ExpiryInterval;
public TimeSpan ExpiryInterval
{
get { return _ExpiryInterval; }
set
{
_ExpiryInterval = value;
DisposeTimer();
_ExpiryTimer = new Timer(o => Expire(), null, value, value);
}
}
private const int DefaultExpiryIntervalSec = 600;
private System.Threading.Timer _ExpiryTimer;
private int _ExpiryIsRunning = 0;
public TimeLimitedCache(TimeSpan maxEntryAge)
: this(maxEntryAge, TimeSpan.FromSeconds(DefaultExpiryIntervalSec))
{
}
public TimeLimitedCache(TimeSpan maxEntryAge, TimeSpan expiryInterval)
{
MaxEntryAge = maxEntryAge;
ExpiryInterval = expiryInterval;
}
private void Expire()
{
if (Interlocked.CompareExchange(ref _ExpiryIsRunning, 1, 0) == 1)
{
// expiry is still running
return;
}
// paranoia
try
{
lock (SyncRoot)
{
var maxAge = MaxEntryAge;
var toExpire = _ValueCache.Where(x => ((CacheValue)x.Value).LastAccess + maxAge < _LastCacheAccess).Select(x => x.Key).ToList();
toExpire.ForEach(InvalidateUnlocked);
}
}
finally
{
_ExpiryIsRunning = 0;
}
}
protected override void UpdateElementAccess(TKey key, ICacheValue cacheValue)
{
_LastCacheAccess = DateTime.Now;
((CacheValue)cacheValue).LastAccess = DateTime.Now;
}
protected sealed override ICacheValue CreateCacheValue(TValue value)
{
return new CacheValue(value);
}
protected override void CacheValueInvalidated(ICacheValue cacheValue)
{
}
private void DisposeTimer()
{
if (_ExpiryTimer != null)
{
_ExpiryTimer.Change(TimeSpan.FromMilliseconds(-1), TimeSpan.Zero);
_ExpiryTimer.Dispose();
_ExpiryTimer = null;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
DisposeTimer();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>Unfortunately requires some casting in the derived classes but I don't think there is a way around it in C#.</p>\n</blockquote>\n\n<p>There is a way around that.</p>\n\n<p>Define a 3rd template parameter to specify the type of cache value; use a <code>where</code> constraint on the 3rd parameter; and change the interface from protected to public (so that you can use it in the definition of the public Cache class):</p>\n\n<pre><code>public abstract class Cache<TKey, TValue, TCacheValue>\n where TCacheValue : class, Cache<TKey, TValue, TCacheValue>.ICacheValue\n{\n public interface ICacheValue\n {\n TValue Value { get; set; }\n }\n</code></pre>\n\n<p>Use the specific TCacheValue type instead of ICacheValue throughout the implementation of the Cache class:</p>\n\n<pre><code> protected readonly Dictionary<TKey, TCacheValue> _ValueCache = new Dictionary<TKey, TCacheValue>();\n protected object SyncRoot = new object();\n\n protected abstract TCacheValue CreateCacheValue(TValue value);\n protected abstract void UpdateElementAccess(TKey key, TCacheValue cacheValue);\n protected abstract void CacheValueInvalidated(TCacheValue cacheValue);\n\n public virtual int Count\n {\n get { return _ValueCache.Count; }\n }\n\n public bool TryGetValue(TKey key, out TValue value)\n {\n TCacheValue v;\n value = default(TValue);\n\n lock (SyncRoot)\n {\n v = GetCacheValueUnlocked(key);\n if (v != null)\n {\n value = v.Value;\n UpdateElementAccess(key, v);\n return true;\n }\n }\n\n return false;\n }\n\n protected virtual TCacheValue GetCacheValueUnlocked(TKey key)\n {\n TCacheValue v;\n return _ValueCache.TryGetValue(key, out v) ? v : null;\n }\n\n public void SetValue(TKey key, TValue value)\n {\n lock (SyncRoot)\n {\n SetValueUnlocked(key, value);\n }\n }\n\n protected virtual TCacheValue SetValueUnlocked(TKey key, TValue value)\n {\n TCacheValue cacheValue = GetCacheValueUnlocked(key);\n if (cacheValue == null)\n {\n cacheValue = CreateCacheValue(value);\n _ValueCache[key] = cacheValue;\n }\n else\n {\n cacheValue.Value = value;\n }\n UpdateElementAccess(key, cacheValue);\n return cacheValue;\n }\n\n public void Invalidate(TKey key)\n {\n lock (SyncRoot)\n {\n InvalidateUnlocked(key);\n }\n }\n\n protected virtual void InvalidateUnlocked(TKey key)\n {\n var value = GetCacheValueUnlocked(key);\n if (value != null)\n {\n _ValueCache.Remove(key);\n CacheValueInvalidated(value);\n }\n }\n\n public virtual void Flush()\n {\n lock (SyncRoot)\n {\n FlushUnlocked();\n }\n }\n\n protected virtual void FlushUnlocked()\n {\n _ValueCache.Clear();\n }\n\n public List<TKey> GetKeys()\n {\n lock (SyncRoot)\n {\n return new List<TKey>(_ValueCache.Keys);\n }\n }\n}\n</code></pre>\n\n<p>Now you can specify a subclass as follows, without using down-casts in the implementation, specifying Cache in the methods' signatures instead of ICache:</p>\n\n<pre><code>public class SizeLimitedCache<TKey, TValue> : Cache<TKey, TValue, SizeLimitedCache<TKey, TValue>.CacheValue>\n{\n public sealed class CacheValue : ICacheValue\n {\n public CacheValue(TValue value)\n {\n Value = value;\n }\n\n public LinkedListNode<KeyValuePair<TKey, CacheValue>> IndexRef { get; set; }\n public TValue Value { get; set; }\n }\n\n private readonly LinkedList<KeyValuePair<TKey, CacheValue>> _IndexList = new LinkedList<KeyValuePair<TKey, CacheValue>>();\n\n public int MaxSize { get; set; }\n\n public SizeLimitedCache(int maxSize)\n {\n MaxSize = maxSize;\n }\n\n protected override void UpdateElementAccess(TKey key, CacheValue cacheValue)\n {\n var value = cacheValue;\n // put element at front of the index list\n // remove first if already present in list, create new otherwise\n var idxRef = value.IndexRef;\n if (idxRef != null)\n {\n _IndexList.Remove(idxRef);\n }\n else\n {\n idxRef = new LinkedListNode<KeyValuePair<TKey, CacheValue>>(new KeyValuePair<TKey, CacheValue>(key, value));\n value.IndexRef = idxRef;\n }\n _IndexList.AddFirst(idxRef);\n\n // remove all entries from end of list until max size is satisfied\n while (_IndexList.Count > MaxSize)\n {\n InvalidateUnlocked(_IndexList.Last.Value.Key);\n }\n }\n\n protected sealed override CacheValue CreateCacheValue(TValue value)\n {\n return new CacheValue(value);\n }\n\n protected override void CacheValueInvalidated(CacheValue cacheValue)\n {\n _IndexList.Remove(cacheValue.IndexRef);\n }\n\n protected override void FlushUnlocked()\n {\n base.FlushUnlocked();\n _IndexList.Clear();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T07:10:20.097",
"Id": "72932",
"Score": "0",
"body": "Hmm, yes I was focused on keeping as much internal as possible. I guess making some implementation detail public might be an acceptable trade-off"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T08:06:15.740",
"Id": "42272",
"ParentId": "42269",
"Score": "5"
}
},
{
"body": "<p>I'm missing <a href=\"http://msdn.microsoft.com/en-us/library/b2s063f7.aspx\" rel=\"nofollow\">XML Documentation on these classes</a>.</p>\n\n<hr>\n\n<pre><code>public abstract class Cache<TKey, TValue>\n</code></pre>\n\n<p>You <em>could</em> short the type parameters with <code>K</code> for key and <code>T</code> for type. That's at least the \"default\" usage in Java, I'm not sure if that rule can be applied to C# (especially now that I see that this style is used in the framework itself, but something nice to keep in mind), too.</p>\n\n<hr>\n\n<p>You're inconsistent with your naming, sometimes you call <code>TValue</code> <code>v</code> or<code>value</code>, on the other hand you also call <code>ICacheValue</code> <code>v</code>, <code>value</code> or <code>valueCache</code>. You should always use <code>value</code> for <code>TValue</code> and <code>valueCache</code> for <code>IValueCache</code>.</p>\n\n<hr>\n\n<pre><code>protected abstract ICacheValue CreateCacheValue(TValue value);\nprotected abstract void UpdateElementAccess(TKey key, ICacheValue cacheValue);\nprotected abstract void CacheValueInvalidated(ICacheValue cacheValue);\n</code></pre>\n\n<p>Due to the missing documentation, these names seem sub-optimal. For exampling, does <code>CreateCacheValue</code> also put the value into the cache? If yes, it should maybe be called <code>Put</code> or <code>Store</code>. What does <code>UpdateElementAccess</code>? Does it update some sort of access control within the cache for the given value? Should it only be called <code>Update</code>? <code>CacheValueInvalidated</code> should most likely be called <code>InvalidateCacheValue</code> or <code>Invalidate</code> or <code>Remove</code>.</p>\n\n<p>Note that all this confusion could be cleared by documentation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T07:09:11.670",
"Id": "72931",
"Score": "1",
"body": "`CacheValueInvalidated` is the correct name, but `UpdateElementAccess` should probably be `ElementAccessed`. These are are called when that action happens so the derived class can perform additional housekeeping. I guess some documentation can't hurt :P"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T11:46:25.093",
"Id": "42291",
"ParentId": "42269",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "42272",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T07:16:30.533",
"Id": "42269",
"Score": "4",
"Tags": [
"c#",
"multithreading",
"cache"
],
"Title": "In-memory cache implementation revisited"
}
|
42269
|
<p>How can I reduce cyclomatic complexity of validation and refactor it better way?</p>
<pre><code>Class Document
def initialize(opts)
@opts = opts
return ArgumentError unless valid?
end
def valid?
return false if @opts.nil?
return false if @opts[:property_1].nil?
return false if @opts[:property_2].nil?
return false if !@opts[:property_4].nil? && @opts[:property_3].nil?
# etc. 12 times more, otherwise valid will return true
true
end
def usage_example
if @opts[:property_3]
"#{@opts[:property_3]} #{@opts[:property_1]}"
else
"#{@opts[:property_4]} #{@opts[:property_2]}"
end
end
end
</code></pre>
<p>I am trying to avoid duplication of <code>return false if</code> and somehow perhaps list parameters that I want to verify</p>
<p>Possible interpretation of what I trying to reach is <strong>"verify set of rules before processing file"</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T09:50:11.330",
"Id": "72719",
"Score": "2",
"body": "Welcome to Code Review. We can usually give better advice for you if you provide real code from an actual project that you are working on, without stripping out the context. As it stands, you have provided barely enough code to constitute a question for Code Review. I encourage you to edit this question to add more detail about what you are trying to accomplish."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T10:27:28.433",
"Id": "72723",
"Score": "1",
"body": "I have edited question and make it more context free"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T23:37:09.297",
"Id": "73468",
"Score": "0",
"body": "@uzzer will you please extend the example? For instance, what type of class is this method contained in? I ask this because in my experience the problem caused by \"duplication of return false if\" is a symptom of a holistic design issue. And also the complexity of the solution depends on the scope of the project."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T08:40:21.890",
"Id": "73640",
"Score": "0",
"body": "I have extended the example little bit. You are probably right about design issue and I would be glad to fix it. Idea behind design is to pass freeform @opts and verify that their body meets business rules before processing, perhaps I have to avoid it and verify presence of data only when data is needed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T20:21:38.247",
"Id": "74109",
"Score": "0",
"body": "If you are satisfied with any of the answers, you should select the one that you find most helpful."
}
] |
[
{
"body": "<p>You could write that as</p>\n\n<pre><code>def valid?\n @opts && !@opts[:property].nil? ? true : false\nend\n</code></pre>\n\n<p>but usually it would be good enough to return a truthy or falsy value instead of a Boolean:</p>\n\n<pre><code>def valid?\n @opts && !@opts[:property].nil?\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T10:23:46.430",
"Id": "72722",
"Score": "0",
"body": "I mentioned `...` meaning there is about 12 different parameters and code becomes overloaded with `return false if opts[:one_of_properties].nil?`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T09:47:51.477",
"Id": "42280",
"ParentId": "42275",
"Score": "2"
}
},
{
"body": "<p>If your tests are about mandatory members in <code>@opts</code> you can do this:</p>\n\n<pre><code>MandatoryProperties = [:property_1, :property_2, ...]\n\ndef valid?\n @opts && MandatoryProperties.all? { |k| !@opts[k].nil? }\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T12:30:43.687",
"Id": "72739",
"Score": "0",
"body": "It is definitely right direction. Currently I will try to extend this to support `nil` and `!a && b` case using array of conditions or something like this"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T11:27:02.593",
"Id": "42289",
"ParentId": "42275",
"Score": "3"
}
},
{
"body": "<p>There are a few things you can do here to improve this code, but with any sort of refactoring or any attempt of reducing complexity, we have to evaluate why. It may very well be the case that this method isn't at fault for its own complexity, but is this complex due to a failure elsewhere in the system of keeping their data correct.</p>\n\n<p>That aside, there are still a few things you could do to clean up this code a little</p>\n\n<p><strong>Explicitly define all the required parameters and use that to iterate over.</strong></p>\n\n<pre><code>REQUIRED_PROPERTIES = %i(prop_1 prop_2 prop_3 prop_4)\nREQUIRED_PROPERTIES.any? { |x| @opts[x].nil? } #=> true if any are nil or false if all are not nil\n</code></pre>\n\n<p><strong>Use <code>hash#fetch</code> instead of <code>[]</code> so you can supply a default value for possible missing keys</strong></p>\n\n<pre><code>return false if @opts[:property_1].nil?\nreturn @opts.fetch(:property_1, false) #only return false if :property_1 is not defined\n#fetch only returns false if :property_1 doesn't exist, not if it has been set to nil\n</code></pre>\n\n<p><strong>Remember that in ruby <code>nil</code> and <code>false</code> are both false-y</strong></p>\n\n<pre><code>def valid?\n @opts && @opts[:property_1] && @opts[:property_2]\n #will return true only if @opts and properties are non nil values\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T03:27:59.743",
"Id": "42568",
"ParentId": "42275",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "42289",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-02-20T09:04:59.910",
"Id": "42275",
"Score": "2",
"Tags": [
"ruby",
"validation",
"null",
"cyclomatic-complexity"
],
"Title": "Validating the presence of properties in a document"
}
|
42275
|
<p>This integration test involves database access and hence opening and closing a database connection. Does it look correct? I am concerned about ensuring the the database connection is closed should the test fail.</p>
<pre><code>"use strict";
describe("MyCtorFunction", function () {
describe("myMethod", function () {
var _db = null,
_testContext = null;
beforeEach(function () {
_testContext = {};
new DbHelper().openConnection(function (err, dbConnection) {
if (err) {
throw err;
}
_db = dbConnection;
});
waitsFor(function () {
return _db;
}, "establishing a connection to the database.", 5000);
});
afterEach(function () {
waitsFor(function () {
return _testContext.assertions.callCount === 1;
}, "waiting for the assertions to be called.", 5000);
runs(function () {
if (_db) {
_db.close();
_db = null;
}
});
});
it("should do something", function () {
runs(function () {
//arrange
_testContext.assertions = assertions;
spyOn(_testContext, "assertions").andCallThrough();
//act (_testContext.assertions invoked as callback)
new MyCtorFunction(_db).myMethod(_testContext.assertions);
//assert
function assertions(err, config) {
expect(config).toNotBe(null);
//etc.
}
});
});
});
});
</code></pre>
|
[] |
[
{
"body": "<p>From a once over and reading some Jasmine docs:</p>\n\n<ul>\n<li><p>I am not a big fan of <code>_db</code> and <code>_testContext</code>, I see no reason for the underscores.</p></li>\n<li><p>It is not guaranteed that <code>_db</code> will be set in <br><code>new MyCtorFunction(_db).myMethod(_testContext.assertions);</code>, <br>so you should check for that prior to calling.</p></li>\n<li><p>You did not tell us what database (API) you are using, so we cannot tell whether you close the connection properly.</p></li>\n<li><p>I wish you had provided us the code in <code>assertions</code>, it would have helped with the review</p></li>\n<li><p>JsHint could find nothing wrong</p></li>\n<li><p>I would advise you to make sure an assertion fails and put a log statement in your db closing code, this way you can be <em>assured</em> that the db connection will be closed. Though from reading the docs you should be fine.</p></li>\n<li><p>This:</p>\n\n<pre><code>waitsFor(function () {\n return _testContext.assertions.callCount === 1;\n}, \"waiting for the assertions to be called.\", 5000);\n</code></pre>\n\n<p>Seems a bit paranoid, <code>afterEach</code> is guaranteed to run after your assertions if I read your code well. If I am right then you can clean up your code tremendously since you will not need <code>_testContext</code> any more.</p></li>\n<li><p>I hope <code>MyCtorFunction</code> and <code>myMethod</code> are not the true names in your code, those are horrible names ;)</p></li>\n</ul>\n\n<p>All in all I dont really like your code, I blame Jasmine for that. I dont like their approach to naming functions nor their approach to asynchronous processing.</p>\n\n<p><strong>Update</strong>:</p>\n\n<p>I realized on the subway that in my mind, the waiting for the db and the waiting for the test to finish ought to be part of the test, not part of the setup/teardown. This approach will definitely simplify since you wont need <code>runs</code> anymore in <code>afterEach</code>, plus you will not need <code>testContext</code> any more.</p>\n\n<p>I cannot test this, but you should get the picture.</p>\n\n<pre><code>\"use strict\";\n\ndescribe(\"MyCtorFunction\", function () {\n\n describe(\"myMethod\", function () {\n var db;\n\n beforeEach(function () {\n\n new DbHelper().openConnection(function (err, dbConnection) {\n if (err) {\n throw err;\n }\n db = dbConnection;\n });\n });\n\n afterEach(function () {\n if (db) {\n db.close();\n db = null;\n }\n });\n\n it(\"should do something\", function () {\n //Wait for the green light\n waitsFor(function () {\n return db;\n }, \"establishing a connection to the database.\", 5000); \n //Start acting!\n runs(function () {\n //arrange\n spyOn(_testContext, \"assertions\").andCallThrough();\n //act (assertions invoked as callback)\n new MyCtorFunction(_db).myMethod( assertions );\n\n //assert\n function assertions(err, config) {\n expect(config).toNotBe(null);\n //etc.\n }\n });\n //Wait for the action to be done\n waitsFor(function () {\n return assertions.callCount === 1;\n }, \"waiting for the assertions to be called.\", 5000); \n //Done \n });\n });\n});\n</code></pre>\n\n<p>Finally, from a library perspective, check out <a href=\"https://github.com/derickbailey/jasmine.async\" rel=\"nofollow\">https://github.com/derickbailey/jasmine.async</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T17:02:45.180",
"Id": "72793",
"Score": "0",
"body": "Thanks! The `waitsFor(... return _testContext.assertions.callCount === 1; ...)` is required for test runner to wait until assertions have been run asynchronously before closing the db conn. Aware of stylistic camps on `_`. It can help with readability denoting variable scoping. Introduced `testContext` to do trickery with the assertions function (and maintain the arr/act/ass ordering in the test). Names changed in this code from the actual source. The `beforeEach` `waitsFor` checks `_db` is set no? Can you recommend another async test runner/something that might help me improve the code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T00:15:45.660",
"Id": "72881",
"Score": "0",
"body": "@Ben the `beforeEach` will only wait 5 seconds, that might still fail.. I will do some research on better async test runners, they must be out there.."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T16:36:16.477",
"Id": "42319",
"ParentId": "42276",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T09:13:14.510",
"Id": "42276",
"Score": "2",
"Tags": [
"javascript",
"jasmine",
"integration-testing"
],
"Title": "Integration test for database access"
}
|
42276
|
<p>I have this assignment where I'm supposed to code an algorithm for finding the quantity of <a href="http://en.wikipedia.org/wiki/Longest_increasing_subsequence" rel="nofollow noreferrer">Longest Increasing Subsequences</a> from an array of (different) integers and print them all.</p>
<p>I developed one which always gives me the right answer, but I have 2 issues with it:</p>
<ol>
<li><p>It's a little slow</p>
</li>
<li><p>When the given array is between 150-200 integers long, it crashes with:</p>
<blockquote>
<p>OutOfMemory: <strong>heap space</strong></p>
</blockquote>
</li>
</ol>
<p>I understand why it's a little slow, and to tell you the truth, it's not that slow when you think of Brute Force Algorithm alternatives.</p>
<p>And also, I'd like to be able to return the quantity of LISs independently from searching them (like finding the number of cheapest paths in a graph without returning them all), but I just can't seem to find a solution without counting them after finding them.</p>
<p>A little explanation:</p>
<p>The algorithm creates an (n+1)*(n+1) matrix (n = length of given array), rows representing given array, columns representing given array after sorting (ascending), fills the first row and the first column with 0s and then loops over it using different conditions to either:</p>
<ul>
<li>add an integer to the array(s) existing at given slot in this matrix (mat[i, j])</li>
<li>copies all the existing arrays of the slot above and the slot aside (mat[i-1, j], mat[i, j-1]) into the current slot (without duplicates)</li>
<li>copies the array(s) from the slot (above or aside) in which they are longer into current slot)</li>
<li>just fills it with "nothing"</li>
</ul>
<p><strong>n.b.:</strong> I'm not actually creating a (n+1)*(n+1) matrix. Instead I create a 2*(n+1) matrix in which I only keep the last row calculated and the one I'm about to, then switch.</p>
<p>My problem might also come from my testing. I just can't seem to see it.</p>
<pre><code>import java.util.Arrays;
import java.util.ArrayList;
public class LIS {
private int[] arr;
public LIS(int[] arr) {
this.arr = new int[arr.length];
System.arraycopy(arr, 0, this.arr, 0, arr.length);
}
public static int BSBinArray(int[] arr, int end, int value) {...}// BinarySearch
public static void mergeSort(int [] arr, int low, int high){...}// 1st part of MergeSort
public static int[] mergeSort(int [] arr){...}// 2nd part of MergeSort
public int LISLength() {// get exclusively the length of the LIS(s)
int[] help = new int[arr.length];
help[0] = arr[0];
int end = 0;
for (int i = 0; i < arr.length; i++) {
int index = BSBinArray(help, end, arr[i]);
help[index] = arr[i];
if(index > end) end++;
}
return end+1;
}
// returns a Node (class below) with all the info in it
private Node buildMatrix() {
int maxLength = LISLength();
int[] sortArr = mergeSort(arr);
Node[][] mat = new Node[2][arr.length + 1];
for (int i = 0; i < mat.length; i++) {
mat[i][0] = new Node(maxLength);
}
for (int i = 0; i < mat[0].length; i++) {
mat[0][i] = new Node(maxLength);
}
int cur = 0;
int prev = 0;
for (int i = 1; i < arr.length+1; i++) {
cur = (cur + 1)%2;
prev = 1-cur;
for (int j = 1; j < mat[0].length; j++) {
if(arr[i-1] == sortArr[j-1]) {
mat[cur][j] = new Node(mat[prev][j-1]);
for (int k = 0; k < mat[cur][j].list.size(); k++) {
mat[cur][j].list.get(k)[mat[cur][j].localLength] = arr[i-1];
}
mat[cur][j].localLength++;
}
else {
if(mat[prev][j].localLength == mat[cur][j-1].localLength) {
if(mat[prev][j].localLength != 0) {
mat[cur][j] = new Node(mat[prev][j]);
for (int k = 0; k < mat[cur][j-1].list.size(); k++) {
boolean contains = false;
for (int k2 = 0; k2 < mat[prev][j].list.size() && !contains; k2++) {
contains = Arrays.equals(mat[cur][j-1].list.get(k), mat[prev][j].list.get(k2));
}
if(!contains) mat[cur][j].list.add(mat[cur][j-1].list.get(k));
}
}
else {
mat[cur][j] = new Node(maxLength);
}
}
else if(mat[prev][j].localLength > mat[cur][j-1].localLength) {
mat[cur][j] = new Node(mat[prev][j]);
}
else {
mat[cur][j] = new Node(mat[cur][j-1]);
}
}
}
}
return mat[cur][mat[0].length-1];
}
public void printLengthLIS() {
int length = LISLength();
System.out.println("LISs are " + length + " integers long.");
}
public void printNumOfLIS() {
int numOfLIS = buildMatrix().list.size();
System.out.println("There are " + numOfLIS + " LISs.");
}
public void printAllLIS() {
ArrayList<int[]> info = buildMatrix().list;
System.out.println("All the LISs are: ");
for (int i = 0; i < info.size(); i++) {
System.out.println(Arrays.toString(info.get(i)));
}
}
private class Node {
int localLength;
ArrayList<int[]> list;
public Node(int x) {
localLength = 0;
list = new ArrayList<int[]>();
list.add(new int[x]);
}
public Node(Node n) {
localLength = n.localLength;
list = new ArrayList<int[]>();
for(int[] temp : n.list) {
list.add(temp.clone());
}
}
}
</code></pre>
<p>And here is my testing code (with a lot of monitoring info):</p>
<pre><code>for(int i = 10; i < 1000; i++) {
System.out.println("available memory BEFORE: " + java.lang.Runtime.getRuntime().maxMemory());
// creates a random array of different integers
Set<Integer> set = new HashSet<Integer>();
int temp = i;
while(temp != 0) {
if(set.add((int)(Math.random()*1000))) temp--;
}
int[] arr = new int[set.size()];
Iterator<Integer> it = set.iterator();
// into an actual array
for (int j = 0; j < arr.length; j++) {
arr[j] = it.next();
}
set = null;// supposed to free this memory allocation for the GC
System.out.println("i="+i+", length="+arr.length);
System.out.println(Arrays.toString(arr));
LIS test = new LIS(arr, arr.length+1);
test.printLengthLIS();
long startTime = System.currentTimeMillis();
test.printNumOfLIS();
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println("It took me " + totalTime + " ms.");
test.printAllLIS();
test = null;
System.out.println("available memory AFTER: " + java.lang.Runtime.getRuntime().freeMemory());
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T21:37:20.053",
"Id": "72844",
"Score": "0",
"body": "Please clarify the problem specification.... if you are allowed to 'skip' out-of-sequence numbers, can you skip 'inconvenient' numbers too? Is the longest sequence in `[1,2,8,3,4,5,6,7,9]` `[3,4,5,6,7,9]` or `[1,2,3,4,5,6,7,9]`? Why?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T23:35:32.220",
"Id": "72866",
"Score": "0",
"body": "@rolfl [1,2,3,4,5,6,7,9]. I can't explain the reason why you can skip over elements, I suppose it's mainly because that's how the problem is given (http://en.wikipedia.org/wiki/Longest_increasing_subsequence)."
}
] |
[
{
"body": "<p><strong>Note</strong>: This review is based on the (apparently incorrect) assumption that the sequence in question is 'contiguous'. In other words, the 'right solutions' in the example:</p>\n\n<pre><code>[2,-3,4,90,-2,-1,-10,-9,-8]\n</code></pre>\n\n<p>are:</p>\n\n<pre><code>[-3, 4, 90] and [-10, -9, -8]\n</code></pre>\n\n<p>In other words, the values have to appear next to each other in the data....</p>\n\n<p>... this was not explicit in the question. Later comments indicate that the sequence can 'skip' values. The rules for 'skipping' appear to be that you can skip any value that is smaller than the first value in the sequence. The above example, if you include skipping has two additional solutions:</p>\n\n<pre><code>[2, 4, 90] and [-3, -2, -1]\n</code></pre>\n\n<hr>\n\n<p>There are a lot of things to cover here.... but, some forewarning, you have completely over-thought this problem.... and your algorithm is far from 'the right one'. Given that I am suggesting that the algorithm is overkill, there are two things I can do:</p>\n\n<ul>\n<li>go through what you have done, and point out general items that you should do differently that are related to things other than the algorithm.</li>\n<li>suggest an algorithm that is better.</li>\n</ul>\n\n<h2>General review</h2>\n\n<ul>\n<li><p><strong>Random data sets</strong></p>\n\n<p>In your test method, you are building up a <code>Set</code> of random integer values. This set is not as random as you would think, though.... The Java implementation of HashSet does not make any guarantee about the order of the values as you retrieve them. Internally it uses a hashing system to build a table, and it stores the values in the table based on the hash, and then when you iterate over the values it returns them in an order that is essentially based on the way the data was hashed. So, as you store your random values, they are then being re-sorted in to the hash table, and then the return value is affected by this.</p>\n\n<p>You really should not be using the hash at all.... you should be using the primitive int-array, and saving yourself the extra step. But, your code looks like it is designed to ensure that there are no duplicates in your data... there are better ways to do that. Here is a simple insertion of a sequence of numbers, <a href=\"http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"nofollow\">followed by a Fisher-Yates shuffle</a>:</p>\n\n<pre><code> // creates a random array of different integers\n int[] arr = new int[i];\n // set the values to be unique.\n for (int j = 0; j < arr.length; j++) {\n arr[j] = j;\n }\n // shuffle the data.\n for (int j = arr.length - 1; j >= 1 ; j--) {\n int p = rand.nextInt(j + 1);\n int v = arr[j];\n arr[j] = arr[p];\n arr[p] = v;\n }\n</code></pre>\n\n<p>OK, that's a good way to get a bunch of int values that are unique, but are in a random order. It also only creates as many random numbers as are needed, it does not keep 'guessing' until it finds a unique value.</p></li>\n<li><p><strong>Copying Arrays</strong></p>\n\n<p>In your LIS constructor, you do the following to copy the input data:</p>\n\n<blockquote>\n<pre><code>this.arr = new int[arr.length];\nSystem.arraycopy(arr, 0, this.arr, 0, arr.length);\n</code></pre>\n</blockquote>\n\n<p>This can easily be replaced with the simpler helper-method from <code>java.util.Arrays</code>:</p>\n\n<pre><code>this.arr = Arrays.copyOf(arr, arr.length);\n</code></pre></li>\n<li><p><strong>Method Naming</strong></p>\n\n<p>Your method <code>public int LISLength()</code> should not be named with a capital letter to start. This is a 'getter' method, and should be named <code>public int getLISLength()</code></p></li>\n</ul>\n\n<h2>Algorithm</h2>\n\n<p>Right, your algorithm. When I look at problems (things to review), I think: <em>how would I solve this?</em> I come up with a strategy, and then see if I can see the strategy in the code I am reviewing. If I can't see the strategy, I look harder, and try to determine what the strategy being used is... and I ask myself: <em>Is it better than what I would have done?</em></p>\n\n<p>In your case, I have to admit, I came up with a strategy, I could not see it in your code, and your strategy is so complicated, and you admit it is slow, that I actually have not figured out your code at all... it's too much effort to understand the intricacies when I <em>know</em> there's a much, much simpler way to do this.</p>\n\n<p>This is a lesson for you... sometimes doing a google-search for an algorithm before trying to implement one is a good idea.</p>\n\n<p>So, instead of trying to understand your algorithm properly, I am just going to demonstrate an alternate algorithm.....</p>\n\n<p>The problem is:</p>\n\n<ul>\n<li>you have an array of values which are in no particular order.</li>\n<li>you need to identify sequences in that data where the values are increasing...</li>\n<li>you need to track how long the longest sequences are</li>\n<li>you need to track exaclty what the longest sequences are.</li>\n</ul>\n\n<p>This can all be done in a single loop, with very little data needed to track the details.</p>\n\n<p>Loop over the data... for each value:</p>\n\n<ul>\n<li>if the value is not increasing, then it is the <em>start</em> of a new sequence</li>\n<li>if the current sequence is longer than previous sequences, then we can forget all previous sequences, and we have a new longest sequence.</li>\n<li>if the current sequence is the same length as the longest sequence, then we need to remember where this sequence is.</li>\n</ul>\n\n<p>I have put this all in a class, with a revised test to be more random.... For me, the code is running all the tests really fast. I had to change the time-monitoring code so that it counts in nanoseconds, instead of milliseconds. The 1000-entry test runs in 0.019ms. A test of 10 million integers took 75.608ms</p>\n\n<p>here's the code that does the above:</p>\n\n<pre><code>import java.util.Arrays;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class LIS {\n private final int[] copy;\n private final int[] startpoints;\n private final int longest;\n\n public LIS(int[] arr) {\n copy = new int[arr.length];\n int[] begin = new int[32];\n int seqcnt = 0;\n int seqlen = 0;\n int longseq = 0;\n int previous = Integer.MAX_VALUE;\n for (int i = 0; i < arr.length; i++) {\n int v = arr[i];\n // copy the data....\n copy[i] = v;\n if (v <= previous) {\n // not-increasing sequence\n seqlen = 0;\n }\n previous = v;\n seqlen++;\n if (seqlen > longseq) {\n // new longest sequence....\n longseq = seqlen;\n // throw away previous sequences.\n seqcnt = 0;\n }\n if (seqlen == longseq) {\n // new sequence.... matching the longest...\n if (seqcnt >= begin.length) {\n // need more space to save this sequence.\n begin = Arrays.copyOf(begin, begin.length * 2);\n }\n // at position `i - seqlen + 1` there begins a sequence that is all ascending.\n begin[seqcnt++] = i - seqlen + 1;\n }\n }\n longest = longseq;\n startpoints = Arrays.copyOf(begin, seqcnt);\n }\n\n public int longestLength() {// get exclusively the length of the LIS(s)\n return longest;\n }\n\n public void printLengthLIS() {\n System.out.println(\"LISs are \" + longest + \" integers long.\");\n }\n public void printNumOfLIS() {\n System.out.println(\"There are \" + startpoints.length + \" LISs.\");\n }\n public void printAllLIS() {\n System.out.println(\"All the LISs are: \");\n for (int sp : startpoints) {\n System.out.println(Arrays.toString(Arrays.copyOfRange(copy, sp, sp + longest)));\n }\n }\n\n private static final void testSize(int size, Random rand) {\n //System.out.println(\"available memory BEFORE: \" + java.lang.Runtime.getRuntime().maxMemory());\n\n // creates a random array of different integers\n int[] arr = new int[size];\n for (int j = 0; j < arr.length; j++) {\n arr[j] = j;\n }\n // shuffle the data.\n for (int j = arr.length - 1; j >= 1 ; j--) {\n int p = rand.nextInt(j + 1);\n int v = arr[j];\n arr[j] = arr[p];\n arr[p] = v;\n }\n\n System.out.println(\"i=\"+size+\", length=\"+arr.length);\n //System.out.println(Arrays.toString(arr));\n\n long startTime = System.nanoTime();\n LIS test = new LIS(arr);\n\n test.printLengthLIS();\n\n test.printNumOfLIS();\n long endTime = System.nanoTime();\n\n long totalTime = endTime - startTime;\n System.out.printf(\"It took me %.3fms.\", totalTime / 1000000.0);\n\n test.printAllLIS();\n\n test = null;\n //System.out.println(\"available memory AFTER: \" + java.lang.Runtime.getRuntime().freeMemory());\n }\n\n public static void main(String[] args) {\n Random rand = new Random();\n for(int i = 10; i < 1000; i++) {\n testSize(i, rand);\n }\n\n testSize(10000000, rand);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T19:55:53.643",
"Id": "72832",
"Score": "0",
"body": "It looks like your algorithm discards previous elements too early. For example, [2,-3,4,90,-2,-1,-10,-9,-8] should return 4 sequences : [2, 4, 90], [-3, 4, 90], [-3, -2, -1] and [-10, -9, -8] but through your code, it returns only 2. Still you gave me some great pointers !!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T21:32:16.430",
"Id": "72843",
"Score": "0",
"body": "@iSoul - I think that the specification for the problem is wrong then.... or, at least, it is ambiguous.... I do not consider a sequence of numbers to have 'gaps'. You skip 'inconvenient' values in the sequence. I assume the results have to be contiguous. Fix your question to make the specification clear."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T15:50:22.233",
"Id": "42314",
"ParentId": "42277",
"Score": "1"
}
},
{
"body": "<p>Taking the changed/alternate specification in to consideration, you are allowed to 'skip' values to get the increasing sequences.</p>\n\n<p>The right algorithm for this problem is to use recursion. Now, because you are skipping things, there are a lot of potential combinations of 'winning' sequences.... as a result, you cannot safely store them all in memory. The right solution to <strong>that</strong> problem is to use an iterator.</p>\n\n<p>Here is your problem worked out with a relatively small memory footprint, and an iterator used to report the actual sequences.....</p>\n\n<p>There is room for optimization still in the recursion, and, it may be worth adopting the iterative approach of the iterator instead of the recursion.... your call. Having both examples will give you something to think about.</p>\n\n<pre><code>import java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\nimport java.util.Random;\n\npublic class SkippingLIS implements Iterable<int[]> {\n\n private static final class MutableInt {\n int value = 0;\n }\n\n private final int[] data;\n private final int sequencecount;\n private final int longest;\n\n public SkippingLIS(int[] arr) {\n\n data = Arrays.copyOf(arr, arr.length);\n\n int[] stack = new int[data.length];\n MutableInt counter = new MutableInt();\n\n longest = recurseCount(data, 0, stack, 0, 0, counter);\n\n sequencecount = counter.value;\n }\n\n private class MyIterator implements Iterator<int[]> {\n\n int[] cursor = new int[1 + longest * 2];\n int[] stack = new int[1 + longest * 2];\n int count = 0;\n int depth = 0;\n\n public MyIterator() {\n cursor[0] = -1;\n }\n\n @Override\n public boolean hasNext() {\n return count < sequencecount;\n }\n @Override\n public int[] next() {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n\n do {\n cursor[depth]++;\n while (cursor[depth] >= data.length) {\n depth--;\n cursor[depth]++;\n }\n if (depth > 0) {\n while (cursor[depth] < data.length && data[cursor[depth]] <= stack[depth - 1]) {\n cursor[depth]++;\n }\n }\n if (cursor[depth] < data.length) {\n stack[depth] = data[cursor[depth]];\n if (depth < longest) {\n depth++;\n cursor[depth] = cursor[depth - 1];\n }\n }\n } while (cursor[depth] >= data.length || depth != longest);\n count++;\n return Arrays.copyOf(stack, longest);\n }\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n\n }\n\n }\n\n @Override\n public Iterator<int[]> iterator() {\n return new MyIterator();\n }\n\n\n private static int recurseCount(final int[] arr, final int cursor, final int[] stack, final int length, final int maxlen,\n final MutableInt results) {\n if (cursor >= arr.length) {\n // max length so far....\n return length;\n }\n int loopmax = maxlen;\n if (length > loopmax) {\n results.value = 0;\n loopmax = length;\n }\n if (loopmax == length) {\n results.value++;\n }\n for (int i = arr.length - 1 - loopmax + length; i >= cursor; i--) {\n if (length == 0 || arr[i] > stack[length - 1]) {\n stack[length] = arr[i];\n int nmax = recurseCount(arr, i, stack, length + 1, loopmax, results);\n if (nmax > loopmax) {\n loopmax = nmax;\n }\n }\n }\n return loopmax;\n\n }\n\n public int longestLength() {// get exclusively the length of the LIS(s)\n return longest;\n }\n\n public void printLengthLIS() {\n System.out.println(\"LISs are \" + longest + \" integers long.\");\n }\n public void printNumOfLIS() {\n System.out.println(\"There are \" + sequencecount + \" LISs.\");\n }\n public void printAllLIS(int limit) {\n if (sequencecount < limit) {\n limit = sequencecount;\n }\n System.out.println(\"First \" + limit + \" of \" + sequencecount + \" of the LISs are: \");\n int cnt = 0;\n for (int[] sp : this) {\n cnt++;\n System.out.println(Arrays.toString(sp));\n if (cnt >= limit) {\n return;\n }\n }\n }\n\n private static final void testSize(int size, Random rand) {\n //System.out.println(\"available memory BEFORE: \" + java.lang.Runtime.getRuntime().maxMemory());\n\n // creates a random array of different integers\n int[] arr = new int[size];\n for (int j = 0; j < arr.length; j++) {\n arr[j] = j;\n }\n // shuffle the data.\n for (int j = arr.length - 1; j >= 1 ; j--) {\n int p = rand.nextInt(j + 1);\n int v = arr[j];\n arr[j] = arr[p];\n arr[p] = v;\n }\n\n System.out.println(\"i=\"+size+\", length=\"+arr.length);\n //System.out.println(Arrays.toString(arr));\n\n long startTime = System.nanoTime();\n SkippingLIS test = new SkippingLIS(arr);\n\n test.printLengthLIS();\n\n test.printNumOfLIS();\n long endTime = System.nanoTime();\n\n long totalTime = endTime - startTime;\n System.out.printf(\"It took me %.3fms.\", totalTime / 1000000.0);\n\n test.printAllLIS(10);\n\n test = null;\n //System.out.println(\"available memory AFTER: \" + java.lang.Runtime.getRuntime().freeMemory());\n }\n\n public static void main(String[] args) {\n SkippingLIS special = new SkippingLIS(new int[]{2,-3,4,90,-2,-1,-10,-9,-8});\n special.printAllLIS(10);\n\n Random rand = new Random();\n for(int i = 10; i < 100f; i++) {\n testSize(i, rand);\n }\n\n //testSize(10000000, rand);\n\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T22:48:13.097",
"Id": "42348",
"ParentId": "42277",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T09:19:56.137",
"Id": "42277",
"Score": "4",
"Tags": [
"java",
"algorithm",
"matrix",
"dynamic-programming"
],
"Title": "Returning all the LIS of given array of int"
}
|
42277
|
<p>I'm trying to create some easily accessible database of different skills. General idea is that every skill should do something different and be able to act on different things (ex. one skill which icreases weapon attack by 'x' [it acts on weapon] and other one which icreases chances to drop item by 'z'% [it acts on monster]).</p>
<p>I see it that way:</p>
<ul>
<li>There is static database of skills accessible from everywhere</li>
<li>Skills have effects(methods with different return types, different parameters and calculations)</li>
<li><p>To use skill we add it's effect in particular calculations;</p>
<ul>
<li>Example: If we want to increase drop chance of monster by 'z'% then, in place where we calculate that drop chance (in this case in Monster class), lets say (Monster.DropChance = 0.5f) we add skill effect : after skill implementation (Monster.DropChance = 0.5f + SkillDatabase.IncreaseDropChance.Effect (this))</li>
</ul>
<p>I came up with a code like this:</p>
<pre><code>public static class SkillData // Static class acting as database for keeping skills in one place
{
// Names of skills
public enum Name
{
IncreaseDropChance = 1,
IncreaseWeaponAtk = 2
}
// T - return type of skill effect, U - type of object on which effect works
public class Skill<T, U>
{
public int Level { get; set; }
public float ExperienceCost { get; set; }
public Name SName;
// Delegate for creating unique effects for each skill
public delegate T EffectDel (U onWhat);
public EffectDel Effect;
public Skill (Name name)
{
SName = name;
}
}
// Custom dictionary for generic skill
public class SkillDictionary
{
private Dictionary<Name, object> _dict = new Dictionary<Name, object>();
public void Add<T, U>(Name key, Skill<T, U> skill)
{
_dict.Add(key, skill);
}
public Skill<T, U> GetValue<T, U>(Name key)
{
return _dict[key] as Skill<T,U>;
}
}
// Static for easy access
public static SkillDictionary DB = new SkillDictionary ();
static SkillData ()
{
// Here I want to create skills one after another and add them to DB
// This is example skill creation
Skill <float, Player> IncrWpnAtk = new Skill<float, Player> (SName.IncreaseWeaponAtk);
IncrWpnAtk.Level = 5;
// Let's say we want to increase weapon attack by 100% * skillLvl
IncrWpnAtk.Effect = (player) => { float additionalAtk = player.Eq.Weapon.Atk * IncrWpnAtk.Level;
return additionalAtk; };
DB.Add <float, Player> (Name.IncreaseWeaponAtk, IncrWpnAtk);
}
}
</code></pre></li>
</ul>
<p>Now in weapon attack calculation we add <code>SkillData.DB.GetValue<float, Player> (IncreaseWeaponAtk).Effect (player)</code> .<br>
Yeah... It's terrible. Load of text for such a tiny effect. It's my second time using delegates and third time creating generic classes, I just don't know any other solution for creating same class with different methods. </p>
<p>How would you solve it guys? Do you know any way to maintain organized, easily accessible database of skills? Or maby this approach is generaly wrong?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T10:40:00.930",
"Id": "72724",
"Score": "0",
"body": "Okay, found solution to the whole problem in general, but the approach is completly different. I still wonder if it could be handled in the way it is in posted code, just improved."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T14:08:47.777",
"Id": "72751",
"Score": "0",
"body": "Right now I'm on idea of deleting name enum, delegates and generics, creating basic skill class and separate static class for each skill which will derive from basic skill class (all classes would be in SkillData class). Ex class IncreaseDropChance : Skill . This way I won't have to rewrite basic information, and will keep all the skills in one place with easy access (SkillData.IncreaseDropChance.Effect(monster)). Also this way I can have different calculations on different objects without complex generics and delegates. I'm just not sure about efficiency of such solution. What do you think?"
}
] |
[
{
"body": "<p>Hmmm,</p>\n\n<p>Well I think the way you are going about it, while functionally correct won't scale well.</p>\n\n<p>Ideally you want to try more of an aggregation. Off the top of my head I would approach this like:</p>\n\n<pre><code>interface Skill\n{\n string Name{get;}\n double value{get;}\n}\n</code></pre>\n\n<p>now with this base object you can write the rest of your code doing calculations based on your skills value. </p>\n\n<p>As for the modifying, well nothing else needs to know if a Skill is modified to use it. \nTo handle that I would make a ModifiedSkill agnostic from everything else:</p>\n\n<pre><code>public interface ModifiedSkill : Skill\n{\n IEnumerable<Modifier> Modifiers { get; }\n\n double BaseValue { get; }\n double Value { get; }\n\n}\n</code></pre>\n\n<p>Now, what is a modifier you ask? well:</p>\n\n<pre><code>public interface Modifier\n{\n string Name { get; }\n string Cause { get; }\n double Apply(double skill);\n Boolean Active { get; set; }\n}\n</code></pre>\n\n<p>So that is all the interfaces you need to cover pretty much all eventualities, allowing for some potentially cool things down the line like timed modifiers or conditional modifiers or whatever.</p>\n\n<p>Now, how to actually implement this?</p>\n\n<pre><code>Public class ModifiedSkillImpl : ModifiedSkill\n {\n private readonly List<Modifier> _modifiers;\n private readonly double _baseValue;\n\n public ModifiedSkillImpl(string name, double baseValue, IEnumerable<Modifier> modifiers)\n {\n if (name == null) throw new ArgumentNullException(\"name\");\n if (modifiers == null) throw new ArgumentNullException(\"modifiers\");\n Name = name;\n _baseValue = baseValue;\n _modifiers = modifiers.ToList();\n }\n\n public string Name { get; private set; }\n\n public IEnumerable<Modifier> Modifiers\n {\n get\n {\n return _modifiers;\n }\n }\n\n public double BaseValue\n {\n get\n {\n return _baseValue;\n }\n }\n\n public double Value\n {\n get\n {\n return Modifiers.Aggregate(_baseValue, (current, modifier) => modifier.Apply(current));\n }\n }\n}\n</code></pre>\n\n<p>Now, this is only one example of course, you could do a lot of alternate skill implementations. \nThe final step would be i suppose to create PoisonModifier/ItchyLeftEarModifier etc\nand then apply them with some effect like +5% -20% etc, or whatever. </p>\n\n<p>This separation also means that while most things will be using the Skill.Value which in the case of a modified skill will be the modified version some special something could check if the skill is a Modified skill, if so cast it and use the base stat instead! </p>\n\n<p>(one final note)\nI was a bit wasteful with the Value aggregation in ModifiedSkillImpl, tbh I would probably have a private variable for modified Skill and only recalculate if the modifiers had changed since last call but you know, this is just a quick POC. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T15:02:37.320",
"Id": "72758",
"Score": "0",
"body": "Interface `Skill`? Why not stick to convention and call it `ISkill`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T15:12:27.847",
"Id": "72761",
"Score": "0",
"body": "@Mat'sMug Well this is one for debate, I for one am a fan of the clean code approach. prefixing I for what is essentially an end-facing class/interface is essentially hungarian notation. Whoever/whatever service consumes this , why do they need to know it's an interface? Also if you plan on passing around the interface but hiding the implementation is it not cleaner to have a Skill and SkllImpl that is never seen rather than a ISkill passed around and Skill class hidden away?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T15:16:36.077",
"Id": "72763",
"Score": "0",
"body": "The vast majority of C# programmers will be expecting an interface to start with a capital `I`. I agree it's somewhat Hungarian, but it's the *exception that confirms the rule*. http://stackoverflow.com/q/2728093/1188513"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T15:21:12.357",
"Id": "72766",
"Score": "0",
"body": "I use exactly this system for stats and attributes but I just don't find it to work well with skill system. Let's take a IncrDropChance example again. Monster has a drop chance of 2%, we want skill to increase it by 50% so it will be 3%. If I understood correctly, to make it work I would have to create modified skill with baseValue of 0.5, add monster's drop chance (0.02) as a modifier to this skill, (assuming we have different Value calculations for multiplication, we don't want 0.5 sum with 0.02, rather 0.5 * 0.02) and finally include it in monster's drop chance calculation. Quite alot work"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T15:26:52.330",
"Id": "72768",
"Score": "0",
"body": "@Mat'sMug well given my assumed usage of these classes I would prefer to have more fluent methods that read like a user story rather than code such as if(Skill is ModifedSkill) ... so on. My loyalty for expectation is more to conform to the glossary of the problem domain than coding convention. If done well the code reads well regardless of whether the person reading it can code or not. The exception is Developer-Centric code. eg if i role my own Modular MEF/Prism System then IModule speaks to developers but things like Skills/Accounts/Members don't lie exclusively in developer world."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T15:36:17.587",
"Id": "72770",
"Score": "0",
"body": "Generally it would work, but that's exactly what I was trying to avoid - messing with modifiers instead of acting directly on object of my choice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T15:36:24.587",
"Id": "72771",
"Score": "0",
"body": "As far as the 'I' prefix goes, I don't consider it all that important either, assuming your IDE colors it differently than a class (and it can), but I consider underscore prefixes far more terrible. As for the modifier calculations, @CantGetEnough, I think I'd do something somewhat similar; anything that can be modified like this probably needs to be a calculation already, and the player should own those modifiers, which makes passing them into a method to get the value may make the most sense."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T14:43:55.360",
"Id": "42307",
"ParentId": "42278",
"Score": "3"
}
},
{
"body": "<p>Given @CantGenEnough 's comments that my previous suggestion didn't fit his needs I thought I'd try an alternate approach I was playing with. </p>\n\n<p>Instead of the above you could try a similar approach with a sort of a weighted calculator instead of the actual skill approach.</p>\n\n<p>So If you had a generic</p>\n\n<pre><code>interface Modification\n{\n int Weight {get;}\n double Calculate(double input);\n}\n</code></pre>\n\n<p>and had a number of calculation classes that implement it such as <code>IncreaseByXPercent</code> or <code>CapAtMaximum</code> or something (*cough better named) you could create a modifier Enumeration just like before with a small factory method with simple functions that just add the appropriate classes to the Modifier Collection then on calculation order by weight and apply. a snapshot of it might look like:</p>\n\n<pre><code>public interface SkillModifier\n{\n void IncreaseByXPercent(int percent);\n void CapAtX(double value);\n\n double Calculate();\n\n}\n</code></pre>\n\n<p>usage might look like:</p>\n\n<pre><code>Skill health = new SkillImpl(100);\n\nhealth.Modify.IncreateByXPercent(5);\nhealth.Modify.CapAt(5000);\n\nPrintTheValue(health.Value);\n</code></pre>\n\n<p>whereby the Modify Accessor is a composite instance of the <code>SkillModifier</code> class, it adds <code>Modification</code> instances to an internal enumeration and orders by weight. </p>\n\n<p>the Skill classes <code>Skill.Value</code> calls its composite Modify.Calculate(_baseValue) or something and still returns the combined result and all is safely encapsulated. </p>\n\n<hr>\n\n<p>Personally I am less inclined towards this, more overhead in terms of building a fluent interface for your equation aggregation and a bit harder for newer people to grasp using but then again it reads better than any other solution at first glance regardless of ability. </p>\n\n<p>So if you were to package this as a modifier API for yourself it might be the way to go (but for api additions I tend to follow the rule of 3 uses so may be premature to do so); but as a problem solve for a particular project I would choose the more straightforward above method.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T17:08:35.273",
"Id": "72795",
"Score": "1",
"body": "I'm quite confused and not sure if we are on the same page. I might have named whole topic and thing wrong. By skill I do not mean something like player's sword fighting skill, or lockpicking or whatever, (in these examples your solution is perfect) but rather something that affects different things in the game world, not necessarily directly related to player. Ex. if there was some storage in game, there could be \"skill\" that would increase it's capacity. I know, that shouldn't be named skill, but I just tend to think of such things as \"skills\". Thats why I don't want to use modifiers"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T17:11:41.503",
"Id": "72796",
"Score": "0",
"body": "and try to force that \"direct acting on different type objects\". I just didn't want to create modifiers in those affected objects classes just to add them to the skill later used in the same class. OR I simply didn't understand well, what you've tried to show me and then this comment is just an effect of this. I'll read your answers few more times and will try to digest it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T17:17:11.453",
"Id": "72799",
"Score": "0",
"body": "@CantGetEnough well that naming is changeable, my understanding of your requirement and above definition of a skill is: \"a changable named value with stacked mathematical calculations that can be applied and altered at runtime\" where these are used and whether they are for a humidifier calculation or a player health is irrelevant. I just use game based glossary/naming convention to hopefully have an easy to relate to example. If this is incorrect what is the requirements for this system?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T17:23:21.200",
"Id": "72802",
"Score": "0",
"body": "@CantGetEnough I think the disconnect is that I view your question as actually two questions. 1) how do i store a large number of potentially reusable modifiers and 2) how can I apply these reusable modifiers to values in my application while keeping everything well encapsulated. The two answers above answer (what I think is the harder one) question 2. The answer to question one as far as I am concerned is simply to put all of the values and names in a database and load them in and create your objects as opposed to static objects. Once you have a good answer to Q2 a factory will solve Q1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T17:27:17.237",
"Id": "72804",
"Score": "0",
"body": "I think it's kind of reversed. (again, firgive me, I'm a newbie and it takes some time for me to understand new stuff) In the example of storage, storage capacity would have to be Skill, and one of player's (in my understanding) \"skills\" would have to be modifier affecting this storage capacity. What I'm looking for is \"skill\" in form of a method that takes object on which it acts as parameter and return some result. Moreover, it would be great if these skills regarding their difference could still be stored in one container and be easily accessed from it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T17:35:21.657",
"Id": "72808",
"Score": "0",
"body": "Thing is that storage capacity normally is not affected by anything. That's why there is no need to use modifiers for it. The only thing that is going to affect that capacity is that \"skill\" im talking about all the time. And that's how it looks in most cases. Skill modifies value which normally is a plain not calculated value."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T16:18:02.607",
"Id": "42318",
"ParentId": "42278",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T09:24:12.867",
"Id": "42278",
"Score": "7",
"Tags": [
"c#",
"game",
"generics",
"hash-map",
"delegates"
],
"Title": "Game passive skill system"
}
|
42278
|
<p>Because the throughput of my radio and device is limited, I wanted to compress my control string. I decided to compress the command into an 8 bytes (quasi) string (throttle high, throttle low, pitch, roll, yaw plus/minus, yaw value, checksum, stop byte) and after parsing in four variables:</p>
<ul>
<li>Pitch (between -45° and 45°)</li>
<li>Roll (between -45° and 45°)</li>
<li>Yaw (between -180° and 180°)</li>
<li>Throttle (between 1000 and ~1900)</li>
</ul>
<p>Because Some number ranges don't fit into a single byte (0 to 255 number range), I used two instead (throttle: one byte for hundreds (1-9) and one byte for tenners (1-99); Yaw: One byte for plus or minus and one byte for 0° - 180°). I send and read these bytes as characters. Then I convert them into numbers (0-255). </p>
<p>I noticed that sometimes a few reads are totally out of range (e.g. value: -31001) but checksum test is OK. I don't know exactly why (maybe radio, maybe I caused unexpected behavior because of type conversions here). This is why I made an additional range test. Now the remote control seems to be reliable. </p>
<p>However I don't feel very nice about it, because I do signed/unsigned and! number range conversions, the checksum function is also not very reliable. Maybe someone has suggestions how to make the code better. </p>
<p>Code (The command stored in buffer is already red correctly until the stop byte and valid in length):</p>
<pre><code>bool Receiver::parse_radio(char *buffer) {
int16_t throttle_high = (uint8_t)buffer[0]; // 1. 1 - 9
int16_t throttle_low = (uint8_t)buffer[1]; // 2. 0 - 99
int16_t pit = (uint8_t)buffer[2] - 127; // 3. -45° - 45°
int16_t rol = (uint8_t)buffer[3] - 127; // 4. -45° - 45°
int16_t yaw_pm = (uint8_t)buffer[4] - 127; // 5. -1 || +1
int16_t yaw_val = (uint8_t)buffer[5]; // 6. yaw angle in degrees 180°
int16_t chk = (uint8_t)buffer[6]; // 7. checksum
int16_t thr = 1000 + (throttle_high * 100) + throttle_low;
int16_t yaw = yaw_val * yaw_pm;
// Calculate checksum
uint8_t checksum = 0;
for(int i = 0; i < 6; i++) {
checksum = (checksum + buffer[i]) << 1; // % 256 can be saved because of the uint8_t
}
// Validity check:
// First checksum
if(checksum != chk)
return false;
// Later other values
if(yaw_pm < -1 || yaw_pm > 1)
return false;
if(rol > 45 || rol < -45)
return false;
if(pit > 45 || pit < -45)
return false;
if(yaw > 180 || yaw < -180)
return false;
if(thr > RC_THR_80P || thr < RC_THR_MIN)
return false;
// Do rest here
return true;
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>I don't know exactly why (maybe radio, maybe I caused unexpected behavior because of type conversions here).</p>\n</blockquote>\n\n<p>Can you keep statistics on how many checksum errors there are?</p>\n\n<ul>\n<li>If there are many that implies that the communications link is noisy</li>\n<li>If there are few or none then it's more probably something else (e.g. a software error)</li>\n</ul>\n\n<p>I'm not sure that you're using a good checksum algorithm.; you might like to use a <a href=\"http://en.wikipedia.org/wiki/Cyclic_redundancy_check\" rel=\"nofollow\">CRC</a> instead.</p>\n\n<p>You're only using 7 of your 8 bytes so you could have a 2-byte CRC (or checksum).</p>\n\n<p>You could compress your data better:</p>\n\n<ol>\n<li>'1 - 9'</li>\n<li>'0 - 99' => 10 bits to store 0..999 throttle</li>\n<li>'-45° - 45°' => 7 bits to store 90 angle values</li>\n<li>'-45° - 45°' => 7 bits to store 90 angle values</li>\n<li>'-1 || +1'</li>\n<li>'yaw angle in degrees 180°' => 9 bits to store 360 angle values</li>\n</ol>\n\n<p>10+7+7+9 => 37 bits = 5 bytes.</p>\n\n<p>Alternatively 999 * 90 * 90 * 360 = 2913084000 which is less than 2<sup>32</sup>. So you could fit your data into 4 bytes and use a 4-byte CRC.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T11:27:05.337",
"Id": "72727",
"Score": "0",
"body": "For this I have to use bitmasks. I noticed, that appr. 1/20 commands fails checksum and maybe one of ~200 is out of range. But I was not doing specific statistics. I will make an update if i did."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T11:47:00.903",
"Id": "72731",
"Score": "0",
"body": "You don't need bitmasks. To encode to a 4-byte unsigned integer, use this formula: _throttle_ + 1000* _pitch_ + 1000*91* _roll_ + 1000*91*91* _yaw_ where the variables e.g. _pitch_ are zero-based unsigned integers. The decode the 4-byte number, use the equivalent division `/` and remainder `%` operators."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T12:11:39.873",
"Id": "72736",
"Score": "0",
"body": "1/20 is a lot of errors. Assuming those are hardware/communications errors (not software errors) I suggest a strong CRC. For improved error detection you could also transmit each packet twice, and ensure that they match as well as passing their CRC check."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T10:59:04.150",
"Id": "42284",
"ParentId": "42282",
"Score": "2"
}
},
{
"body": "<p>I suggest you cast you buffer elements to int16_t not uint8_t.</p>\n\n<p>Here is an example</p>\n\n<pre><code>#include <stdio.h>\n#include <inttypes.h>\n\nint main()\n{\n char buffer = -45;\n printf(\"Original = %d\\n\", buffer);\n printf(\"uint8_t = %d\\n\", (uint8_t)buffer);\n printf(\"int16_t = %d\\n\", (int16_t)buffer);\n\n int16_t a = (uint8_t)buffer - 127;\n int16_t b = (int16_t)buffer - 127;\n printf(\"a = %d\\n\", a);\n printf(\"b = %d\\n\", b);\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Original = -45\nuint8_t = 211\nint16_t = -45\na = 84\nb = -172\n</code></pre>\n\n<p>As you can see in the second line, when you change a negative integer to an unsigned integer it cannot retain its negative status and instead becomes a large positive number.</p>\n\n<p>Edit:\nSorry I didn't realize the date on this question. I guess I'll just leave it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-13T11:56:20.650",
"Id": "87264",
"Score": "0",
"body": "I like the answer anyway. I changed some uint8 to 16. Exception is the checksum. However not tested yet."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-09T11:25:06.070",
"Id": "49324",
"ParentId": "42282",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "42284",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T10:28:34.763",
"Id": "42282",
"Score": "1",
"Tags": [
"c++",
"c",
"arduino"
],
"Title": "Enhancing parser for 8 byte command string (expect problems with type conversions) for Arduino/Radio communication"
}
|
42282
|
<p>I have written the following script that I'd like to have reviewed:</p>
<pre><code>#!/usr/bin/python
import os
os.system('hg tags > tags.txt')
file = 'tags.txt'
path = os.path.join(os.getcwd(), file)
fp = open(path)
for i, line in enumerate(fp):
if i == 1:
latestTagLine = line
elif i == 2:
previousTagLine = line
elif i > 4:
break
fp.close()
revLatestTag = latestTagLine.split(':')
l = revLatestTag[0].split(' ')
revPreviousTag = previousTagLine.split(':')
p = revPreviousTag[0].split(' ')
command = 'hg log -r {}:{} > diff.txt'.format(l[-1],p[-1])
os.system(command)
</code></pre>
<p>Output of <em>hg tags</em> command:</p>
<blockquote>
<pre><code>tip 523:e317b6828206
TOOL_1.4 522:5bb1197f2e36
TOOL_1.3 515:7362c0effe40
TOOL_1.1 406:33379f244971
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T17:23:13.417",
"Id": "72801",
"Score": "3",
"body": "I don't normally edit the code in the question to fix the whitespace. However, since you double-spaced the entire post, including the `hg tags` output (which the code expects to be single-spaced), I assume that the double-spacing is unintentional, and have fixed it up."
}
] |
[
{
"body": "<ol>\n<li>Your code does not run. I'll assume <code>latestTagLine</code> should be indented once more and the ` is to be removed at the end of the line.</li>\n<li><del>You have way too much blank lines, it doesn't help anyone.</del> <em>Formatting subsequently cleaned up.</em></li>\n<li>You could use <a href=\"http://docs.python.org/release/2.5/whatsnew/pep-343.html\" rel=\"nofollow\"><code>with</code> statement</a> to make your code clearer</li>\n<li>You don't need to iterate on fp is all you need is the second and the third line. The easiest solution would be to use <code>readlines</code>. There could be a performance drawback if the file was big at the beginning. This can easily be fixed by redirecting the output of <code>hg tags</code> in <code>head -n 4</code> at the beginning.</li>\n</ol>\n\n<p>At the end, my code would be :</p>\n\n<pre><code>import os\nos.system('hg tags > tags.txt')\nwith open(os.path.join(os.getcwd(), 'tags.txt')) as fp:\n lines = fp.readlines()\n l = lines[1].split(':')[0].split(' ')[-1]\n p = lines[2].split(':')[0].split(' ')[-1]\ncommand = 'hg log -r {}:{} > diff.txt'.format(l,p)\nos.system(command)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T12:13:25.473",
"Id": "42293",
"ParentId": "42285",
"Score": "3"
}
},
{
"body": "<p>You didn't specify that you wanted to leave a <code>tags.txt</code> file as an intentional side-effect of your script. I'm going to assume that it's an unwanted temporary file. In that case, you can read the output of <code>hg</code> directly through a pipe. Furthermore, the file object can be <a href=\"http://docs.python.org/2/library/stdtypes.html#file.next\" rel=\"nofollow\">used as an iterator</a> to fetch just two lines, with no for-loop.</p>\n\n<pre><code>from subprocess import Popen, PIPE\n\n# Read the first two lines of `hg tags`\nwith Popen(['hg', 'tags'], stdout=PIPE).stdout as hg_log:\n latestTagLine = hg_log.next()\n previousTagLine = hg_log.next()\n</code></pre>\n\n<p>The code to interpret each line is repeated, and therefore deserves to be put into a reusable function. Instead of splitting, use a capturing regular expression.</p>\n\n<pre><code>import re\n\ndef parse_tag_line(line):\n match = re.match(r'^(.*) *(\\d+):(.*)', line)\n return dict([\n ('tag', match.group(1)),\n ('rev', match.group(2)),\n ('hash', match.group(3)),\n ])\n</code></pre>\n\n<p>Finish up by generating the output:</p>\n\n<pre><code>log_range = '%s:%s' % (latestTag['hash'], previousTag['hash'])\nwith open('diff.txt', 'w') as diff:\n Popen(['hg', 'log', '-r', log_range], stdout=diff)\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>Personally, I would prefer to just dump the output to <code>sys.stdout</code>, and use the shell to redirect the script's output to a file (<code>script > diff.txt</code>) instead of hard-coding <code>diff.txt</code> in the script itself. Then, the epilogue would become</p>\n\n<pre><code>log_range = '%s:%s' % (latestTag['hash'], previousTag['hash'])\nPopen(['hg', 'log', '-r', log_range])\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>Putting it all together:</p>\n\n<pre><code>import re\nfrom subprocess import Popen, PIPE\n\ndef parse_tag_line(line):\n match = re.match(r'^(.*) *(\\d+):(.*)', line)\n return dict([\n ('tag', match.group(1)),\n ('rev', match.group(2)),\n ('hash', match.group(3)),\n ])\n\n# Read the first two lines of `hg tags`\nwith Popen(['hg', 'tags'], stdout=PIPE).stdout as hg_log:\n latestTag = parse_tag_line(hg_log.next())\n previousTag = parse_tag_line(hg_log.next())\n\nlog_range = '%s:%s' % (latestTag['hash'], previousTag['hash'])\n\n# Write `hg log -r ...:...` to diff.txt\nwith open('diff.txt', 'w') as diff:\n Popen(['hg', 'log', '-r', log_range], stdout=diff)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T17:10:57.883",
"Id": "42324",
"ParentId": "42285",
"Score": "5"
}
},
{
"body": "<p>It is superfluous to write</p>\n\n<pre><code>file = 'tags.txt'\npath = os.path.join(os.getcwd(), file)\nfp = open(path)\n</code></pre>\n\n<p>since the <code>tags.txt</code> is automatically interpreted as a path relative to the current directory.</p>\n\n<p>This is sufficient:</p>\n\n<pre><code>fp = open('tags.txt')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T17:16:14.857",
"Id": "42326",
"ParentId": "42285",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "42324",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T11:03:04.667",
"Id": "42285",
"Score": "5",
"Tags": [
"python",
"parsing",
"child-process"
],
"Title": "Extract changesets between last two tags in Mercurial"
}
|
42285
|
<p>In C++, I have made a basic memset / memcpy / strcpy implementation, yet I am worried that they are slower than the STL equivalent, as they are probably made in assembly, which I do not know. Is there any way of making these quicker, still using C++?</p>
<pre><code>#define BYTE unsigned char
typedef BYTE byte;
void *__memset(void *_Dst, int _Val, UINT _Size)
{
BYTE *buf = (BYTE *)_Dst;
while (_Size--)
{
*buf++ = (BYTE)_Val;
}
return _Dst;
}
void *__memcpy(void *_Dst, const void *_Src, UINT _Size)
{
BYTE *buf = (BYTE *)_Dst;
BYTE *__Src = (BYTE *)_Src;
while (_Size--)
{
*buf++ = *__Src++;
}
return _Dst;
}
char *__strcpy(char *_Dst, const char *_Src)
{
while ((*_Dst++ = *_Src++) != '\0');
return _Dst;
}
</code></pre>
|
[] |
[
{
"body": "<p>You can test for yourself if your implementation is faster or slower than the \"official\" one: Simply write a test program that allocates large chunks of memory and then make a number of calls to your implementation and take the time. Then, rewrite your program to use the corresponding STL functions and repeat the time taking.</p>\n\n<p>About the performance, I would assume that it is faster to operate on data types as large as the word size of your architecture (64 bit, maybe only 32 bit) instead of 8 bit only (=byte aka char). The data type \"unsigned integer\" should do the trick.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T11:22:57.320",
"Id": "42287",
"ParentId": "42286",
"Score": "2"
}
},
{
"body": "<p>These are <a href=\"http://en.wikipedia.org/wiki/Runtime_library\" rel=\"nofollow\">Runtime library</a> functions, not STL (template library) functions.</p>\n\n<p>The run-time library is arguably part of the language (so you can use the built-in library functions and still be \"using C++\").</p>\n\n<p>It's possible that your compiler is able to generate these as <a href=\"https://www.google.com/search?q=intrinsic+strcpy\" rel=\"nofollow\">intrinsic functions</a>.</p>\n\n<p>Things you can try to make your functions faster:</p>\n\n<ul>\n<li>Use a compiler with a better optimizer</li>\n<li>Copy 4 or 8 bytes at a time</li>\n<li>If the buffers aren't aligned on a 4- or 8-byte boundary, copy 1 byte at a time until you come to a boundary alignment, and then copy 4 or 8 bytes at a time</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-29T14:06:10.540",
"Id": "104798",
"Score": "1",
"body": "See implementation and discussion here: http://www.noxeos.com/2013/08/06/code-optimisations/"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T11:32:45.223",
"Id": "42290",
"ParentId": "42286",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T11:07:12.597",
"Id": "42286",
"Score": "1",
"Tags": [
"c++",
"performance"
],
"Title": "C++ memset / memcpy / strcpy implementation performance"
}
|
42286
|
<p>I have a main menu in my application. It loads depending on the role of the user that I validate from a table in my data base, but I have to recreate this menu every time I call a new controller.</p>
<p>User Controller:</p>
<pre><code>class User extends Ci_Controller {
function __construct(){
parent::__construct();
if (!$this->session->userdata('session_user')) {
$this->session->set_flashdata("mensaje", 'No cuenta con permisos *');
redirect();
$this->session_usuario = 1;
}
$session_data = $this->session->userdata('session_user');
$image = $session_data['img'];
$nickname = $session_data['nick'];
$res = "";
$this->layout->setLayout('layout/admin');
$this->layout->setImage(base_url().$image);
$this->layout->setNick($nickname);
$data['module'] = $this->usuarios_model->seleccionarModulos($session_data['perfil'] );
for ($i=0; $i < count($data['module']) ; $i++) {
$info['functionality'] = $this->usuarios_model->seleccionarFuncionalidades( $session_data['usuario'], $data['module'][$i]['id']);
$data['module'][$i]['route'] = $this->load->view($data['module'][$i]['route'], $info, true);
}
foreach ($data['module'] as $key => $value) {
$res .= $value['route'];
}
$this->layout->setMenu($res);
}
</code></pre>
<p>And exactly the same in the Support Controller:</p>
<pre><code>class Support extends Ci_Controller {
private $user;
private $permiso;
private $order;
function __construct(){
parent::__construct();
if (!$this->session->userdata('session_user')) {
$this->session->set_flashdata("mensaje", 'No cuenta con permisos *');
redirect();
$this->session_usuario = 1;
}
$session_data = $this->session->userdata('session_user');
$image = $session_data['img'];
$nickname = $session_data['nick'];
$res = "";
$this->layout->setLayout('layout/admin');
$this->layout->setImage(base_url().$image);
$this->layout->setNick($nickname);
$data['module'] = $this->usuarios_model->seleccionarModulos($session_data['perfil'] );
for ($i=0; $i < count($data['module']) ; $i++) {
$info['functionality'] = $this->usuarios_model->seleccionarFuncionalidades( $session_data['usuario'], $data['module'][$i]['id']);
$data['module'][$i]['route'] = $this->load->view($data['module'][$i]['route'], $info, true);
}
foreach ($data['module'] as $key => $value) {
$res .= $value['route'];
}
$this->layout->setMenu($res);
}
</code></pre>
<p>I know that it's a wrong way to solve this problem, and I want to improve it and reuse the code.</p>
|
[] |
[
{
"body": "<p>You need to extend <code>CI_Controller</code> with your code and extend your classses from your custom class, not default. I'll try to explain:</p>\n\n<p>At first create MY_Controller.php at /application/core/ with next content:</p>\n\n<pre><code> <?php\n\n class MY_Controller extends CI_Controller {\n function __construct() {\n parent::__construct();\n // Your checks here\n }\n }\n\n ?>\n</code></pre>\n\n<p>Now edit your controllers like this:</p>\n\n<p><strong>was</strong></p>\n\n<pre><code>class Support extends Ci_Controller {\n</code></pre>\n\n<p><strong>will be</strong></p>\n\n<pre><code>class Support extends MY_Controller {\n</code></pre>\n\n<p>Now your controller will use constructor from your <code>MY_Controller</code> and still use CodeIgniter's default controller class.</p>\n\n<p>You can read more <a href=\"http://ellislab.com/codeigniter/user-guide/general/core_classes.html\" rel=\"nofollow\">from the manual</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-24T17:32:01.790",
"Id": "89208",
"Score": "0",
"body": "I agree, put all the shared code into MY_Controller and you'll save a lot of code improving maintainability!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T13:11:45.300",
"Id": "49070",
"ParentId": "42296",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T13:20:43.267",
"Id": "42296",
"Score": "2",
"Tags": [
"php",
"mvc",
"codeigniter",
"controller"
],
"Title": "CodeIgniter maintain data through Controllers"
}
|
42296
|
<p>I have tried to implement a basic vector type in C++, yet I am not sure if I can do anything any more efficiently.</p>
<pre><code>template < typename _Ty > class vector
{
public:
typedef _Ty *iterator;
typedef _Ty _Value_type;
typedef vector<_Ty> _Myt;
vector()
: __size(0), __capacity(10), __data((_Value_type *)calloc(10, sizeof(_Value_type)))
{
}
vector(_Myt &_Rhs)
: __data((_Value_type *)calloc((__capacity = _Rhs.size() + 10), sizeof(_Value_type)))
{
memcpy(__data, _Rhs.__data, (__size = _Rhs.size()) * sizeof(_Value_type));
}
~vector()
{
memset(__data, NULL, 1);
}
_Value_type *data() const
{
return __data;
}
_Myt &push_back(const _Value_type &_Rhs)
{
if (++__size > __capacity)
{
reserve(__capacity + 10);
}
__data[__size - 1] = _Rhs;
return *this;
}
_Myt &operator+=(const _Value_type &_Rhs)
{
return push_back(_Rhs);
}
UINT size() const
{
return __size;
}
UINT capacity() const
{
return __capacity;
}
iterator begin() const
{
return &__data[0];
}
iterator rbegin()
{
return reversed_adaptor().begin();
}
iterator end() const
{
return &__data[__size];
}
iterator rend()
{
return reversed_adaptor().end();
}
iterator find(const _Value_type &_Search) const
{
for (iterator i = begin(); i != end(); ++i)
{
if (*i == _Search)
{
return i;
}
}
return NULL;
}
bool contains(const _Value_type &_Search) const
{
return find(_Search) != NULL;
}
_Myt &operator=(_Myt &_Rhs)
{
reserve((__size = _Rhs.size()) + 10);
memcpy(__data, _Rhs.__data, _Rhs.size() * sizeof(_Value_type));
return *this;
}
_Value_type pop_back()
{
_Value_type temp = __data[__size -= 1];
resize(__size);
return temp;
}
const _Value_type &at(UINT _Base) const
{
if (_Base >= 0 && _Base < size())
{
return __data[_Base];
}
throw std::out_of_range("vector::at - out of range");
}
_Value_type &at(UINT _Base)
{
if (_Base >= 0 && _Base < size())
{
return __data[_Base];
}
throw std::out_of_range("vector::at - out of range");
}
_Value_type &operator[](UINT _Base)
{
return __data[_Base];
}
const _Value_type &operator[](UINT _Base) const
{
return __data[_Base];
}
_Myt &swap(_Myt &_Rhs)
{
std::swap(*this, _Rhs);
return *this;
}
_Myt &reserve(UINT _Capacity)
{
__data = (_Value_type *)realloc(__data, (__capacity = _Capacity) * sizeof(_Value_type));
return *this;
}
_Myt &resize(UINT _Size, _Value_type _Value = _Value_type())
{
int over = (_Size > __size), temp = __size;
__data = (_Value_type *)realloc(__data, (__capacity = (__size = _Size)) * sizeof(_Value_type));
if (over)
{
for (iterator i = &__data[temp]; i != end(); ++i)
{
*i = _Value;
}
}
return *this;
}
_Value_type erase(iterator _Iter)
{
if (_Iter == end())
{
return pop_back();
}
for (iterator i = _Iter; i + 1 != end(); ++i)
{
*i = *(i + 1);
}
return pop_back();
}
template < typename _Ty1 > bool operator==(const vector<_Ty1> &_Rhs)
{
if ((typeid(_Value_type) != typeid(_Ty1)) || size() != _Rhs.size())
{
return false;
}
for (iterator i = begin(), j = _Rhs.begin(); i != end(), j != _Rhs.end(); ++i, ++j)
{
if (*i != *j)
{
return false;
}
}
return true;
}
template < typename _Ty1 > bool operator!=(const vector<_Ty1> &_Rhs)
{
return !(*this == _Rhs);
}
bool empty()
{
return size > 0;
}
_Myt &reverse()
{
std::reverse(begin(), end());
return *this;
}
_Myt reversed_adaptor()
{
_Myt adaptor(*this);
return adaptor.reverse();
}
_Myt insert(iterator _Begin, iterator _End)
{
for (iterator i = _Begin; i != _End; ++i)
{
push_back(*i);
}
return *this;
}
private:
_Value_type *__data;
UINT __size, __capacity;
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T05:53:50.637",
"Id": "72928",
"Score": "2",
"body": "Stop using underscore at the beginning of your identifiers (the rules are non trivial). An initial underscore followed by a capitol letter or double underscore anywhere are actually **reserved** for use by the implementation. http://stackoverflow.com/a/228797/14065 This means you should not use them."
}
] |
[
{
"body": "<p>I think your <code>~vector()</code> destructor is doing the wrong thing:</p>\n\n<ul>\n<li>It should free the memory which you allocated using <code>calloc</code></li>\n<li>It shouldn't <code>memset</code> over the objects contained in the array</li>\n<li>My guess is that it should explicitly destroy the objects in the array, using the opposite of <a href=\"http://en.wikipedia.org/wiki/Placement_syntax#Default_placement\" rel=\"nofollow noreferrer\">placement new</a> ... perhaps by doing something like:</li>\n</ul>\n\n\n\n<pre><code>~vector\n{\n for (iterator i = begin(); i != end(); ++i)\n i->~_Ty();\n free(__data);\n}\n</code></pre>\n\n<p>Similarly the methods which create an object in the memory should use <a href=\"https://www.preney.ca/paul/archives/662\" rel=\"nofollow noreferrer\">placement new, for example as described here</a>.</p>\n\n<p>The vector you have at the moment probably works for types which have a trivial/non-existent constructor and destructor (for example <code>int</code>), but not for types which have a non-default constructor and destructor (for example <code>std::string</code>).</p>\n\n<hr>\n\n<p>Your <code>operator==</code> should be const (so that it can be used when <code>*this</code> is const).</p>\n\n<p>I suspect it shouldn't include the <code>typeid(_Value_type) != typeid(_Ty1)</code> expression: instead it shouldn't define the <code>_Ty1</code> template parameter, so that it can only be used to compare vectors which have an identical type.</p>\n\n<p><a href=\"http://www.cplusplus.com/reference/vector/vector/operators/\" rel=\"nofollow noreferrer\">This</a> suggests you code it as a free operator (an inline functions which takes two parameters), instead of as a method.</p>\n\n<hr>\n\n<p>Your <code>find</code> method should return <code>end()</code>, not <code>NULL</code>, if it fails to find.</p>\n\n<hr>\n\n<p>I suspect it's not safe for your <code>resize</code> to call <code>realloc</code>. For example, I might have a type like this ...</p>\n\n<pre><code>class A\n{\n A* self;\npublic:\n A() { self = this; }\n A(const A&) { ... to be supplied ... }\n const A& operator=(const A&) { ... to be supplied ... }\n A(A&&) { ... to be supplied ... }\n A& operator=(A&&) { ... to be supplied ... }\n}\n</code></pre>\n\n<p>... which remembers where itself exists in memory. If you call <code>realloc</code> that will do a bitwise copy of existing elements, which will cause the moved instance of A to have invalid <code>self</code> pointers.</p>\n\n<p>Instead you may need to create a new buffer, and explicitly move all existing instances from the old buffer into their new locations in the new buffer.</p>\n\n<hr>\n\n<p>Your identifiers shouldn't begin with an <code>_</code> underscore. Those identifiers are <a href=\"https://stackoverflow.com/a/228797/49942\">reserved for the compiler and/or the standard run-time library</a>.</p>\n\n<hr>\n\n<p>Your <code>insert</code> method doesn't make much sense: its signature doesn't match any of the <a href=\"http://www.cplusplus.com/reference/vector/vector/insert/\" rel=\"nofollow noreferrer\">three standard insert methods</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T13:39:06.177",
"Id": "42300",
"ParentId": "42297",
"Score": "7"
}
},
{
"body": "<p>Some other points, in completely random order as I came across them...</p>\n\n<ol>\n<li><p><code>pop_back</code>, <code>pop_front</code> and <code>erase</code> should have return type <code>void</code></p>\n\n<p>The reason here is that most of the time the caller does <em>not</em> need the erased object and if you return it, the copy has to be made and it can be pretty expensive. Filling a vector (if done properly, see 3. below) amortizes to just 2 copies per inserted element, so vector is a good choice even for quite complex objects and you don't want useless extra copies.</p></li>\n<li><p><code>calloc</code> is pointless, since you are obliged to construct the objects anyway.</p></li>\n<li><p><code>reserve(__capacity + 10);</code> in <code>push_back</code> is violation of the complexity contract.</p>\n\n<p><code>push_back</code> is required amortized <code>O(1)</code>, which means the reallocation has to be in <em>geometric</em> sequence. Usual values are <code>reserve(__capacity * 2)</code> or <code>reserve(__capacity + (__capacity+1)/2)</code>, and minimal capacity of 16 or so.</p></li>\n<li><p>Just like the <code>realloc</code> already mentioned by ChrisW, calling <code>memcpy</code> on array containing non-POD objects (and vector is for containing non-POD objects) is an UndefinedBehaviour™.</p>\n\n<p>The compiler may choose to do anything it pleases from simply crashing all the way over formatting your hard drive to making daemons fly out of your nose. And modern compilers can be real bitches when punishing UndefinedBehaviour™. Effect of some optimizations applied to incorrect code is next to impossible to understand.</p>\n\n<p>You have to copy the elements one by one with <code>std::copy</code> or a loop to properly invoke constructors and you have to call destructors afterwards.</p></li>\n<li><p>Assigning to unconstructed memory in <code>push_back</code> and <code>resize</code> is also UndefinedBehaviour™.</p>\n\n<p>Non-POD object has to be constructed by constructor and destructed by destructor. Use the placement new:</p>\n\n<pre><code>new (i) _Value_type(_Rhs);\n</code></pre></li>\n<li><p>C++ does not have any type called <code>UINT</code>.</p>\n\n<p>The size type should always be <code>std::size_t</code></p></li>\n<li><p><code>swap()</code> method is another violation of the complexity contract.</p>\n\n<p>Vector <code>swap()</code> is supposed to be O(1). It should simply swap the pointers. That's far from what <code>std::swap</code> would do in C++03 (in C++11 it <em>could</em> do the right thing <em>if</em> you defined the move constructors, but you didn't).</p>\n\n<p>Furthermore <code>std::swap</code> should be overloaded for vector to call the <code>swap()</code> method. Yes, you are allowed and sometimes required to overload functions/specialize classes in <code>std</code> for types you define and this is one such case.</p></li>\n<li><p>You correctly use <code>reserve</code> in <code>push_back</code>, but you fail to do the same in <code>insert</code>.</p></li>\n<li><p>The special condition for <code>i == end()</code> in <code>erase</code> is superfluous.</p>\n\n<p>It is not allowed to pass non-deferrable iterator (end or invalid) to <code>erase</code>.</p></li>\n<li><p>Your <code>erase</code> returns useless element (but see 1. anyway).</p>\n\n<p>You return the value of the final pop_back, which returns the last element. If you deleted any other element than the last, it's not the one that was just deleted. Completely useless. You shouldn't be returning anything anyway.</p></li>\n<li><p>Const correctness failures.</p>\n\n<p>A <code>const</code> method should only ever return pointers and references to <code>const</code>.</p>\n\n<p>Standard collections have <code>iterator</code> and <code>const_iterator</code> and all methods that return iterators (<code>begin()</code>, <code>end()</code>, <code>find()</code> etc.) have non-const overload returning <code>iterator</code> and const overload returning <code>const_iterator</code>. If you use plain pointers (which is legal, the iterator concept is designed so that pointers are iterators), you should define <code>const_iterator</code> to <code>_Value_type const *</code> (const applies to the part before it, so this is the correct syntax; even in C).</p></li>\n<li><p><code>rbegin</code> and <code>rend</code> return dangling pointers (provided you fix the memory leak in destructor).</p>\n\n<p>Another instance of UndefinedBehaviour™. The <code>reversed_adaptor</code> returns a new instance. By value, which is inefficient, but legal. However the return value is temporary and it will only have to have <code>begin</code>/<code>end</code> called on it and than it will be destroyed at the next semicolon. When you fix the memory leak and actually free the memory in destructor, the returned pointers will point to unallocated memory.</p></li>\n<li><p><code>rbegin</code> and <code>rend</code> don't return valid iterators to invocant.</p>\n\n<p>The reverse iterators have to point to the container, <em>not</em> to a copy. Since you can't use plain pointers for reverse operators, it's rather a lot of work to define them. Boost has <a href=\"http://www.boost.org/libs/iterator/doc/reverse_iterator.html\">a generic implementation</a></p></li>\n<li><p>You are missing most of the required typedefs.</p>\n\n<p>There should be <code>value_type</code>, <code>reference</code>, <code>pointer</code>, <code>const_reference</code>, <code>const_pointer</code>, <code>const_iterator</code>, <code>reverse_iterator</code>, <code>const_reverse_iterator</code>, <code>size_type</code> (should be <code>std::size_t</code>) and <code>difference_type</code> (should be <code>std::ptrdiff_t</code>). And <code>allocator_type</code>, which is next point.</p></li>\n<li><p>You should be using allocator instead of <code>malloc</code> and <code>free</code>.</p>\n\n<p>Allocator abstracts the memory allocation, wraps the funny placement new and explicit destructor call syntaxes and makes the allocation and construction separate actions as appropriate for likes of vector.</p>\n\n<p>The default allocator, <code>std::allocator</code> uses global operators <code>new[]</code> and <code>delete[]</code> for allocation, but users may want to provide special allocators.</p>\n\n<p>Also the allocator will properly throw <code>std::bad_alloc</code> as will <code>new[]</code> and <code>delete[]</code> (except on non-conforming platforms like Microsoft Windows) if you use them directly, but when using <code>malloc</code>, you have to check for NULL and throw <code>std::bad_alloc</code> on allocation failure yourself.</p></li>\n</ol>\n\n<p>Plus all the problems already mentioned by chrisW are valid too and I am almost certain I still didn't find everything.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T21:50:42.847",
"Id": "42341",
"ParentId": "42297",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "42341",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T13:20:47.847",
"Id": "42297",
"Score": "12",
"Tags": [
"c++",
"optimization",
"vectors"
],
"Title": "C++ vector implementation"
}
|
42297
|
<p>I am working on the largest Java program I have undertaken to date and feel uncertain in my current code practices. I think that I state and repeat things that don't need to be which can become a headache as development goes on. Specifically, in my GridBag Constraints. I have worked with GridBagLayout before and had gotten what I needed without declaring the width and height of cells that are only (1,1), yet here I was having problems so I decided to define everything I could think of for every cell and I got what I wanted, but now I probably have unnecessary code.</p>
<p>My other concern is in regards to utilizing the EDT. I've done my best to find lessons and videos on the subject but still feel that I have a lack of sufficient understanding.</p>
<p><strong>FrontierMain.java:</strong></p>
<pre><code>public class FrontierMain {
public FrontierMain(){
JFrame frame = new JFrame();
frame.setTitle("Frontier Insulation Labor Record Tool");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
LaborRecordPanel recordPanel = new LaborRecordPanel();
frame.add(recordPanel.scrollPane);
frame.pack();
frame.setLocationRelativeTo ( null );
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
FrontierMain fm = new FrontierMain();
}
});
System.out.println("Hello, World");
}
}
</code></pre>
<p><strong>LaborRecordPanel.java:</strong></p>
<pre><code>public class LaborRecordPanel implements
Printable, ActionListener {
private Color shade = new Color(201,201,201); // color for shaded cells
private JLabel dateSpace[] = new JLabel[7];
private JLabel grandTotalSpace = new JLabel();
private JLabel locAndDescSpace = new JLabel();
private JLabel personnelSpace[] = new JLabel[10]; // empty cells
private JLabel calendarGridLines[] = new JLabel[300]; //empty labels for gridlines
private ImageIcon logoIcon = new ImageIcon("Images/fici_logo1.jpg");
private JLabel logoLabel = new JLabel(logoIcon);
private JLabel authorizedBy = new JLabel("AUTHORIZED BY:_____________________________________________________________");
private JLabel toCertify = new JLabel("THIS IS TO CERTIFY THAT THE ABOVE LABOR HAS BEEN PERFORMED.");
private JLabel laborRecordNO = new JLabel("NO.");
private JLabel nameOfJob = new JLabel("NAME OF JOB:");
private JLabel customerPO = new JLabel("CUSTOMER PO #:");
private JLabel contractNO = new JLabel("CONTRACT NO.");
private JLabel weekEnding = new JLabel("WEEK ENDING");
private JLabel personnelList = new JLabel("<html>LIST SUPERVISION &<br> CRAFT LABOR BELOW:</html>");
private JLabel locAndDescriptionLabel = new JLabel("LOCATION AND DESCRIPTION:");
private JLabel personnelTitle = new JLabel("TITLE");
private JLabel[] titleSpace= new JLabel[10];
private JLabel calendarTitle = new JLabel("NUMBER OF HOURS WORKED @ SITE");
private JLabel dayHeading = new JLabel("DAY");
private JLabel dateHeading = new JLabel("DATE");
private JLabel[] ot2 = new JLabel[10];
private JLabel[] ot1 = new JLabel[10];
private JLabel[] st = new JLabel[10];
private JLabel mon = new JLabel("MON");
private JLabel tues = new JLabel("TUES");
private JLabel wed = new JLabel("WED");
private JLabel thur = new JLabel("THUR");
private JLabel fri = new JLabel("FRI");
private JLabel sat = new JLabel("SAT");
private JLabel sun = new JLabel("SUN");
private JLabel totalHours = new JLabel("<html>TOTAL<br> HOURS</html>");
private JLabel ratePerHour = new JLabel("<html>RATE<br> PER<br> HOUR</html>");
private JLabel totalAmount = new JLabel("<html>TOTAL<br> AMOUNT</html>");
private JLabel grandTotal = new JLabel("TOTAL");
JButton printTest = new JButton("PrintTest");
JPanel rp = new JPanel();
JPanel outer = new JPanel();
JPanel buttonPanel = new JPanel();
JScrollPane scrollPane = new JScrollPane(outer);
LaborRecordPanel(){
outer.setLayout(new BoxLayout(outer,BoxLayout.Y_AXIS ));
outer.add(rp);
outer.add(buttonPanel);
printTest.addActionListener(this);
buttonPanel.add(printTest);
rp.setBorder(null);
rp.setPreferredSize(new Dimension(1295,1830 ));
rp.setMinimumSize(new Dimension(1295,1830 ));
rp.setMaximumSize(new Dimension(1295,1830 ));
scrollPane.setPreferredSize(new Dimension(1295,800 ));
scrollPane.getVerticalScrollBar().setUnitIncrement(50); //increase the scroll speed
for (int i = 0; i <= 9; i++) titleSpace[i] = new JLabel(); // create mechanic labels
for (int i = 0; i <= 9; i++) //create labels for work time
{
ot2[i] = new JLabel("OT-2");
ot1[i] = new JLabel("OT-1");
st[i] = new JLabel("S.T.");
}
//create empty labels for gridlines
for (int i = 0; i <= 9; i++) personnelSpace[i] = new JLabel();
for (int i = 0; i <= 6; i++) dateSpace[i] = new JLabel();
for (int i = 0; i <= 299; i++) calendarGridLines[i] = new JLabel();
GridBagLayout gridbag = new GridBagLayout();
rp.setBackground(Color.WHITE);
GridBagConstraints gbc = new GridBagConstraints();
rp.setLayout(gridbag);
//row 0////////////////////////////////////////////////////////////
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 10;
gbc.gridy = 0;
gbc.weightx = 0;
gbc.weighty = 1;
gbc.gridheight = 1;
gbc.gridwidth = 1;
laborRecordNO.setHorizontalAlignment(JLabel.CENTER);
laborRecordNO.setFont(new Font("Dialog", Font.PLAIN, 18));
gridbag.setConstraints(laborRecordNO, gbc);
rp.add(laborRecordNO, gbc);
//row 1////////////////////////////////////////////////////////////
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 13;
gridbag.setConstraints(logoLabel, gbc);
rp.add(logoLabel, gbc);
//row 2////////////////////////////////////////////////////////////
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridheight = 1;
gbc.gridwidth = 1;
nameOfJob.setFont(nameOfJob.getFont().deriveFont(18.0f));
gridbag.setConstraints(nameOfJob, gbc);
rp.add(nameOfJob, gbc);
gbc.gridx = 5;
gbc.gridy = 2;
gbc.gridheight = 1;
gbc.gridwidth = 10;
contractNO.setFont(contractNO.getFont().deriveFont(18.0f));
gridbag.setConstraints(contractNO, gbc);
rp.add(contractNO, gbc);
//row 3////////////////////////////////////////////////////////////
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridheight = 1;
gbc.gridwidth = 1;
customerPO.setFont(customerPO.getFont().deriveFont(18.0f));
gridbag.setConstraints(customerPO, gbc);
rp.add(customerPO, gbc);
gbc.gridx = 5;
gbc.gridy = 3;
gbc.gridheight = 1;
gbc.gridwidth = 10;
weekEnding.setFont(weekEnding.getFont().deriveFont(18.0f));
gridbag.setConstraints(weekEnding, gbc);
rp.add(weekEnding, gbc);
//row 4////////////////////////////////////////////////////////////
gbc.gridx = 0;
gbc.gridy = 4;
gbc.gridheight = 3;
gbc.gridwidth = 1;
gbc.weightx = .01;
personnelList.setHorizontalAlignment(JLabel.CENTER);
personnelList.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
personnelList.setFont(personnelList.getFont().deriveFont(18.0f));
gridbag.setConstraints(personnelList, gbc);
rp.add(personnelList, gbc);
gbc.gridx = 1;
gbc.gridy = 4;
gbc.gridheight = 3;
gbc.gridwidth = 1;
gbc.weightx = .42;
personnelTitle.setHorizontalAlignment(JLabel.CENTER);
personnelTitle.setBorder(BorderFactory.createMatteBorder(1, 0, 1, 0, Color.BLACK));
personnelTitle.setFont(personnelTitle.getFont().deriveFont(18.0f));
gridbag.setConstraints(personnelTitle, gbc);
rp.add(personnelTitle, gbc);
gbc.gridx = 2;
gbc.gridy = 4;
gbc.gridwidth = 8;
gbc.gridheight = 1;
gbc.weightx = .5;
calendarTitle.setHorizontalAlignment(JLabel.CENTER);
calendarTitle.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 0, Color.BLACK));
calendarTitle.setFont(calendarTitle.getFont().deriveFont(18.0f));
gridbag.setConstraints(calendarTitle, gbc);
rp.add(calendarTitle, gbc);
gbc.gridx = 10;
gbc.gridy = 4;
gbc.gridheight = 3;
gbc.gridwidth = 1;
gbc.weightx = .05;
totalHours.setHorizontalAlignment(JLabel.CENTER);
totalHours.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLACK));
totalHours.setFont(totalHours.getFont().deriveFont(18.0f));
gridbag.setConstraints(totalHours, gbc);
rp.add(totalHours, gbc);
gbc.gridx = 11;
gbc.gridy = 4;
gbc.gridheight = 3;
gbc.gridwidth = 1;
gbc.weightx = .07;
ratePerHour.setHorizontalAlignment(JLabel.CENTER);
ratePerHour.setBorder(BorderFactory.createMatteBorder(1, 0, 1, 0, Color.BLACK));
ratePerHour.setFont(ratePerHour.getFont().deriveFont(18.0f));
gridbag.setConstraints(ratePerHour, gbc);
rp.add(ratePerHour, gbc);
gbc.gridx = 12;
gbc.gridy = 4;
gbc.gridheight = 3;
gbc.gridwidth = 1;
gbc.weightx = .07;
totalAmount.setHorizontalAlignment(JLabel.CENTER);
totalAmount.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLACK));
totalAmount.setFont(totalAmount.getFont().deriveFont(18.0f));
gridbag.setConstraints(totalAmount, gbc);
rp.add(totalAmount, gbc);
//row 5//////////////////////////////////////////////////////////////////
gbc.gridx = 2;
gbc.gridy = 5;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = .07;
dayHeading.setHorizontalAlignment(JLabel.CENTER);
dayHeading.setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
dayHeading.setFont(dayHeading.getFont().deriveFont(18.0f));
gridbag.setConstraints(dayHeading, gbc);
rp.add(dayHeading, gbc);
gbc.gridx = 3;
gbc.gridy = 5;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = .07;
mon.setHorizontalAlignment(JLabel.CENTER);
mon.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
mon.setFont(mon.getFont().deriveFont(18.0f));
gridbag.setConstraints(mon, gbc);
rp.add(mon, gbc);
gbc.gridx = 4;
gbc.gridy = 5;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = .07;
tues.setHorizontalAlignment(JLabel.CENTER);
tues.setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
tues.setFont(tues.getFont().deriveFont(18.0f));
gridbag.setConstraints(tues, gbc);
rp.add(tues, gbc);
gbc.gridx = 5;
gbc.gridy = 5;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = .07;
wed.setHorizontalAlignment(JLabel.CENTER);
wed.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
wed.setFont(wed.getFont().deriveFont(18.0f));
gridbag.setConstraints(wed, gbc);
rp.add(wed, gbc);
gbc.gridx = 6;
gbc.gridy = 5;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = .07;
thur.setHorizontalAlignment(JLabel.CENTER);
thur.setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
thur.setFont(thur.getFont().deriveFont(18.0f));
gridbag.setConstraints(thur, gbc);
rp.add(thur, gbc);
gbc.gridx = 7;
gbc.gridy = 5;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = .09;
fri.setHorizontalAlignment(JLabel.CENTER);
fri.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
fri.setFont(fri.getFont().deriveFont(18.0f));
gridbag.setConstraints(fri, gbc);
rp.add(fri, gbc);
gbc.gridx = 8;
gbc.gridy = 5;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = .07;
sat.setHorizontalAlignment(JLabel.CENTER);
sat.setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
sat.setFont(sat.getFont().deriveFont(18.0f));
gridbag.setConstraints(sat, gbc);
rp.add(sat, gbc);
gbc.gridx = 9;
gbc.gridy = 5;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = .07;
sun.setHorizontalAlignment(JLabel.CENTER);
sun.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
sun.setFont(sun.getFont().deriveFont(18.0f));
gridbag.setConstraints(sun, gbc);
rp.add(sun, gbc);
//row 6//////////////////////////////////////////////////////////////
gbc.gridx = 2;
gbc.gridy = 6;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = 0;
dateHeading.setHorizontalAlignment(JLabel.CENTER);
dateHeading.setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
dateHeading.setFont(dateHeading.getFont().deriveFont(18.0f));
gridbag.setConstraints(dateHeading, gbc);
rp.add(dateHeading, gbc);
int dateSpaceIndex = 3;
boolean flip = true;
for (int k = 0; k <= 6; k++)//create gridlines for day area
{
gbc.gridx = dateSpaceIndex;
gbc.gridy = 6;
gbc.gridheight = 1;
gbc.gridwidth = 1;
if(flip) dateSpace[k].setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
else dateSpace[k].setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
gridbag.setConstraints(dateSpace[k], gbc);
rp.add(dateSpace[k], gbc);
dateSpaceIndex++;
flip = !flip;
}
//row 13-36 plus 7-12 time worked labels//////////////////////////
for (int r = 0; r <= 9; r++)
{
gbc.gridx = 1;
gbc.gridy = 7 + (3*r);
gbc.gridheight = 3;
gbc.gridwidth = 1;
titleSpace[r].setHorizontalAlignment(JLabel.CENTER);
titleSpace[r].setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
titleSpace[r].setFont(titleSpace[r].getFont().deriveFont(18.0f));
gridbag.setConstraints(titleSpace[r], gbc);
rp.add(titleSpace[r], gbc);
}
for (int c = 0; c <= 9; c++){
gbc.gridx = 2;
gbc.gridy = 7 + (3*c);
gbc.gridheight = 1;
gbc.gridwidth = 1;
ot2[c].setHorizontalAlignment(JLabel.CENTER);
ot2[c].setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
ot2[c].setFont(ot2[c].getFont().deriveFont(18.0f));
gridbag.setConstraints(ot2[c], gbc);
rp.add(ot2[c], gbc);
gbc.gridx = 2;
gbc.gridy = 8 + (3*c);
gbc.gridheight = 1;
gbc.gridwidth = 1;
ot1[c].setHorizontalAlignment(JLabel.CENTER);
ot1[c].setOpaque(true);
ot1[c].setBackground(shade);
ot1[c].setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
ot1[c].setFont(ot1[c].getFont().deriveFont(18.0f));
gridbag.setConstraints(ot1[c], gbc);
rp.add(ot1[c], gbc);
gbc.gridx = 2;
gbc.gridy = 9 + (3*c);
gbc.gridheight = 1;
gbc.gridwidth = 1;
st[c].setHorizontalAlignment(JLabel.CENTER);
st[c].setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
st[c].setFont(st[c].getFont().deriveFont(18.0f));
gridbag.setConstraints(st[c], gbc);
rp.add(st[c], gbc);
}
//row 37/////////////////////////////////////////////////////////////////
gbc.gridx = 0;
gbc.gridy = 37;
gbc.gridheight = 1;
gbc.gridwidth = 1;
locAndDescriptionLabel.setFont(locAndDescriptionLabel.getFont().deriveFont(18.0f));
gridbag.setConstraints(locAndDescriptionLabel, gbc);
rp.add(locAndDescriptionLabel);
gbc.gridx = 11;
gbc.gridy = 37;
gbc.gridheight = 1;
gbc.gridwidth = 1;
grandTotal.setHorizontalAlignment(JLabel.CENTER);
grandTotal.setOpaque(true);
grandTotal.setBackground(Color.BLACK);
grandTotal.setForeground(Color.WHITE);
grandTotal.setBorder(BorderFactory.createLineBorder(Color.BLACK,1));
grandTotal.setFont(grandTotal.getFont().deriveFont(18.0f));
gridbag.setConstraints(grandTotal, gbc);
rp.add(grandTotal);
gbc.gridx = 12;
gbc.gridy = 37;
gbc.gridwidth = 1;
gbc.gridheight = 1;
grandTotalSpace.setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
gridbag.setConstraints(grandTotalSpace, gbc);
rp.add(grandTotalSpace);
//row 38////////////////////////////////////////////////////////////////
gbc.gridx = 0;
gbc.gridy = 38;
gbc.gridwidth = 10;
gbc.gridheight = 1;
gbc.ipady = 80;
locAndDescSpace.setBorder(BorderFactory.createLineBorder(Color.BLACK,1));
gridbag.setConstraints(locAndDescSpace, gbc);
rp.add(locAndDescSpace);
//row 39////////////////////////////////////////////////////////////////
gbc.ipady = 0; //reset to default
gbc.gridx = 0;
gbc.gridy = 39;
gbc.gridheight = 1;
gbc.gridwidth = 13;
toCertify.setFont(toCertify.getFont().deriveFont(18.0f));
gridbag.setConstraints(toCertify, gbc);
rp.add(toCertify);
//row 40///////////////////////////////////////////////////////////////
gbc.gridx = 0;
gbc.gridy = 40;
gbc.gridheight = 1;
gbc.gridwidth = 13;
authorizedBy.setFont(authorizedBy.getFont().deriveFont(18.0f));
gridbag.setConstraints(authorizedBy, gbc);
rp.add(authorizedBy);
for (int r = 0; r <= 9; r++)//gridlines for personnel space
{
gbc.gridx = 0;
gbc.gridy = 7 + (3*r);
gbc.gridheight = 3;
gbc.gridwidth = 1;
personnelSpace[r].setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
gridbag.setConstraints(personnelSpace[r], gbc);
rp.add(personnelSpace[r]);
}
//create calendar grid lines
int yPointer = 7;
int xPointer = 3;
int shadePtr = 8;
for (int j = 0; j <= 299; j++)
{
gbc.gridx = xPointer;
gbc.gridy = yPointer;
gbc.gridheight = 1;
gbc.gridwidth = 1;
calendarGridLines[j].setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
if (yPointer == shadePtr){ //if row number = shadePtr then color the cell
calendarGridLines[j].setOpaque(true);
calendarGridLines[j].setBackground(shade);
}
gridbag.setConstraints(calendarGridLines[j], gbc);
rp.add(calendarGridLines[j]);
xPointer++; //go to next cell in row
j++; //use the next jlabel
gbc.gridx = xPointer;
gbc.gridy = yPointer;
gbc.gridheight = 1;
gbc.gridwidth = 1;
calendarGridLines[j].setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
if (yPointer == shadePtr){ //if row number = shadePtr then color the cell
calendarGridLines[j].setOpaque(true);
calendarGridLines[j].setBackground(shade);
}
gridbag.setConstraints(calendarGridLines[j], gbc);
rp.add(calendarGridLines[j]);
xPointer++; //go to next cell in row
if(xPointer == 13) //if end of column then go to next row and reset column pointer to 3 and increment shade pointer by 3
{
yPointer++; //go down a row
xPointer = 3;
if((j % 3) == 0) {
shadePtr = yPointer;
}
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if (printJob.printDialog()){
try{
printJob.print();
}
catch(Exception ex){
throw new RuntimeException(ex);
}
}
}
@Override
public int print(Graphics g, PageFormat pf, int index)
throws PrinterException {
Graphics2D g2 = (Graphics2D)g;
if (index >= 1){
return Printable.NO_SUCH_PAGE;
}
else {
AffineTransform originalTransform = g2.getTransform();
double scaleX = pf.getImageableWidth() / rp.getWidth();
double scaleY = pf.getImageableHeight() / rp.getHeight();
// Maintain aspect ratio
double scale = Math.min(scaleX, scaleY);
g2.translate(pf.getImageableX(), pf.getImageableY());
g2.scale(scale, scale);
rp.printAll(g2);
g2.setTransform(originalTransform);
return Printable.PAGE_EXISTS;
}
}
}
</code></pre>
<p><strong>EDIT:</strong> Images of GUI may help. Top and bottom half respectively.</p>
<p><img src="https://i.stack.imgur.com/F6O79.png" alt="top"></p>
<p><img src="https://i.stack.imgur.com/OIdMM.png" alt="bottom"></p>
|
[] |
[
{
"body": "<p>From a quick look at your code, I can say that your constructor is too big. I would suggest to refactored your constructor into smaller functions with only one task to do. I would probably have different method for each \"zone\" or \"group\" of elements.</p>\n\n<p>There is a lot of magic numbers in your code. Why 5? Why not 6 ? You could use variable with names instead of directly use the number. It would help grasp easily why you're using 5 (Maybe it's the size of a ideal row, etc). A good example of a magic number would be this code :</p>\n\n<pre><code>private JLabel[] ot2 = new JLabel[10];\nprivate JLabel[] ot1 = new JLabel[10];\nprivate JLabel[] st = new JLabel[10];\n</code></pre>\n\n<p>Why are you using 10 ? I guess is the number of columns or somethings like that. But what happens if you need to change it to 11 ? You need to replace each occurence of 10 to 11. But 10 conveys a meaning, it's the number of columns, so you could have <code>private final int NUMBERS_OF_COLUMNS = 10</code>. It would clear to anyone reading your code that you're creating an of labels for each columns. </p>\n\n<pre><code>if(flip) dateSpace[k].setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));\nelse dateSpace[k].setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));\n</code></pre>\n\n<p>It was hard at first glance to see that there was an if-else here. You should use <code>{}</code> to help see at first glance that there is an if statement. This will improve readability and will help a lot with unsuspected bugs or changing the code later on. </p>\n\n<p>Use only one style of formatting. Sometimes you're using :</p>\n\n<pre><code>for (...)\n{\n\n}\n</code></pre>\n\n<p>And I see that you use this variant too :</p>\n\n<pre><code>for (...) {\n\n}\n</code></pre>\n\n<p>Choose only one and keep it in all your code (this is something that an IDE can do automatically). </p>\n\n<p>One final tips that I could give you, find relevant names for your variables. You're doing a good job for the majority of your code, but sometimes you'r using contraction that are not that helpful. For example : <code>JPanel rp = new JPanel();</code> What is an <code>rp</code> ? An other example : <code>GridBagLayout gridbag = new GridBagLayout();</code>. We already know that it's an grid bag by the declaration of the class. You could use something more meaningful. Is the principal container or a container for the data of the weeks or anything else? I always find more helpful to know at glance what the container is used for, just by reading his name. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T15:47:19.087",
"Id": "72775",
"Score": "0",
"body": "Thanks for the advice. I'm not exactly sure what you mean by \"magic numbers\". I think it would help to show my gui, I edited my post with the top and bottom half of the gui. After seeing this, do my numbers still seem arbitrary? If so, I will take action on it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T15:56:20.823",
"Id": "72777",
"Score": "0",
"body": "@solleks I've made an edit to better explain my point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T16:05:09.240",
"Id": "72782",
"Score": "0",
"body": "ah yes, your edit helped very much. I'll be making your suggested changes. If you choose to go into deeper review, I would very much appreciate any suggestions or comments regarding the usage of EDT and `GridBagConstraints`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T16:07:34.807",
"Id": "72784",
"Score": "0",
"body": "For the moment I can't elaborate much, but if I can be sure that I will do it!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T15:34:14.327",
"Id": "42312",
"ParentId": "42309",
"Score": "6"
}
},
{
"body": "<p><strong>METHOD EXTRACTION</strong> that's the key to fixing a lot of what you do....</p>\n\n<p>Consider this code:</p>\n\n<blockquote>\n<pre><code> //row 2////////////////////////////////////////////////////////////\n gbc.gridx = 0;\n gbc.gridy = 2;\n gbc.gridheight = 1;\n gbc.gridwidth = 1;\n nameOfJob.setFont(nameOfJob.getFont().deriveFont(18.0f));\n gridbag.setConstraints(nameOfJob, gbc);\n rp.add(nameOfJob, gbc);\n\n gbc.gridx = 5;\n gbc.gridy = 2;\n gbc.gridheight = 1;\n gbc.gridwidth = 10;\n contractNO.setFont(contractNO.getFont().deriveFont(18.0f));\n gridbag.setConstraints(contractNO, gbc);\n rp.add(contractNO, gbc);\n</code></pre>\n</blockquote>\n\n<p>What if you had a method:</p>\n\n<pre><code>public static addGridComponent(JComponent container, JComponent component, \n GridBagLayout gridbag, GridBagConstraints gbc,\n int x, int y, int height, int width, float font) {\n gbc.gridx = x;\n gbc.gridy = y;\n gbc.gridheight = height;\n gbc.gridwidth = width;\n component.setFont(component.getFont().deriveFont(18.0f));\n gridbag.setConstraints(component, gbc);\n container.add(component, gbc);\n}\n</code></pre>\n\n<p>Then your code would become:</p>\n\n<pre><code>//row 2////////////////////////////////////////////////////////////\naddGridComponent(rp, nameOfJob, gridbag, gbc, 0, 2, 1, 1, 18.0f);\naddGridComponent(rp, contractNO, gridbag, gbc, 5, 2, 1, 10, 18.0f);\n\n//row 3////////////////////////////////////////////////////////////\naddGridComponent(rp, customerPO, gridbag, gbc, 0, 3, 1, 1, 18.0f);\naddGridComponent(rp, weekEnding, gridbag, gbc, 5, 3, 1, 10, 18.0f)\n</code></pre>\n\n<p>This does not solve the problem with the magic numbers, but Marc-Andre has already addressed that. What it does solve is a huge amount of code repetition.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T18:17:32.870",
"Id": "72820",
"Score": "0",
"body": "thanks @rolfl, that's very helpful. I'm in the process of refactoring my code according to your and Marc-Andre's answers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T14:46:00.577",
"Id": "72981",
"Score": "0",
"body": "@Marc-Andre good spotting. Thanks, Fixed"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T16:59:26.953",
"Id": "42322",
"ParentId": "42309",
"Score": "4"
}
},
{
"body": "<ol>\n<li><p>The variable declaration is unnecessary here:</p>\n\n<pre><code>public void run() {\n final FrontierMain fm = new FrontierMain();\n}\n</code></pre>\n\n<p>The following is the same:</p>\n\n<pre><code>public void run() {\n new FrontierMain();\n}\n</code></pre>\n\n<p>(Eclipse also puts a yellow exclamation mark on the line.)</p></li>\n<li><p>I think you are using EDT correctly. Just make sure that creation and every access (read or modify) to Swing components happens on EDT. Swing calls event handlers on EDT, including <code>actionPerformed()</code> and <code>Printable.print()</code>. </p>\n\n<p>If you are not sure you can always check that a method runs on EDT or not with <a href=\"http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingUtilities.html#isEventDispatchThread%28%29\" rel=\"nofollow noreferrer\"><code>SwingUtilities.isEventDispatchThread()</code></a>. You could create a custom method for that:</p>\n\n<pre><code>public static void verifyEventDispatchThread() {\n if (!SwingUtilities.isEventDispatchThread()) {\n Thread.dumpStack();\n }\n}\n</code></pre>\n\n<p>but there are other, already existing solutions: <a href=\"https://stackoverflow.com/q/3014972/843804\">Swing verify code on event dispatch thread at runtime</a></p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T23:26:44.700",
"Id": "42354",
"ParentId": "42309",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "42322",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T15:10:04.680",
"Id": "42309",
"Score": "6",
"Tags": [
"java",
"swing",
"gui"
],
"Title": "Reducing repetition and utlizing EDT"
}
|
42309
|
<p>I have the following Lua script which I use against my redis environment to perform some non-production analytics on my data.</p>
<p>My dataset contains hundreds of millions of records, hence I want to make sure that the approach that I am taking is optimal for query performance and best coding practices.</p>
<pre><code>-- Tables to store the aggregations
local aUsers = {} -- [sizeInBytes] = userID (Table is created the other way around to allow for sorting)
local aFileTypes = {} -- [fileTypeID] = sizeInBytes
local aFileTag = {} -- [fileTagID] = sizeInBytes
-- Global Count of Records and Sum of Sizes in Bytes
local sumCount = 0
local sumSize = 0
-- For users 'sizeBytes' is the Table[ID] to allow sorting. Collissions are not a big deal
local function userAgregations(table, key, size)
table[size] = key
end
-- For other agregations the `fieldID` is the key mapped against the `size` agregation
local function genericAgregations(table, key, size)
if table[key] then
table[key] = table[key] + size
else
table[key] = size
end
end
-- For users only, sort the table by Key (size) and print return it
local function printTopUsers(t)
local str = "["
local sortedTable = {}
local maxResults = 25
for key in pairs(t) do
sortedTable[#sortedTable+1] = key
end
table.sort(sortedTable, function(a,b)
return a > b
end)
if #sortedTable < 25 then
maxResults = #sortedTable
end
for i=1, maxResults do
str = str .. sortedTable[i] .. ":" .. t[sortedTable[i]] .. ","
end
local formatted = str .. "]"
return formatted
end
-- For other fields just return the table
local function printTable(t)
local str = "["
for key,value in pairs(t) do
str = str .. key .. ":" .. value .. ","
end
local formatted = str .. "]"
return formatted
end
-- Return all the keys in redis that match a given pattern (Yes, its non-production)
-- Where the keys are: 0:0000:00:00000:00:00:00:0
-- Sample query is: 5:123?:??:12346:1?:??:??:2--
local matches = redis.call("KEYS", query)
-- For each Key match, get the value and perform the agregations
for _,key in ipairs(matches) do
local val = redis.call("GET", key)
local sCount, sSize = val:match("([^:]+):([^:]+)")
local count = tonumber(sCount)
local size = tonumber(sSize)
-- Extract a part of the key which refers to a particular agregation fieldID
userAgregations(aUsers, string.sub(key, 11, 15), size)
genericAgregations(aFileTypes, string.sub(key, 17, 18), size)
genericAgregations(aFileTags, string.sub(key, 17, 18), size)
-- Increment the Global sum and count
sumCount = sumCount + count
sumSize = sumSize + size
end
-- Contatenate and return response
local globalAgregation = string.format("[%s:%s]", sumCount, sumSize)
local result = printTopUsers(aUsers) .. printTable(aFileTypes) .. printTable(aFileTags) .. globalAgregation
return result
</code></pre>
|
[] |
[
{
"body": "<p>There are a few little things that can be improved:</p>\n\n<pre><code>-- For users 'sizeBytes' is the Table[ID] to allow sorting. Collissions are not a big deal\nlocal function userAgregations(table, key, size)\n table[size] = key\nend\n</code></pre>\n\n<p>If using LuaJIT, this function might be optimized away, but in regular Lua there's no reason to make a function that just does an assignment like this. Just do it straight in your code; table assignments are supposed to be understandable.</p>\n\n<p>In genericAgregations (should be genericAggregations!) you're performing one table access too many:</p>\n\n<pre><code>local function genericAgregations(table, key, size)\n local value = table[key]\n table[key] = value and (value + size) or size\nend\n</code></pre>\n\n<p>In printTopUsers, don't use a custom function in table.sort to sort in descending order. Sort normally and then perform the numeric for backwards. </p>\n\n<p>Also, instead of concatenating str, create a temporary table, insert the bits of the string in it and in the end generate the string at once with table.concat. It's faster than multiple concatenations.</p>\n\n<p>Same in printTable.</p>\n\n<p>As for the redis-specific stuff, I have no knowledge but I hope the little tweaks above are useful!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T18:31:31.660",
"Id": "42333",
"ParentId": "42311",
"Score": "8"
}
},
{
"body": "<p>Don't build strings via concatenation loops like this:</p>\n\n<pre><code>for key,value in pairs(t) do \n str = str .. key .. \":\" .. value .. \",\"\nend\n</code></pre>\n\n<p>Since Lua strings are immutable and interned, this can end up being O(N^2). Instead, put the string parts in a table and do a <code>table.concat</code> to join everything in the end.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T18:52:56.590",
"Id": "42334",
"ParentId": "42311",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "42333",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T15:32:20.027",
"Id": "42311",
"Score": "8",
"Tags": [
"optimization",
"algorithm",
"performance",
"lua"
],
"Title": "Performing non-production analytics on data"
}
|
42311
|
<p>I have asked a question on Stack Overflow and one of the guys actually managed to hack my contact form and inject a fake email into the <code>$header</code> of the PHP! </p>
<p>So after talking to him, he sent me a few articles, and I aimed to update the PHP to secure this gap and prevent the spam. </p>
<p><strong>Here is my old PHP:</strong></p>
<pre><code><?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
ob_start();
if(isset(
$_REQUEST['name'],
$_REQUEST['email'],
$_REQUEST['message'],
$_REQUEST['number'],
$_REQUEST['date'],
$_REQUEST['select'],
$_REQUEST['radio'],
$_REQUEST['checkbox'],
$_REQUEST['token']
)){
if($_SESSION['token'] != $_POST['token']){
$response = "0";
} else {
$_SESSION['token'] = "";
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
$number = $_REQUEST['number'];
$date = $_REQUEST['date'];
$select = $_REQUEST['select'];
$radio = $_REQUEST['radio'];
$checkbox = $_REQUEST['checkbox'];
$to = "";
$subject = "New Message From: $name";
$message = "Name: $name<br/>
number: $number<br/>
date: $date<br/>
select: $select<br/>
radio: $radio<br/>
checkbox: $checkbox<br/>
Email: $email<br/>
Message: $message";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: '.$email . "\r\n";
$mailed = (mail($to, $subject, $message, $headers));
if( isset($_REQUEST['ajax']))$response = ($mailed) ? "1" : "0";
else $response = ($mailed) ? "<h2>Success!</h2>" : "<h2>Error! There was a problem with sending.</h2>";
echo $response;
}
} else {
echo "Form data error!";
}
ob_flush();
die();
}
?>
</code></pre>
<p><strong>and here is the updated version:</strong> </p>
<pre><code><?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
ob_start();
if(isset(
$_REQUEST['name'],
$_REQUEST['email'],
$_REQUEST['message'],
$_REQUEST['number'],
$_REQUEST['date'],
$_REQUEST['select'],
$_REQUEST['radio'],
$_REQUEST['checkbox'],
$_REQUEST['token']
)){
if($_SESSION['token'] != $_POST['token']){
$response = "0";
}
else {
$_SESSION['token'] = "";
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
$number = $_REQUEST['number'];
$date = $_REQUEST['date'];
$select = $_REQUEST['select'];
$radio = $_REQUEST['radio'];
$checkbox = $_REQUEST['checkbox'];
$email_pattern = "/([\w\-]+\@[\w\-]+\.[\w\-]+)/";
$spam_pattern = "/[\r\n]|Content-Type:|Bcc:|Cc:/i";
switch (true){
case !preg_match($email_pattern, $email):
$response = "<b style='color: red'>Invalid email address!</b>";
break;
case !preg_match($spam_pattern, $name):
case !preg_match($spam_pattern, $number):
case !preg_match($spam_pattern, $date):
case !preg_match($spam_pattern, $select):
case !preg_match($spam_pattern, $radio):
case !preg_match($spam_pattern, $checkbox):
case !preg_match($spam_pattern, $message):
$response = "<b style='color: red'>Invalid request made!</b>";
break;
default:
$to = "";
$subject = "New Message From: $name";
$message = "Name: $name<br/>
number: $number<br/>
date: $date<br/>
select: $select<br/>
radio: $radio<br/>
checkbox: $checkbox<br/>
Email: $email<br/>
Message: $message";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: '.$email . "\r\n";
$mailed = (mail($to, $subject, $message, $headers));
$response = ($mailed) ?
"<h2 style='color: green'>Success!</h2>"
:
"<h2 style='color: blue'>Error! There was a problem with sending.</h2>";
break;
}
}
}
else {
$response = "<b style='color: red'> Form data error! </b>";
}
ob_flush();
}
?>
</code></pre>
<p>Can you please share your opinion? Does it look secure?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T16:16:32.027",
"Id": "72787",
"Score": "4",
"body": "You don't have to validate email address yourself. PHP has a built in function filter_var($email, FILTER_VALIDATE_EMAIL);"
}
] |
[
{
"body": "<p>@James is correct, <a href=\"http://www.php.net/manual/en/filter.examples.validation.php\">PHP has function to validate</a> so you don't have to (and they're better).</p>\n\n<p>Your <code>switch (true)</code> is <a href=\"http://jsperf.com/if-else-chain-vs-switch-true\">bothering me</a>. I think an <code>if</code> condition could work there instead, as that's not why <a href=\"http://us3.php.net/manual/en/control-structures.switch.php\">switches</a> were built. </p>\n\n<pre><code>$mailed = (mail($to, $subject, $message, $headers));\n</code></pre>\n\n<p>You don't need the parentheses in this line. In fact, you could just shorten it all a bit and use:</p>\n\n<pre><code>if (mail($to, $subject, $message, $headers)) {\n $response = \"<h2 style='color: green'>Success!</h2>\";\n} else {\n $response = \"<h2 style='color: blue'>Error! There was a problem with sending.</h2>\";\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T18:15:35.350",
"Id": "42329",
"ParentId": "42313",
"Score": "5"
}
},
{
"body": "<p>I tried to clean up your code a bit and implemented what @Alex L and @James said. </p>\n\n<pre><code><?php\n\nsession_start();\n\nif ($_SERVER['REQUEST_METHOD'] === 'POST'){\n ob_start();\n\n $isRequestSet = true;\n $keysToTest = array('name', 'email', 'message', 'number', 'date', 'select', 'radio', 'checkbox', 'token');\n foreach($_REQUEST as $reqKey => $reqValue){\n if(!in_array($reqKey, $keysToTest) || !isset($reqValue)){\n $isRequestSet = false; break;\n }\n }\n\n if($isRequestSet){\n if($_SESSION['token'] !== $_POST['token']){\n $response = \"0\";\n } else {\n unset($_SESSION['token']);\n\n $name = $_REQUEST['name'];\n $email = $_REQUEST['email'];\n $message = $_REQUEST['message'];\n $number = $_REQUEST['number'];\n $date = $_REQUEST['date'];\n $select = $_REQUEST['select'];\n $radio = $_REQUEST['radio'];\n $checkbox = $_REQUEST['checkbox'];\n\n $response = null;\n if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){\n $response = \"<b style='color: red'>Invalid email address!</b>\";\n } else if(preg_grep(\"/[\\r\\n]|Content-Type:|Bcc:|Cc:/i\", array($name, $number, $date, $select, $radio, $checkbox, $message))){\n $response = \"<b style='color: red'>Invalid request made!</b>\";\n } else {\n $to = \"support@loaidesign.co.uk\";\n $subject = \"New Message From: \" . $name;\n $message = \"Name: \" . $name . \"<br/> Number: \" . $number . \"<br/> Date: \" . $date . \"<br/>\" .\n \"Relect: \" . $select . \"<br/> Radio: \" . $radio . \"<br/> Checkbox: \" . $checkbox . \"<br/>\" .\n \"Email: \" . $email . \"<br/> Message: \" . $message;\n $headers = 'MIME-Version: 1.0' . \"\\r\\n\" . 'Content-type: text/html; charset=utf-8' . \"\\r\\n\" .\n 'From: ' . $email . \"\\r\\n\";\n\n if(mail($to, $subject, $message, $headers)){\n $response = \"<h2 style='color: green'>Success!</h2>\";\n } else {\n $response = \"<h2 style='color: blue'>Error! There was a problem with sending.</h2>\";\n }\n }\n }\n } else {\n $response = \"<b style='color: red'> Form data error! </b>\";\n }\n\n ob_flush();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T23:20:05.807",
"Id": "73133",
"Score": "0",
"body": "There is few errors man, it wont work :/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T19:55:35.407",
"Id": "73258",
"Score": "0",
"body": "@Loai Could you elaborate? What errors are being produced?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T04:29:55.167",
"Id": "73366",
"Score": "0",
"body": "@AlexL - missed a closing parenthesis on line 33 (if-preg_grep). Edited to fix that (see http://i.imgur.com/2ceLiHI.png)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T15:57:26.387",
"Id": "42428",
"ParentId": "42313",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T15:48:25.360",
"Id": "42313",
"Score": "3",
"Tags": [
"php",
"security",
"email"
],
"Title": "Preventing email injection"
}
|
42313
|
<p>I have an application which retrieves data from a (potentially) very large XML file. A combination of XMLReader and XDocument seemed to be the only way I could manage the entire thing the way I wanted. It <strong>works</strong>, and it does so fairly quickly and efficiently. But I have a few review questions. </p>
<ul>
<li>Is this combination of XMLReader and XDocument the right way to go? Nothing I read about managing XML documents suggested it, but it was the only option I could come up with since XDocument can't load entire sections, so XMLReader is needed as well.</li>
<li>Activator.CreateInstance is not something I truly understand and it was just the last in a line of options I tried there. It seems to do what I want, but is there some issues I should know about?</li>
<li>The reason for the distinction between factory methods and Activator.CreatInstance is because the factory methods ifs contain classes which may return subclasses, the activator else doesn't. Is there a better way of handling this?</li>
</ul>
<p></p>
<pre><code>public static void Parse(World world, string path)
{
isFinished = false;
World = world;
Path = path;
XReader = XmlReader.Create(new StreamReader(Path, Encoding.GetEncoding("ISO-8859-9")));
XReader.Read();
while (XReader.Read())
{
if (XReader.NodeType == XmlNodeType.Whitespace)
continue;
if (XReader.Name == "df_world")
{
while (XReader.Read())
{
if (XReader.NodeType == XmlNodeType.Whitespace)
continue;
if (XReader.NodeType == XmlNodeType.EndElement && XReader.Name == "df_world")
break;
bool knownSection = true;
switch (XReader.Name)
{
case "regions":
LoadSection<Region>(World.Regions);
break;
case "underground_regions":
LoadSection<UndergroundRegion>(World.UndergroundRegions);
break;
case "sites":
LoadSection<Site>(World.Sites);
break;
//Other cases culled for brevity
default:
Program.Log(LogType.Error, "Unknown XML Section: " + XReader.Name);
XReader.Skip();
knownSection = false;
break;
}
if (knownSection)
OnFinishedSection(XReader.Name);
}
break;
}
}
isFinished = true;
OnFinished();
}
private static void LoadSection<T>(Dictionary<int, T> WorldList) where T : XMLObject
{
while (XReader.Read())
{
if (XReader.NodeType == XmlNodeType.Whitespace)
continue;
if (XReader.NodeType != XmlNodeType.EndElement && XReader.Depth == 2)
LoadItem<T>(WorldList);
else if (XReader.Depth >= 2)
continue;
else if (XReader.NodeType == XmlNodeType.EndElement)
break;
else
Program.Log(LogType.Error, "Unknown part of section xml/n" + XReader.Name);
}
}
private static void LoadItem<T>(Dictionary<int, T> WorldList) where T : XMLObject
{
try
{
XDocument xdoc = XDocument.Load(XReader.ReadSubtree());
if (typeof(T) == typeof(HistoricalEvent))
{
HistoricalEvent evt = HistoricalEvent.Create(xdoc, World);
World.HistoricalEvents.Add(evt.ID, evt);
}
else if (typeof(T) == typeof(HistoricalEventCollection))
{
HistoricalEventCollection evtcol = HistoricalEventCollection.Create(xdoc, World);
World.HistoricalEventCollections.Add(evtcol.ID, evtcol);
}
else
{
T WorldObject = (T)Activator.CreateInstance(typeof(T), new object[] { xdoc, World });
WorldList.Add(WorldObject.ID, WorldObject);
}
}
catch (Exception e )
{
Program.Log(LogType.Error, "Error reading XML item\n" + e.Message);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>My first observations is: wrap disposable classes in using. The code as is probably has a memory leak in it:</p>\n\n<pre><code>using (var streamReader = new StreamReader(Path, Encoding.GetEncoding(\"ISO-8859-9\"))\nusing (var xmlReader = XmlReader.Create(streamReader))\n{\n // rest of logic.\n}\n</code></pre>\n\n<p>I don't like the variable name <code>XReader</code>. I don't see the declaration, but it should be a local variable, and named <code>xReader</code>. If it is a property, I would rethink the name. Same with <code>World</code> and <code>Path</code> (I\"m assuming these are class properties). Why are you saving those variables in Properties any ways? Are they really needed anywhere else?</p>\n\n<p>The layout of the code is not bad, easy to read and follow. Again, the biggest issue I see is that you are not disposing of disposable objects. Please try and get that fixed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T18:11:21.393",
"Id": "43633",
"ParentId": "42316",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T16:03:02.250",
"Id": "42316",
"Score": "5",
"Tags": [
"c#",
"xml",
"factory-method"
],
"Title": "Anonymous methods, factory methods, threading, and XML input"
}
|
42316
|
<p>I am using the GeoComplete plugin with RequireJS
It works, but please could someone confirm I've done this correctly, mainly my understanding of shim:</p>
<pre><code> requirejs.config({
waitSeconds: 120,
paths: {
async: './lib/async',
jquery: './lib/jquery-1.7.2.min',
geocomplete: './lib/jquery.geocomplete.min'
},
shim: {
'geocomplete': ['jquery'],
}
});
require(['async!http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false', 'jquery', 'geocomplete'], function () {
$("#geocomplete").geocomplete({
map: "#map_canvas"
});
}
);
</code></pre>
<p>The way I understand shim, is, GeoComplete doesn't support AMD, but has a dependency on jQuery, so my set up basically says "load geocomplete <strong>after</strong> jquery"</p>
<p>Is that correct?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T15:41:07.270",
"Id": "73693",
"Score": "1",
"body": "Does it work as you expected? If it does, you have probably done it correctly :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T15:42:25.513",
"Id": "73694",
"Score": "0",
"body": "haha, yes, it does.... was just very new to requirejs, and hadn't quite got my head around the idea of the shim. Think I get it now!"
}
] |
[
{
"body": "<p>The only thing that I see looking at this code is that you didn't keep a fully consistent formatting, and I at first thought you had an extra set of brackets or parentheses.</p>\n\n<p><img src=\"https://i.stack.imgur.com/SWuyB.png\" alt=\"enter image description here\"></p>\n\n<p>You should do it like the <code>});</code> farther above in the code. </p>\n\n<p>Keep everything consistent, you probably already know this though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:03:12.873",
"Id": "73701",
"Score": "1",
"body": "I agree, and I usually have code-ocd when it comes to this!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T15:44:58.267",
"Id": "42773",
"ParentId": "42321",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T16:45:24.270",
"Id": "42321",
"Score": "2",
"Tags": [
"javascript",
"require.js"
],
"Title": "Using GeoComplete with RequireJS (with shim config)"
}
|
42321
|
<p>I've recently stumbled upon an interesting challenge for me:</p>
<blockquote>
<p>You should develop C application, that solves math expressions. Operations such as (+,-,*,/) should be supported, as well as (cos, sin, exp). Application should replace constants Pi and E with built-in values. We may have any amount of spaces between operators and braces.</p>
<p>Example:</p>
<p>stdin: 11 + (exp(2.010635 + sin(PI/2)*3) + 50) / 2</p>
<p>stdout: 111.00000 (may have insignificant deviations)</p>
</blockquote>
<p>I am interested in solving this problem using Java. I know that the best way is to use lexical analysis or regexp, but for now it is too complex for me. I am trying to solve this task without them. My code works well, but it looks awful, I think.</p>
<p>My code is also on <a href="http://pastebin.com/ijSyh4CK" rel="noreferrer">pastebin</a>.</p>
<p>Can you help me make my code style better?</p>
<pre><code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by Vladimir on 20.02.14.
*/
public class Main {
private static final ArrayList<Character> DIVIDERS = new ArrayList<Character>
(Arrays.asList('*', '/', '-', '+'));
private static final int RIGHT_DIRECTION = 1;
private static final int LEFT_DIRECTION = -1;
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String expression = "";
System.out.print("Enter expression: ");
try {
expression = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Expression: " + expression);
expression = prepareExpression(expression);
System.out.println("Prepared expression: " + expression);
System.out.println("Answer: " + calc(expression));
}
//Recursive function with the state machine
//states "(", "sin", "cos", "exp", "*", "/", "+", "-"
private static String calc(String expression) {
int pos = 0;
System.out.println("Solving expression: "+expression);
//Extracting expression from braces, doing recursive call
//replace braced expression on result of it solving
if (-1 != (pos = expression.indexOf("("))) {
String subexp = extractExpressionFromBraces(expression,pos);
expression = expression.replace("("+subexp+")", calc(subexp));
return calc(expression);
//Three states for calculating sin cos exp
//input must be like sin0.7
} else if (-1 != (pos = expression.indexOf("sin"))) {
pos += 2;//shift index to last symbol of "sin" instead of first
String number = extractNumber(expression, pos, RIGHT_DIRECTION);
expression = expression.replace("sin"+number,
Double.toString(Math.sin(Double.parseDouble(number))));
return calc(expression);
} else if (-1 != (pos = expression.indexOf("cos"))) {
pos += 2;
String number = extractNumber(expression, pos, RIGHT_DIRECTION);
expression = expression.replace("cos"+number,
Double.toString(Math.cos(Double.parseDouble(number))));
return calc(expression);
} else if (-1 != (pos = expression.indexOf("exp"))) {
pos += 2;
String number = extractNumber(expression, pos, RIGHT_DIRECTION);
expression = expression.replace("exp" + number,
Double.toString(Math.exp(Double.parseDouble(number))));
return calc(expression);
} else if (expression.indexOf("*") > 0 | expression.indexOf("/") > 0) {
int multPos = expression.indexOf("*");
int divPos = expression.indexOf("/");
pos = Math.min(multPos, divPos);
if (multPos < 0) pos = divPos; else if (divPos < 0) pos = multPos;
//If one value of
//*Pos will be -1 result of min will be incorrect.
char divider = expression.charAt(pos);
String leftNum = extractNumber(expression, pos, LEFT_DIRECTION);
String rightNum = extractNumber(expression, pos, RIGHT_DIRECTION);
expression = expression.replace(leftNum + divider + rightNum,
calcShortExpr(leftNum, rightNum, divider));
return calc(expression);
} else if (expression.indexOf("+") > 0 | expression.indexOf("-") > 0) {
int summPos = expression.indexOf("+");
int minusPos = expression.indexOf("-");
pos = Math.min(summPos, minusPos);
if (summPos < 0) pos = minusPos; else if (minusPos < 0) pos = summPos;
char divider = expression.charAt(pos);
String leftNum = extractNumber(expression, pos, LEFT_DIRECTION);
String rightNum = extractNumber(expression, pos, RIGHT_DIRECTION);
expression = expression.replace(leftNum + divider + rightNum,
calcShortExpr(leftNum, rightNum, divider));
return calc(expression);
} else return expression;
}
private static String extractExpressionFromBraces(String expression, int pos) {
int braceDepth = 1;
String subexp="";
for (int i = pos+1; i < expression.length(); i++) {
switch (expression.charAt(i)) {
case '(':
braceDepth++;
subexp += "(";
break;
case ')':
braceDepth--;
if (braceDepth != 0) subexp += ")";
break;
default:
if (braceDepth > 0) subexp += expression.charAt(i);
}
if (braceDepth == 0 && !subexp.equals("")) return subexp;
}
return "Failure!";
}
private static String extractNumber(String expression, int pos, int direction) {
String resultNumber = "";
int currPos = pos + direction;//shift pos on next symbol from divider
//For negative numbers
if (expression.charAt(currPos) == '-') {
resultNumber+=expression.charAt(currPos);
currPos+=direction;
}
for (; currPos >= 0 &&
currPos < expression.length() &&
!DIVIDERS.contains(expression.charAt(currPos));
currPos += direction) {
resultNumber += expression.charAt(currPos);
}
if (direction==LEFT_DIRECTION) resultNumber = new
StringBuilder(resultNumber).reverse().toString();
return resultNumber;
}
private static String calcShortExpr(String leftNum, String rightNum, char divider) {
switch (divider) {
case '*':
return Double.toString(Double.parseDouble(leftNum) *
Double.parseDouble(rightNum));
case '/':
return Double.toString(Double.parseDouble(leftNum) /
Double.parseDouble(rightNum));
case '+':
return Double.toString(Double.parseDouble(leftNum) +
Double.parseDouble(rightNum));
case '-':
return Double.toString(Double.parseDouble(leftNum) -
Double.parseDouble(rightNum));
default:
return "0";
}
}
private static String prepareExpression(String expression) {
expression = expression.replace("PI", Double.toString(Math.PI));
expression = expression.replace("E", Double.toString(Math.E));
expression = expression.replace(" ", "");
return expression;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You're right that a proper expression parser would be the superior approach. Nevertheless, your <em>ad hoc</em> solution works surprisingly well, though it will have some odd behaviour.</p>\n\n<p>I'll just start by pointing out that your exception handling in <code>main()</code> is shaky. If you get an <code>IOException</code>, you'll print a stack trace, then proceed to evaluate an empty string anyway.</p>\n\n<p>What you probably want to do if there is an <code>IOException</code> is to skip the rest of the program:</p>\n\n<pre><code>try {\n String expression = reader.readLine();\n System.out.println(\"Expression: \" + expression);\n expression = prepareExpression(expression);\n System.out.println(\"Prepared expression: \" + expression);\n System.out.println(\"Answer: \" + calc(expression));\n} catch (IOException e) {\n e.printStackTrace();\n}\n</code></pre>\n\n<p>In this particular case, since all you do is print a stack trace and abort, you could just take advantage of Java's default behaviour. All you have to do is declare that <code>main()</code> can throw an <code>IOException</code>.</p>\n\n<pre><code>public static void main(String[] args) throws IOException {\n BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));\n\n System.out.print(\"Enter expression: \");\n String expression = reader.readLine();\n System.out.println(\"Expression: \" + expression);\n\n expression = prepareExpression(expression);\n System.out.println(\"Prepared expression: \" + expression);\n\n System.out.println(\"Answer: \" + calc(expression));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T19:52:03.597",
"Id": "42337",
"ParentId": "42323",
"Score": "6"
}
},
{
"body": "<p>I agree with that a different approach would be better, so just a few random notes, mostly about the current code:</p>\n\n<ol>\n<li><p>It's good to know that it's already in the JDK, in form a script engine. So, if you don't want to reinvent the wheel just use it:</p>\n\n<pre><code>import javax.script.ScriptEngine;\nimport javax.script.ScriptEngineManager;\n\nfinal ScriptEngineManager engineManager = new ScriptEngineManager();\nfinal ScriptEngine engine = engineManager.getEngineByName(\"JavaScript\");\nString expression = \"11 + (Math.exp(2.010635 + Math.sin(Math.PI/2)*3) + 50) / 2\";\nSystem.out.println(engine.eval(expression)); // prints 110.99997794278411\n</code></pre>\n\n<p>The syntax is not the same (you need the <code>Math.</code> prefix) but I guess it can be changed.</p></li>\n<li><p>Instead of doubles (and floating point numbers) consider using <code>BigDecimal</code>s. Floating point numbers are not precise. Here is an example:</p>\n\n<pre><code>Enter expression: 1.03-0.42\nExpression: 1.03-0.42\nPrepared expression: 1.03-0.42\nSolving expression: 1.03-0.42\nSolving expression: 0.6100000000000001\nAnswer: 0.6100000000000001\n</code></pre>\n\n<p>(It might not fit well for trigonometric functions.)</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/q/3730019/843804\">Why not use Double or Float to represent currency?</a></li>\n<li><em>Effective Java, 2nd Edition, Item 48: Avoid float and double if exact answers are required</em></li>\n</ul></li>\n<li><p><code>DIVIDERS</code> currently mutable. You could wrap it with <code>Collections.unmodifiableList</code> to avoid accidental modification. A more compact form is <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ImmutableList.html\" rel=\"nofollow noreferrer\">Guava's <code>ImmutableList</code></a>:</p>\n\n<pre><code>private static final List<Character> DIVIDERS = ImmutableList.of('*', '/', '-', '+');\n</code></pre></li>\n<li><p>In some places I would use a<code>String.contains</code> instead of <code>indexOf</code>. It's more meaningful, closer to the English language, easier to read since you cat get rid of the comparison. In conditionals like this</p>\n\n<pre><code>expression.indexOf(\"*\") > 0 | expression.indexOf(\"/\") > 0\n</code></pre>\n\n<p>I'd use the even more compact </p>\n\n<pre><code>StringUtils.containsAny(expression, \"*/\")\n</code></pre>\n\n<p>(<a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#containsAny%28java.lang.CharSequence,%20java.lang.CharSequence%29\" rel=\"nofollow noreferrer\">from Apache Commons Lang</a>)</p></li>\n<li><p>The following lines also could be replaced with <code>StringUtils</code>:</p>\n\n<pre><code>int multPos = expression.indexOf(\"*\");\nint divPos = expression.indexOf(\"/\");\n\npos = Math.min(multPos, divPos);\nif (multPos < 0)\n pos = divPos;\nelse if (divPos < 0)\n pos = multPos;\n</code></pre>\n\n<p>Use <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#indexOfAny%28java.lang.CharSequence,%20java.lang.CharSequence...%29\" rel=\"nofollow noreferrer\"><code>indexOfAny</code></a>:</p>\n\n<pre><code>pos = StringUtils.indexOfAny(expression, \"*/\")\n</code></pre>\n\n<p>It's the same.</p></li>\n<li><p>Instead of returning with an error string, like</p>\n\n<pre><code>return \"Failure!\";\n</code></pre>\n\n<p>I think you should throw an exception and stop the processing immediately, there is no point to \"continue\" the processing with wrong subresult (or to pretend that it continues). (<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>\n\n<p>The same is true for the default branch of <code>calcShortExpr</code>. If you call it with an invalid \"divider\" it's definitely an error in the program and it should stop.</p></li>\n<li><p>The <code>divider</code> variable actually contains the operator which is a little bit confusing. I'd rename it for better readability.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T07:24:54.210",
"Id": "42399",
"ParentId": "42323",
"Score": "8"
}
},
{
"body": "<p>I understand that this project has been posted many years ago but I have noticed a mistake: the program works perfectly except when the first number is negative.</p>\n\n<p>For example, with the following input: <code>-8 + 3</code>. The program enters the function (see stacktrace below) and fails to execute the calculation.</p>\n\n<blockquote>\n<pre><code>java.lang.StringIndexOutOfBoundsException: String index out of range: -1\n at java.lang.String.charAt(String.java:646)\n at Main.extractNumber(Main.java:161)\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-20T07:24:11.663",
"Id": "132492",
"ParentId": "42323",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "42399",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T17:08:40.060",
"Id": "42323",
"Score": "13",
"Tags": [
"java",
"beginner",
"parsing",
"recursion",
"math-expression-eval"
],
"Title": "Math expression solver"
}
|
42323
|
<p>I want to create XML messages for webservice communication. These messages should be created from a pool of reusable elements. Therefore I have created different classes. A "factory" class, that only returns a message class. An element class, that consists of the reusable parts and the message classes that are the blueprints for the desired XML messages.</p>
<p>My code delivers the expected result, but I'm looking for a best practice. Especially a way to get rid of rewriting the same <code>save()</code> and <code>__construct</code> method in every of the message classes.</p>
<p><strong>Update:</strong></p>
<blockquote>
<p>I have improved my example and moved the <code>root</code> property and the
<code>save()</code> method from the message classes to the <code>Elements</code> class. I
also changed the name of the method from <code>save</code> to <code>getMessage</code> as
there is a <code>DOMDocument</code> method with the same name. Due to these
changes I have little less redudant code. I still don't know if it is
good practice, particularly to use the "grandparent" methods in the
message classes.</p>
</blockquote>
<pre><code>// class to create webservice messages
class Messages{
private function __construct(){}
public static function get($type) {
//some error handling if class not exists
return new $type;
}
}
// message no.1
class Message_1 extends Elements{
public function __construct() {
parent::__construct();
$this->root = $this->createElement("message1");
}
public function add_anotherElement(){
$this->root->appendChild($this->add_anotherElementBlock("foo", "bar"));
}
public function add_element(){
$this->root->appendChild($this->add_someElementBlock("foo", "bar"));
}
}
// message no.2
class Message_2 extends Elements {
public function __construct() {
parent::__construct();
$this->root = $this->createElement("message2");
}
public function add_elements(){
$this->root->appendChild($this->add_anotherElementBlock("foo", "bar"));
$this->root->appendChild($this->add_someElementBlock("foo", "bar"));
}
}
// message no.3
class Message_3 extends Elements {
public function __construct() {
parent::__construct();
$this->root = $this->createElement("message3");
}
public function add_element(){
// unique Element
$this->root->appendChild($this->createElement("foo", "bar"));
}
}
// reusable elements
class Elements extends DOMDocument{
protected $root;
protected function add_someElementBlock($foo, $bar) {
$node = $this->createElement("root");
$attr = $this->createAttribute("id");
$attr->value = $foo;
$node->appendChild($attr);
$subnode = $this->createElement("sub",$bar);
$node->appendChild($subnode);
return $node;
}
protected function add_anotherElementBlock($foo, $bar) {
$node = $this->createElement("anotherRoot");
$subnode = $this->createElement("anotherSubNode",$bar);
$attr = $this->createAttribute("anotherAttribute");
$attr->value = $foo;
$subnode->appendChild($attr);
$node->appendChild($subnode);
return $node;
}
public function getMessage(){
return $this->saveXML($this->root);
}
}
$message1 = Messages::get('Message_1');
$message1->add_element();
$message1->add_anotherElement();
$message2 = Messages::get('Message_2');
$message2->add_elements();
$message3 = Messages::get('Message_3');
$message3->add_element();
//********************************************
echo "<pre>";
print_r(htmlentities($message1->getMessage()));
echo "</pre>";
echo "<hr />";
echo "<pre>";
print_r(htmlentities($message2->getMessage()));
echo "</pre>";
echo "<hr />";
echo "<pre>";
print_r(htmlentities($message3->getMessage()));
echo "</pre>";
</code></pre>
|
[] |
[
{
"body": "<p>Your message classes currently have two responsibilities: representing an application logic message and transforming itself into a representation. If you want to add other ways of serialization you have to modify the message classes itself.</p>\n\n<p>The message classes only should represent the message while some other facility should be responsible for serializing your messages into xml. This keeps the interface of your message classes clean (not inheriting all those methods from <code>DOMDocument</code>) and allows to easily add other serialization formats. </p>\n\n<p>This particular situation wants a strategy pattern: a dedicated <code>MessageXmlSerializer</code> takes a message, creates the surrogate <code>DOMDocument</code> and itself delegates the serialization of the message further to specialized classes for each message:</p>\n\n<pre><code><?php\n\nclass MessageXmlSerializer {\n\n private $messageSerializers;\n\n public function serialize(Message $message) {\n $node = $this->createDocumentContainer();\n\n foreach ($this->messageSerializers as $serializer) {\n if ($serializer->canHandle($message)) {\n $node->appendChild($serializer->serialize($message));\n }\n }\n }\n\n protected function createDocumentContainer() {\n $node = new DOMDocument();\n // Do your intialization here\n return $node;\n }\n}\n</code></pre>\n\n<p>The dedicated serializers are rather simple. Of course they all share a common interface:</p>\n\n<pre><code>interface MessageSerializer {\n public function canHandle(Message $message);\n\n public function serialize(Message $message);\n}\n</code></pre>\n\n<p>And finally the serializer specialized on serializing <code>Message_1</code></p>\n\n<pre><code>class MessageOneSerializer implements MessageSerializer {\n public function canHandle(Message $message) {\n return $message instanceof Message_1;\n }\n\n public function serialize(Message $message) {\n // create your node here and return it\n }\n}\n</code></pre>\n\n<p>So far the basic concept. Now new message types can easily be added and serializiation the messages itself are separated. Of course, as for any pattern, this concept can (should) be extended and adjusted to your needs. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T16:49:37.810",
"Id": "73011",
"Score": "0",
"body": "Looks very promising to me. The non encapsulated DOMDocument methods were really unpleasent. I yet don't have an idea how the messages should look like in this pattern, but I try to implement this pattern this weekend."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T15:13:01.457",
"Id": "74745",
"Score": "0",
"body": "I didn't used this approach for creating the messages, but for parsing the response. Thanks a lot for your answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T23:15:17.300",
"Id": "42351",
"ParentId": "42327",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T17:35:44.707",
"Id": "42327",
"Score": "3",
"Tags": [
"php",
"object-oriented",
"classes",
"xml",
"dom"
],
"Title": "Best practice to create XML messages with DOMDocument class in PHP"
}
|
42327
|
<p>Given an array of n elements, where each element is at most k away from its target position, devise an algorithm that sorts in O(n log k) time.
For example, let us consider k is 2, an element at index 7 in the sorted array, can be at indexes 5, 6, 7, 8, 9 in the given array. I'm looking for code review, best practices, optimizations etc. Also for some reason I could not get assertarrayequals hooked up so tested arrays unconventionally. Please ignore that as part of feedback</p>
<pre><code>public final class KSortedArray {
private KSortedArray() { }
/**
* Returns the sorted array provided the input array is k-sorted.
* If input array is not k-sorted, then results are unpredictable.
*
* @param arr The k-sorted array
* @param k the value of k, the deviation of placement.
* @return the sorted array
*/
public static int[] kSortDontModifyInput(int[] arr, int k) {
int[] n = new int[arr.length];
final Queue<Integer> queue = new PriorityQueue<Integer>(k + 1);
for (int i = 0; i <= k; i++) {
queue.add(arr[i]);
}
int ctr = 0;
for (int i = k + 1; i < arr.length; i++) {
n[ctr++] = queue.poll();
queue.add(arr[i]);
}
while (!queue.isEmpty()) {
n[ctr++] = queue.poll();
}
return n;
}
/**
* Sorted array provided the input array is k-sorted.
* If input array is not k-sorted, then results are unpredictable.
*
* @param arr The k-sorted array
* @param k the value of k, the deviation of placement.
*/
public static void kSortMoidifyInput(int[] arr, int k) {
Queue<Integer> queue = new PriorityQueue<Integer>(k + 1);
for (int i = 0; i <= k; i++) {
queue.add(arr[i]);
}
int ctr = 0;
for (int i = k + 1; i < arr.length; i++) {
arr[ctr++] = queue.poll();
queue.add(arr[i]);
}
while (!queue.isEmpty()) {
arr[ctr++] = queue.poll();
}
}
public static void main(String[] args) {
int arr[] = {2, 6, 3, 12, 56, 8};
int[] expected = {2, 3, 6, 8, 12, 56};
int[] actual = kSortDontModifyInput(arr, 3);
kSortMoidifyInput(arr, 3);
for (int i = 0; i < expected.length; i++) {
Assert.assertEquals(expected[i], actual[i]);
Assert.assertEquals(expected[i], arr[i]);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p><code>kSortDontModifyInput()</code> and <code>kSortMoidifyInput()</code> use the same algorithm to do the sorting. The only difference is that <code>kSortDontModifyInput()</code> creates a new array instead of using the given one. Therefor you can implment <code>kSortDontMoidifyInput()</code> by making a copy of the input array and passing it to <code>kSortMoidifyInput()</code>. Since they are meant to be doing the same operation, if you find a bug in one, you don't have to remember to change the other one.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T18:22:18.980",
"Id": "42330",
"ParentId": "42328",
"Score": "2"
}
},
{
"body": "<p>When you use a class in a 'hacky' way, like you do by using a PriorityQueue as a TreeSet, you should make sure that you document why the class is used, and what properties of the class are being leveraged.</p>\n\n<p><strike>\nYour code does not work in <em>O(n log(k) )</em> time because it uses a PriorityQueue, which has <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html\" rel=\"nofollow\"><em>O( log(n) )</em> time-complexity for add()</a>:</p>\n\n<blockquote>\n <p>Implementation note: this implementation provides O(log(n)) time for the enqueing and dequeing methods (offer, poll, remove() and add); linear time for the remove(Object) and contains(Object) methods; and constant time for the retrieval methods (peek, element, and size)</p>\n</blockquote>\n\n<p></strike></p>\n\n<p>Your algorithm is not correct for the requirements given:</p>\n\n<ul>\n<li><p>For a start, it will fail for input where the input array is smaller than <code>k</code>. It will throw an <code>ArrayIndexOutOfBoundsException</code>.</p></li>\n<li><p>Secondly, you are working in <code>k+1</code> space instead of <code>k</code>. Why? Where is the comment?</p></li>\n</ul>\n\n<p>Further, because you auto-box all your values to Integer, from int, you have a significant performance penalty. If you keep your data as primitives (and use an array of primitives rather than a PriorityQueue), you will have better results.</p>\n\n<p>The algorithm you need you use is strongly hinted at by the complexity requirement...</p>\n\n<p><em>O( n log(k) )</em> strongly implies that you need to iterate over each value once, and, with that element, there is an <em>O(log(k))</em> way to sort it.</p>\n\n<p>For the loop, think a for-loop. For the log(k), think a binary search....</p>\n\n<pre><code>for (int i = 0; i < data.length; i++) {\n int from = i > k ? i - k : 0;\n int val = data[i];\n int pos = Arrays.binarySearch(data, from, i, val);\n if (pos < 0) {\n pos = -pos - 1;\n }\n System.arraycopy(data, pos, data, pos+1, i - pos - 1);\n data[pos] = val;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T08:36:36.927",
"Id": "72939",
"Score": "0",
"body": "I am a little consfused with your comment \"which has O( log(n) ) time-complexity for add()\", my question is why logn rather than logk if I have declared by Queue of size \"k + 1\" ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T08:37:40.557",
"Id": "72940",
"Score": "1",
"body": "Also I poll before I add another, once size exceeds k + 1. This means my queue is never more than k elements"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T11:27:36.640",
"Id": "72953",
"Score": "0",
"body": "@JavaDeveloper You are correct ... and, that goes to show why comments are important."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-27T07:09:36.870",
"Id": "79309",
"Score": "1",
"body": "confused of how you use binary search when stuff in range is not sorted ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-27T11:13:46.373",
"Id": "79336",
"Score": "0",
"body": "The binary search is happening on the data that we are inserting in to. This is data that we are inserting 'in order'. We can guarantee that the last 'k' elements of that data are sorted, thus BSearch is fine."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T19:26:32.943",
"Id": "42336",
"ParentId": "42328",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T17:49:57.523",
"Id": "42328",
"Score": "4",
"Tags": [
"java",
"algorithm",
"sorting"
],
"Title": "Produce a nearly sorted (or K sorted) array"
}
|
42328
|
<p>A couple of days ago I <a href="https://codereview.stackexchange.com/questions/41725/factory-for-classes-unknown-at-compile-time">posted my code</a> that models systems made up of moving parts. I got several great tips and ideas and here is my latest version. My actions are now methods annotated with @Action (instead of separate classes as in my original code). My <code>Model</code> class contains a <code>HashMap</code> of Class, <code>ArrayList<? extends Agent></code> so each <code>ArrayList</code> contains agents of the same type.</p>
<p>In my<code>Model.start()</code> method I get annotated methods for each class and invoke them on each <code>ArrayList</code> member. The code looks more promising than the original one, but my main concern is that I had to use reflection to invoke actions on each model agent as I read that reflection is costly. </p>
<p>I would also like to hear your opinions on my usage of generics as I am new to the concept.</p>
<pre><code>import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GenericsTest
{
public static void main(String[] args)
throws NoSuchFieldException, SecurityException
{
Model machine = new Model();
ArrayList<Gear> gears = new ArrayList<Gear>();
ArrayList<Lever> levers = new ArrayList<Lever>();
int i;
for (i = 0; i < 1000; i++)
{
Gear gear = new Gear();
gear.setDiameter(i);
gears.add(gear);
Lever lever = new Lever();
lever.setLength(i + 2000);
levers.add(lever);
}
machine.addAgentList(Gear.class, gears);
machine.addAgentList(Lever.class, levers);
machine.start();
}
}
class Model
{
public void start()
{
for (Class<? extends Agent> clazz : listOfAgents.keySet())
{
List<Method> actions = new ArrayList<Method>();
for (Method m : clazz.getDeclaredMethods())
{
if (m.isAnnotationPresent(Action.class))
{
actions.add(m);
}
}
for (Agent agent : listOfAgents.get(clazz))
{
for (Method action : actions)
{
try
{
action.invoke(agent, new Object[]
{});
} catch (IllegalAccessException
| IllegalArgumentException
| InvocationTargetException e)
{
e.printStackTrace();
}
}
}
}
}
public Map<Class<? extends Agent>, ArrayList<? extends Agent>> getAgentLists()
{
return listOfAgents;
}
public void addAgentList(Class<? extends Agent> cls,
ArrayList<? extends Agent> agents)
{
listOfAgents.put(cls, agents);
}
private final Map<Class<? extends Agent>, ArrayList<? extends Agent>> listOfAgents =
new HashMap<Class<? extends Agent>, ArrayList<? extends Agent>>();
}
interface Agent
{
}
@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.METHOD)
@interface Action
{
}
/*
* Agent classes
*/
class Gear implements Agent
{
private int diameter;
public int getDiameter()
{
return diameter;
}
public void setDiameter(int diameter)
{
this.diameter = diameter;
}
@Action
public void rotate()
{
System.out.println("rotating ... " + this.toString() + " "
+ this.diameter);
}
@Action
public void replace()
{
System.out.println("replacing ..." + this.toString() + " "
+ this.diameter);
}
}
class Lever implements Agent
{
private int length;
public int getLength()
{
return length;
}
public void setLength(int length)
{
this.length = length;
}
@Action
public void move()
{
System.out.println("moving ..." + this.toString() + " " + this.length);
}
}
</code></pre>
<p>I will also try improve my original <code>FactoryClass</code> idea making <code>Action</code> an interface and post the code in another post.</p>
<p><strong>EDIT</strong></p>
<p>Changed the code to improve my list declarations:</p>
<pre><code>import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GenericsTest
{
public static void main(String[] args)
throws NoSuchFieldException, SecurityException
{
Model machine = new Model();
List<Gear> gears = new ArrayList<Gear>();
List<Lever> levers = new ArrayList<Lever>();
int i;
for (i = 0; i < 1000; i++)
{
Gear gear = new Gear();
gear.setDiameter(i);
gears.add(gear);
Lever lever = new Lever();
lever.setLength(i + 2000);
levers.add(lever);
}
machine.addAgentList(Gear.class, gears);
machine.addAgentList(Lever.class, levers);
machine.start();
}
}
class Model
{
public void start()
{
for (Class<? extends Agent> clazz : listOfAgents.keySet())
{
List<Method> actions = new ArrayList<Method>();
for (Method m : clazz.getDeclaredMethods())
{
if (m.isAnnotationPresent(Action.class))
{
actions.add(m);
}
}
for (Agent agent : listOfAgents.get(clazz))
{
for (Method action : actions)
{
try
{
action.invoke(agent, new Object[]
{});
} catch (IllegalAccessException
| IllegalArgumentException
| InvocationTargetException e)
{
e.printStackTrace();
}
}
}
}
}
public Map<Class<? extends Agent>, List<? extends Agent>> getAgentLists()
{
return listOfAgents;
}
public void addAgentList(Class<? extends Agent> cls,
List<? extends Agent> agents)
{
listOfAgents.put(cls, agents);
}
private final Map<Class<? extends Agent>, List<? extends Agent>> listOfAgents =
new HashMap<Class<? extends Agent>, List<? extends Agent>>();
}
interface Agent
{
}
@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.METHOD)
@interface Action
{
}
/*
* Agent classes
*/
class Gear implements Agent
{
private int diameter;
public int getDiameter()
{
return diameter;
}
public void setDiameter(int diameter)
{
this.diameter = diameter;
}
@Action
public void rotate()
{
System.out.println("rotating ... " + this.toString() + " "
+ this.diameter);
}
@Action
public void replace()
{
System.out.println("replacing ..." + this.toString() + " "
+ this.diameter);
}
}
class Lever implements Agent
{
private int length;
public int getLength()
{
return length;
}
public void setLength(int length)
{
this.length = length;
}
@Action
public void move()
{
System.out.println("moving ..." + this.toString() + " " + this.length);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T13:41:28.567",
"Id": "72967",
"Score": "2",
"body": "Last time the accepted answer says: `ArrayList<...>` reference types should be simply `List<...>`. But you still have `ArrayList`s all over."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T17:05:27.817",
"Id": "73016",
"Score": "1",
"body": "You are right. I have now changed my code accordingly and post it as an edit to my post."
}
] |
[
{
"body": "<ol>\n<li><pre><code>private final Map<Class<? extends Agent>, List<? extends Agent>> listOfAgents =\n new HashMap<Class<? extends Agent>, List<? extends Agent>>();\n</code></pre>\n\n<p>The map creation would be readable with Java 7's diamond operator</p>\n\n<pre><code>private final Map<Class<? extends Agent>, List<? extends Agent>> listOfAgents =\n new HashMap<>();\n</code></pre>\n\n<p>or Guava's <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Maps.html#newHashMap%28%29\" rel=\"nofollow\"><code>newHashMap</code></a>.</p>\n\n<pre><code>private final Map<Class<? extends Agent>, List<? extends Agent>> listOfAgents =\n newHashMap();\n</code></pre>\n\n<p>(I like the <code>final</code> keyword here, I saved me from searching code which could change the reference.)</p></li>\n<li><p>According to <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141855.html#1852\" rel=\"nofollow\">Code Conventions for the Java Programming Language , 3 - File Organization</a> field declarations should be before methods. (<code>Model.listOfAgents</code>).</p></li>\n<li><p>I've seen earlier the <code>listOfAgents</code> style variables but I've found <code>agents</code> or <code>agentList</code> more easier to work with. Maybe because if more than one variable starts with <code>listOf</code> it's hard to differentiate them. Hm, I've just noticed that it's actually a map. Then, the list is a little bit misleading. I think <code>agents</code> or <code>agentMap</code> could be better.</p></li>\n<li><p>Instead of maps like</p>\n\n<pre><code>Map<X, List<Y>> \n</code></pre>\n\n<p>use a <code>Multimap</code>. Guava has great implementations. (<a href=\"https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained\" rel=\"nofollow\">Doc</a>, <a href=\"https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap\" rel=\"nofollow\">Javadoc</a>) It's easier to read. (The same is true for new <code>ArrayList<Method>()</code>).</p></li>\n<li><pre><code>System.out.println(\"moving ...\" + this.toString() + \" \" + this.length);\n</code></pre>\n\n<p>You don't need <code>this.</code> here. Modern IDEs use highlighting to separate local variables from instance variables.</p></li>\n<li><p>I'd rename <code>Method m</code> to <code>method</code> for better readability. If you just look at the <code>actions.add(m)</code> line you don't have to search its type to figure out what it is, it's more obvious.</p></li>\n<li><p>I'd move the <code>isAnnotationPresent</code> check to a separate method with an additional check:</p>\n\n<pre><code>private boolean isActionMethod(Method method) {\n if (!method.isAnnotationPresent(Action.class)) {\n return false;\n }\n if (method.getParameterTypes().length != 0) {\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>It prevents runtime errors when the action method has parameters.</p></li>\n<li><p>Extracting out another methods would increase the abstarction level of the code:</p>\n\n<pre><code>public void start() {\n for (final Class<? extends Agent> clazz: agentMap.keySet()) {\n final List<Method> actionMethods =\n getActionMethods(clazz);\n\n for (final Agent agent: agentMap.get(clazz)) {\n runAgentActions(agent, actionMethods);\n }\n }\n}\n\nprivate List<Method> getActionMethods(Class<? extends Agent> clazz) {\n final List<Method> actions = new ArrayList<Method>();\n for (final Method method: clazz.getDeclaredMethods()) {\n if (isActionMethod(method)) {\n actions.add(method);\n }\n }\n return actions;\n}\n\nprivate void runAgentActions(Agent agent, List<Method> actionsMethods) {\n for (final Method actionMethod: actionsMethods) {\n try {\n actionMethod.invoke(agent, new Object[] {});\n } catch (IllegalAccessException |\n IllegalArgumentException | InvocationTargetException e) {\n e.printStackTrace();\n }\n }\n}\n</code></pre>\n\n<p>It provides an overview in the <code>start</code> method about what it does (without the details) and you can still check them if you are interested in.</p></li>\n<li><p>If you don't switch to <code>Multimap</code> iterate over <code>Map.entrySet()</code> instead of <code>keySet</code> and <code>get</code>. It's faster.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T19:15:14.153",
"Id": "73749",
"Score": "1",
"body": "1. I think NetBeans actually notified me of the diamond operator at one point but I forgot about it and never checked what it is. 2. Noted 3. Yes, it's an unfortunate name, it is a map of lists 4. Thanks, haven't heard of Guava before, still struggling with JDK, will check it out. 5. I use this to help me with autocompletion and delete it afterwards, left it out. Thank you for your comments, I appreciate it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T01:27:53.020",
"Id": "42719",
"ParentId": "42332",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "42719",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T18:30:04.827",
"Id": "42332",
"Score": "7",
"Tags": [
"java",
"design-patterns",
"beginner",
"generics",
"simulation"
],
"Title": "Model simulation using Java annotations"
}
|
42332
|
<p>I asked <a href="https://stackoverflow.com/questions/21913273/stdbad-cast-exception-thrown-by-dynamic-cast">this</a> question on Stack Overflow and in the comments someone had this to say.</p>
<blockquote>
<p>In a proper design, you should almost never have to do a dynamic_cast, even if it's hidden inside some nice getter function.</p>
</blockquote>
<p>Now this got me thinking a lot. I have been thinking of various ways in which I could eliminate the <code>dynamic_cast</code> in question, or any cast for that matter from my code. Now I come here rather frustrated as the only thing I can think of to get rid of that cast; in that location is by doing the cast elsewhere.</p>
<p>So I ask, how can I improve upon this design?</p>
<pre><code>#include <iostream>
#include <string>
// Properties for all components
class ComponentProperties {
public:
ComponentProperties( std::string componentProperty ):
componentProperty_( componentProperty ) { }
virtual ~ComponentProperties( ) { }
std::string getComponentProperty( ) const { return componentProperty_; }
protected:
std::string componentProperty_;
};
// Properties specific to Textboxes
class TextboxProperties: public ComponentProperties {
public:
TextboxProperties( std::string componentProperty, std::string textboxProperty ):
ComponentProperties( componentProperty ),
textboxProperty_( textboxProperty ) { }
std::string getTextboxProperty( ) { return textboxProperty_; }
private:
std::string textboxProperty_;
};
class Component {
public:
Component( ComponentProperties& properties ):
properties_( properties ) { }
virtual ~Component( ) { }
protected:
ComponentProperties& properties_;
};
class Textbox : public Component {
public:
Textbox( TextboxProperties& properties ):
Component( properties ) { }
// overload << purely for displaying properties.
friend std::ostream & operator << ( std::ostream& out, const Textbox& textbox );
};
std::ostream & operator << ( std::ostream& out, const Textbox& textbox ) {
return out << textbox.properties_.getComponentProperty( ) << ", "
<< dynamic_cast< TextboxProperties& >( textbox.properties_ ).getTextboxProperty( );
}
int main( ) {
TextboxProperties properties( "PropertyOne", "PropertyTwo" );
Textbox textbox( properties );
std::cout << textbox << std::endl;
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>There are a number of ways you can remove the dynamic cast here. The first thing that comes to my mind in this case is the Decorator Pattern which will allow you to compose your properties classes.</p>\n\n<p>Alternatively,</p>\n\n<p>A simpler solution might be to make the <code>getComponentProperty()</code> method virtual, override it in TextboxProperties, and have the TextboxProperties version return a combination of both the <code>componentProperty_</code> and <code>textboxProperty_</code> formatted appropriately.</p>\n\n<p>In this case it might be better to rename <code>getComponentProperty()</code> as something like <code>getProperties()</code> or <code>getPropertiesAsString()</code>. This would remove the need for the <code>getTextboxProperty()</code> method in your TextboxProperties class.</p>\n\n<p>Ideally, you should think of your base class as the client interface to your derived classes. If user's only have access to pointers to a base class, they shouldn't need to know which derived classes exist at all, they should be able to accomplish their tasks with the base class public interface. The base class should then have points of customization (virtual functions) where derived classes can implement their own specific behaviors. At least, this is how it would work in an ideal situation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T21:01:28.583",
"Id": "42338",
"ParentId": "42335",
"Score": "2"
}
},
{
"body": "<p>The best solution is to make <code>ComponentProperties</code> know how to print itself.</p>\n\n<pre><code> class ComponentProperties {\n friend std::ostream& operator<<(std::ostream& s, ComponentProperties const& d) {\n return d.print(s);\n }\n virtual std::ostream& print(std::ostream& s) const {\n return s << componentProperty_;\n }\n // STUFF\n };\n\n class TextboxProperties: public ComponentProperties {\n virtual std::ostream& print(std::ostream& s) const {\n return ComponentProperties::print(s) << \", \" << textboxProperty_;\n }\n // STUFF\n };\n\n class Component {\n // PS. I tend to put my simple friend class definitions.\n // inline within the class. They are after all part\n // of the classes public interface and tightly bound\n // to the implementation of the class.\n friend std::ostream& operator<<(std::ostream& out, const Component& component) { \n return out << component.properties_;\n }\n // STUFF\n };\n</code></pre>\n\n<p>Advantage of doing it this way is you can get rid of this getter methods.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T05:39:44.953",
"Id": "42392",
"ParentId": "42335",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T19:25:45.450",
"Id": "42335",
"Score": "5",
"Tags": [
"c++",
"inheritance",
"casting",
"polymorphism",
"c++03"
],
"Title": "Avoiding casts in abstract types"
}
|
42335
|
<p>Does this look like a good method to hash a user password? I'm not very familiar with how this whole hashing process works and below is a bunch of stuff I've seen on many different posts.</p>
<p>My main concern are all of the numbers. Do they all need to match? Do they need to match something like the <code>array.copy</code>?</p>
<p>And then the <code>array.copy</code> lines. I just want to try and understand it better before I move forward with it further.</p>
<pre><code>public const int SALT_BYTE_SIZE = 16;
public const int HASH_BYTE_SIZE = 20;
[ChildActionOnly]
private static void CreateHash(string password)
{
// Generate Random Salt
RNGCryptoServiceProvider csprng = new RNGCryptoServiceProvider();
byte[] salt = new byte[SALT_BYTE_SIZE];
csprng.GetBytes(salt);
// hash value
var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 10000);
byte[] hash = pbkdf2.GetBytes(20);
// combine salt + hash
byte[] hashBytes = new byte[HASH_BYTE_SIZE];
Array.Copy(salt, 0, hashBytes, 0, 16);
Array.Copy(hash, 0, hashBytes, 16, 20);
// Convert hash into string to DB storage
string savedPasswordHash = Convert.ToBase64String(hashBytes);
// save to DB
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T23:07:54.353",
"Id": "72859",
"Score": "0",
"body": "Both `RNGCryptoServiceProvider` and `Rfc2898DeriveBytes` implement `IDisposable`, so you should be wrapping each of their lifetimes in `using` statements."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T10:25:18.970",
"Id": "72945",
"Score": "0",
"body": "`Rfc2898DeriveBytes` has a built in salt generator."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T15:32:19.367",
"Id": "72991",
"Score": "0",
"body": "@CodesInChaos Does that allow me to grab the salt for storage in the DB? I'll have to look into that and see what it does. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-05T04:50:04.547",
"Id": "428801",
"Score": "0",
"body": "`hashBytes` is an unfortunate name since it contains more than just `hash`. This amalgamation is generally called `digest`."
}
] |
[
{
"body": "<p>Looks fine for the most part. The main thing here is to make sure that the function to generate and compare the hash with existing matches what you have.</p>\n\n<p>As far as <code>Array.Copy</code>, check out <a href=\"http://msdn.microsoft.com/en-us/library/system.array.copy%28v=vs.110%29.aspx\" rel=\"nofollow\">MSDN</a> for this particular overload.</p>\n\n<p>Since you set the salt and hash size to 16 and 20 accordingly, what it's doing below is copying the value from <code>salt</code> and <code>hash</code> into the <code>hashBytes</code> array.</p>\n\n<pre><code>Array.Copy(salt, 0, hashBytes, 0, 16);\nArray.Copy(hash, 0, hashBytes, 16, 20);\n</code></pre>\n\n<p><code>hashBytes</code> will store bytes from <code>salt</code> on index 1-15, and the next line, bytes from <code>hash</code> will be stored on index 16-35.</p>\n\n<p>The problem with this is your <code>byte[] hashBytes = new byte[HASH_BYTE_SIZE]</code> is being set to 20 which is not equal to the size of the <code>salt</code> (16) and <code>hash</code> (20) combined. It will NOT work since the size of the array is not big enough to hold the range of values being stored.</p>\n\n<p>It should be below to accommodate the combined size of the hash and the salt:</p>\n\n<pre><code>byte[] hashBytes = new byte[SALT_BYTE_SIZE + HASH_BYTE_SIZE];\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T22:57:35.393",
"Id": "42349",
"ParentId": "42342",
"Score": "2"
}
},
{
"body": "<p>No, your code does not look good.</p>\n\n<p>Since you did not mention that your code is for personal research, I am assuming it is for getting work done. For such a case it contains too many low-level details. Just use an existing password hashing library and be done with the whole task. Your code should then become one-liners:</p>\n\n<pre><code>var hashed = PasswordHashing.Hash(password);\n</code></pre>\n\n<p>and</p>\n\n<pre><code>if (PasswordHashing.Check(hashed, password)) { … }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-04T17:50:20.437",
"Id": "428743",
"Score": "0",
"body": "That's kind of harsh. Isn't Rfc2898DeriveBytes the equivalent of 'PasswordHashing' here? He is using existing APIs both for generating the salt and hash."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-04T20:14:44.590",
"Id": "428763",
"Score": "0",
"body": "No, it isn't. When using bcrypt, the code is really a single line. When using bcrypt, there is no hard-coded 10000 or 20 or 16 or another 16, or any mention of Base64. Each of these numbers is a potential source of errors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-05T04:48:27.770",
"Id": "428800",
"Score": "0",
"body": "There are indeed packages with less overhead than built-in .NET Framework. As long the framework doesn't foresee an equivalent facade, hiding these remaining details, there is nothing wrong combining the salt and hash yourself. The main argument I like his approach is he used best practices without using third party libraries."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-03T07:35:34.727",
"Id": "148808",
"ParentId": "42342",
"Score": "-3"
}
}
] |
{
"AcceptedAnswerId": "42349",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T22:10:12.757",
"Id": "42342",
"Score": "2",
"Tags": [
"c#",
"hashcode"
],
"Title": "Hashing a password"
}
|
42342
|
<p>I'm not sure about that if else statement in function Change(). I'm guessing there is a way to eliminate this and make better use of OOP principles. Does anyone have any suggestions? </p>
<p>PS This code is functional and produces the desired result.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1_testStrategy
{
class Program
{
static void Main(string[] args)
{
string message = "mytext";
Changer chng = new Changer();
//THis is how I want the usage, I want the user to specify the string
//and also which algorithm to invoke by specifyin the enumeration type
string messageModified = chng.Change(message, types.type2);
}
}
//ENUMERATION OF TYPES
public enum types
{
type1,
type2
}
//Abstact strategy
public interface IStringModifier
{
string Modify(string input);
}
//concrete strategy 1
class type1 : IStringModifier
{
public string Modify(string input)
{
return "hello1";
}
}
//conctrete strategy 2
class type2 : IStringModifier
{
public string Modify(string input)
{
return "hello2";
}
}
//MAIN API I WANT USER TO ACCESS
public class Changer
{
public Changer()
{
}
private IStringModifier _stringModifier;
public void SetStringModifier(IStringModifier stringModefier){
this._stringModifier = stringModefier;
}
public string Change(string text, types type) //not sure about this part
{
if (type == types.type1)
{
SetStringModifier(new type1());
}
else if (type == types.type2)
{
SetStringModifier(new type2());
}
return _stringModifier.Modify(text);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T22:41:22.260",
"Id": "72848",
"Score": "0",
"body": "Is this functional code? As in, you can run it and it works?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T22:50:24.687",
"Id": "72852",
"Score": "0",
"body": "It compiles, I tested it briefly - actually it wont work how I want anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T22:57:35.197",
"Id": "72854",
"Score": "0",
"body": "I'd love to help you out but you should probably read [this](http://meta.codereview.stackexchange.com/q/813/29587)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T22:59:37.290",
"Id": "72855",
"Score": "0",
"body": "did I post to the wrong site?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T23:02:02.693",
"Id": "72856",
"Score": "0",
"body": "That's what I'm thinking but I'm not a moderator. Generally, this site is for fully functional code that needs improvement. Questions about design in general are better directed to [Programmers](http://programmers.stackexchange.com) or something. Also see [this](http://meta.codereview.stackexchange.com/q/1503/29587)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T23:04:37.170",
"Id": "72857",
"Score": "0",
"body": "Ok i'll make it fully functional, I want improvement suggestions, and I know what I need to fix to make it work"
}
] |
[
{
"body": "<p>You can do this more elegantly by specifying a <code>Func</code> delegate instead of an enum and a set of interfaces.</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n string message = \"mytext\";\n\n Changer chng = new Changer();\n\n string messageModified = chng.Change(message, Strategy2); \n }\n\n // These methods have a Func<string,string> signature\n // i.e. accept string as parameter and return a string\n static string Strategy1(string input)\n {\n return \"hello1\";\n }\n static string Strategy2(string input)\n {\n return \"hello2\";\n }\n}\n\npublic class Changer\n{\n public Changer()\n {\n }\n\n private Func<string,string> _stringModifier;\n\n public void SetStringModifier(Func<string,string> stringModifier)\n {\n this._stringModifier = stringModifier;\n }\n\n public string Change(string text, Func<string,string> stringModifier)\n {\n SetStringModifier(stringModifier); // why?\n\n return _stringModifier(text);\n }\n}\n</code></pre>\n\n<blockquote>\n <p>what was meant by the comment <code>//why?</code></p>\n</blockquote>\n\n<p>I would have thought that one of the following might be better.</p>\n\n<p>Either, set the strategy once and use it repeatedly, like this ...</p>\n\n<pre><code>public class Changer\n{\n public Changer()\n {\n }\n\n private Func<string,string> _stringModifier;\n\n public void SetStringModifier(Func<string,string> stringModifier)\n {\n this._stringModifier = stringModifier;\n }\n\n public string Change(string text)\n {\n return _stringModifier(text);\n }\n}\n</code></pre>\n\n<p>... or like this ...</p>\n\n<pre><code>public class Changer\n{\n public Changer(Func<string,string> stringModifier)\n {\n this._stringModifier = stringModifier;\n }\n\n private Func<string,string> _stringModifier;\n\n public string Change(string text)\n {\n return _stringModifier(text);\n }\n}\n</code></pre>\n\n<p>Or, pass the strategy into the Change method every time, in which case there's no need to store it in as member data, like this ...</p>\n\n<pre><code>public class Changer\n{\n public Changer()\n {\n }\n\n public string Change(string text, Func<string,string> stringModifier)\n {\n return stringModifier(text);\n }\n}\n</code></pre>\n\n<blockquote>\n <p>Thank you, another question is, wouldn't this allow the user to just write their own strategy and pass it to chng.Change() method?</p>\n</blockquote>\n\n<p>Yes it would. That's often a good thing: it makes the class more 'flexible', so that it can be used in ways you hadn't imagined.</p>\n\n<blockquote>\n <p>And if my end goal is to make this an API, is that acceptable? Should I restrict them like I did in my original post using the enumeration?</p>\n</blockquote>\n\n<p>I don't know. If you want to keep the enum, you could still use a Func delegate instead of an interface with several subclasses (and use a switch statement instead of repeated if/else).</p>\n\n<pre><code>public class Changer\n{\n public Changer()\n {\n }\n\n private Func<string,string> _stringModifier;\n\n public void SetStringModifier(Types type)\n {\n switch (type)\n {\n case Types.Type1:\n this._stringModifier = Strategy1;\n break;\n case Types.Type2:\n this._stringModifier = Strategy2;\n break;\n default:\n throw new NotImplementedException();\n }\n\n public string Change(string text)\n {\n return _stringModifier.Modify(text);\n }\n\n static string Strategy1(string input)\n {\n return \"hello1\";\n }\n static string Strategy2(string input)\n {\n return \"hello2\";\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T02:03:56.527",
"Id": "72889",
"Score": "0",
"body": "Thank you, another question is, wouldn't this allow the user to just write their own strategy and pass it to chng.Change() method? And if my end goal is to make this an API, is that acceptable? Should I restrict them like I did in my original post using the enumeration?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T20:46:04.083",
"Id": "73104",
"Score": "0",
"body": "Is there a way to preserve the original that uses interfaces, and also eliminate the need for conditionals?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T20:49:20.137",
"Id": "73106",
"Score": "1",
"body": "@erotavlas How about `public string Change(string text, IStringModifier stringModifier)`? You can remove the enum and expect the caller to create and pass an instance of a class which implements the required interface."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T00:10:34.663",
"Id": "42358",
"ParentId": "42343",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T22:20:24.873",
"Id": "42343",
"Score": "2",
"Tags": [
"c#",
"design-patterns",
".net"
],
"Title": "Are there any improvements I can make to my implementation of the strategy pattern?"
}
|
42343
|
<p>I have several generic methods that use the <code>typeof</code> operator to determine the type of mapper class to create. Eventually this is going to get out of hand.</p>
<p>Can anyone suggest a better way to handle this? I have been reading up a bit and it seems like an abstract factory pattern or IOC would be a good pattern to use. I'm not familiar with IOC. Can someone provide an opinion on which would be better in this scenario?</p>
<pre><code>internal UpdateStudentDocumentRequest MapDocToUpdateDocumentRequest<T>(T doc)
{
Type docType = typeof(T);
//V1
if
(
docType == typeof(IndV1201314Model) ||
docType == typeof(IndV1201415Model) ||
docType == typeof(DepV1201415Model)
)
{ return new V1DocMapper<Models.Verification.V1Base>().MapV1ToUpdateStudentDocumentRequest(doc as Models.Verification.V1Base); }
//V3
if
(
docType == typeof(IndV3201314Model) ||
docType == typeof(IndV3201415Model) ||
docType == typeof(DepV3201415Model)
)
{ return new V3DocMapper<Models.Verification.V3Base>().MapV3ToUpdateStudentDocumentRequest(doc as Models.Verification.V3Base); }
//FASchol
if (docType == typeof(FAScholModel))
{return new FAScholMapper().MapFAScholToUpdateStudentDocumentRequest(doc as FAScholModel);}
return new UpdateStudentDocumentRequest();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T08:41:40.317",
"Id": "72941",
"Score": "0",
"body": "The over-the-counter remedy would be visitor pattern or making each document map itself, but the real useful answer would depend on who owns what classes, for example if different teams/vendors own document and mapper classes. Even if you own all of them which classes are in the same assembly (and are easy to modify together)."
}
] |
[
{
"body": "<p>IOC vs Abstract factory is kind of an apples to oranges question. Abstract factory assumes you have a collection of related classes for which you don't want to know any of details involved in creating instances of those classes. IOC doesn't necessarily abstract you away from the creation, it just sort of moves it to another area of your code base. In your particular scenario, one way to simplify that code might be like this</p>\n\n<pre><code>public class DocumentMappingSelector\n{\n private Dictionary<Type, Type> mappingRoutes = new Dictionary<Type,Type>();\n\n public void AddRoute(DocumentMappingRoute route)\n {\n if (this.mappingRoutes.ContainsKey(route.SourceType))\n {\n // you could throw an exception or replace the route here, for this \n // example i'll just replace it\n if (this.mappingRoutes[route.SourceType] != route.MapperType)\n {\n this.mappingRoutes[route.SourceType] = route;\n }\n else\n {\n this.mappingRoutes.Add(route.SourceType, route);\n }\n }\n }\n\n public DocumentMappingRoute SelectMappingRoute(Type sourceType)\n {\n DocumentMappingRoute result = null;\n if (this.mappingRoutes.ContainsKey(sourceType))\n {\n result = this.mappingRoutes[sourceType];\n }\n return result;\n }\n}\n\npublic class DocumentMappingRoute\n{\n public DocumentMappingRoute(Type sourceTypeToBeMapped, Type mappingStrategyType, Action<object,UpdateStudentDocumentRequest> mappingProcessAction)\n {\n this.SourceType = sourceTypeToBeMapped;\n this.MapperType = mappingStrategyType;\n this.MappingProcess = mappingProcessAction;\n\n }\n Type SourceType { get; private set; }\n Type MapperType { get; private set; }\n Action<object,UpdateStudentDocumentRequest> PerformMapping { get; private set; }\n}\ninternal UpdateStudentDocumentRequest MapDocToUpdateDocumentRequest<T>(T doc)\n{\n Type sourceType = typeof(T);\n UpdateStudentDocumentRequest updateStudentDocumentRequestInstance = new UpdateStudentDocumentRequest ();\n return selectorInstance.SelectMappingRoute(sourceType).MappingProcess(doc, updateStudentDocumentRequestInstance); // you might not need the updateStudentDocumentRequestIsntance paramter here\n}\n</code></pre>\n\n<p>For give any errors, I didn't type this in visual studio I just typed it in this editor. </p>\n\n<ol>\n<li>Create and Add Document mapping routes to the selector</li>\n<li>Get the mapping from the selector</li>\n</ol>\n\n<p>Sorry this doesn't show the full code. I ran short on time, but this should give you a general direction that will keep your code tight. Let me know if you have any questions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:34:26.540",
"Id": "73308",
"Score": "0",
"body": "there is a bug in the AddRoute method... i'll fix it in a few"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:26:04.210",
"Id": "42545",
"ParentId": "42344",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T22:23:46.990",
"Id": "42344",
"Score": "5",
"Tags": [
"c#",
"factory-method"
],
"Title": "Abstract factory or inversion of control pattern?"
}
|
42344
|
<p>I got a lot of good feedback on <a href="https://codereview.stackexchange.com/q/42232/29587">my other question</a>. So I will take another swing at it, post my revisions, and hopefully get some more.</p>
<p>First, the configuration hasn't changed. Here's the JSON file:</p>
<pre><code>{
"DisplaySettings": {
"IsFullScreen": false,
"PreferredBackBufferWidth": 800,
"PreferredBackBufferHeight": 600
},
"GamePadSettings": {
"Back": "Exit",
"DPadDown": "MoveDown",
"DPadLeft": "MoveLeft",
"DPadRight": "MoveRight",
"DPadUp": "MoveUp"
},
"KeyboardSettings": {
"Escape": "Exit",
"S": "MoveDown",
"A": "MoveLeft",
"D": "MoveRight",
"W": "MoveUp"
}
}
</code></pre>
<p>This is parsed into a Settings object:</p>
<pre><code>public class Settings
{
public DisplaySettings DisplaySettings = new DisplaySettings();
public GamePadSettings GamePadSettings = new GamePadSettings();
public KeyboardSettings KeyboardSettings = new KeyboardSettings();
}
public class DisplaySettings
{
public bool IsFullScreen = false;
public int PreferredBackBufferWidth = 800;
public int PreferredBackBufferHeight = 600;
}
public class GamePadSettings
{
public string Back = "Exit";
public string DPadDown = "MoveDown";
public string DPadLeft = "MoveLeft";
public string DPadRight = "MoveRight";
public string DPadUp = "MoveUp";
}
public class KeyboardSettings
{
public string Escape = "Exit";
public string S = "MoveDown";
public string A = "MoveLeft";
public string D = "MoveRight";
public string W = "MoveUp";
}
</code></pre>
<p>I might still change these to properties, but public fields are simple and work well with the JSON parser. Main method of Program is largely the same, except now I pass <code>level</code> and <code>player</code> to the Input class:</p>
<pre><code>public static class Program
{
private static void Main( string[] args )
{
IFileHandler fileHandler = new JsonHandler();
var settings = fileHandler.Read<Settings>( "settings.json" );
var level = fileHandler.Read<Level>( "level.json" );
var player = fileHandler.Read<Entity>( "player.json" );
using ( var game = new MyGame( new Graphics( settings.DisplaySettings, level, player ),
new Input( settings.GamePadSettings, settings.KeyboardSettings, level, player ) ) )
{
game.Run();
fileHandler.Write( "player.json", player );
fileHandler.Write( "level.json", level );
}
}
}
</code></pre>
<p>The reason for this change is MyGame doesn't handle the player actions directly anymore:</p>
<pre><code>public class MyGame : Game
{
private readonly IGraphics graphics;
private readonly IInput input;
public MyGame( IGraphics graphics, IInput input )
{
if ( graphics == null || input == null )
{
throw new ArgumentNullException();
}
this.graphics = graphics;
this.input = input;
graphics.Setup( this );
input.Setup( this );
}
protected override void Update( GameTime gameTime )
{
input.Process();
base.Update( gameTime );
}
protected override void Draw( GameTime gameTime )
{
graphics.Draw();
base.Draw( gameTime );
}
}
</code></pre>
<p>Input handles them instead:</p>
<pre><code>public class Input : IInput
{
private readonly GamePadSettings gamePadSettings;
private readonly KeyboardSettings keyboardSettings;
private readonly Level level;
private readonly Entity player;
private Game game;
private IDictionary<Buttons, string> gamePadBindings;
private IDictionary<Keys, string> keyboardBindings;
private GamePadState gamePadState;
private KeyboardState keyboardState;
public Input( GamePadSettings gamePadSettings, KeyboardSettings keyboardSettings, Level level, Entity player )
{
if ( gamePadSettings == null || keyboardSettings == null || level == null || player == null )
{
throw new ArgumentNullException();
}
this.gamePadSettings = gamePadSettings;
this.keyboardSettings = keyboardSettings;
this.level = level;
this.player = player;
}
public void Setup( Game game )
{
if ( game == null )
{
throw new ArgumentNullException();
}
this.game = game;
SetupGamePad();
SetupKeyboard();
}
public void Process()
{
ProcessGamePad();
ProcessKeyboard();
}
private void SetupGamePad()
{
gamePadBindings = new Dictionary<Buttons, string>
{
{ Buttons.Back, gamePadSettings.Back },
{ Buttons.DPadDown, gamePadSettings.DPadDown },
{ Buttons.DPadLeft, gamePadSettings.DPadLeft },
{ Buttons.DPadRight, gamePadSettings.DPadRight },
{ Buttons.DPadUp, gamePadSettings.DPadUp }
};
}
private void SetupKeyboard()
{
keyboardBindings = new Dictionary<Keys, string>
{
{ Keys.Escape, keyboardSettings.Escape },
{ Keys.S, keyboardSettings.S },
{ Keys.A, keyboardSettings.A },
{ Keys.D, keyboardSettings.D },
{ Keys.W, keyboardSettings.W }
};
}
private void ProcessGamePad()
{
gamePadState = GamePad.GetState( PlayerIndex.One );
if ( !gamePadState.IsConnected )
{
return;
}
foreach ( var binding in gamePadBindings )
{
if ( gamePadState.IsButtonDown( binding.Key ) )
{
DoAction( binding.Value );
}
}
}
private void ProcessKeyboard()
{
keyboardState = Keyboard.GetState( PlayerIndex.One );
foreach ( var binding in keyboardBindings )
{
if ( keyboardState.IsKeyDown( binding.Key ) )
{
DoAction( binding.Value );
}
}
}
private void DoAction( string action )
{
if ( action.Equals( Actions.Exit, StringComparison.OrdinalIgnoreCase ) )
{
game.Exit();
return;
}
if ( action.Equals( Actions.MoveDown, StringComparison.OrdinalIgnoreCase ) )
{
Scroll( Directions.Down );
return;
}
if ( action.Equals( Actions.MoveLeft, StringComparison.OrdinalIgnoreCase ) )
{
Scroll( Directions.Left );
return;
}
if ( action.Equals( Actions.MoveRight, StringComparison.OrdinalIgnoreCase ) )
{
Scroll( Directions.Right );
return;
}
if ( action.Equals( Actions.MoveUp, StringComparison.OrdinalIgnoreCase ) )
{
Scroll( Directions.Up );
return;
}
}
private void Scroll( Vector2 direction )
{
// TODO: Collision detection
player.Turn( direction );
player.Animate();
level.Move( direction * -1 );
}
}
</code></pre>
<p>Before, I was using reflection to create a dictionary of bindings. This seemed pretty elegant, but had several problems. What I lose in elegance though I more than gain (in my humble opinion) in simplicity. i.e., the DoAction method is very easy to understand. In addition, I no longer have to worry about accidentally exposing a method the user can access via configuration, I don't have a bunch of methods that ReSharper can't find usages of, and performance should be improved.</p>
<p>So what do you think? Is this better than <a href="https://codereview.stackexchange.com/q/42232/29587">my previous attempt</a>? What else can be improved?</p>
|
[] |
[
{
"body": "<p>I guess one minor thing is I might suggest refactoring DoAction to something like below.</p>\n\n<p>Whether that helps improve the code I guess is a matter of opinion. To me though it does appear that you can only do one action at a time so having multiple if statements does not seem plausible to me.</p>\n\n<p>To avoid the need to <code>ToUpperInvariant</code> on the Actions I would consider having them uppercase\nalready.</p>\n\n<pre><code>public void DoAction(string action)\n{\n // Or better move this to a class level instance variable to avoid re-creating\n // every time\n Dictionary<string, Action> actionHandler = new Dictionary<string, Action>\n {\n {Actions.Exit.ToUpperInvariant(), () => game.Exit() },\n {Actions.MoveDown.ToUpperInvariant(), () => Scroll(Directions.Down) },\n {Actions.MoveUp.ToUpperInvariant(), () => Scroll(Directions.Up) },\n {Actions.MoveLeft.ToUpperInvariant(), () => Scroll(Directions.Left) },\n {Actions.MoveRight.ToUpperInvariant(),() => Scroll(Directions.Right) },\n };\n\n actionHandler[action.ToUpperInvariant()]();\n}\n</code></pre>\n\n<p>Or if Dictionary is overkill, I would consider using a switch:</p>\n\n<pre><code>switch(action.ToUpperInvariant()) \n{\n case Actions.Exit.ToUpperInvariant():\n game.Exit();\n break;\n case Actions.MoveDown.ToUpperInvariant():\n Scroll(Directions.Down);\n break;\n case Actions.MoveMoveUp.ToUpperInvariant():\n Scroll(Directions.Up);\n break;\n case Actions.MoveLeft.ToUpperInvariant():\n Scroll(Directions.Left);\n break;\n case Actions.MoveRight.ToUpperInvariant():\n Scroll(Directions.Right);\n break;\n}\n</code></pre>\n\n<p>NOTE: Using ToUpper() may not be the fully correct way as discussed <a href=\"https://stackoverflow.com/questions/2334134/how-to-make-the-c-sharp-switch-statement-use-ignorecase\">here</a> but I think from the OP solution it would probably be sufficient.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T23:22:15.683",
"Id": "72864",
"Score": "0",
"body": "Funny, that's almost what I had before except without the reflection bits. DoAction only processes one action at a time but it is being called continuously, so it actually looks like several things are happening on the screen simultaneously. It's magical."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T23:27:54.077",
"Id": "72865",
"Score": "0",
"body": "One thing I just thought of: both of these require case-sensitivity no?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T23:42:22.857",
"Id": "72868",
"Score": "0",
"body": "@davidkennedy85 Is there a reason why they need to be case-insensitive?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T23:44:39.627",
"Id": "72869",
"Score": "0",
"body": "They should probably be case-insensitive because the names of the methods are specified in a configuration file."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T23:49:32.813",
"Id": "72870",
"Score": "0",
"body": "Ok, you could ToLower() everything I guess but perhaps Enums might be the better way to go (Other than using classes and inheritance/interfaces so that this switching is not required)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T16:10:03.893",
"Id": "73003",
"Score": "0",
"body": "I'm doing something not altogether unlike this, myself. Because I'm making a fighter, I not only had to bind keys, but match sequences (backward, due to varying lengths). It's nice to see a similar approach here. I hope your game is in a far easier genre."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T17:55:33.150",
"Id": "73037",
"Score": "0",
"body": "Is there any real difference between `action.ToUpperInvariant() == Actions.MoveDown.ToUpperInvariant()` and `action.Equals( Actions.MoveDown, StringComparison.OrdinalIgnoreCase)`?"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T23:19:27.523",
"Id": "42352",
"ParentId": "42345",
"Score": "4"
}
},
{
"body": "<p>There are two design issues I can see:</p>\n\n<ul>\n<li><code>Game</code> class stands for two things, game as a whole and game logic component.</li>\n</ul>\n\n<blockquote>\n <p>I don't understand this part.</p>\n</blockquote>\n\n<p>When I say \"game-as-whole,\" I mean it is a top level component that has an aggregation (HAS-A) relationship with subcomponents. When I read <code>Program</code> and <code>MyGame</code>:</p>\n\n<pre><code>public class MyGame : Game\n{\n private readonly IGraphics graphics;\n private readonly IInput input;\n</code></pre>\n\n<p>This class is, or is like, the aggregate root of all the components.</p>\n\n<blockquote>\n <p>Since I'm using XNA, I don't think I can\n get around the requirement for MyGame to extend XNA's Game class and\n to implement Update and Draw methods. Where else would I do this?</p>\n</blockquote>\n\n<p>They could stay in <code>MyGame</code>. But where would, for example, the code that determines whether is over (an example of game logic) go?</p>\n\n<blockquote>\n <p>I try to hand those tasks off as best I can by having Input handle key\n presses (for example), but then Input is doing game logic - why is\n this bad?</p>\n</blockquote>\n\n<p>If you separate your components at an inappropriate boundary their surfaces (the sum of the public interface[s] they expose and the public interface[s] of the objects they depend on) become too large. More concretely, since <code>Input</code> is the component that knows about <code>player</code> and <code>level</code> any collision detection method (an example of game logic) would want to be there. If you put them there, other methods that depend on collision (e.g. score keeping) may want to go there, and so on. The name <code>Input</code> implies no such intention.</p>\n\n<blockquote>\n <p>And what exactly do you mean by \"game logic\" anyways?</p>\n</blockquote>\n\n<p>When I say \"game logic component,\" I mean the top level object that encapsulates objects that are related to the \"model\" part of the software, such as <code>player</code>, <code>level</code> and methods that act on them such as <code>DoAction</code>.</p>\n\n<p>The best analogy I can think of now is a desktop computer:</p>\n\n<pre><code>class Program\n{\n void Main()\n {\n var motherboard = new MotherBoard();\n var networkCard = new NetworkCard();\n var graphicsCard = new GraphicsCard();\n var computer = assembleInACase( motherboard, networkCard, graphicsCard );\n\n computer.pressStartButton();\n }\n\n IComputer assembleInACase( MotherBoard motherboard, NetworkCard networkCard, GraphicsCard graphicsCard )\n {\n IComputer computer = new ComputerCase( motherboard, networkCard, graphicsCard );\n\n // Wire up cards\n networkCard.pciExpressEvent += motherboard.pciExpressEventHandler;\n graphicsCard.agpEvent += motherboard.agpEventHandler;\n\n return computer;\n }\n}\n</code></pre>\n\n<p>In the above example <code>ComputerCase:IComputer</code> is analogous to \"game-as-whole\" and <code>MotherBoard</code> is analogous to \"game logic.\" Frameworks like XNA are infrastructure, and you should isolate them from the game logic. <code>MyGame:Game</code> is analogous to <code>ComputerCase:AC110_220VDevice</code> or <code>ComputerCase:DC12VDevice</code>. The motherboard doesn't need to know about the power inlet, but the computer as a whole does.</p>\n\n<ul>\n<li><code>Input</code> does game logic, which is partly caused by the first.</li>\n</ul>\n\n<p>From the snippet below:</p>\n\n<pre><code>public class Input : IInput\n{\n private readonly GamePadSettings gamePadSettings;\n private readonly KeyboardSettings keyboardSettings;\n private readonly Level level;\n private readonly Entity player;\n private Game game;\n private IDictionary<Buttons, string> gamePadBindings;\n private IDictionary<Keys, string> keyboardBindings;\n private GamePadState gamePadState;\n private KeyboardState keyboardState;\n</code></pre>\n\n<p><code>Input</code> knows about <code>level</code> and <code>player</code>, which is a case of <strong>inappropriate intimacy</strong>.\n[EDIT: Because what <code>Input</code> class does with them is not related strictly to input. These fields are internals of <code>MyGame</code> class. A class named <code>Input</code> should not have to change because I decide to use <code>LevelV2</code> instead of <code>Level</code>, <code>Some.Other.Namespace.Level</code>, or no <code>Level</code> at all. <strong>Inappropriate intimacy</strong> is a violation of the single responsibility principle. In this particular case <code>Input</code> is an <strong>adapter</strong>. It separates game logic, which only needs to know users' intended actions (move left, move up), from actual keystrokes. In the code from the original post however we see it knows too much about <code>MyGame</code>, therefore it doesn't separate game logic as well as expected. An ideal separator has very low coupling with both components it separates.]</p>\n\n<p><code>Input</code> depends on <code>Game</code>, and even if this would not automatically mean a circular dependency if <code>Game</code> <em>were</em> an interface, it is a violation of the <strong>interface segregation principle</strong>. Instead an input class would depend on a specific interface (e.g. <code>IInputHandler</code>) and <code>Game</code> class would implement it in addition to other interfaces it exposes to other components.</p>\n\n<p>In the code provided <code>gamePadState</code> and <code>keyboardState</code> fields are not used, and it seems they would not need to be used in the code as a whole. They could be local variables.</p>\n\n<p><code>gamePadSettings</code> and <code>keyboardSettings</code> are not used after <em>setup</em> (object creation time). Since they are not used and <code>Input</code> depends on <code>gamePadBindings</code> and <code>keyboardBindings</code> during its lifetime it should depend on them only (get them as constructor args).</p>\n\n<p>In the method <code>private void DoAction( string action )</code>, <code>action</code> parameter can only take a value from a fixed set: <code>{\"Exit\", \"MoveDown\", ...}</code>. This is a case of <strong>primitive obsession</strong>. This concept can better be implemented as an <code>enum</code> : <code>enum Actions {Exit, MoveDown, ...}</code>.</p>\n\n<p>You can now decouple <code>Game</code> and <code>Input</code> by declaring an event handler:</p>\n\n<pre><code>public enum Actions {Exit, MoveLeft, ...}\n\npublic delegate void ActionHandler( Actions action );\n\npublic interface IInput {\n\n // Change the name of the event to something that makes sense to you\n event ActionHandler ActionRequested;\n\n // Setup method can be removed\n</code></pre>\n\n<p><code>DoAction</code> can then be moved to another class, making <code>Input</code> follow the <strong>single responsibility principle</strong> more closely.</p>\n\n<p>This class now encapsulates user input and converts them to game actions and does nothing else:</p>\n\n<pre><code>public class Input : IInput\n{\n // See how much smaller the surface is now\n public event ActionHandler ActionRequested;\n\n private IDictionary<Buttons, Actions> gamePadBindings;\n private IDictionary<Keys, Actions> keyboardBindings;\n\n public Input( IDictionary<Buttons, Actions> gamePadBindings,\n IDictionary<Keys, Actions> keyboardBindings )\n {\n // ...\n }\n\n // This does one thing, although Process is too generic a name\n public void Process()\n {\n ProcessGamePad();\n ProcessKeyboard();\n }\n\n private void ProcessGamePad()\n {\n var actions = GetPressedButtons().Select( button => GetActionFor(button) );\n foreach ( var action in actions )\n ActionRequested( action );\n }\n\n private void ProcessKeyboard()\n {\n // As above...\n }\n}\n</code></pre>\n\n<p>This class encapsulates game logic. It does not depend on infrastructure classes as much as possible:</p>\n\n<pre><code>// Rename me\nclass GameLogic\n{\n // Relieve Input from the burden of these\n private readonly Level level;\n private readonly Entity player;\n\n public void DoAction( Actions action )\n {\n // ...\n }\n\n // This is now a good place to hang new behavior\n // Test whether game ended, keep scores, etc.\n}\n</code></pre>\n\n<p>This class encapsulates subcomponents and enables separation of infrastructure and game logic:</p>\n\n<pre><code>class MyGame : Game\n{\n private readonly IGraphics graphics;\n private readonly IInput input;\n\n public MyGame( IGraphics graphics, IInput input )\n {\n // Disallowing null dependencies makes testing code harder\n // Let's not put it until ABSOLUTELY necessary\n\n this.graphics = graphics;\n this.input = input;\n\n // Nothing other than field assignment\n // graphics.Setup() etc. belongs to a Factory or Main method\n }\n\n protected override void Update( GameTime gameTime )\n {\n // No change\n }\n\n protected override void Draw( GameTime gameTime )\n {\n // No change\n }\n}\n</code></pre>\n\n<p>By moving the setup code to <code>Program</code>, it enables further refactorings and extraction of factory methods/classes:</p>\n\n<pre><code>class Program\n{\n void Main()\n {\n IFileHandler fileHandler = new JsonHandler();\n\n var settings = fileHandler.Read<Settings>( \"settings.json\" );\n\n var level = fileHandler.Read<Level>( \"level.json\" );\n var player = fileHandler.Read<Entity>( \"player.json\" );\n\n // Move SetupGamePad method to a public method and rename it\n // so it can be tested and also keeps Input class more focused.\n var gamePadBindings = CreateGamePadBindings( settings.GamePadSettings );\n\n // Do the same for SetupKeyboard method\n // var keyboardBindings = ...\n\n var inputHandler = new Input( gamePadBindings, keyboardBindings );\n\n using ( var game = new MyGame( new Graphics(...), inputHandler ) )\n {\n // TODO game set up: move to a method\n\n // Taking the wiring out of constructors keeps constructors super simple,\n // makes testing easier and enables us to extract Factory classes as needed.\n inputHandler.ActionRequested += gameLogic.DoAction;\n\n // Also by using an event we broke the circular dependency\n // The same can be done from the graphics below\n graphics.Setup( game )\n\n game.Run();\n\n // TODO game tear down: move to a method\n }\n }\n}\n</code></pre>\n\n<h2>EDIT</h2>\n\n<blockquote>\n <p>Should <code>GameLogic</code> have a dependency on <code>Game</code>? When the escape key is pressed, I need to call <code>Game.Exit()</code>, which would be in <code>DoAction()</code>.</p>\n</blockquote>\n\n<p>As I said, I wouldn't make model depend on infrastructure types as much as possible.\nIf pressing Esc is an action in your game then your input handler (<code>Input</code>) would generate an action event,\nand your model (<code>GameLogic</code>) would then generate some <code>GameEnded</code> event after doing something with the model (e.g. save&exit)\nMyGame which listens to events would call <code>Exit()</code>.</p>\n\n<blockquote>\n <p>I can't instantiate Graphics without an instance of Game. This is a limitation of the framework and the reason graphics.Setup( this ) was called in the Game constructor. </p>\n</blockquote>\n\n<p>It should be called, as I did in the example, by the method that calls the <code>new MyGame()</code> constructor.\nIf they should always be together, you can put the two calls in a factory method such as <code>createMyGame()</code> in <code>Program</code>.</p>\n\n<p>Calling <code>graphics.Setup(this)</code> on is bad OOP practice, because:</p>\n\n<ol>\n<li>It <a href=\"http://msmvps.com/blogs/jon_skeet/archive/2010/09/02/don-t-let-this-get-away.aspx\" rel=\"nofollow\">leaks <code>this</code></a> </li>\n<li>You are <a href=\"http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/\" rel=\"nofollow\">doing more than field assignment in constructor</a>.</li>\n<li>Disallows passing <code>null</code> as <code>graphics</code> parameter to the constructor. (Google this one yourself.) That you cannot test pressing Esc causes <code>Game.Exit</code> method to be called without instantiating a graphics object indicates your code isn't modular enough.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T19:24:48.963",
"Id": "73077",
"Score": "0",
"body": "I'm confused: `Input` knows about `level` and `player` because it needs to respond to key presses, which it does by moving the `level` and animating the `player`. That doesn't meet my criteria for **inappropriate intimacy** but please feel free to correct me. As for **interface segregation**, `Input` is only dependent on `Game` for its `Exit` method, which it uses. So I don't detect that code smell either. I *could* stick `Exit` in an interface which `MyGame` implements, but then it smells like **contrived complexity**. Good catch on the `State` and `Settings` objects. Still processing..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T19:31:49.893",
"Id": "73080",
"Score": "0",
"body": "\"`Game` class stands for two things, game as a whole and game logic component.\" I don't understand this part. Since I'm using XNA, I don't think I can get around the requirement for `MyGame` to extend XNA's `Game` class and to implement `Update` and `Draw` methods. Where else would I do this? I try to hand those tasks off as best I can by having `Input` handle key presses (for example), but then `Input` is doing game logic - why is this bad? And what exactly do you mean by \"game logic\" anyways? I don't mean to sound defensive by the way. I actually want to know."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T08:15:52.733",
"Id": "73491",
"Score": "0",
"body": "I tried to explain *inappropriate intimacy* in an EDIT in the question. As for interface segregation: you said \"Input is only dependent on `Game` for its `Exit` method\", however definition of [interface segregation principle](http://en.wikipedia.org/wiki/Interface_segregation_principle) is \"... that no client should be forced to depend on methods it does not use.\" Of course creating an interface like `IExitor` would be too contrived, but moving `DoAction` to `Game` obviated that problem altogether."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T10:39:42.603",
"Id": "73499",
"Score": "0",
"body": "@davidkennedy85 I added more code with review comments in them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T21:15:55.703",
"Id": "73584",
"Score": "0",
"body": "Thanks a lot for the detailed feedback. I have a question and a problem. First, the question: should `GameLogic` have a dependency on `Game`? When the escape key is pressed, I need to call `Game.Exit()`, which would be in `DoAction()`. Second, my problem: [I can't instantiate `Graphics` without an instance of `Game`](http://codereview.stackexchange.com/q/42472/29587). This is a limitation of the framework and the reason `graphics.Setup( this )` was called in the `Game` constructor. How should I handle this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T08:20:03.217",
"Id": "73637",
"Score": "0",
"body": "@davidkennedy85 First of all thanks for the edits. I'll add my answer to you questions about `Game.Exit()` and `graphics.Setup()` because the won't fit in comments."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T09:12:13.563",
"Id": "73643",
"Score": "0",
"body": "@davidkennedy85 I'll take a look at [the other question](http://codereview.stackexchange.com/q/42472/29587)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T10:04:46.103",
"Id": "42404",
"ParentId": "42345",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T22:30:06.413",
"Id": "42345",
"Score": "12",
"Tags": [
"c#",
"game",
"json",
"dependency-injection"
],
"Title": "Setting up keyboard bindings using JSON (no reflection!)"
}
|
42345
|
<pre><code>str, ski = int(input("text here")), int(input("text here"))
if str < 1 or str > 50 or ski < 1 or ski > 50:
print("did not enter between 1 and 50")
</code></pre>
<p>Is there anyway to shorten the if statement in that code? I find that it is a bit too long, but I don't really know how to shorten it.</p>
<p>Any suggestions?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T00:10:54.327",
"Id": "72880",
"Score": "1",
"body": "When asking a question, *please make an effort to choose a good title* that tells the community specifically what the point of the code in question is. I have edited the title to this effect."
}
] |
[
{
"body": "<p>+1 <em>@instanceofTom</em> and you could remove some more duplication and create a more readable code with a named function which would tell the intent of the condition:</p>\n\n<pre><code>def is_valid_property(property):\n return 1 <= property <= 50\n\nif (not is_valid_property(strength) or not is_valid_property(ski)):\n print(\"<> please write numbers between 1 and 50\")\n</code></pre>\n\n<p>(Feel free to rename it, I'm just guessing about the intent.)</p>\n\n<p>Note the changed message too. Error messages shouldn't blame the user (don't say what he did is wrong), give a suggestion about what they should do. (See: <a href=\"https://ux.stackexchange.com/q/48256/14623\">Should we avoid negative words when writing error messages?</a>, <a href=\"https://ux.stackexchange.com/q/8112/14623\">What will be the Best notifications and error messages?</a>)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T23:14:39.237",
"Id": "72861",
"Score": "0",
"body": "This answer can't work for the [same reason](http://codereview.stackexchange.com/questions/42346/how-can-i-shorten-an-if-statement#comment72860_42347) as the other answer, and in addition `!` is a syntax error in Python."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T23:05:17.720",
"Id": "42350",
"ParentId": "42346",
"Score": "0"
}
},
{
"body": "<ul>\n<li><p>This snippet is <em>not very useful</em>. You should not let the user continue after giving you wrong input; rather, as soon as an incorrect number is entered, you should figure out what to do next.<br>\n(As you have not included any context in your question, this is left as an exercise to you).</p></li>\n<li><p>Your <strong>names are extremely poor</strong>:<br>\n<code>str</code> is a library function and should therefore never be used as a variable name.<br>\n<code>str</code> and <code>ski</code> are useless as they do not reveal what the variables are about.<br>\n<strong>Be expressive.</strong></p></li>\n<li><p>You are <strong>repeating yourself</strong> on a small scale: you are writing <code>int(input(...))</code> twice and the two portions of the if statement follow the same logic. <strong>Get rid of the duplication.</strong></p></li>\n</ul>\n\n<p>Consider these improvements applied to your code:</p>\n\n<ol>\n<li>Use list comprehensions and generator expressions to your advantage</li>\n<li>Use the <code>all(...)</code> function with a generator expresssion to verify that all answers are in the specified range</li>\n</ol>\n\n<hr>\n\n<pre><code>prompts = ('text here', 'text here')\nanswers = [int(input(p)) for p in prompts]\nif not all(0 < a <= 50 for a in answers):\n print('did not enter between 1 and 50')\n\n# if you need to access the answers individually, use\nfirst, second = answers\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T23:53:16.160",
"Id": "42355",
"ParentId": "42346",
"Score": "7"
}
},
{
"body": "<p>You could do something like this:</p>\n\n<pre><code>attributes = {}\nfor attribute in [\"STR\", \"PER\", \"END\", \"CHA\", \"INT\", \"AGI\", \"LCK\"]:\n input_value = 0\n while not 1 <= input_value <= 50:\n print \"Please enter a value between 1 and 50 (inclusive).\"\n try:\n input_value = int(input(\"Enter %s: \" % attribute))\n except ValueError:\n pass\n\n attributes[attribute] = input_value\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T05:19:09.010",
"Id": "42391",
"ParentId": "42346",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "42355",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T22:34:35.240",
"Id": "42346",
"Score": "6",
"Tags": [
"python"
],
"Title": "Checking if multiple user-entered numbers are in the right range"
}
|
42346
|
<p>Here is a SQLite Helper Class I created. Any input appreciated, including security and simplification.</p>
<pre><code>using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SQLiteHelper
{
public class EntryList
{
public EntryList()
{
ColumnName = new List<string>();
DbType = new List<DbType>();
Content = new List<string>();
}
public List<string> ColumnName { set; get; }
public List<DbType> DbType { set; get; }
public List<string> Content { set; get; }
}
public class ListWithName
{
public ListWithName()
{
SubItems = new List<string>();
}
public string Text { set; get; }
public List<string> SubItems { set; get; }
}
public class ColumnProperties
{
public string ID { get; set; }
public string Name { get; set; }
public string DataType { get; set; }
public string Content { get; set; }
public bool AllowNull { get; set; }
}
public class Column : IEnumerable<ColumnProperties>
{
public Column()
{
cols = new List<ColumnProperties>();
}
private List<ColumnProperties> cols = new List<ColumnProperties>();
public IEnumerator<ColumnProperties> GetEnumerator()
{
return this.cols.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Add(string Name)
{
ColumnProperties ml = new ColumnProperties();
ml.Name = Name;
ml.DataType = "VARCHAR";
ml.AllowNull = true;
cols.Add(ml);
}
public void Add(string Name, string DataType)
{
ColumnProperties ml = new ColumnProperties();
ml.Name = Name;
ml.DataType = DataType;
ml.AllowNull = true;
cols.Add(ml);
}
public void Add(string Name, string DataType, bool AllowNulls)
{
ColumnProperties ml = new ColumnProperties();
ml.Name = Name;
ml.DataType = DataType;
ml.AllowNull = AllowNulls;
cols.Add(ml);
}
public void Add(string Name, string DataType, bool AllowNulls, string ID)
{
ColumnProperties ml = new ColumnProperties();
ml.Name = Name;
ml.DataType = DataType;
ml.ID = ID;
ml.AllowNull = AllowNulls;
cols.Add(ml);
}
public int Count
{
get { return cols.Count; }
}
}
public class Table
{
public Table()
{
Columns = new Column();
}
public string Name { set; get; }
public Column Columns { set; get; }
}
class SQLiteHelper
{
SQLiteDataReader DataReader;
public string DatabaseFile { set; get; }
public string Password { set; get; }
SQLiteConnection DataBaseConnnection = new SQLiteConnection();
private void SetConnection()
{
if (DataBaseConnnection.State== System.Data.ConnectionState.Open)
{
DataBaseConnnection.Close();
}
if (Password != null)
{
DataBaseConnnection.ConnectionString = @"Data Source=" + DatabaseFile + "; Password=" + Password + ";";
DataBaseConnnection.Open();
}
if (Password == null)
{
DataBaseConnnection.ConnectionString = @"Data Source=" + DatabaseFile + ";";
DataBaseConnnection.Open();
}
}
public void CreateDatabase()
{
SetConnection();
SQLiteConnection.CreateFile(DatabaseFile);
if (Password !=null)
{
DataBaseConnnection.SetPassword(Password);
}
}
public void CreateTable(Table Table)
{
try
{
SetConnection();
string firstLine = "CREATE TABLE IF NOT EXISTS [" + Table.Name + "] ([ID] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ";
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.Append(firstLine);
foreach (var item in Table.Columns)
{
string nl = "";
if (item.AllowNull) nl = "NULL";
else nl = "NOT NULL";
queryBuilder.Append("[" + item.Name + "] " + item.DataType + " " + nl + ", ");
}
queryBuilder.Remove(queryBuilder.Length - 2, 2);
queryBuilder.Append(")");
SQLiteCommand sqliteCommand = new SQLiteCommand(queryBuilder.ToString(), DataBaseConnnection);
sqliteCommand.ExecuteNonQuery();
DataBaseConnnection.Close();
MessageBox.Show(queryBuilder.ToString());
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
frmPassword fp = new frmPassword();
if (fp.ShowDialog() == DialogResult.OK)
{
Password = fp.txtPass.Text;
CreateTable(Table);
}
}
}
public void CreateTable(string TableName, string[] ColumnNames, bool[] AllowNulls, DbType[] DbTypes)
{
TableName = RemoveSpecialCharacters(TableName);
try
{
SetConnection();
string firstLine = "CREATE TABLE IF NOT EXISTS [" + TableName + "] ([ID] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ";
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.Append(firstLine);
for (int i = 0; i < ColumnNames.Length; i++)
{
string nl = "";
if (AllowNulls[i]) nl = "NULL";
else nl = "NOT NULL";
queryBuilder.Append("[" + ColumnNames[i] + "] " + DbTypes[i] + " " + nl + ", ");
}
queryBuilder.Remove(queryBuilder.Length - 2, 2);
queryBuilder.Append(")");
SQLiteCommand sqliteCommand = new SQLiteCommand(queryBuilder.ToString(), DataBaseConnnection);
sqliteCommand.ExecuteNonQuery();
DataBaseConnnection.Close();
MessageBox.Show(queryBuilder.ToString());
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
frmPassword fp = new frmPassword();
if (fp.ShowDialog() == DialogResult.OK)
{
Password = fp.txtPass.Text;
CreateTable(TableName, ColumnNames, AllowNulls, DbTypes);
}
}
}
public void DeleteTable(string TableName)
{
try
{
SetConnection();
SQLiteCommand sqliteCommand = new SQLiteCommand("DROP TABLE IF EXISTS " + TableName, DataBaseConnnection);
sqliteCommand.ExecuteNonQuery();
SQLiteCommand VacuumCommand = new SQLiteCommand("vacuum;", DataBaseConnnection);
VacuumCommand.ExecuteNonQuery();
DataBaseConnnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
frmPassword fp = new frmPassword();
if (fp.ShowDialog() == DialogResult.OK)
{
Password = fp.txtPass.Text;
DeleteTable(TableName);
}
}
}
public List<string> GetTableNames()
{
List<string> tables = new List<string>();
try
{
SetConnection();
SQLiteCommand sqliteCommand = new SQLiteCommand("SELECT NAME FROM sqlite_master WHERE TYPE='table' ORDER BY NAME", DataBaseConnnection);
DataReader = sqliteCommand.ExecuteReader();
while (DataReader.Read())
{
if (DataReader.HasRows)
{
tables.Add(DataReader[0].ToString());
}
}
DataBaseConnnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
return tables;
}
public Column GetColumnsFromTableName(string TableName)
{
TableName = RemoveSpecialCharacters(TableName);
Column cols = new Column();
try
{
SetConnection();
SQLiteCommand sqliteCommand = new SQLiteCommand("PRAGMA table_info('" + TableName + "');", DataBaseConnnection);
DataReader = sqliteCommand.ExecuteReader();
while (DataReader.Read())
{
ColumnProperties ml = new ColumnProperties();
ml.ID = DataReader[0].ToString();
ml.Name = DataReader[1].ToString();
ml.DataType = DataReader[2].ToString();
bool nl = false;
if (DataReader[3].ToString() == "0") nl = true;
if (DataReader[3].ToString() == "1") nl = false;
ml.AllowNull = nl;
cols.Add(DataReader[1].ToString(), DataReader[2].ToString(), nl, DataReader[0].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
return cols;
}
public void CreateEntry(string TableName, EntryList EntryList)
{
TableName = RemoveSpecialCharacters(TableName);
try
{
SetConnection();
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.Append("insert into " + TableName + " (");
foreach (var item in EntryList.ColumnName)
{
queryBuilder.Append(item + ", ");
}
queryBuilder.Remove(queryBuilder.Length - 2, 2);
queryBuilder.Append(")");
queryBuilder.Append(" values (");
foreach (var item in EntryList.ColumnName)
{
queryBuilder.Append("@" + item + ", ");
}
queryBuilder.Remove(queryBuilder.Length - 2, 2);
queryBuilder.Append(")");
SQLiteCommand sqliteCommand = new SQLiteCommand(queryBuilder.ToString(), DataBaseConnnection);
for (int i = 0; i < EntryList.ColumnName.Count; i++)
{
sqliteCommand.Parameters.Add("@" + EntryList.ColumnName[i], EntryList.DbType[i]).Value = EntryList.Content[i];
}
sqliteCommand.ExecuteNonQuery();
DataBaseConnnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
public void CreateEntry(string TableName, object[] Content)
{
TableName = RemoveSpecialCharacters(TableName);
try
{
SetConnection();
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.Append("insert into " + TableName + " (");
foreach (var item in GetColumnsFromTableName(TableName))
{
queryBuilder.Append(item.Name + ", ");
}
queryBuilder.Remove(queryBuilder.Length - 2, 2);
queryBuilder.Append(")");
queryBuilder.Append(" values (");
foreach (var item in GetColumnsFromTableName(TableName))
{
queryBuilder.Append("@" + item.Name + ", ");
}
queryBuilder.Remove(queryBuilder.Length - 2, 2);
queryBuilder.Append(")");
SQLiteCommand sqliteCommand = new SQLiteCommand(queryBuilder.ToString(), DataBaseConnnection);
List<string> colsNames = new List<string>();
foreach (var item in GetColumnsFromTableName(TableName))
{
colsNames.Add(item.Name);
}
for (int i = 0; i < GetColumnsFromTableName(TableName).Count; i++)
{
sqliteCommand.Parameters.Add("@" + colsNames[i], DbType.Object).Value = Content[i];
}
sqliteCommand.ExecuteNonQuery();
DataBaseConnnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
public void DeleteEntry(string TableName, string ColumnName, string Equals)
{
TableName = RemoveSpecialCharacters(TableName);
ColumnName = RemoveSpecialCharacters(ColumnName);
Equals = RemoveSpecialCharacters(Equals);
try
{
SetConnection();
SQLiteCommand sqliteCommand = new SQLiteCommand("DELETE FROM " + TableName + " WHERE " + ColumnName + "=@" + ColumnName, DataBaseConnnection);
sqliteCommand.Parameters.Add("@" + ColumnName, DbType.Object).Value = Equals;
sqliteCommand.ExecuteNonQuery();
SQLiteCommand VacuumCommand = new SQLiteCommand("vacuum;", DataBaseConnnection);
VacuumCommand.ExecuteNonQuery();
DataBaseConnnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
public void UpdateEntry(string TableName, EntryList EntryList, string ColumnName, string Equals)
{
TableName = RemoveSpecialCharacters(TableName);
ColumnName = RemoveSpecialCharacters(ColumnName);
Equals = RemoveSpecialCharacters(Equals);
try
{
SetConnection();
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.Append("update " + TableName + " set ");
foreach (var item in EntryList.ColumnName)
{
queryBuilder.Append(item + "=@" + item + ", ");
}
queryBuilder.Remove(queryBuilder.Length - 2, 2);
queryBuilder.Append(" ");
queryBuilder.Append(" WHERE " + ColumnName + "='" + Equals + "'");
SQLiteCommand sqliteCommand = new SQLiteCommand(queryBuilder.ToString(), DataBaseConnnection);
for (int i = 0; i < EntryList.ColumnName.Count; i++)
{
sqliteCommand.Parameters.Add("@" + EntryList.ColumnName[i], EntryList.DbType[i]).Value = EntryList.Content[i];
}
sqliteCommand.ExecuteNonQuery();
DataBaseConnnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
public List<ListWithName> GetEntries(string TableName)
{
TableName = RemoveSpecialCharacters(TableName);
List<ListWithName> listLvi = new List<ListWithName>();
try
{
SetConnection();
SQLiteCommand sqliteCommand = new SQLiteCommand("select * from " + TableName, DataBaseConnnection);
DataReader = sqliteCommand.ExecuteReader();
while (DataReader.Read())
{
ListWithName lwn = new ListWithName();
lwn.Text = DataReader[0].ToString();
for (int i = 1; i < DataReader.FieldCount; i++)
{
lwn.SubItems.Add(DataReader[i].ToString());
}
listLvi.Add(lwn);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
return listLvi;
}
public List<ListWithName> SearchDatabase(string ColumnName, string SearchKeyWord)
{
ColumnName = RemoveSpecialCharacters(ColumnName);
SearchKeyWord = RemoveSpecialCharacters(SearchKeyWord);
List<ListWithName> listLwn = new List<ListWithName>();
try
{
foreach (var table in GetTableNames())
{
if (table != "sqlite_sequence")
{
SetConnection();
SQLiteCommand sqliteCommand = new SQLiteCommand("SELECT * FROM " + table + " WHERE " + ColumnName + " LIKE @searchKey", DataBaseConnnection);
sqliteCommand.Parameters.Add("@searchKey", DbType.String).Value = "%" + SearchKeyWord + "%";
DataReader = sqliteCommand.ExecuteReader();
if (DataReader.HasRows)
{
while (DataReader.Read())
{
ListWithName lwn = new ListWithName();
lwn.Text = DataReader[0].ToString();
for (int i = 1; i < DataReader.FieldCount; i++)
{
lwn.SubItems.Add(DataReader[i].ToString());
}
listLwn.Add(lwn);
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
return listLwn;
}
public List<ListWithName> SearchDatabase(string SearchKeyWord)
{
SearchKeyWord = RemoveSpecialCharacters(SearchKeyWord);
List<ListWithName> listLwn = new List<ListWithName>();
try
{
foreach (var table in GetTableNames())
{
foreach (var col in GetColumnsFromTableName(table))
{
if (table != "sqlite_sequence")
{
SetConnection();
SQLiteCommand sqliteCommand = new SQLiteCommand("SELECT * FROM " + table + " WHERE " + col.Name + " LIKE @searchKey", DataBaseConnnection);
sqliteCommand.Parameters.Add("@searchKey", DbType.String).Value = "%" + SearchKeyWord + "%"; ;
DataReader = sqliteCommand.ExecuteReader();
if (DataReader.HasRows)
{
while (DataReader.Read())
{
ListWithName lwn = new ListWithName();
lwn.Text = DataReader[0].ToString();
for (int i = 1; i < DataReader.FieldCount; i++)
{
lwn.SubItems.Add(DataReader[i].ToString());
}
listLwn.Add(lwn);
}
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
return listLwn;
}
public static string RemoveSpecialCharacters(string str)
{
StringBuilder sb = new StringBuilder();
foreach (char c in str)
{
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '.' || c == '_')
{
sb.Append(c);
}
}
return sb.ToString();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T21:42:11.387",
"Id": "74134",
"Score": "1",
"body": "Please see [Can I edit my own question to include suggested changes from answers?](http://meta.codereview.stackexchange.com/a/1483/34757)"
}
] |
[
{
"body": "<p>Some things that jump at me for the first look.</p>\n\n<ol>\n<li><p>Your DataType should definitely not be a String but some Enum. This makes passing invalid arguments to the function almost impossible. something like the following should do:</p>\n\n\n\n<pre class=\"lang-c# prettyprint-override\"><code> public enum DbDataTypes{\n VARCHAR, TIMESTAMP, LONG, INT, DOUBLE, DATETIME, [...]\n }\n</code></pre></li>\n<li><p>I personally prefer to have the overloaded methods with less parameters call the higher overloaded ones: </p>\n\n<pre class=\"lang-c# prettyprint-override\"><code>public void Add(string name){\n Add(name, DbDataType.VARCHAR, true);\n}\n</code></pre></li>\n<li><p>The singular in <code>Column</code> class makes one think you have only one column, when in fact you have several. Chose a more speaking name like <code>ColumnList</code></p></li>\n<li><p>I don't like that you add the ID column as primary key for every table you create. Mapping tables as the most common example often do not have a column named ID. They also usually have a combined primary key.</p></li>\n<li><p>You don't check the size of the passed arrays in your <code>CreateTable</code> method. This may lead to difficult to debug <code>IndexOutOfRange</code> exceptions</p></li>\n<li><p>you might want to refactor your entryList. it probably will be better to have:</p>\n\n<pre class=\"lang-c# prettyprint-override\"><code>public class EntryList<Entry> : IList<T> {\n\n}\npublic class Entry{\n public string ColumnName {get; set;}\n public DbType DataType {get; set;}\n public string Value {get; set;}\n}\n</code></pre>\n\n<p>that way you ensure to always have a corresponding number of ColumnName, DataType and Value.</p></li>\n<li><p>Also you should chose one naming convention to follow. some of your variables are in camelCase some in MixedCase. </p></li>\n<li><p>Finally you really should move this to multiple files. You could create partial classes to have some more overview of what functionality is where. Luckily, as opposed to java, the filename can be different from the classname ;)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T21:50:07.247",
"Id": "74137",
"Score": "0",
"body": "Thanks for your detailed feedback,\n1. I've enumerated the DataTypes.\n2. Done that too :)\n3. Changed that too.\n4. I've always done that, since most of my applications depend on that.\n5. I use foreach, I could be wrong but I think that will be fine since I haven't had any errors.\n6. That doesn't work in my case.\n7. renamed the variables.\n8. It's all in one class one file, for portability reasons, since all you have to do is add one file to the project, or create one class and paste the code in it.\nAgain, thanks for your feedback."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T21:53:04.853",
"Id": "74139",
"Score": "0",
"body": "@NetInfo what do you mean by 6. \"doesn't work in my case\" ? is it just that it's not applicable due to project circumstances or are you having trouble applying the changes? Btw. you're welcome, it was a joy analyzing ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T22:06:01.763",
"Id": "74144",
"Score": "0",
"body": "Because I still need to access ColumnName, DbType and Content in other scenarios, plus I think I'm just being a bit lazy trying to change it lol, thanks again, I really appreciate it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T22:09:08.813",
"Id": "74146",
"Score": "0",
"body": "Oh n plus I've added a method inside that class \"Add(string columnName, DbType dbType, string content)\"."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T10:03:44.607",
"Id": "42947",
"ParentId": "42356",
"Score": "8"
}
},
{
"body": "<p>I think this method:</p>\n\n<pre><code>RemoveSpecialCharacters(string str)\n</code></pre>\n\n<p>can be replaced by:</p>\n\n<pre><code>Regex.Replace(input, @\"[^.\\w]\",string.Empty)\n</code></pre>\n\n<p>It will be better and you won't need to create special method.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-28T22:01:32.693",
"Id": "78920",
"ParentId": "42356",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "42947",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T23:58:34.717",
"Id": "42356",
"Score": "7",
"Tags": [
"c#",
"sqlite",
"helper"
],
"Title": "SQLite Helper Class in C#"
}
|
42356
|
<p>For learning purposes, I made this little class which determines the <a href="http://en.wikipedia.org/wiki/Condorcet_winner" rel="nofollow noreferrer">Condorcet winner of a rank voting election</a> (basically, a Condorcet winner is a candidate that would beat every other candidate in a head-to-head election).</p>
<p>This code does work, but I'd like to learn two-three things by posting it here:</p>
<ol>
<li><strong>Is this class written in a correct Pythonic way?</strong></li>
<li><strong>Do you see any ways to improve this code?</strong></li>
<li>(bonus) If there are voting specialists among you, could you tell if that way of going through a Condorcet algorithm seems correct?</li>
</ol>
<hr />
<p><strong>Condorcet.py:</strong></p>
<pre><code>import itertools
class Condorcet:
"""
Gives Concorcet winner from a list of votes
"""
def __init__(self, filename):
self.candidates = set()
self.scores = dict() # score for each permutation of two candidates
self.results = dict() # winner of each pair of candidates
self.winner = None # Condorcet winner of the election
self.voters = list() # ranking of each voter
self.filename = filename
def process(self):
self._get_data_from_file()
self._build_dict()
self._matches_candidates()
self._elect_winner()
return self.winner
def _get_data_from_file(self):
with open(self.filename, encoding='utf-8') as file:
for lines in file:
# currently hard-coding the number of candidates at 4
# needs fixing but it's not my point here
# (more a question for StackOverflow actually)
(one, two, three, four) = lines.split(None, 4)
self.voters.append((one, two, three, four))
def _build_dict(self):
"""
Builds a dictionary of scores
for each permutation of two candidates
"""
for voting in self.voters:
for candidate in voting:
self.candidates.add(candidate)
for pair in list(itertools.permutations(voting, 2)):
if pair not in self.scores:
self.scores[pair] = 0
if voting.index(pair[0]) < voting.index(pair[1]):
self.scores[pair] += 1
def _matches_candidates(self):
"""
Analyses the dictionary of scores and
gives the winner of every pair of candidates
"""
for match in list(itertools.combinations(self.candidates, 2)):
reverse = tuple(reversed(match))
if self.scores[match] > self.scores[reverse]:
self.results[match] = match[0]
else:
self.results[match] = match[1]
def _elect_winner(self):
"""
If a candidates is the winner against
every other candidate, declares him the winner
(Note: does not detect Condorcet cycles yet)
"""
for candidate in self.candidates:
candidate_score = 0
for result in self.results:
if candidate in result and self.results[result] == candidate:
candidate_score += 1
if candidate_score == len(self.candidates) - 1:
self.winner = candidate
</code></pre>
<hr />
<p><strong>execute_condorcet.py:</strong></p>
<pre><code>import Condorcet
condorcet = Condorcet.Condorcet('condorcet.txt')
winner = condorcet.process()
print(winner)
</code></pre>
<hr />
<p><strong>condorcet.txt:</strong></p>
<pre><code># each line represents the ranking
# of candidates A, B, C and D
# by a unique voter
A B C D # this voter ranked A first, B second, C third, D fourth
C B D A
A B D C
C A D B
C B A D
C A B D
# and it goes on
</code></pre>
<p>and the winner could be C, beating :</p>
<ul>
<li>A 4 votes to 2</li>
<li>B 4 votes to 2</li>
<li>D 5 votes to 1</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T05:19:56.623",
"Id": "72926",
"Score": "0",
"body": "Please fix your indentation. Indentation is crucial in Python."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T08:12:45.627",
"Id": "72937",
"Score": "0",
"body": "Looks good. There are some places where you could use list comprehensions instead of loops, but that's not a \"must\" e.g. self.voters = [lines.split(None, 4) for lines in file]. Some of your other loops could be turned into list comprehensions by pulling out a helper function. But that's absolutely an impression rather than a prescription."
}
] |
[
{
"body": "<p>The purpose of your class is to perform a single computation: given <code>filename</code>, determine <code>winner</code>. That's a task for a function; there is no need for a class. You can turn each method to an independent function that takes one or two arguments and returns one or two values instead of accessing instance attributes, and provide this function to orchestrate the whole computation:</p>\n\n<pre><code>def concordet_winner(filename):\n voters = _get_data_from_file(filename)\n candidates, scores = _build_dict(voters)\n results = _matches_candidates(candidates, scores)\n return _elect_winner(candidates, results)\n</code></pre>\n\n<p>Now, reading this code gives a clear picture how the data flows through the computation.</p>\n\n<hr>\n\n<p>For the purpose of learning OOP, you could consider a slightly different exercise: instead of having all votes in a file, create a class with a <code>vote</code> method that takes in an individual voter's vote, and a <code>winner</code> property that updates automatically after every vote.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T18:13:50.283",
"Id": "73439",
"Score": "0",
"body": "Thanks for your answer. I upvoted you because you advised interesting alternatives."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T07:34:36.393",
"Id": "42400",
"ParentId": "42359",
"Score": "5"
}
},
{
"body": "<p>Taking into account Janne Karila's comment as a basis :</p>\n\n<pre><code>#!/usr/bin/python3\n\nimport itertools\n\ndef condorcet_winner(filename):\n voters = get_data_from_file(filename)\n candidates, scores = build_dict(voters)\n results = matches_candidates(candidates, scores)\n return elect_winner(candidates, results)\n\ndef get_data_from_file(filename):\n voters = []\n with open(filename, encoding='utf-8') as file:\n for lines in file:\n # currently hard-coding the number of candidates at 4\n # needs fixing but it's not my point here\n # (more a question for StackOverflow actually)\n (one, two, three, four) = lines.split(None, 4)\n voters.append((one, two, three, four))\n return voters\n\ndef build_dict(voters):\n \"\"\"\n Builds a dictionary of scores\n for each permutation of two candidates\n \"\"\"\n candidates = set()\n scores = dict()\n for voting in voters:\n for candidate in voting:\n candidates.add(candidate)\n for pair in list(itertools.permutations(voting, 2)):\n if pair not in scores:\n scores[pair] = 0\n if voting.index(pair[0]) < voting.index(pair[1]):\n scores[pair] += 1\n return candidates, scores\n\ndef matches_candidates(candidates, scores):\n \"\"\"\n Analyses the dictionary of scores and\n gives the winner of every pair of candidates\n \"\"\"\n results = dict()\n for match in list(itertools.combinations(candidates, 2)):\n reverse = tuple(reversed(match))\n if scores[match] > scores[reverse]:\n results[match] = match[0]\n else:\n results[match] = match[1]\n return results\n\n\ndef elect_winner(candidates, results):\n \"\"\"\n If a candidates is the winner against\n every other candidate, declares him the winner\n (Note: does not detect Condorcet cycles yet)\n \"\"\"\n for candidate in candidates:\n candidate_score = 0\n for result in results:\n if candidate in result and results[result] == candidate:\n candidate_score += 1\n if candidate_score == len(candidates) - 1:\n return candidate\n\nprint(condorcet_winner('condorcet.txt'))\n</code></pre>\n\n<p>Now, in <code>get_data_from_file</code>, if you want to handle any number of candidates, just use <code>lines.split(None)</code>. It will use a list instead of a tuple but it doesn't make any difference to you because of the way you use it afterwards.</p>\n\n<p>You function now becomes :</p>\n\n<pre><code>def get_data_from_file(filename):\n voters = []\n with open(filename, encoding='utf-8') as file:\n for lines in file:\n voters.append(lines.split(None))\n return voters\n</code></pre>\n\n<p>which can be rewritten using list comprehension :</p>\n\n<pre><code>def get_data_from_file(filename):\n with open(filename, encoding='utf-8') as file:\n return [l.split(None) for l in file]\n return []\n</code></pre>\n\n<p>Now, the whole code could be simplified by using the right data structure : for each pair of candidates <code>C1</code> and <code>C2</code>, instead of having the counts of victories of <code>C1</code> over <code>C2</code> and the count of victories of <code>C2</code> over <code>C1</code>, you could just count positively the former and negatively the latter. In order to do so, you could store the results in a dictionnary mapping pairs of (different) candidates to (signed) results. In order to keep things simple, we can assume that the first element of the pair is the smallest.</p>\n\n<p>Then, abusing all the good things from Python : set comprehension, itertools, tuple unpacking, generator expression, etc, one could write :</p>\n\n<pre><code>def short_solution(voters):\n results = defaultdict(int)\n for voter in voters:\n for c1,c2 in itertools.combinations(voter, 2):\n assert(c1!=c2)\n mini,maxi,res = (c1,c2,1) if c1 < c2 else (c2,c1,-1)\n results[mini,maxi] += res\n for c in {c for voter in voters for c in voter}:\n if (all((res>0 if c==mini else res<0) for (mini,maxi),res in results.items() if c in [mini,maxi])):\n return c\n return None\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T18:12:40.840",
"Id": "73438",
"Score": "0",
"body": "I'm quite impressed with your \"one could write...\" section. Thanks for that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T10:03:28.740",
"Id": "42403",
"ParentId": "42359",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "42403",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-02-21T00:29:22.623",
"Id": "42359",
"Score": "15",
"Tags": [
"python",
"algorithm",
"object-oriented",
"python-3.x"
],
"Title": "Condorcet voting method in OOP Python"
}
|
42359
|
<p>Programming associated with creating and managing networks as well as adding network connectivity to a (set of) programs. This tag is designated for software related interfacing with networking protocols. Typically, the term is not associated with interfacing with the hardware, but basic knowledge of how the hardware processes network packets can be crucial in debugging connectivity problems.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T01:19:29.783",
"Id": "42361",
"Score": "0",
"Tags": null,
"Title": null
}
|
42361
|
Networking is associated with creating and managing networks as well as adding network connectivity to a (set of) programs.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T01:19:29.783",
"Id": "42362",
"Score": "0",
"Tags": null,
"Title": null
}
|
42362
|
"Promises" are a particular tactic for deferred computing, suitable for several styles of concurrency: thread and event loop concurrency for local computation, and both synchronous and asynchronous remote messaging.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T01:24:38.070",
"Id": "42364",
"Score": "0",
"Tags": null,
"Title": null
}
|
42364
|
<h3>A brief introduction</h3>
<p>system.reactive refers to the Reactive Extensions (Rx), a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators. <strong>System.Reactive</strong> is the root namespace used through the library. Using Rx, developers <strong><em>represent</em></strong> asychronous data streams using <a href="http://msdn.microsoft.com/en-us/library/hh242983%28v=VS.103%29.aspx" rel="nofollow" title="LINQ operators">LINQ operators</a>, and <strong><em>parameterize</em></strong> the concurrency in the asynchronous data streams using <a href="http://msdn.microsoft.com/en-us/library/hh242963%28v=VS.103%29.aspx" rel="nofollow" title="Schedulers">Schedulers</a>. Simply put, Rx = Observables + LINQ + Schedulers.</p>
<p>Whether you are authoring a traditional desktop or web-based application, you have to deal with asynchronous and event-based programming from time to time. Desktop applications have I/O operations and computationally expensive tasks that might take a long time to complete and potentially block other active threads. Furthermore, handling exceptions, cancellation, and synchronization is difficult and error-prone.</p>
<p>Using Rx, you can represent multiple asynchronous data streams (that come from diverse sources, e.g., stock quote, tweets, computer events, web service requests, etc., and subscribe to the event stream using the <code>IObserver<T></code> interface. The <code>IObservable<T></code> interface notifies the subscribed <code>IObserver<T></code> interface whenever an event occurs.</p>
<p>Because observable sequences are data streams, you can query them using standard LINQ query operators implemented by the <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable%28v=VS.103%29.aspx" rel="nofollow" title="IObservable">Observable</a> extension methods. Thus you can filter, project, aggregate, compose and perform time-based operations on multiple events easily by using these standard LINQ operators. In addition, there are a number of other reactive stream specific operators that allow powerful queries to be written. Cancellation, exceptions, and synchronization are also handled gracefully by using the extension methods provided by Rx.</p>
<p>Rx complements and interoperates smoothly with both synchronous data streams (<code>IEnumerable<T></code>) and single-value asynchronous computations (<code>Task<T></code>).</p>
<h3>Source and further information</h3>
<p>The project is actively developed by Microsoft Open Technologies, Inc., in collaboration with a community of open source developers. The source code is hosted on codeplex <a href="http://rx.codeplex.com/" rel="nofollow" title="Rx Source">here</a>.</p>
<p>Additional documentation, video, tutorials and hands-on-labs are available on <a href="http://msdn.microsoft.com/en-us/data/gg577609" rel="nofollow">MSDN</a>, and help and discussions the <a href="http://social.msdn.microsoft.com/forums/en-us/rx/threads/" rel="nofollow">Rx Forums</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T01:26:35.287",
"Id": "42365",
"Score": "0",
"Tags": null,
"Title": null
}
|
42365
|
System.Reactive refers to the Reactive Extensions for .NET, also known as Rx, but it more specifically refers to the use of the System.Reactive.dll assembly, which is part of Rx. System.Reactive provides developers with a reactive programming model, as opposed to the traditional imperative programming model.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T01:26:35.287",
"Id": "42366",
"Score": "0",
"Tags": null,
"Title": null
}
|
42366
|
Hashcode is a result of applying a hash function to data, usually an integer.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T01:28:18.317",
"Id": "42368",
"Score": "0",
"Tags": null,
"Title": null
}
|
42368
|
<p>The Roman numeral system is an ancient way of representing numbers. The symbols are I, IV, V, IX, X, XL, L, XC, C, CD, D, CM, and M. These symbols are valued as follows:</p>
<blockquote>
<p>I = 1<br>
IV = 4<br>
V = 5<br>
IX = 9<br>
X = 10<br>
XL = 40<br>
L = 50<br>
XC = 90<br>
C = 100<br>
CD = 400<br>
D = 500<br>
CM = 900<br>
M = 1000</p>
</blockquote>
<p>These symbols are arranged in increasing value to create a number, where MCMDCDCXCLXLXIXVIVI = 3108. Values represented by a two values, with a smaller value preceding a larger value, such as <code>IX</code>, are only used once per number, while values represented by a single letter, such as <code>X</code>, can be used multiple times while creating a number, so <code>MIXV</code> is valid, while <code>MIXIXV</code> is not - this should be represented by <code>MXXIII</code>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T01:29:18.820",
"Id": "42369",
"Score": "0",
"Tags": null,
"Title": null
}
|
42369
|
The Roman numeral system is an ancient way of representing numbers. The symbols are I, V, X, L, C, D and M.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T01:29:18.820",
"Id": "42370",
"Score": "0",
"Tags": null,
"Title": null
}
|
42370
|
<p>Windows Phone is a mobile operating system developed by Microsoft, and is the successor to its Windows Mobile platform. </p>
<h3>Development Platforms</h3>
<ul>
<li><strong>Windows Phone 7.0 (deprecated)</strong>: <a href="http://stackoverflow.com/questions/tagged/silverlight">Silverlight</a> and <a href="http://stackoverflow.com/questions/tagged/xna">XNA</a></li>
<li><strong>Windows Phone 7.5</strong>: <a href="http://stackoverflow.com/questions/tagged/silverlight">Silverlight</a> and <a href="http://stackoverflow.com/questions/tagged/xna">XNA</a> (note that the development platform version is 7.1)</li>
<li><strong>Windows Phone 8</strong>: <a href="http://stackoverflow.com/questions/tagged/silverlight">Silverlight</a>, C++ with the Windows Phone Runtime (<a href="http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj207212%28v=vs.105%29.aspx" rel="nofollow">WinPRT</a>). <a href="http://stackoverflow.com/questions/tagged/xna">XNA</a> is supported but you cannot target a XNA project to Windows Phone 8. XNA Apps <a href="http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj207003%28v=vs.105%29.aspx" rel="nofollow">targeting OS 7.1 will run on 8</a>, though.</li>
</ul>
<h3>External Resources</h3>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff402535%28v=vs.105%29.aspx" rel="nofollow">Windows Phone Development on MSDN</a> </li>
<li><a href="http://dev.windowsphone.com" rel="nofollow">Windows Phone Dev Center</a> </li>
<li><a href="http://www.windowsphone.com/" rel="nofollow">http://www.windowsphone.com/</a></li>
</ul>
<p><a href="http://windowsphone.interoperabilitybridges.com/articles/windows-phone-7-guide-for-android-application-developers" rel="nofollow">Windows Phone guide for Android developers</a> </p>
<h3>Free Windows Phone Programming Book</h3>
<ul>
<li><a href="http://blogs.msdn.com/b/microsoft_press/archive/2010/10/28/free-ebook-programming-windows-phone-7-by-charles-petzold.aspx" rel="nofollow">Programming Windows Phone 7</a></li>
</ul>
<h3>More information</h3>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Windows_Phone" rel="nofollow">Windows Phone Phone Wikipedia Article</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T01:29:53.937",
"Id": "42371",
"Score": "0",
"Tags": null,
"Title": null
}
|
42371
|
Windows Phone is Microsoft's mobile operating system and software development platform.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T01:29:53.937",
"Id": "42372",
"Score": "0",
"Tags": null,
"Title": null
}
|
42372
|
<p>Mobile development refers to the process of programming specifically for hand-held devices, such as cell phones and PDAs.</p>
<p>Mobile computing is human–computer interaction by which a computer is expected to be transported during normal usage. Mobile computing involves mobile communication, mobile hardware, and mobile software. Communication issues include ad hoc and infrastructure networks as well as communication properties, protocols, data formats and concrete technologies. Hardware includes mobile devices or device components. Mobile software deals with the characteristics and requirements of mobile applications.</p>
<h3>Reference</h3>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Mobile_computing" rel="nofollow">Mobile computing</a></li>
<li><a href="http://www.tutorialspoint.com/listtutorials/mobile-computing/1" rel="nofollow">Mobile Tutorials</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T01:30:44.770",
"Id": "42373",
"Score": "0",
"Tags": null,
"Title": null
}
|
42373
|
<p>Initially ported from <a href="http://www.junit.org/" rel="nofollow">JUnit</a>, the current production release, version 2.6, is the seventh major release of this xUnit based unit testing tool for Microsoft .NET. It is written entirely in C# and has been completely redesigned to take advantage of many .NET language features, for example custom attributes and other reflection related capabilities. NUnit brings xUnit to all .NET languages.</p>
<p><strong>References</strong></p>
<ul>
<li><a href="http://www.nunit.org/" rel="nofollow">Homepage</a></li>
<li><a href="https://launchpad.net/nunit-xtp" rel="nofollow">Current development</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T01:31:38.023",
"Id": "42375",
"Score": "0",
"Tags": null,
"Title": null
}
|
42375
|
NUnit is an open source unit testing framework for Microsoft .NET and Silverlight written in C#. It serves the same purpose as JUnit does in the Java world, and is one of many in the xUnit family.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T01:31:38.023",
"Id": "42376",
"Score": "0",
"Tags": null,
"Title": null
}
|
42376
|
<p>Clients are generally classified as either "fat clients", "thin clients", or "hybrid clients".</p>
<p><strong>Fat</strong></p>
<p>A <a href="http://en.wikipedia.org/wiki/Fat_client" rel="nofollow">fat client</a>, also known as a rich client or thick client, is a client that performs the bulk of any data processing operations itself, and does not necessarily rely on the server.</p>
<p><strong>Thin</strong></p>
<p>A <a href="http://en.wikipedia.org/wiki/Thin_client" rel="nofollow">thin client</a> is a minimal sort of client. Thin clients use the resources of the host computer.</p>
<p><strong>Hybrid</strong></p>
<p>A hybrid client is a mixture of the above two client models. Similar to a fat client, it processes locally, but relies on the server for storage data. This approach offers features from both the fat client (multimedia support, high performance) and the thin client (high manageability, flexibility).</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T01:33:43.437",
"Id": "42377",
"Score": "0",
"Tags": null,
"Title": null
}
|
42377
|
A client is an application or system that accesses a service made available by a server.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T01:33:43.437",
"Id": "42378",
"Score": "0",
"Tags": null,
"Title": null
}
|
42378
|
<p>The AWT is now part of the Java Foundation Classes (JFC) — the standard API for providing a graphical user interface (GUI) for a Java program.</p>
<p>AWT is also the GUI toolkit for a number of Java ME profiles. For example, Connected Device Configuration profiles require Java runtimes on mobile telephones to support AWT.</p>
<p><a href="http://en.wikipedia.org/wiki/Abstract_Window_Toolkit" rel="nofollow">http://en.wikipedia.org/wiki/Abstract_Window_Toolkit</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T01:34:15.143",
"Id": "42379",
"Score": "0",
"Tags": null,
"Title": null
}
|
42379
|
The Abstract Window Toolkit (AWT) is Java's original platform-independent windowing, graphics, and user-interface widget toolkit.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T01:34:15.143",
"Id": "42380",
"Score": "0",
"Tags": null,
"Title": null
}
|
42380
|
<p>I have an application that allows the user to place a string of text into a PDF document. I have three different ways that they can do this:</p>
<ol>
<li><strong>Use a Form Field.</strong> Then they have four properties to define:
<ol>
<li>Provide field name</li>
<li>provide instance of the field</li>
<li>provide an X-axis Offset</li>
<li>provide a Y-axis Offset </li>
</ol></li>
<li><strong>Search for a string of text.</strong> Then they have four properties to define:
<ol>
<li>Provide string of text to search for</li>
<li>provide instance of that string of text</li>
<li>provide an X-axis Offset</li>
<li>provide a Y-axis Offset </li>
</ol></li>
<li><strong>Define Page Coordinates.</strong> Then they have three properties to define:
<ol>
<li>Provide page number </li>
<li>provide an X-axis Offset</li>
<li>provide a Y-axis Offset</li>
</ol></li>
</ol>
<p>In my API, I want the object to be setup intuitively so that it is clear they are choose one of the three different methods and then whichever one they choose, they have the options for each.</p>
<p>In my old API, all of those options are grouped together as a list of properties like this:</p>
<pre><code>Placement.FormField_FieldName
Placement.FormField_Instance
Placement.SearchText_Text
Placement.SearchText_Instance
Placement.PageCoordinates_PageNumber
Placement.XOffset
Placement.YOffset
</code></pre>
<p>I find this to be a little confusing for the developer using the API because you could never use all of the properties together. </p>
<p>You would either use <strong>Form Field</strong> like this:</p>
<pre><code>Placement myPlacement = new Placement();
myPlacement.FormField_FieldName = "MyPdfFormFieldName";
myPlacement.FormField_Instance = ;
myPlacement.XOffset = 0;
myPlacement.YOffset = 0;
</code></pre>
<p>Or use <strong>Text Search</strong> like this:</p>
<pre><code>Placement myPlacement = new Placement();
myPlacement.SearchText_Text = "My String Of Text";
myPlacement.FormField_Instance = 1;
myPlacement.XOffset = 0;
myPlacement.YOffset = 0;
</code></pre>
<p>Or use <strong>Page Coordinates</strong> like this:</p>
<pre><code>Placement myPlacement = new Placement();
myPlacement.PageCoordinates_PageNumber = "My String Of Text";
myPlacement.XOffset = 0;
myPlacement.YOffset = 0;
</code></pre>
<p>Is there a better way to setup the class (or sub classes) to make it easier for the developer to understand how to use this functionality?</p>
<p><strong>UPDATE</strong></p>
<p>This is what I currently am using because the abstract class thing didn't work.</p>
<pre><code>public class SignatureBlock
{
public List<SignatureBlockPlacement> SignatureBlockPlacements = new List<SignatureBlockPlacement>();
}
public class SignatureBlockPlacement
{
public Enumerations.SignatureBlock.SignatureBlockTypes Type { get; set; }
public string FormField_FieldName { get; set; }
public int FormField_InstanceOfField { get; set; }
public string SearchText_TextToSearch { get; set; }
public int SearchText_InstanceOfText { get; set; }
public string PageCoordinates_PageNumber { get; set; }
public int XOffset { get; set; }
public int YOffset { get; set; }
}
</code></pre>
<p>Which I'm implementing like this:</p>
<pre><code>SignatureBlock sigBlock = new SignatureBlock();
SignatureBlockPlacement sig = new SignatureBlockPlacement();
sig.Type = Enumerations.SignatureBlock.SignatureBlockTypes.Signature;
sig.FormField_FieldName = "SignatureField";
sig.FormField_InstanceOfField = 1;
SignatureBlockPlacement title = new SignatureBlockPlacement();
title.Type = Enumerations.SignatureBlock.SignatureBlockTypes.Title;
title.FormField_FieldName = "SignatureField";
title.FormField_InstanceOfField = 1;
title.XOffset = 0;
title.YOffset = -20;
SignatureBlockPlacement org = new SignatureBlockPlacement();
org.Type = Enumerations.SignatureBlock.SignatureBlockTypes.Organization;
org.FormField_FieldName = "SignatureField";
org.FormField_InstanceOfField = 1;
org.XOffset = 0;
org.YOffset = -40;
sigBlock.SignatureBlockPlacements = new List<SignatureBlockPlacement>() { sig, title, org };
</code></pre>
<p>If there's a better way to do this, please let me know.</p>
<p><strong>UPDATE #2</strong></p>
<p>I should have mentioned this is for a WCF SOAP web service.</p>
<p><strong>UPDATE #3</strong></p>
<p>Long story short on this one, I need to allow the developer three different ways to place the signature but they should only be allowed to use one of the three ways . Each way shares the X/Y Offset properties but their other properties are unique to each way.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T03:22:40.117",
"Id": "72898",
"Score": "0",
"body": "Is `Placement` a subclass of something like `Form` or is it just a class? Do those properties need to be available to an [IDE designer](http://msdn.microsoft.com/en-us/library/h51z5c0x.aspx), or do they just need to be available to a programmer who is writing code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T05:06:03.987",
"Id": "72924",
"Score": "0",
"body": "Yes, Placement would either be a sub class of a \"Task\" class or a property of Task - I haven't decided."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T12:59:20.467",
"Id": "74940",
"Score": "0",
"body": "I think that your original code is clear. It's a simple POCO with 4 well-named properties, this shouldn't be hard for any developer to use. IF you had to make it even clearer I guess you could incorporate ChrusWue's answer as an `AddPlacement(...)` function in your `SignatureBlock` class which just adds the new placement to the `SignatureBlockPlacement` list."
}
] |
[
{
"body": "<p>not very sure about your placement class, whether it's a pure class designed to encapsulate options, or a win-form. </p>\n\n<p>If it's the former, i would suggest you use Polymorphism to have certain abstract layer, a quick sample:</p>\n\n<p>At your side: </p>\n\n<pre><code>public abstract class Placement\n{\n public int XOffset { get; set; }\n public int YOffset { get; set; }\n\n public class FrmField:Placement\n {\n public string FieldName { get; set; }\n public int Instance { get; set; }\n }\n\n public class TextSearch:Placement\n {\n public TextSearch(){}\n public string Text { get; set; }\n public int Instance { get; set; }\n }\n\n public class PageCoord : Placement\n {\n public string PageNumber { get; set; }\n }\n}\n\npublic class SomeObjRequriePlacement\n{\n public void DoSomething(Placement pla)\n {\n // this class and method may be a winform that do something based on given options\n }\n}\n</code></pre>\n\n<p>Other dev using your api:</p>\n\n<pre><code>public class TestAtDev\n{\n public void TestGeneric()\n {\n Placement pla = null;\n if (false) //some condition\n {\n pla = new Placement.FrmField() { FieldName = \"\", Instance = 1, XOffset = 1, YOffset = 2 };\n }\n else if (true) // some condition\n {\n pla = new Placement.PageCoord() { PageNumber = \"xxx\", XOffset = 1, YOffset = 2 };\n }\n else\n {\n pla = new Placement.TextSearch() { Text = \"\", XOffset = 1, YOffset = 2 };\n }\n\n var someObj = new SomeObjRequriePlacement();\n someObj.DoSomething(pla); \n }\n}\n</code></pre>\n\n<p>if your Placement class is already an UI components, i would then suggest you separate the options away and wrap them as PlacementOption and use it in your placement class. </p>\n\n<p>and if necessary, you may define an interface to make the code more independent. And Generic (like Type constraint) could make your code even tidier. </p>\n\n<p>EDIT: </p>\n\n<p>use type constraint to have strong typed object where necessary - but the basic implementation of the placement is still the same. </p>\n\n<pre><code>public abstract class HandlePlacement<T> where T:Placement\n{\n public virtual void DoWork(T thePlacement) { }\n}\n\npublic class HandleTextSearch : HandlePlacement<Placement.TextSearch>\n{\n public override void DoWork(Placement.TextSearch thePlacement)\n {\n // do some specific work for text search option\n }\n}\n\n/*implementations for other placement options*/\n/* ... */\n\npublic class TestAtDev\n{\n public void DoTextSearch()\n {\n Placement.TextSearch ts = new Placement.TextSearch() { XOffset = 0, YOffset = 1, Instance = 2, Text = \"\" };\n HandlePlacement<Placement.TextSearch> hanlder = new HandleTextSearch();\n hanlder.DoWork(ts);\n }\n}\n</code></pre>\n\n<p>another sample:</p>\n\n<pre><code>public abstract class SomeHandler\n{\n public virtual void DoWork() { }\n}\n\npublic abstract class SomeHandler<T>:SomeHandler where T : Placement\n{\n protected SomeHandler(T thePlacement)\n {\n this.Placement = thePlacement;\n }\n\n protected T Placement { get; set; }\n}\n\npublic class SomeHandlerForTextSearch : SomeHandler<Placement.TextSearch>\n{\n public SomeHandlerForTextSearch(Placement.TextSearch ts):base(ts){}\n\n public override void DoWork()\n {\n // some specific handling for text search\n }\n}\n\npublic class SomeHandlerForPageCoord : SomeHandler<Placement.PageCoord>\n{\n public SomeHandlerForPageCoord(Placement.PageCoord pc) : base(pc) { }\n\n public override void DoWork()\n {\n // some specific handling for page coordinates\n }\n}\n\npublic class TestAtDev2\n{\n public void DoSomeTest()\n {\n SomeHandler h = null;\n if (true) // some condition\n {\n h = new SomeHandlerForTextSearch(new Placement.TextSearch() { XOffset = 1, YOffset = 2, Instance = 3, Text = \"test\" });\n }\n else if (true) // some condition\n {\n h = new SomeHandlerForPageCoord(new Placement.PageCoord() { XOffset = 1, YOffset = 2, PageNumber = \"PageNo.\" }); \n }\n h.DoWork();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T05:06:52.287",
"Id": "72925",
"Score": "0",
"body": "Yes, I like this very much. I think this is exactly what I'm looking for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T14:46:43.703",
"Id": "72982",
"Score": "0",
"body": "I worry about this breaking the [Law of Demeter](http://en.wikipedia.org/wiki/Law_of_Demeter), any thoughts on that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T15:30:33.177",
"Id": "72990",
"Score": "0",
"body": "Also, don't you lose the `FieldName = \"\", Instance = 1` values the second you assign `FrmField` into `pla`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T17:28:14.153",
"Id": "73025",
"Score": "0",
"body": "@RichC I don't see how this could break the Law of Demeter. Can you clarify?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T17:44:38.440",
"Id": "73032",
"Score": "0",
"body": "@ANeves The bigger issue is that if you assign `Placement pla = new Placement.FrmField() { FieldName = \"\", Instance = 1, XOffset = 1, YOffset = 2 };` you lose the `.FieldName` and `.Instance` properties when you try to do work with `pla`. At least, in my testing, I did."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T18:05:52.967",
"Id": "73042",
"Score": "0",
"body": "@RichC I really don't understand how that could happen, unless: you re-assign `pla`; or re-assign its variables; or you made the classes from @Rex *static*? If you share sample code (e.g. via gist, or pastie.org) showing that problem happening, we can look into it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T18:16:36.697",
"Id": "73046",
"Score": "0",
"body": "Well, Placement only has two properties (`.XOffset` and `.YOffset`) so when I assign the `FrmField` object into `pla`, I no longer have access to the unique properties that are found in `FrmField`. I'll do some more testing since you think that shouldn't happen but I already deleted that code. have a great weekend."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T00:12:13.133",
"Id": "73470",
"Score": "0",
"body": "Ah, yes, I understand now; it does work like you say. (I don't think that's related to the Law of Demeter.) I have no idea how you use those objects, but my guess is that you would need some abstract method like `public abstract string GetLabel();` or `public abstract string GetTextToWrite();` in this abstract class `Placement`, that you could then call."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T01:47:14.193",
"Id": "73477",
"Score": "0",
"body": "I have to clarify - the sample i gave is just a quick demo and I never tested it. If you want a more elegant way doing it, i think you'd better think about type constraint (then you could have strong typed object whenever you need), for which you could find plenty of resources online. If you really want an example, let me know and I can do another sample."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T20:07:51.160",
"Id": "74104",
"Score": "0",
"body": "Hi @Rex I'm back on this now. ANeves was able to confirm that the abstract class doesn't work as you have it in the example but I'm curious about your type constraint solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T03:16:30.410",
"Id": "74873",
"Score": "0",
"body": "ok, see my edited part about type-constraint. note it really depends on how you wrap up your handler and separate it into different layers will be even better."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T03:51:06.443",
"Id": "42386",
"ParentId": "42382",
"Score": "4"
}
},
{
"body": "<p>One possibility is to use a factory class (which contains static methods to create the Placement); or put the static factory methods in the Placement class itself.</p>\n\n<p>The factory methods can:</p>\n\n<ul>\n<li>Be well-named so that they're self-documenting</li>\n<li>Name their parameters</li>\n<li>Include XML documentation</li>\n</ul>\n\n<p>For example:</p>\n\n<pre><code>/// <summary>\n/// Describe the method here.\n/// </summary>\n/// <param name=\"fieldName\">Describe the parameter here</param>\n/// <param name=\"instance\">Describe the parameter here</param>\n/// <param name=\"xOffset\">Describe the parameter here</param>\n/// <param name=\"yOffset\">Describe the parameter here</param>\n/// <returns>Describe the return value here</returns>\nstatic Placement CreateFormField(string fieldName, int instance, int xOffset, int yOffset)\n{\n Placement placement = new Placement();\n placement.FormField_FieldName = fieldName;\n placement.FormField_Instance = instance;\n placement.XOffset = xOffset;\n placement.YOffset = yOffset;\n return placement;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T17:47:49.563",
"Id": "73033",
"Score": "0",
"body": "Will this cause problems when used in WCF SOAP? (I probably should have mentioned this in my original post. Looks like I just mentioned API and not SOAP) Since the SOAP client won't be able to get the return for that method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T20:16:54.023",
"Id": "73093",
"Score": "0",
"body": "What is the SOAP client doing to use the existing code? In what way is the code in the question SOAP-specific: what/where is the SOAP API?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T20:23:03.120",
"Id": "73097",
"Score": "0",
"body": "nothing different than I posted in my first update."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T20:32:02.810",
"Id": "73101",
"Score": "0",
"body": "@RichC I see no SOAP in your first update. IMO if the client can do `new Placement()` and assign to `FormField_FieldName`, then they could alternatively call a `CreateFormField` method which does the same thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T21:09:00.787",
"Id": "73113",
"Score": "0",
"body": "sorry, you are right that I didn't post SOAP. I thought you were asking how it was being implemented on the SOAP client which looks basically the same as the code in my first update."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T12:55:48.477",
"Id": "74939",
"Score": "1",
"body": "should be `return placement;`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T16:43:14.520",
"Id": "42437",
"ParentId": "42382",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "42386",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T01:52:04.117",
"Id": "42382",
"Score": "6",
"Tags": [
"c#",
"classes"
],
"Title": "How can I layout this class to make it easier to use for API developers?"
}
|
42382
|
<p>I am currently working on a problem of an online judge (not a contest). The program must calculate how many years will require for the population A (which is always less than B) to be higher than B. If the time is more than a Century then print "More than a century" in Portuguese.<br>
Input</p>
<pre><code>1
90000 120000 5.5 3.5
</code></pre>
<p>Where 1 is the number of test cases and in the next line are the population of A, population of B, percentage growing rate of A and percentage growing rate of B. For this input the result will be 16 years.</p>
<p>However, my code keeps exceeding the time limit, which is only 1 second. I have used <code>Scanner</code> and <code>System.out.print()</code> however I have been told that such methods will make my code slower and will consume more memory, that is way I buffered the input and output. I cannot use types such as <code>long</code> or <code>int</code> as the data stored the variables is longer than those values.</p>
<pre class="lang-java prettyprint-override"><code>import java.io.*;
import java.math.BigDecimal;
class Main {
public static void main(String[] args) throws NumberFormatException, IOException{
java.io.InputStreamReader iSR = new java.io.InputStreamReader(System.in);
java.io.BufferedReader bR = new java.io.BufferedReader(iSR, 16 * 1024);
BufferedWriter bW = new BufferedWriter(new OutputStreamWriter(System.out));
String tL;
BigDecimal PRA = BigDecimal.ZERO, PRB = BigDecimal.ZERO, PA = BigDecimal.ZERO, PB = BigDecimal.ZERO;
int input = Integer.parseInt(bR.readLine());
for(int j = 0; j < input; j++){
tL = bR.readLine();
String [] = arr = tL.split(" ");
PA = BigDecimal.valueOf(Integer.parseInt(arr[0]));
PB = BigDecimal.valueOf(Integer.parseInt(arr[1]));
PRA = BigDecimal.valueOf(Double.parseDouble(arr[2]));
PRB = BigDecimal.valueOf(Double.parseDouble(arr[3]));
PRA = PRA.divide(BigDecimal.valueOf(100)); PRA = PRA.add(BigDecimal.ONE);
PRB = PRB.divide(BigDecimal.valueOf(100)); PRB = PRB.add(BigDecimal.ONE);
int i = 1;
while(PA.compareTo(PB) < 0 && i < 103){
BigDecimal ibd = BigDecimal.valueOf(i);
PA = PA.multiply(PRA).multiply(ibd);
PB = PB.multiply(PRB).multiply(ibd);
i++;
}
i--;
if(i > 100) bW.write("Mais de 1 seculo.\n");
else bW.write(String.valueOf(i) + " anos.\n");
bW.flush();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T03:44:07.107",
"Id": "72907",
"Score": "0",
"body": "What exactly is the program supposed to do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T03:53:19.437",
"Id": "72908",
"Score": "0",
"body": "@Saposhiente Please have a look at the first edit"
}
] |
[
{
"body": "<p>First, the syntax error:</p>\n\n<pre><code> String [] = arr = tL.split(\" \");\n</code></pre>\n\n<p>You probably meant</p>\n\n<pre><code> String[] arr = tL.split(\" \");\n</code></pre>\n\n<p>Now, let's make all of your variable names readable. Longer names take the same amount of time to access:</p>\n\n<pre><code> java.io.InputStreamReader inputStream = new java.io.InputStreamReader(System.in);\n java.io.BufferedReader reader = new java.io.BufferedReader(inputStream, 16 * 1024);\n BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));\n String input;\n BigDecimal GrowthA, GrowthB, PopulationA, PopulationB; //no need to assign initial values to them; the values are never used\n int repetitions = Integer.parseInt(reader.readLine());\n</code></pre>\n\n<p>Now, as always, choosing a better algorithm is a far bigger deal than small things such as your particular means of input and output. On my computer, the code between <code>input = reader.readLine();</code> and <code>writer.flush();</code> takes 6 milliseconds to run once and 24 milliseconds to run 50 times for the example input you gave; make sure that your timing measurement does not include the amount of time it spends waiting for you to enter input. For your algorithm, you have chosen to iteratively simulate each year of population growth; this is mathematically inefficient. Your problem algebraically reduces to</p>\n\n<pre><code>PA*(1+PRA/100)^t>PB*(1+PRB/100)^t, solve for t. \n=PA*((PRA+100)/100)^t>...\n=PA*(PRA+100)^t*(1/100)^t>...\nPA*(PRA+100)^t>...\nln(PA)+t*ln(PRA+100)>ln(PB)+t*ln(PRB+100)\nt(ln(PRA+100)-ln(PRB+100))>ln(PB)-ln(PA)\nt>(ln(PB)-ln(PA))/(ln(PRA+100)-ln(PRB+100)) (assuming PRA > PRB)\n</code></pre>\n\n<p>It will be much faster to just use this one computation, and as bonus you will get more precise answers. Also, since you will not be increasing your numbers exponentially in your algorithm, you will now be able to directly use <code>Integer.parseInt</code> instead of having to ever make <code>BigDecimal</code>s. </p>\n\n<p>Marginal changes: Testing reveals that using <code>final</code> local variables is faster than reusing larger-scope variables, and that using <code>BufferedReader</code> and <code>BufferedWriter</code> does not create any significant difference in performance (at least on my machine), so unless you test it and get a different result you should use <code>Scanner</code> and <code>System.out</code> just because it's simpler. Also, you should mark all variables that are never modified as <code>final</code>.</p>\n\n<pre><code> final Scanner scanner = new Scanner(System.in);\n final int repetitions = scanner.nextInt();\n scanner.skip(\"\\n\");\n for(int j = 0; j < repetitions; j++){\n final String input = scanner.nextLine();\n final String[] arr = input.split(\" \");\n final double PopulationA = Double.parseDouble(arr[0]);\n final double PopulationB = Double.parseDouble(arr[1]);\n final double GrowthA = Double.parseDouble(arr[2]);\n final double GrowthB = Double.parseDouble(arr[3]);\n System.out.print((Math.log(PopulationB)-Math.log(PopulationA))/(Math.log(GrowthA+100)-Math.log(GrowthB+100)) + \" anos.\\n\");\n }\n</code></pre>\n\n<p>If integer output is required, throw in a call to <code>Math.ceil</code>. On my machine, the code after <code>final String input = scanner.nextLine();</code> runs once in 3 milliseconds, 50 times in 6 milliseconds, and 10,000 times in 450 milliseconds, with your example input. A doubling of speed for one run, and faster and faster for the same input repeated.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T08:18:45.280",
"Id": "72938",
"Score": "1",
"body": "Comments are a code smell. Your `print` statement is horrible, especially in the light of what you put in the comment is valid Java syntax. `(log(pb) - log(pa)) / (log(pra + 100) - log(prb + 100))` Why not just say what you mean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T14:19:32.013",
"Id": "72975",
"Score": "0",
"body": "I don't find `Scanner` and `System.out` less or more readable than `BufferedReader` and `BufferedWriter`. They are just different tools to do the \"same\" kind of task. If you don't need buffering than don't use it, but I don't find readability a problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T03:00:42.937",
"Id": "73161",
"Score": "0",
"body": "@abuzittingillifirca Had initially written that because asker wanted performance over clarity, testing reveals that using `final` variables instead has no significant performance difference, edited to use those instead."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T05:15:43.033",
"Id": "42390",
"ParentId": "42385",
"Score": "2"
}
},
{
"body": "<ol>\n<li><p>The code prints a short line in every iteration and forces the <code>BufferedWriter</code> to flush in every iteration. It just makes no sense to buffer such small amount of data. I would move the flushing outside the for loop. I'm not sure that it will help at all (since you are writing to the standard output) but I guess it would help if you redirect the output to a file.</p></li>\n<li><p>The <code>tL</code> variable could be declared inside the loop. (<em>Effective Java, Second Edition</em>, <em>Item 45: Minimize the scope of local variables</em>)</p></li>\n<li><p><code>BigDecimal.valueOf(100)</code> is used and created multiple times. You could create a constant for it. Although the JVM might already optimize it for you it would be readable.</p></li>\n<li><p>I'd put the variable declarations to separate lines. From Code Complete, 2nd Edition, p759:</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 margin \n of the code. It shouldn’t have to dip into each and every line just \n because a single line might contain two statements.</p>\n</blockquote></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T08:53:58.563",
"Id": "42401",
"ParentId": "42385",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T03:39:14.397",
"Id": "42385",
"Score": "5",
"Tags": [
"java",
"optimization"
],
"Title": "How to optimize population projections for speed?"
}
|
42385
|
<p>I have my program working. I just need to redo it a little bit, and it could use some improvements.</p>
<p>I got different % rates depending on what the income and status is.</p>
<pre><code>#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <cstdio>
//functions called
float wages_loop();
float other_loop();
float interest_loop();
float dividends_loop();
int dependatnts_loop();
void check_status();
float get_total_income(float wage, float div, float intre, float other, int dep);
int single_total = 0;
int mj_total = 0;
int ms_total = 0;
int sh_total = 0;
//start main
int main(void)
{
char another[10];
char buffer[80][90];
float wages, other_income, interest, dividends, income_tax;
int dependents;
printf("Would you like to start: ");
gets_s(another);
if (another[0] != 'y' && another[0] != 'n')
{
while (another[0] != 'y' && another[0] != 'n')
{
printf("\n\n INCORRECT ANSWER. \n\n");
printf("\n Would you like to start. (y or n)");
gets_s(another);
}
}
while (another[0] == 'y')
{
//add all info together.
wages = wages_loop();
other_income = other_loop();
interest = interest_loop();
dividends = dividends_loop();
//enter dependats
dependents = dependatnts_loop();
//function to indicate the status and other things.
income_tax = get_total_income(wages, other_income, dividends, interest, dependents);
if (income_tax < 0)
{
printf("\n\n\t\t Your income tax RETURN is: %.2f \n", income_tax);
}
else if (income_tax >= 0)
{
printf("\n\n\t\t Your income tax OWED is: %.2f \n", income_tax);
}
printf("Would you like to do anoter: ");
gets_s(another);
if (another[0] != 'y' && another[0] != 'n')
{
while (another[0] != 'y' && another[0] != 'n')
{
printf("\n\n INCORRECT ANSWER. \n\n");
printf("\n Would you like anoter. (y or n)");
gets_s(another);
}//end if
}
} //end loop
printf("\n\n\t\t\t Number of Singles filleing: %i \n", single_total);
printf("\n\n\t\t\t Number of Married Filing Jointly: %i \n", mj_total);
printf("\n\n\t\t\t Number of Married Filing Separately: %i \n", ms_total);
printf("\n\n\t\t\t Number of Single Head of Household filleing: %i \n", sh_total);
system("pause");
return 0;
}//end main
float wages_loop()
{
char again[10];
char buffer[80];
float wages, total_wages = 0;
printf("\n How much in Wages. ");
gets_s(buffer);
wages = atof(buffer);
total_wages = wages + total_wages;
printf("\n Do you have any more wages. (y or n)");
gets_s(again);
if (again[0] != 'y' && again[0] != 'n')
{
while (again[0] != 'y' && again[0] != 'n')
{
printf("\n\n INCORRECT ANSWER. \n\n");
printf("\n Do you have any more wages. (y or n)");
gets_s(again);
}
}
while (again[0] == 'y')
{
printf("\n Enter Wages: ");
gets_s(buffer);
wages = atof(buffer);
total_wages = wages + total_wages;
printf("\n Do you have any more wages. ");
gets_s(again);
}
return total_wages;
}//end wage_loop
float other_loop()
{
char again[10];
char buffer[80];
float other_income, total_other_income = 0;
printf("\n How much in other income. ");
gets_s(buffer);
other_income = atof(buffer);
total_other_income = other_income + total_other_income;
printf("\n Do you have any more other income. (y or n)");
gets_s(again);
if (again[0] != 'y' && again[0] != 'n')
{
while (again[0] != 'y' && again[0] != 'n')
{
printf("\n\n INCORRECT ANSWER. \n\n");
printf("\n Do you have any more other income. (y or n)");
gets_s(again);
}
}
while (again[0] == 'y')
{
printf("\n Enter other income: ");
gets_s(buffer);
other_income = atof(buffer);
total_other_income = other_income + total_other_income;
printf("\n Do you have any more other income. ");
gets_s(again);
}
return total_other_income;
}
float interest_loop()
{
char again[10];
char buffer[80];
float interest, total_interest = 0;
printf("\n How much in interest. ");
gets_s(buffer);
interest = atof(buffer);
total_interest = interest + total_interest;
printf("\n Do you have any more interest. (y or n)");
gets_s(again);
if (again[0] != 'y' && again[0] != 'n')
{
while (again[0] != 'y' && again[0] != 'n')
{
printf("\n\n INCORRECT ANSWER. \n\n");
printf("\n Do you have any more interest. (y or n)");
gets_s(again);
}
}
while (again[0] == 'y')
{
printf("\n Enter interest: ");
gets_s(buffer);
interest = atof(buffer);
total_interest = interest + total_interest;
printf("\n Do you have any more interest. ");
gets_s(again);
}
return total_interest;
}
float dividends_loop()
{
char again[10];
char buffer[80];
float dividends, total_dividends = 0;
printf("\n How much in dividends. ");
gets_s(buffer);
dividends = atof(buffer);
total_dividends = dividends + total_dividends;
printf("\n Do you have any more dividends. (y or n)");
gets_s(again);
if (again[0] != 'y' && again[0] != 'n')
{
while (again[0] != 'y' && again[0] != 'n')
{
printf("\n\n INCORRECT ANSWER. \n\n");
printf("\n Do you have any more dividends. (y or n)");
gets_s(again);
}
}
while (again[0] == 'y')
{
printf("\n Enter dividends: ");
gets_s(buffer);
dividends = atof(buffer);
total_dividends = dividends + total_dividends;
printf("\n Do you have any more dividends. ");
gets_s(again);
}
return total_dividends;
}//end dividends_loop
//dependants
int dependatnts_loop()
{
char again[10];
char buffer[80];
int dependants, total_dependants = 0;
printf("\n How much in dependants. ");
gets_s(buffer);
dependants = atof(buffer);
total_dependants = dependants + total_dependants;
printf("\n Do you have any more dependants. (y or n)");
gets_s(again);
if (again[0] != 'y' && again[0] != 'n')
{
while (again[0] != 'y' && again[0] != 'n')
{
printf("\n\n INCORRECT ANSWER. \n\n");
printf("\n Do you have any more dependants. (y or n)");
gets_s(again);
}
}
while (again[0] == 'y')
{
printf("\n Enter dependants: ");
gets_s(buffer);
dependants = atof(buffer);
total_dependants = dependants + total_dependants;
printf("\n Do you have any more dependants. ");
gets_s(again);
}
total_dependants = total_dependants * 2800;
return total_dependants;
}
void check_status()
{
char status[10];
int check = 0;
while (check != 1)
{
printf("What is your Status: ");
gets_s(status);
if (status[0] == 'S' && status[1] == 'H')
{
printf("\n\n CORRECT ANSWER. SH \n\n");
single_total = single_total + 1;
check = 1;
}
else if (status[0] == 'S' && status[1] == '\0')
{
printf("\n\n CORRECT ANSWER. S \n\n");
single_total = single_total + 1;
check = 1;
}
else if (status[0] == 'M' && status[1] == 'J')
{
printf("\n\n CORRECT ANSWER. MJ \n\n");
mj_total = mj_total + 1;
check = 1;
}
else if (status[0] == 'M' && status[1] == 'S')
{
printf("\n\n CORRECT ANSWER. MS \n\n");
ms_total = ms_total + 1;
check = 1;
}
else
{
printf("\n\n INCORRECT NSWER. noting \n\n");
}
}
}
float get_total_income(float wage, float div, float intre, float other, int dep)
{
char status[10];
float income = 0, sum = 0, adjusted_income = 0;
int check = 0;
sum = wage + div + intre + other;
income = sum - dep;
while (check != 1)
{
printf("\n\nWhat is your Status: ");
gets_s(status);
if (status[0] == 'S' && status[1] == 'H')
{
sh_total = sh_total + 1;
check = 1;
if (income <= 6000)
{
adjusted_income = income * 0.0;
}
else if (income > 6000 && income <= 9000)
{
adjusted_income = income * .038;
}
else if (income > 9000 && income <= 15000)
{
adjusted_income = income * .074;
}
else if (income > 15000 && income <= 21000)
{
adjusted_income = income * .110;
}
else if (income > 21000 && income <= 25000)
{
adjusted_income = income * .138;
}
else if (income > 25000 && income <= 30000)
{
adjusted_income = income * .154;
}
else if (income > 30000)
{
adjusted_income = income * .35;
}
else
{
printf("\n\n INCORRECT ANSWER. CODE IS WRONG. \n\n");
}
}
else if (status[0] == 'S' && status[1] == '\0')
{
single_total = single_total + 1;
check = 1;
if (income <= 6000)
{
adjusted_income = income * .028;
}
else if (income > 6000 && income <= 9000)
{
adjusted_income = income * .075;
}
else if (income > 9000 && income <= 15000)
{
adjusted_income = income * .096;
}
else if (income > 15000 && income <= 21000)
{
adjusted_income = income * .135;
}
else if (income > 21000 && income <= 25000)
{
adjusted_income = income * .155;
}
else if (income > 25000 && income <= 30000)
{
adjusted_income = income * .174;
}
else if (income > 30000)
{
adjusted_income = income * .35;
}
else
{
printf("\n\n INCORRECT ANSWER. CODE IS WRONG. \n\n");
}
}
else if (status[0] == 'M' && status[1] == 'J')
{
mj_total = mj_total + 1;
check = 1;
if (income <= 6000)
{
adjusted_income = income * 0.0;
}
else if (income > 6000 && income <= 9000)
{
adjusted_income = income * .052;
}
else if (income > 9000 && income <= 15000)
{
adjusted_income = income * .083;
}
else if (income > 15000 && income <= 21000)
{
adjusted_income = income * .122;
}
else if (income > 21000 && income <= 25000)
{
adjusted_income = income * .146;
}
else if (income > 25000 && income <= 30000)
{
adjusted_income = income * .163;
}
else if (income > 30000)
{
adjusted_income = income * .35;
}
else
{
printf("\n\n INCORRECT ANSWER. CODE IS WRONG. \n\n");
}
}
else if (status[0] == 'M' && status[1] == 'S')
{
ms_total = ms_total + 1;
check = 1;
if (income <= 6000)
{
adjusted_income = income * .023;
}
else if (income > 6000 && income <= 9000)
{
adjusted_income = income * .072;
}
else if (income > 9000 && income <= 15000)
{
adjusted_income = income * .089;
}
else if (income > 15000 && income <= 21000)
{
adjusted_income = income * .131;
}
else if (income > 21000 && income <= 25000)
{
adjusted_income = income * .152;
}
else if (income > 25000 && income <= 30000)
{
adjusted_income = income * .172;
}
else if (income > 30000)
{
adjusted_income = income * .35;
}
else
{
printf("\n\n INCORRECT ANSWER. CODE IS WRONG. \n\n");
}
}
else
{
printf("\n\n INCORRECT STATUS. Enter (S, MJ, MS, or SH) \n\n");
}
}
printf("\n\n\n\t YOUR WAGES: %.2f", wage);
printf("\n\t YOUR OTHER INCOME: %.2f", other);
printf("\n\t YOUR DIVIDENS: %.2f", div);
printf("\n\t YOUR INTEREST: %.2f", intre);
printf("\n\t YOUR INCOME AFTER DEPENDANTS: %.2f", income);
return adjusted_income;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T08:04:43.917",
"Id": "72936",
"Score": "1",
"body": "This is some sort of school project I guess? A couple of questions: 1. Have you learned about `struct`? 2. Have you learned about passing pointers to functions? (Example: `void some_fun(int *store_value_here) { *store_value_here = 42; }`)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T14:22:24.337",
"Id": "72976",
"Score": "0",
"body": "yes and no. I don't have to learn about struct yet. And far as pointers i couldn't wrap my head around the usefulness of it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T18:34:18.817",
"Id": "73052",
"Score": "0",
"body": "Thank you guys for the info. I am looking into this now. going to take some time."
}
] |
[
{
"body": "<h1>Things you did well:</h1>\n\n<ul>\n<li><p>You used the function <a href=\"http://en.cppreference.com/w/c/io/gets\" rel=\"nofollow noreferrer\"><code>gets_s</code></a>, which is an <a href=\"https://en.wikipedia.org/wiki/C11_%28C_standard_revision%29\" rel=\"nofollow noreferrer\">optional C11</a> function from Annex K. Not many people use this standard yet because it is newer. I was surprised to see it in your code.</p></li>\n<li><p>Your organization of the prototype functions is good.</p></li>\n<li><p>You initialize your variables as soon as you create them in some areas.</p></li>\n</ul>\n\n<h1>Things you could improve:</h1>\n\n<p>There is a lot that could be improved in this code, so I doubt I will be able to mention them all.</p>\n\n<h3>Preprocessor</h3>\n\n<ul>\n<li><p>You include both <code><stdio.h></code> and <code><cstdio></code>.</p>\n\n<blockquote>\n<pre><code>#include <stdio.h>\n#include <conio.h>\n#include <stdlib.h>\n#include <cstdio>\n</code></pre>\n</blockquote>\n\n<p>I couldn't get the code to compile as C code with the <code>#include <cstdio></code> in there, so it should be removed.</p></li>\n</ul>\n\n<h3>User-experience</h3>\n\n<ul>\n<li><p>You ask the user if he is ready to start.</p>\n\n<blockquote>\n<pre><code>printf(\"Would you like to start: \");\ngets_s(another);\n\nif (another[0] != 'y' && another[0] != 'n')\n{\n while (another[0] != 'y' && another[0] != 'n')\n {\n printf(\"\\n\\n INCORRECT ANSWER. \\n\\n\");\n printf(\"\\n Would you like to start. (y or n)\");\n gets_s(another);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>The user initiated your program for a reason. Asking him if he would like start is useless, and can be frustrating to a user. To add onto the annoyance, you then tell the user that his input is \"incorrect\", if he doesn't input <code>'y'</code>, and you then loop the question. I would remove the whole thing.</p></li>\n</ul>\n\n<h3>Logic</h3>\n\n<ul>\n<li><p>Some of your logic can be simplified.</p>\n\n<blockquote>\n<pre><code>if (status[0] == 'S' && status[1] == 'H')\n{\n printf(\"\\n\\n CORRECT ANSWER. SH \\n\\n\");\n single_total = single_total + 1;\n check = 1;\n}\nelse if (status[0] == 'S' && status[1] == '\\0')\n{\n printf(\"\\n\\n CORRECT ANSWER. S \\n\\n\");\n single_total = single_total + 1;\n check = 1;\n}\n</code></pre>\n</blockquote>\n\n<p>Both times you are checking if <code>status[0] == 'S'</code>, so use that as the \"master\" <code>if</code> test condition. Use the other tests as \"children\" tests.</p>\n\n<pre><code>if (status[0] == 'S')\n{\n if (status[1] == 'H') puts(\"Correct answer: SH\");\n if (status[1] == '\\0') puts(\"Correct answer: S\");\n single_total = single_total + 1;\n check = 1;\n}\n</code></pre>\n\n<p>Pull out the code that the original test conditions had in common to the \"master\" condition, and you have a refined test condition statement!</p></li>\n<li><p>You sometimes have logic that will print out to the console that the logic in the code is wrong.</p>\n\n<blockquote>\n<pre><code>else\n{\n printf(\"\\n\\n INCORRECT ANSWER. CODE IS WRONG. \\n\\n\");\n}\n</code></pre>\n</blockquote>\n\n<p>I would use <a href=\"https://en.cppreference.com/w/c/error/assert\" rel=\"nofollow noreferrer\"><code>assert()</code></a> instead. If this expression evaluates to <code>0</code>, this causes an assertion failure that terminates the program. Also, assertions are the right mechanism to use, since those positions in the code would only be reachable due to programmer error, not due to unanticipated runtime conditions.</p>\n\n<pre><code>else\n{\n assert(income > 30000);\n adjusted_income = income * .35;\n}\n</code></pre></li>\n</ul>\n\n<h3>Variables</h3>\n\n<ul>\n<li><p>You have a lot of <a href=\"https://en.wikipedia.org/wiki/Magic_number_%28programming%29\" rel=\"nofollow noreferrer\">\"magic numbers\"</a> in your code. </p>\n\n<blockquote>\n<pre><code>if (income <= 6000)\n{\n adjusted_income = income * 0.0;\n}\nelse if (income > 6000 && income <= 9000)\n{\n adjusted_income = income * .038;\n}\nelse if (income > 9000 && income <= 15000)\n{\n adjusted_income = income * .074;\n}\nelse if (income > 15000 && income <= 21000)\n{\n adjusted_income = income * .110;\n}\nelse if (income > 21000 && income <= 25000)\n{\n adjusted_income = income * .138;\n}\nelse if (income > 25000 && income <= 30000)\n{\n adjusted_income = income * .154;\n}\nelse if (income > 30000)\n{\n adjusted_income = income * .35;\n}\n</code></pre>\n</blockquote>\n\n<p>You should extract all of those numbers to variables in case you have to change them later. Then you only have to change one number in one place, instead of changing the number in multiple different places. What if you missed a place?</p></li>\n<li><p>Your variable <code>char buffer[80][90]</code> is unused and should be removed.</p></li>\n<li><p>It's generally good practice to initialize all of your non-static variables when possible.</p></li>\n<li><p>Don't use global variables.</p>\n\n<blockquote>\n<pre><code>int single_total = 0;\nint mj_total = 0;\nint ms_total = 0;\nint sh_total = 0;\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>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></li>\n</ul>\n\n<h3>Syntax</h3>\n\n<ul>\n<li><p>You use too much space when printing to the console. Also, use <a href=\"https://en.cppreference.com/w/c/io/puts\" rel=\"nofollow noreferrer\"><code>puts()</code></a> instead of <code>printf()</code> in some cases where you are not actually formatting the string but just printing it with a newline character at the end.</p></li>\n<li><p><code>mj_total = mj_total + 1</code> can be simplified to <code>mj_total += 1</code>.</p></li>\n</ul>\n\n<h3>Input</h3>\n\n<ul>\n<li><p>Your code can't handle the input of a string properly.</p>\n\n <pre class=\"lang-none prettyprint-override\"><code>How much in other income. ten\n</code></pre>\n\n<p>It should tell the user that it is unacceptable input and ask for re-entry of the data.</p></li>\n<li><p>Your program can't handle the input of a malformed string properly.</p>\n\n <pre class=\"lang-none prettyprint-override\"><code>How much in other income. 107t\n</code></pre>\n\n<p>It should tell the user that it is unacceptable input and ask for re-entry of the data.</p></li>\n<li><p>Your program can't handle the input of a <code>\\n</code> (new-line) character (pressing <kbd>enter</kbd>).</p>\n\n <pre class=\"lang-none prettyprint-override\"><code>How much in other income. <enter>\n</code></pre>\n\n<p>It should tell the user that it is unacceptable input and ask for re-entry of the data.</p></li>\n<li><p>Your program is very unforgiving when asking the status of the user. </p>\n\n<blockquote>\n<pre><code>printf(\"\\n\\nWhat is your Status: \");\ngets_s(status);\n</code></pre>\n</blockquote>\n\n<p>If you input a lower-case character, it won't be accepted. Use the <a href=\"https://en.cppreference.com/w/c/string/byte/toupper\" rel=\"nofollow noreferrer\"><code>toupper()</code></a> function on your input character to fix this. You have this same issue when asking the user if he has more <code>wages</code>, <code>dividends</code>, etc.</p>\n\n<blockquote>\n<pre><code>printf(\"\\n Would you like anoter. (y or n)\");\ngets(another);\n</code></pre>\n</blockquote>\n\n<p>Here you might want to use the <a href=\"https://en.cppreference.com/w/c/string/byte/tolower\" rel=\"nofollow noreferrer\"><code>tolower()</code></a> function.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T15:06:22.983",
"Id": "72984",
"Score": "3",
"body": "The only thing I would suggest for this post is adding `{}` to the single line if statements. It's a coding-style issue, but the OP is also just starting programming. I've seen all sorts of errors/bugs pop up due to unbracketed ifs, fors, whiles, etc, so imo it's just better to explicitly use `{}`, even for one line statements where it doesn't make a semantic difference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T18:55:27.470",
"Id": "73067",
"Score": "0",
"body": "your logic is not idempotent in the case where status = S{anything but H or \\0}"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T19:10:44.063",
"Id": "73073",
"Score": "0",
"body": "@njzk2 That was only a snippet of the longer logic block."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T20:20:29.927",
"Id": "73095",
"Score": "0",
"body": "@sybo0rg still, in the original code, `SH` and `S\\0` are considered good answers, in your case, anything that starts with an `S` goes into that block, getting `single_total` to be incremented."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T22:35:33.417",
"Id": "73123",
"Score": "0",
"body": "@njzk2 If the user enters `S` into the program in any form, he is indicating that he is single in some way, so the `single_total` should be incremented if the input starts with an 'S' in my opinion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T14:03:29.130",
"Id": "73516",
"Score": "0",
"body": "I don't disagree with your analysis of the problem. But in the original program, S + something else (not H, not \\0, say, A for example) results in `printf(\"\\n\\n INCORRECT NSWER. noting \\n\\n\");`, while in your case it results in nothing being printed, but the input being taken into account anyway."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-02-21T04:27:42.890",
"Id": "42388",
"ParentId": "42387",
"Score": "23"
}
},
{
"body": "<h3>Language Usage Problems</h3>\n\n<p>You call <code>gets_s()</code> with only one parameter. It expects two parameters — the second parameter is supposed to be the size of the buffer. I would be surprised that this compiled at all.</p>\n\n<p>You tagged this question as <a href=\"/questions/tagged/c\" class=\"post-tag\" title=\"show questions tagged 'c'\" rel=\"tag\">c</a>, and it is indeed <em>mostly</em> C. However, you <code>#include <cstdio></code>, which is a C++ header file, instead of <code><stdio.h></code>, which is what you should use in C. (<code><cstdio></code> provides declarations for C-style I/O functions to C++ programs, for compatibility with legacy C code.)</p>\n\n<p>If you <code>#include <stdio.h></code>, I don't believe you need <code><conio.h></code>, which is Windows-specific.</p>\n\n<p><code>system(\"pause\")</code> works on Windows, but is not portable. <a href=\"https://stackoverflow.com/a/4869519/1157100\"><code>getchar()</code></a> would be a portable alternative.</p>\n\n<p>The <code>check_status()</code> function is defined but never used. If you compile with warnings enabled, your compiler should tell you that <code>char buffer[80][90]</code> in <code>main()</code> is an unused variable.</p>\n\n<h3>Logic Bug</h3>\n\n<p>Compare the signature of this function</p>\n\n<pre><code>float get_total_income(float wage, float div, float intre, float other, int dep)\n{\n …\n}\n</code></pre>\n\n<p>against the way you call it:</p>\n\n<pre><code>income_tax = get_total_income(wages, other_income, dividends, interest, dependents);\n</code></pre>\n\n<p>Notice the discrepancy?</p>\n\n<h3>Code Organization</h3>\n\n<p>You input routines include <strong>nearly identical code, repeated four times</strong>. Instead, you should be able to define a single function to be used four times, like this:</p>\n\n<pre><code>wages = prompt_amount_in_category(\"wages\");\nother_income = prompt_amount_in_category(\"other income\");\ninterest = prompt_amount_in_category(\"interest\");\ndividends = prompt_amount_in_category(\"dividends\");\n</code></pre>\n\n<p>Your functions could be named better. For example, <code>dependents_loop()</code> would be better named <code>prompt_number_of_dependents()</code>. It reads better as English and is more descriptive. Also, the caller is more interested in the purpose of the function; the fact that there happens to be a loop inside the function is an implementation detail that doesn't deserve to be part of the function's name.</p>\n\n<p><code>get_total_income()</code> is a misnomer — it actually does much more than that. After calculating the total income, it also asks the user for the marital/filing status, increments a global counter based on that answer, calculates the tax, and displays a report. <strong>A function should do <em>one</em> thing only,</strong> and its name should reflect its purpose.</p>\n\n<pre><code>enum filing_status {\n SINGLE,\n MARRIED_FILING_JOINTLY,\n MARRIED_FILING_SEPARATELY,\n SINGLE_HEAD_OF_HOUSEHOLD\n};\n#define FILING_STATUS_MAX (SINGLE_HEAD_OF_HOUSEHOLD + 1)\n\nfloat get_total_income(float wage, float div, float intre, float other, float dep)\n{\n return wage + div + intre + other + dep;\n}\n\nenum filing_status prompt_filing_status()\n{\n char status[10];\n do {\n printf(\"\\n\\nWhat is your Status: \");\n gets_s(status, sizeof(status));\n switch (status[0]) {\n case 'S': case 's':\n switch (status[1]) {\n case '\\0':\n return SINGLE;\n case 'H': case 'h':\n return SINGLE_HEAD_OF_HOUSEHOLD;\n }\n break;\n case 'M': case 'm':\n switch (status[1]) {\n case 'J': case 'j':\n return MARRIED_FILING_JOINTLY;\n case 'S': case 's':\n return MARRIED_FILING_SEPARATELY;\n }\n break;\n }\n printf(\"\\n\\n INCORRECT STATUS. Enter (S, MJ, MS, or SH) \\n\\n\");\n } while (1);\n}\n\nfloat calculate_tax(float income, enum filing_status status)\n{\n …\n}\n\nint main() {\n int return_counts[FILING_STATUS_MAX] = { 0 };\n …\n\n wages = prompt_amount_in_category(\"wages\");\n other_income = prompt_amount_in_category(\"other income\");\n interest = prompt_amount_in_category(\"interest\");\n dividends = prompt_amount_in_category(\"dividends\");\n dependants = -2000 * prompt_number_of(\"dependants\");\n\n //function to indicate the status and other things. \n enum filing_status status = prompt_filing_status();\n return_counts[status]++;\n\n total_income = get_total_income(wages, dividends, interest, other_income, dependents);\n income_tax = calculate_tax(total_income, status);\n\n\n printf(\"\\n\\n\\n\\t YOUR WAGES: %.2f\", wages);\n printf(\"\\n\\t YOUR OTHER INCOME: %.2f\", other_income);\n printf(\"\\n\\t YOUR DIVIDENS: %.2f\", dividends);\n printf(\"\\n\\t YOUR INTEREST: %.2f\", interest);\n printf(\"\\n\\t YOUR INCOME AFTER DEPENDANTS: %.2f\", total_income);\n\n …\n}\n</code></pre>\n\n<h3>Accountancy Errors</h3>\n\n<p>According to your program, a single filer with 9000.00 of income owes 468.00 in income tax. A single filer with 9000.01 in income owes 747.00 in income tax. That's the most regretful cent that anyone has ever earned! Tax brackets don't work like that — each marginal tax rate only applies to the part of the income that falls within that tax bracket, not to the entire income.</p>\n\n<p>I know that this is just a toy program, but such an error makes it awkward for me to suggest a way to reduce the amount of code to compute the tax. I could either propose a buggy solution that is compatible with your original, or a plausible solution that is hard to compare against the original code. Therefore, I'll just end the review here without improving <code>calculate_tax()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T04:39:51.280",
"Id": "72921",
"Score": "0",
"body": "I should point out that I was the one who removed the C++ tag. Only that one header was from C++, and wasn't enough for the tag."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T04:43:15.513",
"Id": "72922",
"Score": "0",
"body": "@Jamal Thanks for the clarification. The point remains, though: the original question claimed to be polyglot [tag:c]/[tag:c++], and it wasn't [tag:c]."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T04:47:19.020",
"Id": "72923",
"Score": "0",
"body": "Even if it were to be reviewed as C++ code as well, it would need even more changes. This is from an assignment, so perhaps it was meant to be C++, but without the STL. Perhaps I was wrong to remove the tag, or we just need more clarification from the OP."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T15:47:52.307",
"Id": "72998",
"Score": "0",
"body": "Like your *\"prompt\"* naming. Should have used that. The `get_income_group` becomes a miss compared to the other `get_` functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T21:46:37.880",
"Id": "423659",
"Score": "0",
"body": "Great catch with subject-specific knowledge of Accountancy Errors. That is a great point."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T04:37:31.033",
"Id": "42389",
"ParentId": "42387",
"Score": "12"
}
},
{
"body": "<p>New to this site, so hope this is in correct format. I did a rewrite of your code. I also notice others has entered some of the same conclusions, so some redundancy.</p>\n\n<p>I assume this is a school project and as such I will omit some things that I otherwise would have used. Among other things <code>struct</code>'s.</p>\n\n<p>Ended up with a rather big rewrite. It is not certain you will find it useful, but hopefully you can draw something from it. I almost feel a bit rude here, but.</p>\n\n<p>As this text likely is easier to read and understand with the complete source for the rewrite in one collective file i have <a href=\"http://codepad.org/4dqrfHMR\">pasted it here</a>.</p>\n\n<p>OK. Lets start.</p>\n\n<hr>\n\n<p>Firstly I will mention that I use the <code>fprintf()</code> version. This is from habit as if I later find the need to output to something else then <code>stdout</code> it is easy to change. I also have some coding style when it comes to <code>printf()</code> that I have found to be working well.</p>\n\n<p>I have also not used <code>gets_s()</code> as it simply is not available on my system.</p>\n\n<h1>User input</h1>\n\n<p>When we look at your code one of the things that is most clear is the redundancy in user input functions. The functions:</p>\n\n<pre><code>float wages_loop();\nfloat other_loop();\nfloat interest_loop();\nfloat dividends_loop();\n</code></pre>\n\n<p>can be merged into one function. If we notice we repeat our selves, we should take a good long look at what we are doing and how we can re factor the code.</p>\n\n<p>Secondly it is a good rule to have as number one:</p>\n\n<ol>\n<li>A function should: <strong>Do one thing, and do it well.</strong></li>\n</ol>\n\n<p>A second thing that we use when appropriate is helper functions. This both helps us splitting up the code into manageable parts, as well as make the code much less redundant.</p>\n\n<p>Lets start with confirmations. We have repeated requests for confirmation where answer is <code>y</code> for yes and <code>n</code> for no. Using the power of <code>printf()</code> we can then make a general confirmation function.</p>\n\n<p>Secondly we have input by float and int. Dividing this into functions we can end up with something like this. (Hopefully they should be rather self-explaining).</p>\n\n<p>We should have had both <code>int</code> and <code>float</code> versions + some error checking, but this should be an OK starter. For <code>int</code> input I cast the float.</p>\n\n<pre><code>static int confirm(char *title)\n{\n char buf[10];\n\n fprintf(stdout, \"%s (y or n) \", title);\n while (1) {\n fgets(buf, sizeof(buf), stdin);\n switch (*buf) {\n case 'y': case 'Y':\n return 1;\n case 'n': case 'N':\n return 0;\n }\n fprintf(stderr, \"Please answer with y for Yes or n for No: \");\n }\n}\n\nstatic float get_float(char *title) {\n char buf[80];\n\n fputs(title, stdout);\n fgets(buf, sizeof(buf), stdin);\n return atof(buf);\n}\n\nstatic float get_info_float(char *type)\n{\n float amount, total = 0;\n\n fprintf(stdout, \"\\n -- %s --\\n\", type);\n do {\n amount = get_float(\"\\n Enter amount: \");\n total += amount;\n fprintf(stdout, \"\\n Do you have any more %s? \", type);\n } while(confirm(\"\"));\n\n return total;\n}\n</code></pre>\n\n<p>In the <code>get_info_float()</code> function we could also have informed the user to enter <code>0</code> to abort request for values. That would perhaps be more user-friendly then a <em>\"y/n request - one more?\"</em> for each input.</p>\n\n<h1>Result printing</h1>\n\n<p>The next thing we can take a look at is printing information. I like to put these into separate functions. Usually there would have been the use of <code>struct</code> instead of loads of parameters, but lets go for it this time.</p>\n\n<p>The two main print functions can be defined like this:</p>\n\n<pre><code>static void print_result(\n float wages,\n float income_other,\n float interests,\n float dividends,\n float income_dep,\n float income_adj\n) {\n int hdr_w = 29;\n\n fprintf(stdout,\n \"\\n\\n\"\n \"-----------------------------------------------\\n\"\n \" %-*s: %.2f\\n\"\n \" %-*s: %.2f\\n\"\n \" %-*s: %.2f\\n\"\n \" %-*s: %.2f\\n\"\n \" %-*s: %.2f\\n\"\n \"\\n\"\n \" %-*s: %.2f\\n\"\n \"-----------------------------------------------\\n\"\n \"\\n\"\n ,\n hdr_w, \"YOUR WAGES\", wages,\n hdr_w, \"YOUR OTHER INCOME\", income_other,\n hdr_w, \"YOUR INTEREST\", interests,\n hdr_w, \"YOUR DIVIDEND\", dividends,\n hdr_w, \"YOUR INCOME AFTER DEPENDENTS\", income_dep,\n hdr_w,\n (\n income_adj < 0 ?\n \"Your income tax RETURN is\" :\n \"Your income tax OWED is\"\n ),\n income_adj\n );\n}\nstatic void print_filing_stats(\n int files_s,\n int files_mj,\n int files_ms,\n int files_sh\n) {\n int hdr_w = 44;\n\n fprintf(stdout,\n \"%-*s: %i\\n\"\n \"%-*s: %i\\n\"\n \"%-*s: %i\\n\"\n \"%-*s: %i\\n\"\n ,\n hdr_w, \"Number of Singles Filing\", files_s,\n hdr_w, \"Number of Married Filing Jointly\", files_mj,\n hdr_w, \"Number of Married Filing Separately\",files_ms,\n hdr_w, \"Number of Single Head of Household Filing\", files_sh\n );\n}\n</code></pre>\n\n<p>Note the use of a variable to adjust the labels/headers namely by <code>hdr_w</code>. This makes it very easy to make nice prints as well as adjusting the width if we find ourselves expanding or removing print data.</p>\n\n<p>I am also always very strict in the formatting as it makes it that much easier to maintain and keep track of.</p>\n\n<p>If you are not used to the ternary operator, <code>income_adj < 0 ? \"one thing\" : \"other thing\"</code> you can separate that out to <code>if</code>'s, but I find it rather powerful in combination with <code>printf</code>.</p>\n\n<h1>Income groups</h1>\n\n<p>Your biggest function is the income testing and re-calculation. As you are familiar with arrays we can simplify this a lot by using them. We declare one <em>adjustment</em> array for each filing type, and one holding the different income groups.</p>\n\n<p>These could have been local to functions, but decided instead to have them in global scope and declare them as <code>const</code> – as such they should not be modified. We could further set them <code>static</code> if you are familiar with that.</p>\n\n<pre><code>const float adjust_SH[] = { 0.000, 0.038, 0.074, 0.110, 0.138, 0.154, 0.350 };\nconst float adjust_S[] = { 0.028, 0.075, 0.096, 0.135, 0.155, 0.174, 0.350 };\nconst float adjust_MJ[] = { 0.000, 0.052, 0.083, 0.122, 0.146, 0.163, 0.350 };\nconst float adjust_MS[] = { 0.023, 0.072, 0.089, 0.131, 0.152, 0.172, 0.350 };\n\nconst int income_group[] = { 6000, 9000, 15000, 21000, 25000, 30000 };\n\n#define STATUS_S 1\n#define STATUS_MJ 2\n#define STATUS_MS 3\n#define STATUS_SH 4\n\n#define STATUS_MIN 1\n#define STATUS_MAX 4\n\n#define INCOME_GR_LEN 6\n</code></pre>\n\n<p>Instead of checking the income by <code>if</code>'s we can now make a short function doing the same by looping. Also note in your original code that you do not need to check for both bigger and lower in each <code>if</code> statement. You can simply start at bottom and say </p>\n\n<pre><code>if (income <= 6000) ... do something\nelse if (income <= 9000) ... do something etc.\n</code></pre>\n\n<p>As by <code>else if</code> you will not have to check that it is greater then. Anyhow, by array we can also do this:</p>\n\n<pre><code>/*\n * Return index of adjust_XX array for income group.\n */\nstatic int get_income_group(float income)\n{\n int i;\n\n for (i = 0; i < INCOME_GR_LEN; ++i) {\n if (income <= income_group[i])\n return i;\n }\n return i; /* As the adjust arrays are one item longer then the\n * income_group array, this will give us last index. */\n}\n</code></pre>\n\n<h1>Filing / Status types</h1>\n\n<p>Instead of using the a bit cumbersome acronyms and check by <code>char</code> we print a short menu and ask for numeric input. As we already have the <code>get_float()</code> helper function this also makes it for a short and concise function:</p>\n\n<pre><code>static int get_status() {\n int status = 0;\n\n fputs( \"\\n\"\n \" Status types:\\n\"\n \" 1. Single Fileing\\n\"\n \" 2. Married Filing Jointly\\n\"\n \" 3. Married Filing Separately\\n\"\n \" 4. Single Head of Household Fileing\\n\"\n \"\\n\"\n ,\n stdout\n );\n\n do {\n status = (int)get_float(\"Enter Status type number: \");\n } while (status < STATUS_MIN && status > STATUS_MAX);\n\n return status;\n}\n</code></pre>\n\n<h1>Adjusted income</h1>\n\n<p>By this the final <code>adjust_income()</code> function can be written like:</p>\n\n<pre><code>static float get_income_adjusted(\n float inc_dep,\n int status\n) {\n float adjusted_income = 0;\n int inc_group;\n\n /* If we are to follow the same requirement as in the\n * \"if\" chain in the original function, we check that\n * income minus dep is above 0. */\n assert(inc_dep > 0);\n if (inc_dep < 0) {\n fprintf(stderr, \"FAIL!\\n\");\n return 0.0;\n }\n\n inc_group = get_income_group(inc_dep);\n\n /* Switch status / filing type and multiply by array \n * value given index by income group */\n switch (status) {\n case STATUS_SH:\n adjusted_income = inc_dep * adjust_SH[inc_group];\n break;\n case STATUS_S:\n adjusted_income = inc_dep * adjust_S[inc_group];\n break;\n case STATUS_MJ:\n adjusted_income = inc_dep * adjust_MJ[inc_group];\n break;\n case STATUS_MS:\n adjusted_income = inc_dep * adjust_MS[inc_group];\n break;\n }\n\n return adjusted_income;\n}\n</code></pre>\n\n<h1>Back to main()</h1>\n\n<p>To stitch it together we can go back to <code>main()</code>. We already have discussed the print functions, and as such there is one tricky thing left, and that is the global counters for type of filing. We can solve this by yet another array, else we would likely have passed a <code>struct</code> by address, but lets do it this way:</p>\n\n<pre><code>int main(void)\n{\n int loop,\n filing,\n filings[] = {0, 0, 0, 0};\n\n loop = 1; // = confirm(\"Should we start? \");\n\n while (loop) {\n\n filing = process_filing();\n filings[filing] += 1;\n\n loop = confirm(\"Would you like to file another? \");\n }\n\n print_filing_stats(\n filings[0],\n filings[1],\n filings[2],\n filings[3]\n );\n\n fprintf(stderr, \"\\nPress enter to quit. \");\n getchar();\n\n return 0;\n}\n</code></pre>\n\n<p>We use the <code>filings[] = {0, 0, 0, 0};</code> array to count type of filing returned by \nprocess filing. Look at the signature for <code>print_filing_stats()</code> to get how it is stitched together.</p>\n\n<h1>Final count up</h1>\n\n<p>Now the final piece of the puzzle is the <code>process_filing()</code> function. The main motor. By now it is simply a row of instructions and function calls that should be easy to follow.</p>\n\n<pre><code>#define DEP_FACTOR 2800\nint process_filing()\n{\n float wages,\n income_other,\n interests,\n dividends,\n income_dep,\n income_adj,\n sum;\n int dependents,\n status;\n\n wages = get_info_float(\"Wages\");\n income_other = get_info_float(\"Other income\");\n interests = get_info_float(\"Interest\");\n dividends = get_info_float(\"Dividends\");\n\n dependents = DEP_FACTOR * (int)get_info_float(\"Dependents\");\n\n sum = wages + income_other + interests + dividends;\n income_dep = sum - dependents;\n\n status = get_status();\n\n income_adj = get_income_adjusted(\n income_dep,\n status\n );\n\n print_result(\n wages,\n income_other,\n interests,\n dividends,\n income_dep,\n income_adj\n );\n\n return status;\n}\n</code></pre>\n\n<h1>Final note</h1>\n\n<p>I have mostly looked at the structuring of the code, and not validated a correct result. Hope it or some of it can be useful anyhow.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T14:24:42.513",
"Id": "72977",
"Score": "0",
"body": "Very nicely done. You did some things I don't agree with, such as using multiple `#define`s instead of an `enum`, but overall you give some very good advice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T14:44:23.273",
"Id": "72980",
"Score": "0",
"body": "@syb0rg: Thanks :) and yes, I was actually considering `enum`, but was very unsure on what level to put it. `struct` and pointers was another consideration. At the end I even considered posting it as a new \"review this please\" post, but guess an answer here was better."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T12:31:19.517",
"Id": "42412",
"ParentId": "42387",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "42388",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T03:53:03.893",
"Id": "42387",
"Score": "11",
"Tags": [
"c"
],
"Title": "Total income program"
}
|
42387
|
<pre><code>#include <iostream>
#include <fstream>
#include <algorithm>
#include <thread>
#include <cmath>
#include <sstream>
#include <cstdlib>
using namespace std;
ostream* outfile = &cout;
bool testCantor(unsigned long long p, unsigned long long q){
while(q % 3 == 0){
q /= 3;
if (p/q == 1) return p==q;
p %= q;
}
unsigned long long p_start = p;
do{
unsigned long long p3 = p * 3;
if(p3/q == 1) return false;
p = p3 % q;
} while(p != p_start);
return true;
}
void genRational(unsigned long long minNum, unsigned long long maxNum, int step, string *result){
ostringstream buffer;
for(unsigned long long q = minNum; q <= maxNum; q += step)
for(unsigned long long p = 1; p <= q/3; p += 2){
if(testCantor(p, q))
for(unsigned long long i = p; i <= q/3; i *= 3)
if(__gcd(i,q) == 1)
buffer << q << ',' << 2 << endl;
if(testCantor(++p, q))
for(unsigned long long i = p; i <= q/3; i *= 3)
if(__gcd(i,q) == 1)
buffer << q << ',' << 2 << endl;
}
*result = buffer.str();
}
int main(int argc, char* argv[]){
unsigned long long minNum, maxNum;
int THREADS = thread::hardware_concurrency() != 0 ? thread::hardware_concurrency() : 8;
switch(argc){
case 2:
minNum = pow(3, atoi(argv[1]));
maxNum = pow(3, atoi(argv[1]) + 1);
break;
case 4:
THREADS = atoi(argv[3]);
case 3:
minNum = pow(3, atoi(argv[1]));
maxNum = pow(3, atoi(argv[2]));
break;
case 5:
minNum = atoi(argv[1]);
maxNum = atoi(argv[2]);
THREADS = atoi(argv[3]);
outfile = new ofstream(argv[4]);
break;
default:
return 1;
}
string* tempStream = nullptr;
thread* tempThread = nullptr;
vector<thread*> usedThreads;
vector<string*> results;
for(int i = 0; i < THREADS; i++){
tempStream = new string("");
results.push_back(tempStream);
tempThread = new thread(genRational, minNum + i, maxNum, THREADS, tempStream);
usedThreads.push_back(tempThread);
}
for(auto i = usedThreads.begin(); i != usedThreads.end(); i++) (*i)->join();
for(auto i = results.begin(); i != results.end(); i++) *outfile << **i ;
return 0;
}
</code></pre>
<p>That is a program I am currently using to get an idea of rational numbers on the Cantor Set. I'm looking for any way to optimize (currently running from 3<sup>13</sup> to 3<sup>16</sup> with 320 threads (one per core) takes 5 hours and it will probably take 819 times longer to compute from 3<sup>16</sup> to 3<sup>19</sup>).</p>
<p>Is there any way to further optimize this?</p>
|
[] |
[
{
"body": "<p>It's probably not going to speed it up a huge amount, but you are doing un-necessary dynamic allocations for <code>thread</code> and <code>string</code> (and leaking memory in the process, as these are never <code>delete</code>d).</p>\n\n<pre><code>void genRational(unsigned long long minNum, unsigned long long maxNum, int step, string *result)\n</code></pre>\n\n<p>Just return the <code>string</code> by value. Named return value optimization should kick in (and could give you a slight performance gain here, because you don't need to dynamically allocate a <code>std::string</code> each time). I assume you're doing this as you're unsure how to get returned values from a thread. The answer is to use either a <code>std::packaged_task</code> or <code>std::async</code>, both of which give a <code>std::future</code>:</p>\n\n<pre><code>std::string genRational(unsigned long long minNum, unsigned long long maxNum, int step)\n{\n ...\n}\n\nstd::vector<std::future<std::string>> futures;\nstd::vector<std::string> results;\n\nfor(int i = 0; i < THREADS; i++){\n futures.emplace_back(std::async(std::launch_async, genRational, minNum + i, maxNum, THREADS));\n}\n\nfor(auto& f : futures) {\n results.push_back(f.get());\n}\n</code></pre>\n\n<p>For further optimization, I'd profile and see exactly where the hotspots are (which will be in one of your <code>testCantor</code> and <code>genRational</code> functions). Look at the most expensive operations there (which will almost certainly be <code>%</code> and <code>/</code>). If you can find a way of reducing the number of these and/or coming up with something that uses other primitive operators in their place, you may be able to get a performance improvement - but I doubt you'll be able to squeeze out anything that'll make the running time reasonable for numbers as large as you want.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T01:07:10.953",
"Id": "44215",
"ParentId": "42394",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T05:47:22.533",
"Id": "42394",
"Score": "3",
"Tags": [
"c++",
"optimization",
"mathematics"
],
"Title": "Filtering function"
}
|
42394
|
<p>In my game, I need to detect whether any buttons/keys are pressed at all before I try to process any input. This is easy enough for keys since the XNA library provides a <code>GetPressedKeys</code> method on the <code>KeyboardState</code> class:</p>
<pre><code>private void ProcessKeyboard()
{
keyboardState = Keyboard.GetState( PlayerIndex.One );
if ( !keyboardState.GetPressedKeys().Any() )
{
DoAction( Actions.Idle );
return;
}
foreach ( var binding in keyboardBindings )
{
if ( keyboardState.IsKeyDown( binding.Key ) )
{
DoAction( binding.Value );
}
}
}
</code></pre>
<p>However, it doesn't provide a corollary for the <code>GamePadState</code> class:</p>
<pre><code>private void ProcessGamePad()
{
gamePadState = GamePad.GetState( PlayerIndex.One );
// detect no input?
foreach ( var binding in gamePadBindings )
{
if ( gamePadState.IsButtonDown( binding.Key ) )
{
DoAction( binding.Value );
}
}
}
</code></pre>
<p>I tried whipping up my own extension method but, as I'm not really familiar with enums or arrays in C#, I'm afraid it's a little sloppy:</p>
<pre><code>public static class GamePadStateExtensions
{
public static Buttons[] GetPressedButtons( this GamePadState gamePadState )
{
// 25 is the number of items in Buttons
var pressedButtons = new Buttons[25];
foreach ( Buttons button in Enum.GetValues( typeof(Buttons) ) )
{
if ( gamePadState.IsButtonDown( button ) )
{
pressedButtons[pressedButtons.Count()] = button;
}
}
return pressedButtons;
}
}
</code></pre>
<p>Would I be better off doing something else with <code>ProcessKeyboard</code> and/or <code>ProcessGamePad</code>? How can I improve <code>GetPressedButtons</code>?</p>
|
[] |
[
{
"body": "<p>Rather than using an array to return you should use a <code>List<T></code> which can be easily appended to:</p>\n\n<pre><code>public static List<Buttons> GetPressedButtons( this GamePadState gamePadState )\n{\n var pressedButtons = List<Buttons>();\n\n foreach ( Buttons button in Enum.GetValues( typeof(Buttons) ) )\n {\n if ( gamePadState.IsButtonDown( button ) )\n {\n pressedButtons.Add(button);\n }\n }\n\n return pressedButtons;\n}\n</code></pre>\n\n<p>However this can be simplified still with the use of <code>LINQ</code>. The for loop basically selects all buttons which are pressed:</p>\n\n<pre><code>public static List<Buttons> GetPressedButtons(this GamePadState gamePadState)\n{\n return Enum.GetValues(typeof(Buttons))\n .Cast<Buttons>()\n .Where(b => gamePadState.IsButtonDown(b))\n .ToList();\n}\n</code></pre>\n\n<p>The <code>Cast<T></code> is required because <code>GetValue</code> returns a non-generic <code>Array</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T17:39:45.993",
"Id": "73030",
"Score": "1",
"body": "This is an interesting way of doing it. In my case, I mapped both XNA buttons and keys to my own Buttons flags enum, which I'd argue is more efficient than a list to store button state."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T07:20:08.797",
"Id": "42398",
"ParentId": "42395",
"Score": "4"
}
},
{
"body": "<p>There is one problem you may face with that code,</p>\n\n<p>I did a lot of input work with XNA and you may find that getting the \"down\" keys is not actually what you want. it is not the same thing as the pressed keys, that will fire constantly as you hold the key, triggering a new event each time.E.g if you press a to open a chat dialog and a again to close it, just pressing the button once may trigger like 6 actual presses and flicker the popup.</p>\n\n<p>For getting the PRESSED buttons you would actually need to store the prior state of the gamepad and assert if it was not pressed last frame e.g</p>\n\n<pre><code>public static List<Buttons> GetPressedButtons(this GamePadState gamePadState,GamePadState previousState)\n{\n return Enum.GetValues(typeof(Buttons))\n .Cast<Buttons>()\n .Where(b => gamePadState.IsButtonDown(b) && !previousState.IsButtonDown(b))\n .ToList();\n}\n</code></pre>\n\n<p>As for getting the prior state that is simply a matter of having a prior state variable and at the end of your update cycle set <code>previousState = currentState</code> .</p>\n\n<p><em><strong>P.s</strong> I robbed @ChrisWue 's very clean snippet for my example.</em> </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T17:48:54.847",
"Id": "73034",
"Score": "1",
"body": "Another way around this is to only collect changes (or only collect duplicates every n ticks) into some kind of collection and only observe on specific patterns, rather than tying input directly to the frame. It can be complicated, but it's somewhat more flexible - it can be extended to recognize patterns."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T19:36:07.230",
"Id": "73082",
"Score": "0",
"body": "I had not thought that far ahead yet! I will surely need to do this."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T14:01:56.140",
"Id": "42418",
"ParentId": "42395",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T06:03:05.643",
"Id": "42395",
"Score": "4",
"Tags": [
"c#",
"game",
"extension-methods",
"event-handling"
],
"Title": "Get array of pressed buttons using extension method"
}
|
42395
|
<blockquote>
<p>Given a source and destination, in an integer matrix, find path, such
that the next position in the path has a greater than or equal to
value than the previous position. In other words monotonically
increasing. In event of multiple paths, a non-optimal solution may be
returned.</p>
</blockquote>
<p>I'm looking for code review, best practices, optimizations etc. Verifying complexity to be O (n * m) where <em>n</em> is row and <em>m</em> is column count.</p>
<pre><code>final class Point {
private final int row;
private final int col;
public Point(int i, int j) {
this.row = i;
this.col = j;
}
public int getI() {
return row;
}
public int getJ() {
return col;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (getClass() != o.getClass()) return false;
final Point c = (Point)o;
return row == c.row && col == c.col;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + row;
result = prime * result + col;
return result;
}
}
public class IncreasingPath {
private int[][] m;
public IncreasingPath(int[][] m) {
if (m == null) throw new NullPointerException("The matrix cannot be null");
if (m.length == 0) throw new IllegalArgumentException("The matrix should not be empty");
this.m = m;
}
/**
* Given a start and end position in matrix returns the path of continously increasing numbers.
* If multiple paths exists then any one of the path would be returned.
* If no such path exists then empty list is returned.
*
*
*
* @param startRow the row index of the start position
* @param startColumn the col index of the start position
* @param endRow the row index of the end position
* @param endCol the col index of the end position
* @return the increasing path from source to destination if it exists.
*/
public List<Point> increasingPath(int startRow, int startColumn, int endRow, int endCol) {
validate(startRow, startColumn, endRow, endCol);
final List<Point> pointPath = new ArrayList<Point>();
pathFind(startRow, startColumn, endRow, endCol, pointPath);
return pointPath;
}
private void validate (int startRow, int startColumn, int endRow, int endCol) {
if (startRow < 0 || startRow >= m.length)
throw new IllegalArgumentException("The start row " + startRow + " out of bounds." );
if (startColumn < 0 || startColumn >= m[0].length)
throw new IllegalArgumentException("The start col " + startColumn + " out of bounds." );
if (endRow < 0 || endRow >= m.length)
throw new IllegalArgumentException("The end row " + endRow + " out of bounds." );
if (endCol < 0 || endCol >= m[0].length)
throw new IllegalArgumentException("The end col " + endCol + " out of bounds." );
}
private boolean pathFind(int row, int col, int endRow, int endCol, List<Point> pointPath) {
final Point coordinate = new Point(row, col);
if (row == endRow && col == endCol) {
pointPath.add(coordinate);
return true;
}
if (pointPath.contains(coordinate)) {
return false;
} else {
pointPath.add(coordinate);
}
for (int i = Math.max(0, row - 1); i < Math.min(m.length, row + 2); i++) {
for (int j = Math.max(0, col - 1); j < Math.min(m[0].length, col + 2); j++) {
// Skip the tile (i, j) itself
if (i == row && j == col)
continue;
if (m[row][col] <= m[i][j] && m[i][j] <= m[endRow][endCol]) {
if (pathFind(i, j, endRow, endCol, pointPath)) return true;
}
}
}
pointPath.remove(coordinate);
return false;
}
public static void main(String[] args) {
int[][] m = { {1, 2, 3, 4 },
{5, 6, 7, 8 },
{9, 10, 11, 12 } };
IncreasingPath lip = new IncreasingPath(m);
List<Point> points1 = new ArrayList<Point>();
points1.add(new Point(0, 0));
points1.add(new Point(0, 1));
points1.add(new Point(0, 2));
points1.add(new Point(0, 3));
points1.add(new Point(1, 2));
points1.add(new Point(1, 3));
points1.add(new Point(2, 2));
points1.add(new Point(2, 3));
Assert.assertEquals(points1, lip.increasingPath(0, 0, 2, 3));
List<Point> points2 = new ArrayList<Point>();
points2.add(new Point(0, 2));
points2.add(new Point(1, 1));
points2.add(new Point(2, 0));
Assert.assertEquals(points2, lip.increasingPath(0, 2, 2, 0));
Assert.assertEquals(new ArrayList<Point>(), lip.increasingPath(2, 0, 0, 2));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T10:20:39.603",
"Id": "72943",
"Score": "4",
"body": "You've indicated that you are preparing for interviews, and indeed we've seen your coding skills improve over the last 88 questions. I think that if you try answering some other users' questions, you'll find it rewarding and educational as well. Part of being a good programmer is being able to work with other people's code and communicate your thoughts effectively. I humbly suggest that at this point, trying to answer questions may do more for your interview skills than cranking out yet another algorithm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T10:24:37.273",
"Id": "72944",
"Score": "0",
"body": "I'd consider this question to have a self-contradiction. If the sequence is monotonically increasing, then each element is strictly greater than the previous. If the sequence is monotonically nondecreasing, then each element is greater than or equal to the previous."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T17:25:41.900",
"Id": "73021",
"Score": "2",
"body": "It is very much in my mind, it might be some while before I contribute, but I certainly would."
}
] |
[
{
"body": "<p>Just two quick notes:</p>\n\n<ol>\n<li><p>It's usually a good practice to make a copy of mutable input parameters. (<code>int[][] m</code> array in this case.) It prohibits malicious clients to modify the internal structure of the class or it could save you from a few hours of debugging. (<em>Effective Java, 2nd Edition, Item 39: Make defensive copies when needed</em>) </p></li>\n<li><p>There is some duplication is the validate method. Every condition is the same with different variable names. You could move that to a helper function:</p>\n\n<pre><code>private void validate (int startRow, int startColumn, int endRow, int endCol) {\n checkInRange(startRow, 0, m.length, \"The start row \" + startRow + \" out of bounds.\");\n checkInRange(startColumn, 0, m[0].length), \"The start col \" + startColumn + \" out of bounds.\");\n checkInRange(endRow, 0, m.length, \"The end row \" + endRow + \" out of bounds.\");\n checkInRange(endCol, 0, m[0].length, \"The end col \" + endCol + \" out of bounds.\");\n}\n\nprivate void checkInRange(int value, int lowerBound, int upperBound, String message) {\n if (value < lowerBound || value >= upperBound) {\n throw new IllegalArgumentException(message);\n }\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T07:16:19.567",
"Id": "42397",
"ParentId": "42396",
"Score": "4"
}
},
{
"body": "<blockquote>\n <p>In event of multiple paths, a non-optimal solution may be returned.</p>\n</blockquote>\n\n<p>Problem description clearly states there may be multiple solutions.</p>\n\n<p>But in the test:</p>\n\n<pre><code> List<Point> points1 = new ArrayList<Point>();\n points1.add(new Point(0, 0));\n //....more points........\n points1.add(new Point(2, 3));\n\n Assert.assertEquals(points1, lip.increasingPath(0, 0, 2, 3));\n</code></pre>\n\n<p>You compare the found solution (which is suboptimal) to itself after the fact. Instead you should verify that the solution is correct using the definition given in the question. e.g. </p>\n\n<ul>\n<li>first element is the solution is the given start point, </li>\n<li>last element is the given end point, </li>\n<li>each point in the path is the neighbor to another. </li>\n<li>and the values in the matrix corresponding to those points are non-decreasing.</li>\n</ul>\n\n<p>I also don't like empty list as failure. I would prefer guava's <code>Optional</code> or something equivalent.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T13:56:05.797",
"Id": "73515",
"Score": "2",
"body": "Welcome to 2K! You've been around for a while, FYI you're welcome anytime in [The 2nd Monitor](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor)!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T14:55:57.897",
"Id": "42422",
"ParentId": "42396",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T06:41:23.887",
"Id": "42396",
"Score": "3",
"Tags": [
"java",
"matrix"
],
"Title": "Path from source to destination, with increasing values"
}
|
42396
|
<p>This is my first major PHP project and I haven't gotten much feedback. I wanted to learn how to use PHP and I wanted to learn about Minecraft's status protocol, so I did what was obvious at the time.</p>
<h1>File listing</h1>
<p>The code is also <a href="https://github.com/winny-/mcstat" rel="nofollow noreferrer">on GitHub</a>.</p>
<h2>mcstat.php</h2>
<p>Contains class <code>MinecraftStatus</code> and is also a stand-alone CLI tool.</p>
<pre><code>#!/usr/bin/env php
<?php
class MinecraftStatus {
public $hostname;
public $port;
public $stats;
function __construct($hostname, $port=25565)
{
$this->hostname = $hostname;
$this->port = $port;
}
public function ping()
{
$newStats = $this->serverListPing($this->hostname, $this->port);
$this->stats[microtime()] = array(
'stats' => $newStats,
'method' => 'Server List Ping',
'hostname' => $this->hostname,
'port' => $this->port
);
return $newStats;
}
public function query($fullQuery=true)
{
if ($fullQuery) {
$newStats = $this->fullQuery($this->hostname, $this->port);
$this->stats[microtime()] = array(
'stats' => $newStats,
'method' => 'Full Query',
'hostname' => $this->hostname,
'port' => $this->port
);
} else {
$newStats = $this->basicQuery($this->hostname, $this->port);
$this->stats[microtime()] = array(
'stats' => $newStats,
'method' => 'Basic Query',
'hostname' => $this->hostname,
'port' => $this->port
);
}
return $newStats;
}
/*
================
Server List Ping
================
An example of how to get a Minecraft server status's using a "Server List Ping" packet.
See details here: http://www.wiki.vg/Server_List_Ping
*/
private function packString($string)
{
return pack('n', strlen($string)) . mb_convert_encoding($string, 'UCS-2BE');
}
// This is needed since UCS-2 text rendered as UTF-8 contains unnecessary null bytes
// and could cause other components, especially string functions to blow up. Boom!
private function decodeUCS2BE($string)
{
return mb_convert_encoding($string, 'UTF-8', 'UCS-2BE');
}
private function serverListPing($hostname, $port=25565)
{
// 1. pack data to send
$request = pack('nc', 0xfe01, 0xfa) .
$this->packString('MC|PingHost') .
pack('nc', 7+2*strlen($hostname), 73) .
$this->packString($hostname) .
pack('N', 25565);
// 2. open communication socket and make transaction
$time = microtime(true);
$fp = stream_socket_client('tcp://' . $hostname . ':' . $port);
if (!$fp) {
return false;
}
fwrite($fp, $request);
$response = fread($fp, 2048);
fclose($fp);
$time = round((microtime(true)-$time)*1000);
// 3. unpack data and return
if (strpos($response, 0xFF) !== 0) {
return false;
}
$response = substr($response, 3);
$response = explode(pack('n', 0), $response);
return array(
'player_count' => $this->decodeUCS2BE($response[4]),
'player_max' => $this->decodeUCS2BE($response[5]),
'motd' => $this->decodeUCS2BE($response[3]),
'server_version' => $this->decodeUCS2BE($response[2]),
'protocol_version' => $this->decodeUCS2BE($response[1]),
'latency' => $time
);
}
/*
=====
Query
=====
This section utilizes the UT3 Query protocol to query a Minecraft server.
Read about it here: http://wiki.vg/Query
*/
private function getStrings($fp, $count)
{
$nulsProcessed = 0;
while ($nulsProcessed < $count) {
while ($c != chr(0)) {
$s .= $c;
$c = fread($fp, 1);
}
$strings[] = $s;
$nulsProcessed++;
unset($c);
unset($s);
}
return $strings;
}
private function makeSessionId()
{
return rand(1, 0xFFFFFFFF) & 0x0F0F0F0F;
}
// Verify packet type and ensure it references our session ID.
private function validateQueryResponse($response, $responseType, $sessionId)
{
if (strpos($response, $responseType) !== 0 && (int)substr($response, 1, 4) === $sessionId) {
error_log('Received invalid response "' . bin2hex($response) . '". Returning.');
return false;
}
return true;
}
private function handleQueryHandshake($fp, $sessionId)
{
$handshakeRequest = pack('cccN', 0xFE, 0xFD, 9, $sessionId);
fwrite($fp, $handshakeRequest);
$handshakeResponse = fread($fp, 2048);
if (!$this->validateQueryResponse($handshakeResponse, 9, $sessionId)) {
return false;
}
$challengeToken = substr($handshakeResponse, 5, -1);
return $challengeToken;
}
private function basicQuery($hostname, $port=25565)
{
$sessionId = $this->makeSessionId();
$fp = stream_socket_client('udp://' . $hostname . ':' . $port);
if (!$fp) {
return false;
}
$time = microtime(true);
$challengeToken = $this->handleQueryHandshake($fp, $sessionId);
if (!$challengeToken) {
fclose($fp);
return false;
}
$time = round((microtime(true)-$time)*1000);
$statRequest = pack('cccNN', 0xFE, 0xFD, 0, $sessionId, $challengeToken);
fwrite($fp, $statRequest);
$statResponseHeader = fread($fp, 5);
if (!$this->validateQueryResponse($statResponseHeader, 0, $sessionId)) {
fclose($fp);
return false;
}
$statData = array_merge($this->getStrings($fp, 5), unpack('v', fread($fp, 2)), $this->getStrings($fp, 1));
fclose($fp);
return array(
'motd' => $statData[0],
'gametype' => $statData[1],
'map' => $statData[2],
'player_count' => $statData[3],
'player_max' => $statData[4],
'port' => (string)$statData[5],
'ip' => $statData[6],
'latency' => $time
);
}
private function fullQuery($hostname, $port=25565)
{
$sessionId = $this->makeSessionId();
$fp = stream_socket_client('udp://' . $hostname . ':' . $port);
if (!$fp) {
return false;
}
$time = microtime(true);
$challengeToken = $this->handleQueryHandshake($fp, $sessionId);
if (!$challengeToken) {
fclose($fp);
return false;
}
$time = round((microtime(true)-$time)*1000);
$statRequest = pack('cccNNN', 0xFE, 0xFD, 0, $sessionId, $challengeToken, 0);
fwrite($fp, $statRequest);
$statResponseHeader = fread($fp, 5);
if (!$this->validateQueryResponse($statResponseHeader, 0, $sessionId)) {
fclose($fp);
return false;
}
fread($fp, 11);
// Should only encounter double null thrice.
while ($doubleNulsEncountered < 3) {
$c = fread($fp, 1);
$statResponse .= $c;
if ($lastWasNul && $c === chr(0)) {
$doubleNulsEncountered++;
}
$lastWasNul = ($c === chr(0));
}
fclose($fp);
$statResponseData = explode(pack('cccccccccccc', 0x00, 0x00, 0x01, 0x70, 0x6C, 0x61,
0x79, 0x65, 0x72, 0x5F, 0x00, 0x00), $statResponse);
foreach (explode(chr(0), $statResponseData[0]) as $index => $item) {
if (!($index % 2)) {
switch ($item) {
case 'numplayers':
$key = 'player_count';
break;
case 'maxplayers':
$key = 'player_max';
break;
case 'hostname':
$key = 'motd';
break;
case 'hostip':
$key = 'ip';
break;
case 'hostport':
$key = 'port';
break;
default:
$key = $item;
break;
}
} else {
if ($key == 'port') {
$item = (string)$item;
}
$stats[$key] = $item;
}
}
$stats['latency'] = $time;
$players = explode(chr(0), $statResponseData[1]);
array_pop($players);
$stats['players'] = $players;
return $stats;
}
}
// ============================================================
if (!count(debug_backtrace())) {
$args = array_slice($argv, 1);
foreach ($args as $arg) {
$e = explode(':', $arg, 1);
$len = count($e);
if ($len > 2 || $len < 1) {
print('Invalid host '.$arg);
exit(1);
} elseif ($len == 1) {
$e[1] = 25565;
}
$m = new MinecraftStatus($e[0], $e[1]);
$reply = $m->ping();
$motd = preg_replace("/(\\x{00A7}.|\n)/u", '', $reply['motd']);
$message = $e[0].':'.$e[1].' '.$motd.' ';
$message .= $reply['player_count'].'/'.$reply['player_max']. ' ';
$message .= $reply['latency'].'ms'."\n";
print($message);
}
}
?>
</code></pre>
<h2>minecraft_users.php</h2>
<p>Stand-alone <a href="http://munin-monitoring.org/" rel="nofollow noreferrer">Munin</a> plugin.</p>
<pre><code>#!/usr/bin/env php
<?php
/*
===============
minecraft_users
===============
This is munin plugin to monitor the player count on a Minecraft server.
Install it like any other munin plugin:
# cp minecraft_users.php /usr/share/munin/plugins/minecraft_users
# chmod 755 /usr/share/munin/plugins/minecraft_users
# ln -s /usr/share/munin/plugins/minecraft_users /etc/munin/plugins/minecraft_users
Config:
[minecraft_users]
env.host aminecraftserver.org
env.port 25565
*/
error_reporting(E_ERROR | E_PARSE);
$host = getenv('host');
$host = $host ? $host : 'localhost';
$port = getenv('port');
$port = $port ? $port : '25565';
if ((count($argv) > 1) && ($argv[1] == 'config')) {
print("graph_title Connected players\n");
print("graph_vlabel players\n");
print("players.label Number of players\n");
print("max_players.label Max players\n");
print("graph_info Number of players connected to Minecraft\n");
print("graph_scale no\n");
print("graph_category minecraft\n");
exit();
}
/*
================
Server List Ping
================
An example of how to get a Minecraft server status's using a "Server List Ping" packet.
See details here: http://www.wiki.vg/Server_List_Ping
*/
function MC_packString($string)
{
return pack('n', strlen($string)) . mb_convert_encoding($string, 'UCS-2BE');
}
// This is needed since UCS-2 text rendered as UTF-8 contains unnecessary null bytes
// and could cause other components, especially string functions to blow up. Boom!
function MC_decodeUCS2BE($string)
{
return mb_convert_encoding($string, 'UTF-8', 'UCS-2BE');
}
function MC_serverListPing($hostname, $port=25565)
{
// 1. pack data to send
$request = pack('nc', 0xfe01, 0xfa) .
MC_packString('MC|PingHost') .
pack('nc', 7+2*strlen($hostname), 73) .
MC_packString($hostname) .
pack('N', 25565);
// 2. open communication socket and make transaction
$time = microtime(true);
$fp = stream_socket_client('tcp://' . $hostname . ':' . $port);
if (!$fp) {
return false;
}
fwrite($fp, $request);
$response = fread($fp, 2048);
fclose($fp);
$time = round((microtime(true)-$time)*1000);
// 3. unpack data and return
if (strpos($response, 0xFF) !== 0) {
return false;
}
$response = substr($response, 3);
$response = explode(pack('n', 0), $response);
return array(
'player_count' => MC_decodeUCS2BE($response[4]),
'player_max' => MC_decodeUCS2BE($response[5]),
'motd' => MC_decodeUCS2BE($response[3]),
'server_version' => MC_decodeUCS2BE($response[2]),
'protocol_version' => MC_decodeUCS2BE($response[1]),
'latency' => $time
);
}
// ============================================================
$reply = MC_serverListPing($host, $port);
print('players.value ' . $reply['player_count'] . "\n");
print('max_players.value ' . $reply['player_max'] . "\n");
?>
</code></pre>
<h2>stat.php</h2>
<p>Basic webpage to check Minecraft server status.</p>
<pre><code><?php
require_once './mcstat.php';
require_once './mcformat.php';
$hostname = NULL;
if (array_key_exists('server', $_GET)) {
$hostname = $_GET['server'];
}
if ($hostname) {
$m = new MinecraftStatus($hostname);
$status = $m->ping();
}
$hostname = htmlspecialchars($hostname);
echo '
<html>
<head>
<style>
.motd {
text-shadow: 1px 1px 1px #000000;
filter: dropshadow(color=#000000, offx=1, offy=1);
}
</style>';
echo '<title> Minecraft Server Status' . ($hostname ? ' :: ' . $hostname : '') . '</title>';
echo '</head>
<body>
<p>Query server status:</p>
<form name="MC" method="get" action="">
<input type="text" name="server" onClick="this.select();" value="'.($hostname ? $hostname : '').'">
<input type="submit">
</form>';
if ($hostname) {
echo '<h1>Status for ' . $hostname . '</h1>';
if ($status) {
echo '<table>
<tr><th>MOTD</th><th>Server version</th><th>Players</th><th>Ping</th></tr>';
echo '<tr><td class="motd">' . MC_parseMotdColors($status['motd']). '</td><td>' .
$status['server_version'] . '</td><td>' . $status['player_count'] .
'/' . $status['player_max'] . '</td><td>' . $status['latency'] . '</td></tr>';
echo '</table>';
} else {
echo '<p>Could not query server.</p>';
}
}
echo '</body>
</html>';
?>
</code></pre>
<h2>mcformat.php</h2>
<p>HTML formatter for <a href="http://wiki.vg/Chat#Control_Sequences" rel="nofollow noreferrer">Minecraft chat color escapes</a>.</p>
<pre><code><?php
// Multibyte str_split()
function MC_str_split( $string )
{
return preg_split('/(?<!^)(?!$)/u', $string );
}
// http://www.wiki.vg/Chat
function MC_parseMotdColors($motd)
{
$inColorSequence = false;
$openSpan = false;
$coloredMotd = '';
foreach (MC_str_split($motd) as $character) {
if ($inColorSequence) {
// find color and insert span
switch ($character) {
case '0':
$color = '#000000';
break;
case '1':
$color = '#0000aa';
break;
case '2':
$color = '#00aa00';
break;
case '3':
$color = '#00aaaa';
break;
case '4':
$color = '#aa0000';
break;
case '5':
$color = '#aa00aa';
break;
case '6':
$color = '#ffaa00';
break;
case '7':
$color = '#aaaaaa';
break;
case '8':
$color = '#555555';
break;
case '9':
$color = '#5555ff';
break;
case 'a':
$color = '#55ff55';
break;
case 'b':
$color = '#55ffff';
break;
case 'c':
$color = '#ff5555';
break;
case 'd':
$color = '#ff55ff';
break;
case 'e':
$color = '#ffff55';
break;
case 'f':
case 'r':
$color = '#ffffff';
break;
default:
$color = false;
break;
}
if ($color) {
if ($openSpan) {
$coloredMotd .= '</span>';
}
$coloredMotd .= '<span style="color:' . $color . ';">';
$openSpan = true;
}
$inColorSequence = false;
} elseif ($character== '§') {
$inColorSequence = true;
} else {
$coloredMotd .= $character;
}
}
if ($openSpan) {
$coloredMotd .= '</span>';
}
return $coloredMotd;
}
?>
</code></pre>
<h1>Information on Minecraft's Protocols</h1>
<p>If you want to learn more about getting information from <a href="https://minecraft.net" rel="nofollow noreferrer">Minecraft</a>, see this <a href="http://wiki.vg/Server_List_Ping" rel="nofollow noreferrer">article on Server List Ping</a> and <a href="http://wiki.vg/Query" rel="nofollow noreferrer">this on the Query protocol</a>.</p>
<p>If you're looking for a server to test my code with, try <a href="http://Uberminecraft.com" rel="nofollow noreferrer">Uberminecraft.com</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-03T11:32:05.537",
"Id": "174622",
"Score": "1",
"body": "Looks fairly concise, I would maybe `FILTER` your `GETs` though using PHP's `filter_input` function `$foo = filter_input(INPUT_GET, 'foo', FILTER_SANITIZE_SPECIAL_CHARS);`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-08T03:43:12.933",
"Id": "275127",
"Score": "0",
"body": "Hello. I'm using https://github.com/xPaw/PHP-Minecraft-Query solution\n\nI got some issue with response HostName:\n\n ?8?m-]?5?m--?2?l ?b?l+!6?c?l7/2,$ ?5?m--?8?m[-?c ?f?lKavBuy.Ru ?e?l1.8-1.10 ?b?l?e?lSurvival?b?l?b,?a?lMarry?b?l?b,?b?lSkyWars,?c?lClans?b?l?b,?f?lParkour\n\nHow to convert it into human view?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-09T04:29:26.770",
"Id": "275308",
"Score": "1",
"body": "@Adobe you're better off asking at https://github.com/xPaw/PHP-Minecraft-Query/issues"
}
] |
[
{
"body": "<h2>Foreword</h2>\n\n<p>Bearing in mind that this post was created more than 4 years ago, you likely have changed the code and learned more about PHP features - perhaps you don't even use/maintain this code anymore. I honestly have never played Minecraft, nor had any reason to monitor server statuses. But I wanted to give some feedback to this question.</p>\n\n<h2>Feedback</h2>\n\n<p>The code looks pretty sophisticated. I honestly haven't used <code>pack()</code> before. That is neat that the class <code>MinecraftStatus</code> can function as a stand-alone CLI tool.</p>\n\n<h2>Suggestions</h2>\n\n<h3>Utilize member variable instead of passing</h3>\n\n<p>The methods <code>MinecraftStatus::ping()</code> and <code>MinecraftStatus::query()</code> make calls to private methods like <code>serverListPing()</code>, <code>basicQuery()</code> and <code>fullQuery()</code>, which all appear to be private methods. Instead of passing the hostname and portnumber to those methods, the methods can utilize the member variables using <code>$this-></code>. That way, the member variables don't need to be passed around.</p>\n\n<h3>Mapping Character to colors</h3>\n\n<p>The <code>switch</code> statement in <code>MC_parseMotdColors()</code> could be replaced by a lookup in an array. </p>\n\n<pre><code>define('COLOR_MAPPING', [\n '0' => '000000',\n '1' => '0000aa',\n //2-9, a-e...\n 'f' => 'ffffff',\n 'r' => 'ffffff'\n]);\n</code></pre>\n\n<p>Then lookup the value of <code>$character</code> using <a href=\"http://array_key_exists\" rel=\"nofollow noreferrer\"><code>array_key_exists()</code></a>:</p>\n\n<pre><code>$color = false; //default value\nif (array_key_exists($character, COLOR_MAPPING)) {\n $color = '#' . COLOR_MAPPING[$character];\n}\n</code></pre>\n\n<p>The same is true for the <code>switch</code> statement within <code>MinecraftStatus::fullQuery()</code> - though instead of using <code>define()</code>, a class constant could be created using <code>const</code>:</p>\n\n<pre><code>const RESPONSE_ITEM_KEY_MAPPING = [\n 'numplayers' => 'player_count',\n 'maxplayers' => 'player_max',\n 'hostname' => 'motd',\n 'hostip' => 'ip',\n 'hostport' => 'port',\n];\n</code></pre>\n\n<p>and then that constant can be accessed using <code>self::RESPONSE_ITEM_KEY_MAPPING</code>.</p>\n\n<pre><code>$key = $item; //default value\nif (array_key_exists($item, self::RESPONSE_ITEM_KEY_MAPPING)) {\n $key = self::RESPONSE_ITEM_KEY_MAPPING[$item];\n}\n</code></pre>\n\n<h3>Alternatives to <code>fwrite()</code>, <code>fread()</code>, <code>fclose()</code></h3>\n\n<p>I am not sure if it would work but you could consider using <a href=\"http://php.net/curl\" rel=\"nofollow noreferrer\">cURL wrapper functions</a> or <a href=\"http://php.net/file_get_contents\" rel=\"nofollow noreferrer\"><code>file_get_contents</code></a> - that way the parsing of individual characters could possibly be eliminated.</p>\n\n<h3>Reading characters in <code>getStrings()</code></h3>\n\n<p>I haven't tested it but in theory the (outer) <code>while</code> loop could be simplified to a <code>for</code> loop:</p>\n\n<pre><code>for ($nulsProcessed = 0; $nulsProcessed < $count; $nulsProcessed++) {\n while ($c != chr(0)) {\n $s .= $c;\n $c = fread($fp, 1);\n }\n $strings[] = $s;\n unset($c);\n unset($s);\n})\n</code></pre>\n\n<p>And also the nested <code>while</code> could also be rewritten as a <code>for</code> loop:</p>\n\n<pre><code>while($c = fread($fp, 1); $c != char(0); $c = fread($fp, 1)) {\n $s .= $c;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-05-31T23:51:26.873",
"Id": "195614",
"ParentId": "42405",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-02-21T10:25:12.670",
"Id": "42405",
"Score": "7",
"Tags": [
"php",
"networking",
"minecraft"
],
"Title": "Minecraft query tools"
}
|
42405
|
<p>I came across this snippet and am wondering if I should return blank in this case.</p>
<p>Which is more practical to return: <code>blank</code> or <code>null</code>?</p>
<pre><code>public String getInfo() {
String result = "";
String uri = clientConfiguration.getUri();
String regex = "http://(.*)/consolidate";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(uri);
if (matcher.find()) {
result = matcher.group(1);
}
return result;
}
</code></pre>
<p><strong>Edit</strong>: Should I change it to:</p>
<pre><code> if(matcher.find()) {
return matcher.group(1);
}
return null;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T10:33:15.097",
"Id": "72946",
"Score": "7",
"body": "It is entirely dependent on the context (ie, callers); what is more, your regex is seriously flawed. Hint: use the `URI` class to parse URIs in general (and this includes URLs)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T10:42:25.350",
"Id": "72947",
"Score": "0",
"body": "The question is too generic in its current form to be answered as a code review; it may be appropriate for [Programmers SE](http://programmers.stackexchange.com/). Could you provide more information about what you are trying to accomplish, and what the code that will be calling this function will do with the result?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T10:45:24.653",
"Id": "72948",
"Score": "0",
"body": "Sorry my question is not so clear. Actually I would like to rewrite the last 4 lines as this:\nif(matcher.find()) {\n return matcher.group(1);\n}\nreturn null;\n\nThe thing I wonder is Should I?"
}
] |
[
{
"body": "<p>I agree with <code>fge</code>, it depends on the context. A third approach: it might be better to throw an exception in that case.</p>\n\n<p>Another note: you don't need to declare the <code>result</code> variable at the beginning of the method, declare on the first use. Actually, you could completely get rid of it:</p>\n\n<pre><code> if (matcher.find()) {\n return matcher.group(1);\n }\n return \"\";\n</code></pre>\n\n<p>(See also: <em>Effective Java, Second Edition</em>, <em>Item 45: Minimize the scope of local variables</em> It has a good overview on the topic.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T16:39:57.140",
"Id": "73010",
"Score": "0",
"body": "I would compress it even further, with `return matcher.find()? matcher.group(1):\"\";`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T11:10:41.347",
"Id": "42409",
"ParentId": "42406",
"Score": "1"
}
},
{
"body": "<p>The general question you ask <strong><em>\"Which is better, \"\" or null?\"</em></strong> is off-topic for CodeReview, but your code snippet has a number of reviewable items....</p>\n\n<h2>Regex Usage</h2>\n\n<p><strong>Compiled Pattern performance</strong></p>\n\n<pre><code> String regex = \"http://(.*)/consolidate\";\n Pattern pattern = Pattern.compile(regex);\n Matcher matcher = pattern.matcher(uri);\n if(matcher.find()){\n result = matcher.group(1);\n }\n</code></pre>\n\n<p>This snippet makes it look like you know what you are doing, with the <code>Pattern</code> compile, etc. But, there is no performance benefit in the way you have done this. Compiled Java <code>Pattern</code> instances are thread-safe, and compiling them for one-time-use is not useful. It is common practice to make the Pattern a static-final field:</p>\n\n<pre><code>private static final Pattern MYPATTERN = Pattern.compile(\"http://(.*)/consolidate\");\n</code></pre>\n\n<p>Then you can re-use that compiled pattern as much as you like, in any method, in any thread, like:</p>\n\n<pre><code> Matcher matcher = MYPATTERN.matcher(uri);\n if(matcher.find()){\n result = matcher.group(1);\n }\n</code></pre>\n\n<p><strong>find vs. matches</strong></p>\n\n<p>Now, <code>matcher.find()</code> and <code>matcher.matches()</code> are different methods.</p>\n\n<ul>\n<li><code>find()</code> will scan the input looking for any point inside the input where the pattern will match....</li>\n<li><code>matches()</code> does just one scan, and it matches the entire input string against the entire pattern.</li>\n</ul>\n\n<p>With the input <code>junkhttp://a/consolidate/junk</code>:</p>\n\n<ul>\n<li>find() will find your pattern</li>\n<li>matches() will not find your pattern</li>\n</ul>\n\n<p><strong>The pattern</strong></p>\n\n<p>Now, as for the actual Regex... it appears that you want your pattern to match the HTTP 'host' against which you have the 'consolidate' path.... but, your pattern will match a lot of things which I would consider to be unexpected... for example, your pattern will return the following:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>http://myhost/consolidate from http://http://myhost/consolidate/consolidate\nmyhost/consolidate from http://myhost/consolidate/consolidate\nmyhost:8080 from http://myhost:8080/consolidate\n from http:///consolidate\n</code></pre>\n\n<p>Each of the above input values will produce unexpected results.</p>\n\n<h2>Correct Regex</h2>\n\n<p>There is not a correct regex for matching URL's.... even if a regex appears that it will match, it is still not the correct solution ;-)</p>\n\n<h2>Solution</h2>\n\n<p>Use the <code>java.net.URI</code> class to validate your input. I have an example here, where I choose to return null if there is no configured URI, or throw an exception if there is a configured URI and that URI is not a valid value. This would be 'sensible' for many configurations, I expect.</p>\n\n<pre><code>public String getInfo() {\n String urival = clientConfiguration.getUri();\n if (urival == null || urival.isEmpty()) {\n return null;\n }\n try {\n URI uri = new URI(urival);\n return uri.getHost();\n } catch (URISyntaxException e) {\n throw new IllegalStateException(\"The configured URI is not valid: \" + e.getMessage(), e);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T13:51:34.203",
"Id": "72968",
"Score": "0",
"body": "\"There is not a correct regex for matching URL's...\" I'm sure there is one somewhere out there which gets very close, but it most likely looks similar to the [E-Mail address verification regular expression](http://ex-parrot.com/~pdw/Mail-RFC822-Address.html)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T15:21:53.490",
"Id": "72986",
"Score": "0",
"body": "@Bobby indeed, if the url language is regular then there will be a regex that accepts it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T15:35:34.780",
"Id": "72992",
"Score": "0",
"body": "Just to note: That doesn't mean that I think you *should* us regular expressions for that...you shouldn't...seriously..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T13:28:36.387",
"Id": "42415",
"ParentId": "42406",
"Score": "10"
}
},
{
"body": "<p>As \"getInfo\" does not hint at something functional or even crucial - only displaying the info, its usage should not fail with a NullPointerException or need to catch a thrown not-found exception. So neither return null here, nor throw an IllegalStateException, but return an empty string.</p>\n\n<p>Better however would be to return an informative string \"(Info missing)\".</p>\n\n<p>Should the result of <code>getInfo()</code> being used instead of only displayed, <strong>throw an exception</strong>. In this way the usage can be skipped. This already might be the case, if you embed the result is a surrounding text message. <em>A comparable strategy is done for the hideous NumberFormatException.</em></p>\n\n<p>Returning null, like in JDBC for field values, requires discipline by the user, and makes only sense in a context where more such \"optional\" data can be retrieved (= the null does not come unsuspected).</p>\n\n<p>For good order: In Java 8 there also is the class <code>Optional</code> to indicate the optional presence of an object, and getting the object in a next step. <em>(Overkill here)</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T14:48:13.923",
"Id": "42421",
"ParentId": "42406",
"Score": "1"
}
},
{
"body": "<p>If your question is whether you could refactor the code to return <code>null</code> instead of <code>\"\"</code>, without knowing more about your code, I would say <strong>no</strong>.</p>\n\n<p>Changing the return value from <code>\"\"</code> to <code>null</code> may break existing code calling your method, and expects it to always return a <code>string</code> value.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T15:08:50.500",
"Id": "42423",
"ParentId": "42406",
"Score": "0"
}
},
{
"body": "<p>Really, does every return value need to be assigned to a value? The code would be far clearer if you removed these spurious variables. <code>result</code> should be removed as well; just use two return statements. And for such a small piece of code, I would also suggest shortening <code>matcher</code>, both to avoid confusion with <code>Matcher</code>, and to allow further statements to be more concise.</p>\n\n<pre><code>/** \n * You need to add javadoc!\n * @return The info, or an empty string if there is no info.\n */\npublic String getInfo() {\n Matcher m = Pattern.compile(\"http://(.*)/consolidate\")\n .matcher(clientConfiguration.getUri());\n\n return m.find()?m.group(1):\"\";\n}\n</code></pre>\n\n<p>Some people insist one must use a full if statement, regardless of the occasion. In any case, don't use a result variable if returns will do, like this:</p>\n\n<pre><code>if(m.find()) return m.group(1);\nreturn \"\";\n</code></pre>\n\n<p>As for returning <code>\"\"</code> or <code>null</code>, as long as you <strong>document</strong> it in your javadoc (with an <code>@return</code>), either way is fine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T17:01:42.263",
"Id": "73014",
"Score": "0",
"body": "+1 overall, but 1-liner `if(m.find()) return m.group(1);` means you can't put a debug breakpoint on the `return`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T17:05:49.883",
"Id": "73017",
"Score": "0",
"body": "@rolfl although you can put a breakpoint on the whole thing, and then step through it from there, if needed, or just stick a line break in."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T16:36:53.817",
"Id": "42434",
"ParentId": "42406",
"Score": "1"
}
},
{
"body": "<p>It is always better to return null, in place of blank if you are not getting any info. Your method name goes to getInfo(). Returning blank means you get some information but it is blank. But returning null means you did not get any information at all.</p>\n\n<p>It is all upon you to decide what exactly you want to deduce from the returned value.</p>\n\n<pre><code>return null;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T13:48:37.443",
"Id": "42502",
"ParentId": "42406",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T10:28:07.527",
"Id": "42406",
"Score": "2",
"Tags": [
"java",
"null"
],
"Title": "Which Java string value is preferred to return: blank or null?"
}
|
42406
|
<p>Based on this <a href="https://stackoverflow.com/questions/11187582/javascript-sandbox-pattern-example-implementation">Stack Overflow</a> question I came up with the following code. I'd like your general thoughts about it. Code style, functional, logical, disadvantages, just anything you can come up based on the code that should be mentioned about it and springs into your eyes.</p>
<p>This is the sandbox:</p>
<pre><code>function Sandbox() {
// turning arguments into an array
var args = Array.prototype.slice.call(arguments),
// the last argument is the callback
callback = args.pop(),
// modules can be passed as an array or as individual parameters
modules = (args[0] && "string" === typeof args[0]) ? args : args[0], i;
// make sure the function is called
// as a constructor
if (!(this instanceof Sandbox)) {
return new Sandbox(modules, args[1], callback);
}
// if supported use old values
if (undefined != args[1] && "object" === typeof args[1]) {
this.loadedScripts = args[1].loadedScripts;
this.eventHandlers = args[1].eventHandlers;
}
// now add modules to the core 'this' object
// no modules or "*" both mean "use all modules"
if (!modules || '*' === modules) {
modules = [];
for (i in Sandbox.modules) {
if (Sandbox.modules.hasOwnProperty(i)) {
modules.push(i);
}
}
}
// always load internals
Sandbox.modules['internal'](this);
// initialize the required modules
for (i = 0; i < modules.length; i += 1) {
var module = modules[i];
// load modules if not present
if (typeof Sandbox.modules[module] == "undefined") {
$.ajax({
async : false,
dataType : "script",
cache : false,
url : 'js//modules/' + module + '.js'
});
}
Sandbox.modules[modules[i]](this);
}
// call the callback
callback(this);
// any prototype properties as needed
Sandbox.prototype = {
name : "Sandbox",
version : "1.1",
getName : function() {
return this.name;
}
};
};
// set space for modules to add to the sandbox
Sandbox.modules = {};
Sandbox.modules.internal = function(box) {
var box = box || {};
box.eventHandlers = box.eventHandlers || [];
box.loadedScripts = box.loadedScripts || [];
box.loadScript = function(options) {
var urls = options.urls || options.url || [];
urls = $.isArray(urls) ? urls : [ urls ];
$.each(urls, function(index, value) {
if (-1 == $.inArray(value, box.loadedScripts)) {
$.ajax({
async : false,
cache : false,
url : value,
success : function() {
box.loadedScripts.push(value);
}
});
}
});
};
box.removeOldEventHandlers = function(options) {
if (box.eventHandlers.length > 0) {
for (key in box.eventHandlers) {
if (box.eventHandlers.hasOwnProperty(key) && /^0$|^[1-9]\d*$/.test(key) && key <= 4294967294) {
box.eventHandlers[key].off(); // remove event handler
box.eventHandlers.splice(key, 1); // remove from array
}
}
}
};
};
</code></pre>
<p>Here a sample module ("comment.js"):</p>
<pre><code>Sandbox.modules.comment = function(box) {
var box = box || {};
box.loadScript({
url : "/js/template.js"
});
box.addComment = function(options) {
var templateURL = options.templateURL || 'templates/comment/comment.js.tpl', commentsContainer = options.commentsContainer, trigger = options.trigger, text = options.text, guid = options.guid, newComment = $('<article style="display:none;"><img src="images/ajax-loader.gif" alt="loading comment" /></article>');
newComment.prependTo(commentsContainer).show('fade', function() {
$.post(SERVICE_URL, {
o : 'comment',
f : 'add',
set : {
text : text,
id : id
}
}, function(response) {
if (-99 == response.header.code) {
newComment.setTemplateURL(templateURL).processTemplate(response.content).fadeIn();
} else {
box.buttonMessage({
message : response.header.userMessage,
button : trigger,
title : 'Error!'
});
}
}, 'json');
});
};
};
</code></pre>
<p>Here is the call to a modules function ("addComment.js"):</p>
<pre><code>var Sandbox = Sandbox([ 'comment', 'message' ], Sandbox, function(box) {
// add comment
var trigger = $('#button_addComment'), comments = $('#comments'), commentsContainer = $('#commentsContainer', comments), input = $('#text', comments);
box.eventHandlers.push(trigger);
box.addComment({
text : input.val(),
guid : comments.attr('data-guid'),
trigger : trigger,
commentsContainer : commentsContainer
});
});
</code></pre>
<p>And here the actual call to the code:</p>
<pre><code>var SERVICE_URL = 'service.php';
$(function() {
$('section#addComment').on('click', 'button.button', function(e) {
e.preventDefault();
var name= $(this).attr('id').split('_')[1];
//getCachedScript is just the $.ajax equivalent of $.getScript but with caching
// this would load "addComment.js"
$.getCachedScript( "js/app/" + name + ".js" ).fail(function() {
alert("This function is temporarily not available");
});
});
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T10:53:30.103",
"Id": "72950",
"Score": "0",
"body": "In `box.loadScript` you can reduce to `var urls = [].concat(options.url||options.urls||[])` and you save the line below."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T15:46:59.313",
"Id": "72997",
"Score": "0",
"body": "Thanks!\nWhat I do not like so far is in \"addComment.js\". As you can see there are two modules loaded `comment` and `message`. But `message` is actually needed in the module `comment` for the function `box.buttonMessage`. So actually that module should be loaded in the module `comment`!\nBut today I did not figure out how to do this.\nI guess I need to create a function for the code of loading modules in the Sandbox itself and make this function callable in a module to load (an)other module(s)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-09T09:46:47.640",
"Id": "119506",
"Score": "0",
"body": "[What you may and may not do after receiving answers](http://meta.codereview.stackexchange.com/a/1765). I've rolled back Rev 6 → 5."
}
] |
[
{
"body": "<p>From a reverse once over:</p>\n\n<ul>\n<li><code>$(this).attr('id')</code> -> could be <code>this.id</code></li>\n<li>The <code>click</code> handler should not have to know where the path is of the js file</li>\n<li>The <code>click</code> handler should not have to deal with the failure of loading the js file</li>\n<li>The <code>var</code> statement in <code>addComment.js</code> is crazy, new lines are good for you</li>\n<li>Same goes your <code>var</code> statement in <code>comment.js</code></li>\n<li>Using <code>o</code> and <code>f</code> as part of your API seems bad form, even for a Spartan coder like myself</li>\n<li><code>if (-99 == response.header.code)</code> <- Why ? </li>\n<li><code>key <= 4294967294</code> <- This should be a commented constant</li>\n<li>Using <code>for (key in box.eventHandlers)</code> is bad form when <code>box.eventHandlers</code> is an array, just use the good old <code>for</code> loop then you probably wont even have to check for <code>hasOwnProperty</code></li>\n</ul>\n\n<p>All in all, I am not sure what you are trying to achieve with this pattern. You can download JavaScripts in an <a href=\"https://stackoverflow.com/questions/1834077/which-browsers-support-script-async-async\">asynchronous</a> fashion now. This will provide a much better user experience than lazy loading.</p>\n\n<p>Edit:</p>\n\n<ul>\n<li>RE:Edge, opening a connection to the server to download less than 1kb of JavaScript will appear slower than just loading 1 extra kb of code ( I am assuming that you minify your code agressively ) upfront, especially on Edge. Loading it asynchronously means that the page will render before all the js is loaded and gives the impression of speed.</li>\n<li>Using booleans instead of -99 -> good idea</li>\n<li><a href=\"http://www.eclipse.org/forums/index.php/t/235159/\" rel=\"nofollow noreferrer\">Eclipse and var statements</a> -> Maybe change editor :P</li>\n<li><p>As for the click handler, it should call an intermediate function that</p>\n\n<ol>\n<li>Knows where the js files are (\"js/app/\")</li>\n<li>Deals with the failure of loading the script</li>\n</ol>\n\n<p>Otherwise every click handler has to know the path and has to deal with script loading failure.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T11:41:13.150",
"Id": "73863",
"Score": "0",
"body": "Thanks for your answer!\nActually I want to separate code and implement lazy loading to improve page speed. Why load all the magic™ if you never make a comment?\nI'm not sure how asynchronous loading would help in all cases. Imagine if you are on Edge on a mobile phone."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T11:41:40.417",
"Id": "73864",
"Score": "0",
"body": "For the click handler I think I either don't understand what you mean or I have no idea how to do it in another way.\n\nMy var statement is usually chained but to different lines, to this day I could not find out how to tell eclipse not to push it back into one line."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T11:44:15.193",
"Id": "73865",
"Score": "0",
"body": "`if(-99 == response.header.code)` is a bit historic. code is `-99` if everything is fine and a number bigger than zero if not (error codes). You are right maybe I should change it to `if(true == response.header.success)` and `elseif(true == response.header.failure)`? Something like that or do you have a better option?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T13:54:05.073",
"Id": "73886",
"Score": "0",
"body": "Update question."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T21:04:40.653",
"Id": "42699",
"ParentId": "42407",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T10:31:29.013",
"Id": "42407",
"Score": "6",
"Tags": [
"javascript",
"optimization",
"design-patterns",
"sandbox"
],
"Title": "JavaScript Sandbox Pattern"
}
|
42407
|
<p>LCA = <a href="http://en.wikipedia.org/wiki/Lowest_common_ancestor" rel="nofollow">Lowest Common Ancestor</a></p>
<p>The following code finds the lowest common ancestor in tree of nodes, where a node can have two parents, left and right.</p>
<p>The tree looks like this:</p>
<pre><code> J-K
/ \
E-F-G-H-I
</code></pre>
<p>And K and H input, the output is F</p>
<pre><code>public TreeSet<Node> find(Node node, TreeSet<Node> nodeSet) {
nodeSet.add(node);
if (node.getLeft() != null) {
find(node.getLeft(), nodeSet);
}
if (node.getRight() != null) {
find(node.getRight(), nodeSet);
}
return nodeSet;
}
</code></pre>
<p>which is called here:</p>
<pre><code>TreeSet<Node> nodeList1 = new TreeSet<Node>();
TreeSet<Node> nodeList2 = new TreeSet<Node>();
nodeList1 = find(node1, nodesList1); // node1 = K
nodeList2 = find(node2, nodesList2); // node2 = H
Iterator iterator = nodeList1.descendingIterator();
while (iterator.hasNext()){
Node node = (Node) iterator.next();
if(nodeList2.contains(node)){
return node.getValue();
}
}
</code></pre>
<p>and a <code>Node</code> looks like you'd expect and implements comparable.</p>
<p>Is my implementation O(n), I think it is, but can it be improved?</p>
<p>The relvant snippet of <code>Node</code>:</p>
<pre><code>class Node implements Comparable<Node> {
private String value;
private Node left;
private Node right;
@Override
public int hashCode() {
return this.getValue().hashCode();
}
@Override
public int compareTo(Node o) {
return this.getValue().compareTo(o.getValue());
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T12:36:31.830",
"Id": "72956",
"Score": "2",
"body": "You use the words *\"finds the lowest common ancestor in tree of nodes\"* but the picture you draw is not a tree, and nowhere in your code do you have a 'root'... your 'find' method just builds a set of **children**, not **ancestors**. Does your code work?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T12:43:48.347",
"Id": "72961",
"Score": "0",
"body": "@rolfl ok, what would you call the picture ? children/ancestors semantics ? Yes the code works."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T12:49:27.470",
"Id": "72963",
"Score": "1",
"body": "@NimChimpsky - A tree does not contain cycles... yet your picture shows a cycle. Since your node does not contain a 'parent' pointer, you cannot find the 'parent' of either of your nodes, so you cannot scan 'up' the tree. And, since you do not show us where you keep the 'root', there is no apparent way to find the 'ancestors' of either node. Which means your code will only work if `node1` is a child of `node2` (or `node2` is a child of `node1`)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T12:53:20.313",
"Id": "72964",
"Score": "0",
"body": "@rolfl left and right are parents, the root node is available... I just haven't used it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T12:59:34.100",
"Id": "72965",
"Score": "1",
"body": "This data structure is not a tree."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T13:11:23.003",
"Id": "72966",
"Score": "0",
"body": "@rolfl ok, not arguing with you ... any help very much appreciated."
}
] |
[
{
"body": "<p><strong>Naming</strong> - the method <code>find(Node, TreeSet<Node>)</code> implies it will find the <code>Node</code> inside the <code>TreeSet</code>, which, of course it doesn't - a better name might be <code>buildNodeParents</code> or something like that.</p>\n\n<p>Also, your <code>Node</code> has <code>getLeft()</code> and <code>getRight()</code>. In most implementations of a node tree, <code>left</code> and <code>right</code> implied the node's <em>children</em>. In your case, for clarity - I would have called those methods <code>getLeftParent()</code> and <code>getRightParent()</code>.</p>\n\n<p><strong>Algorithm</strong></p>\n\n<p>I assume your node implements <code>Comparable</code> (because you are using descendingIterator()) it would be useful if you've added that code, so complexity will be more easily calculated - how does it know if it is lower than another node? Maybe I've missed the correct definition for 'lowest' from your description? The sample tree you've shown is not very clear...</p>\n\n<p><strong>Complexity</strong></p>\n\n<p>Your algorithm's complexity is \\$O(n) * (O(i) + O(f))\\$ where <code>n</code> is the number of the nodes in your tree, <code>i</code> is the complexity of inserting a single value to the <code>TreeSet</code> (<code>add()</code>), and <code>f</code> is the complexity of finding a single value to the <code>TreeSet</code> (<code>contains()</code>). Assuming the <code>Node.compareTo</code> is of complexity \\$O(1)\\$, AFAIK <code>TreeSet</code> complexity is \\$O(log(n))\\$.</p>\n\n<p>This means that your algorithm's complexity is <em>at least</em> \\$O(n \\cdot log(n))\\$</p>\n\n<p>To achieve complexity of \\$O(n)\\$, I would choose a <code>HashSet</code> (which has complexity \\$O(1)\\$ for inserting and finding elements) over <code>TreeSet</code>. Then in the last part of the algorithm, instead of returning the <em>first</em> mutual ancestor, return the <em>lowest</em> mutual ancestor:</p>\n\n<pre><code>HashSet<Node> nodeList1 = new HashSet<Node>();\nHashSet<Node> nodeList2 = new HashSet<Node>();\nnodeList1 = find(node1, nodesList1); // node1 = K\nnodeList2 = find(node2, nodesList2); // node2 = H\nIterator iterator = nodeList1.iterator();\nNode minimalNode = null\nwhile (iterator.hasNext()){\n Node node = (Node) iterator.next();\n if(nodeList2.contains(node)){\n if (minimalNode == null || node.compareTo(minimalNode) < 0) {\n minimalNode = node;\n }\n }\n}\nreturn minimalNode;\n</code></pre>\n\n<p>This has, again the same complexity of \\$O(n) * (O(i) + O(f))\\$, but in this case \\$O(i)\\$ and \\$O(f)\\$ are \\$O(1)\\$ - so the total complexity is \\$O(n)\\$.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T12:34:34.793",
"Id": "72955",
"Score": "0",
"body": "Added a suggestion for O(n)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T12:39:48.233",
"Id": "72959",
"Score": "0",
"body": "@UriAgassi can you figure out how the ancestor of two nodes is somewhere in the intersection of the descendants of two nodes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T13:54:17.133",
"Id": "72969",
"Score": "1",
"body": "@NimChimpsky - no, because `LinkedList` has a find complexity of `O(n)` - this would make for a total complexity of `O(n^2)`. @rolfl - you can see that my second passage - my assumption was that `getLeft()` and `getRight()` are actually `getLeftParent()` and `getRightLeft()`..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T13:56:00.597",
"Id": "72970",
"Score": "0",
"body": "@UriAgassi oh yes of course. Thanks muchly."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T11:33:59.193",
"Id": "42410",
"ParentId": "42408",
"Score": "3"
}
},
{
"body": "<p>Just a minor note: you could add the <code>Node</code> type to the iterator which would make the casting unnecessary and would remove the compiler warning:</p>\n\n<pre><code>Iterator<Node> iterator = nodeList1.descendingIterator();\nwhile (iterator.hasNext()) {\n Node node = iterator.next();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T13:15:44.453",
"Id": "42414",
"ParentId": "42408",
"Score": "3"
}
},
{
"body": "<p>You seem to be have a few misconceptions, as @rolfl points out.</p>\n\n<p>First, the data structure you have described and illustrated does not fit the definition of a <a href=\"https://codereview.stackexchange.com/tags/tree/info\">tree</a>. Rather, I would characterize your data structure as a graph of maximum in-degree 2.</p>\n\n<p>Second, you seem to be under the impression that the <code>TreeSet</code> internally contains a tree that resembles part of your original graph. Actually, a <code>TreeSet</code> is nothing more than a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/SortedSet.html\" rel=\"nofollow noreferrer\"><code>SortedSet</code></a>; the fact that the <code>SortedSet</code> is implemented by using a tree internally is irrelevant to you. <code>nodeList1.descendingIterator()</code> does not produce an iterator that walks from root to leaf. Rather, it yields nodes reverse-sorted according to the value contained in the node.</p>\n\n<p>As a result, the code does not work.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T17:28:52.997",
"Id": "42441",
"ParentId": "42408",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "42410",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T10:41:15.963",
"Id": "42408",
"Score": "1",
"Tags": [
"java",
"optimization",
"algorithm",
"recursion",
"tree"
],
"Title": "Lowest common ancestor in recursive tree traversal"
}
|
42408
|
<p>A day ago I have asked a question on here about <a href="https://codereview.stackexchange.com/questions/42313/preventing-email-injection/42329?noredirect=1#42329">Preventing email injection</a>. I had some feedback and worked on it, and below is the latest update.</p>
<p>Could anyone please share their opinion? Is it secure enough? Is there a way to short-cut the code? </p>
<pre><code><?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
ob_start();
if(isset(
$_REQUEST['name'],
$_REQUEST['email'],
$_REQUEST['message'],
$_REQUEST['number'],
$_REQUEST['date'],
$_REQUEST['select'],
$_REQUEST['radio'],
$_REQUEST['checkbox'],
$_REQUEST['token']
)){
if($_SESSION['token'] != $_POST['token']){
$response = "0";
}else{
$_SESSION['token'] = "";
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
$number = $_REQUEST['number'];
$date = $_REQUEST['date'];
$select = $_REQUEST['select'];
$radio = $_REQUEST['radio'];
$checkbox = $_REQUEST['checkbox'];
$spam_pattern = "/[\r\n]|Content-Type:|Bcc:|Cc:/i";
switch (true){
case !filter_var($email, FILTER_VALIDATE_EMAIL):
$response = "<b style='color: red'>Invalid Email Address!</b>";
break;
case !preg_match($spam_pattern, $name):
case !preg_match($spam_pattern, $number):
case !preg_match($spam_pattern, $date):
case !preg_match($spam_pattern, $select):
case !preg_match($spam_pattern, $radio):
case !preg_match($spam_pattern, $checkbox):
case !preg_match($spam_pattern, $message):
$response = "<b style='color: red'>Invalid Request!</b>";
break;
default:
$to = "";
$subject = "New Message From: $name";
$message = "Name: $name<br/>
number: $number<br/>
date: $date<br/>
select: $select<br/>
radio: $radio<br/>
checkbox: $checkbox<br/>
Email: $email<br/>
Message: $message";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: '.$email . "\r\n";
if(mail($to, $subject, $message, $headers)){
$response = "<h2 style='color: green'>Success! Your submission has been sent.</h2>";
}else{
$response = "<h2 style='color: blue'>Error! There was a problem with sending.</h2>";
}
break;
}
}
}
else {
$response = "<b style='color: red'>Error</b>";
}
ob_flush();
}
?>
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>Due to the nested and long conditions the code becomes hard to follow\nat some points. Early returns prevent nesting of conditions.</li>\n<li>Some code is duplicate (step 9)</li>\n<li>Possibly some values could be overwritten by url-forging (depending on the server-configuration). (step 5)</li>\n</ul>\n\n<p>I'll do a step-by-step refactoring here with some explanations.</p>\n\n<ol>\n<li><p>Move everything in a function. This eases early-return. </p>\n\n<pre><code>function sendMail() {\n // your code here. \n}\n</code></pre></li>\n<li><p>While not necessary, it's I like to invert the conditions so the static expression stands on the left side. This avoids accidental assignment in conditions. Avoids tricky to detect bugs (though most IDEs and codesniffer emit a warning).</p></li>\n<li><p>Using the <code>===</code> operator for comparison avoids bugs to unforeseen casting</p>\n\n<pre><code>function sendMail() {\n if ('POST' !== $_SEVER['REQUEST_METHOD']) {\n return '';\n }\n\n if ($_SESSION['token'] !== $_POST['token']) {\n return '0';\n }\n // remaining code\n}\n</code></pre></li>\n<li><p>What's the purpose of your output-cachting? I can't see any outputs being made? Trying to catch any errors? Hiding them is a bad idea, catch and handle them. If simply removed them.</p></li>\n<li>You are using <code>$_REQUEST</code> instead of <code>$_POST</code>. Sure you do check if the request type. But this doesn't prevent anyone from submitting both, GET and POST values. And here lies a dangerous problem: If I send you a link to <code>form.php?message=something</code> this does get send to the server as well when you submit the form. Now GET and POST both having the key <code>name</code> collide. Depending on the <a href=\"http://www.php.net/manual/de/ini.core.php#ini.variables-order\" rel=\"nofollow\">variables_order</a> the GET value I set overwrites your message. If you use <code>$_POST</code> to access your variables instead this issue can be prevented. </li>\n<li><p>I have extracted a simple accessor function to check for existence of a $_POST variable and return else:</p>\n\n<pre><code>function getPostValue($key) {\n return isset($_POST[$key]) ? $_POST[$key] : null;\n}\n\nfunction sendMail() {\n if ('POST' !== $_SEVER['REQUEST_METHOD']) {\n return '';\n }\n\n if ($_SESSION['token'] !== $_POST['token']) {\n return '0';\n }\n\n $_SESSION['token'] = '';\n\n $name = getPostValue('name');\n $email = getPostValue('email');\n $message = getPostValue('message');\n $number = getPostValue('number');\n $date = getPostValue('date');\n $select = getPostValue('select');\n $radio = getPostValue('radio');\n $checkbox = getPostValue('checkbox');\n\n if (!isset($name, $email, $message, $number, $date, $select, $radio, $checkbox)) {\n $response = \"<b style='color: red'>Error</b>\";\n }\n}\n</code></pre></li>\n<li><p>All those input validations go with early return again (snippet only):</p>\n\n<pre><code> $spam_pattern = \"/[\\r\\n]|Content-Type:|Bcc:|Cc:/i\";\n if (!preg_match($spam_pattern, $name) \n || !preg_match($spam_pattern, $number)\n || !preg_match($spam_pattern, $date)\n || !preg_match($spam_pattern, $radio)\n || !preg_match($spam_pattern, $checkbox)\n || !preg_match($spam_pattern, $select)\n || !preg_match($spam_pattern, $message)) {\n return '<b style=\"color: red\">Invalid Request!</b>';\n }\n</code></pre></li>\n<li><p>The <code>$to</code> variables and others you use as parameters for <code>mail</code> are only used once. Furthermore the <code>$message</code> variable is overwritten, removing the original content. Variable reuse makes stuff hard to track though. I just do this all as arguments in the mail function (snippet):</p>\n\n<pre><code> $sendResult = mail(\n 'support@loaidesign.co.uk', \n 'New Message From: ' . $name, \n \"Name: <br/>\n number: $number<br/>\n date: $date<br/>\n select: $select<br/>\n radio: $radio<br/>\n checkbox: $checkbox<br/>\n Email: $email<br/>\n Message: $message\", \n \"MIME-Version: 1.0 r\\n Content-type: text/html; charset=utf-8 \\r\\n From: '.$email . '\\r\\n\"\n );\n</code></pre></li>\n<li><p>All those returns have their html-markup in common. We sure can extract this into a common helper:</p>\n\n<pre><code>function getResponse($message, $isError) {\n return '<b style=\"color: ' . ($isError ? 'red' : 'green') . '\">' . $message . '</b>';\n}\n</code></pre></li>\n<li><p>Final remarks & further points of improvement: </p>\n\n<ul>\n<li>Indention of three characters is unusual. Most times its two or four. </li>\n<li>This can of course be further refactored: Especially creating local variables from <code>$_POST</code> is a point of repetation. Maybe it could be handled as an array. That'd make mass-checking (<code>preg_match</code>) easier: just loop over all input variables.</li>\n<li>If desired, this could of course be moved into a dedicated mailer class</li>\n<li>The functions depend on the global state (<code>$_POST</code>). A next step would be to pass the required input variables as argument (maybe an array :)). This would make this function reusable as well.</li>\n<li>Returning formated strings limits reusability to HTML output. Throwing expections or error codes puts this into the responsibility of the caller, not the callee.</li>\n</ul></li>\n</ol>\n\n<p>My final result: </p>\n\n<pre><code>function getPostValue($key) {\n return isset($_POST[$key]) ? $_POST[$key] : null;\n}\n\nfunction getResponse($message, $isError) {\n return '<b style=\"color: ' . ($isError ? 'red' : 'green') . '\">' . $message . '</b>';\n}\n\nfunction sendMail() {\n if ('POST' !== $_SEVER['REQUEST_METHOD']) {\n return '';\n }\n\n if ($_SESSION['token'] !== $_POST['token']) {\n return '0';\n }\n\n $_SESSION['token'] = '';\n\n $name = getPostValue('name');\n $email = getPostValue('email');\n $message = getPostValue('message');\n $number = getPostValue('number');\n $date = getPostValue('date');\n $select = getPostValue('select');\n $radio = getPostValue('radio');\n $checkbox = getPostValue('checkbox');\n\n if (!isset($name, $email, $message, $number, $date, $select, $radio, $checkbox)) {\n $response = getResponse('Error', true);\n }\n\n if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {\n return getResponse('Invalid Email Address!', true);\n }\n\n $spam_pattern = \"/[\\r\\n]|Content-Type:|Bcc:|Cc:/i\";\n if (!preg_match($spam_pattern, $name) \n || !preg_match($spam_pattern, $number)\n || !preg_match($spam_pattern, $date)\n || !preg_match($spam_pattern, $radio)\n || !preg_match($spam_pattern, $checkbox)\n || !preg_match($spam_pattern, $select)\n || !preg_match($spam_pattern, $message)) {\n return getResponse('Invalid Request!', true);\n }\n\n $sendResult = mail(\n 'support@loaidesign.co.uk', \n 'New Message From: ' . $name, \n \"Name: <br/>\n number: $number<br/>\n date: $date<br/>\n select: $select<br/>\n radio: $radio<br/>\n checkbox: $checkbox<br/>\n Email: $email<br/>\n Message: $message\", \n \"MIME-Version: 1.0 r\\n Content-type: text/html; charset=utf-8 \\r\\n From: '.$email . '\\r\\n\"\n );\n\n if (true === $sendResult) {\n return getResponse('Success! Your submission has been sent.', false);\n } else {\n return getResponse('Error! There was a problem with sending.', true);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T20:48:43.293",
"Id": "42462",
"ParentId": "42411",
"Score": "4"
}
},
{
"body": "<p>Your <code>switch</code> block makes my head hurt. It involves a <code>true</code> constant, non-constant <code>case</code> expressions (something that is forbidden in many other languages), fall-through cases, and negated regular expression matches — each of which would have hurt code clarity, but the combination is really hard to understand.</p>\n\n<p>In the end, I distilled the code down to a simple test case to see what would happen.</p>\n\n<pre><code><?php\n$name = \"Ha ha\\r\\nCc: victim@example.com\";\n\n$spam_pattern = \"/[\\r\\n]|Content-Type:|Bcc:|Cc:/i\";\nswitch (true) {\n case !preg_match($spam_pattern, $name):\n $response = \"Invalid request\";\n break;\n\n default:\n $response = \"Sending mail to $name\";\n}\n\necho $response, \"\\n\";\n</code></pre>\n\n<p>Running that produces</p>\n\n<blockquote>\n<pre><code>Sending mail to Ha ha\nCc: victim@example.com\n</code></pre>\n</blockquote>\n\n<p>I think that that indicates that your exploit-mitigation measure doesn't work.</p>\n\n<p>Instead of restricting the inputs you accept, a better exploit countermeasure is to <a href=\"https://codereview.stackexchange.com/a/43091/9357\">escape your header values using <code>mb_encode_mimeheader()</code></a>. According to RFC 2047, you ought to be encoding your header values anyway. As it happens such encoding will also protect you against CR-LF header injections.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T08:44:32.077",
"Id": "47132",
"ParentId": "42411",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T11:45:35.020",
"Id": "42411",
"Score": "3",
"Tags": [
"php",
"security",
"email"
],
"Title": "Preventing email injection - Part 2"
}
|
42411
|
<p>The following code is intended to implement a <a href="https://www.nuget.org/packages/LinFu.DynamicProxy.OfficialRelease/">LinFu DynamicProxy interceptor</a> to lazy load given virtual properties from an Umbraco datastore.</p>
<p>My concerns:</p>
<ol>
<li>Thread safety, Have I covered all the bases, Am I storing variables correctly?</li>
<li>Duplication - Getting the child type, am I safe to store a variable via my Lazy to use later?</li>
<li>Efficiency, If I have everything else correct, am I being wasteful? </li>
</ol>
<p>The code:</p>
<pre><code>/// <summary>
/// The content interceptor for intercepting virtual content properties.
/// </summary>
internal class ContentInterceptor : IInvokeWrapper
{
/// <summary>
/// The reader writer lock slim.
/// </summary>
private static readonly ReaderWriterLockSlim ReaderWriterLockSlim
= new ReaderWriterLockSlim();
/// <summary>
/// The lazy content.
/// </summary>
private static readonly Lazy<IContent> LazyParent = new Lazy<IContent>(
() =>
{
IContent content = contentService.GetById(id);
IContent parent = content.Parent();
return parent;
});
/// <summary>
/// The lazy list content.
/// </summary>
private static readonly Lazy<IEnumerable<IContent>> LazyChildren =
new Lazy<IEnumerable<IContent>>(
() =>
{
IContent content = contentService.GetById(id);
Type childType = returnType.GetGenericArguments().Single();
AliasAttribute aliasAttribute = childType.FirstAttribute<AliasAttribute>();
string alias = Conventions
.GetPropertyTypeAlias(aliasAttribute, childType.Name);
IEnumerable<IContent> umbracoChildren = contentService
.GetChildrenByName(content.Id, alias);
return umbracoChildren;
});
/// <summary>
/// The id.
/// </summary>
private static int id;
/// <summary>
/// The return type.
/// </summary>
private static Type returnType;
/// <summary>
/// The content service.
/// </summary>
private static IContentService contentService;
/// <summary>
/// The target to intercept.
/// </summary>
private readonly object target;
/// <summary>
/// Initializes a new instance of the <see cref="ContentInterceptor"/> class.
/// </summary>
/// <param name="target">
/// The target to intercept.
/// </param>
/// <param name="id">
/// The id.
/// </param>
public ContentInterceptor(object target, int id)
{
ContentInterceptor.id = id;
this.target = target;
contentService = GlobalServices.Current.ContentService;
}
/// <summary>
/// The event that runs after invocation.
/// </summary>
/// <param name="info">
/// The information.
/// </param>
/// <param name="returnValue">
/// The return Value.
/// </param>
public void AfterInvoke(InvocationInfo info, object returnValue)
{
Debug.WriteLine("AfterInvoke() called");
}
/// <summary>
/// The event that runs before invocation.
/// </summary>
/// <param name="info">The information.</param>
public void BeforeInvoke(InvocationInfo info)
{
Debug.WriteLine("BeforeInvoke() called");
}
/// <summary>
/// Performs the proxy invocation.
/// </summary>
/// <param name="info">The <see cref="InvocationInfo"/>.</param>
/// <returns>The object to replace the original value.</returns>
public object DoInvoke(InvocationInfo info)
{
lock (ReaderWriterLockSlim)
{
returnType = info.TargetMethod.ReturnType;
// Skip by any ignored properties.
IgnoreAttribute ignoreAttribute = returnType
.FirstAttribute<IgnoreAttribute>();
if (ignoreAttribute != null)
{
// Call the original implementation.
return info.TargetMethod.Invoke(this.target, info.Arguments);
}
// Check whether we are looking for children or not.
if (returnType.IsCollectionType())
{
IEnumerable<IContent> children = LazyChildren.Value;
if (children != null)
{
// TODO: Would rather not be getting this twice.
Type childType = returnType.GetGenericArguments().Single();
MethodInfo getModelList = this.GetType()
.GetMethod("GetModelList")
.MakeGenericMethod(childType);
return getModelList.Invoke(this, new object[] { children });
}
}
else
{
IContent parent = LazyParent.Value;
MethodInfo getModel = this.GetType()
.GetMethod("GetModel")
.MakeGenericMethod(returnType);
return getModel.Invoke(this, new object[] { parent });
}
return null;
}
}
/// <summary>
/// Gets a lazily invoked converted list of type from the content service.
/// </summary>
/// <param name="content">
/// The list of children to convert from.
/// </param>
/// <typeparam name="T">
/// The type to convert to.
/// </typeparam>
/// <returns>
/// The <see cref="T:System.Lazy{List{T}}"/> representing the content.
/// </returns>
private T GetModel<T>(IContent content) where T : class
{
return content.ToType<T>();
}
/// <summary>
/// Gets a list of the given type from an <see cref="IEnumerable{IContent}"/>.
/// </summary>
/// <param name="collection">
/// The list of children to convert from.
/// </param>
/// <typeparam name="T">
/// The type to convert to.
/// </typeparam>
/// <returns>
/// The <see cref="T:System.Lazy{List{T}}"/> representing the content.
/// </returns>
// ReSharper disable once UnusedMember.Local
private List<T> GetModelList<T>(IEnumerable<IContent> collection) where T : class
{
List<T> typedCollection = new List<T>();
typedCollection.AddRange(collection.Select(this.GetModel<T>));
return typedCollection;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I'm not familiar with Umbraco, and I could not find any documentation on LinFu, I do, however, have some remarks on your code:</p>\n\n<p><strong>Comments</strong> - your code is more than 40% comments, and un-useful comments at that - a comment that tells me that <code>id</code> is <code>/// The id</code> is a waste of space and reduces readability of your code - I actually needed to copy your code locally and remove all the comments to read it.</p>\n\n<p><strong>Static vs. instance scopes</strong> - you chose to put some of the state in the instance, and some in the class, but you manage both from the class. This means that if you create two instances of your class, their state will be unexpected, as they will change each-other's state. If you this class is meant to be a Singleton, make it a Singleton.</p>\n\n<p><strong>Use locks properly</strong> - you chose to use <code>ReaderWriterLockSlim</code> as your lock object. That's OK, though I don't see why you would need a <a href=\"http://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock\" rel=\"noreferrer\">reader-writer lock</a>. </p>\n\n<p>The problem is that you misuse it - the way you use it is as if it was just a regular object. Again, a simple lock object is fine, but declaring it as a fancy lock type, you confuse the code reader to look for (and assume) its use.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T01:01:53.463",
"Id": "73352",
"Score": "1",
"body": "Thanks! I comment code heavily for documentation generation, I should have stripped it out for brevity. \n\nAs regards to the scoping, yeah, it's messed up. The class is an instance class but when you initialize a Lazy<T> the function is static so any non-instance properties can't be referenced. I didn't realise you could simply initialize it from the constructor. I have since moved everything to an instance scope.\n\nIn all honesty I saw the `ReaderWriterLockSlim` class used in a similar fashion within the source for entity framework. I'll use lock."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T19:33:27.457",
"Id": "42456",
"ParentId": "42413",
"Score": "7"
}
},
{
"body": "<pre><code>new Lazy<IContent>(\n() =>\n{\n IContent content = contentService.GetById(id);\n IContent parent = content.Parent();\n return parent;\n});\n</code></pre>\n\n<p>Sometimes, extracting subexpressions into locals and giving them a name can improve the readability of code. But other times, it just makes the code longer for no good reason. I think this is the latter case, so I would rewrite this as:</p>\n\n<pre><code>new Lazy<IContent>(() => contentService.GetById(id).Parent());\n</code></pre>\n\n<p>Also, why is <code>Parent()</code> a method? It sounds like it should be a property. If you want to keep it as a method, I think a better name would be something like <code>GetParent()</code>.</p>\n\n<hr>\n\n<pre><code>List<T> typedCollection = new List<T>();\ntypedCollection.AddRange(collection.Select(this.GetModel<T>));\n\nreturn typedCollection;\n</code></pre>\n\n<p>Again, unnecessarily verbose, this could be just:</p>\n\n<pre><code>return collection.Select(this.GetModel<T>).ToList();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T01:05:37.290",
"Id": "73354",
"Score": "0",
"body": "Thanks for the input! You're right on the code. I have an overly verbose style at times which can be a bad habit. Nice use of a method group in the last example :) I've updated my source to match.\n\nAlso you're right, `Parent()` is icky. It's not mine though, it come from the Umbraco codebase."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T03:32:01.653",
"Id": "73362",
"Score": "1",
"body": "“Nice use of a method group in the last example” I copied that directly from your code :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T11:22:23.043",
"Id": "73389",
"Score": "0",
"body": "I must code in a trance half the time! :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T22:55:17.633",
"Id": "42474",
"ParentId": "42413",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "42456",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T12:47:32.033",
"Id": "42413",
"Score": "5",
"Tags": [
"c#",
"thread-safety"
],
"Title": "Am I using Lazy initialization properly?"
}
|
42413
|
<p>I'm running into a problem with my code in a ASP.NET MVC application. Maybe it's not a problem and I'm just being paranoid, but it seems like a problem to me (might be because I've just read the book <em>Clean Code</em>).</p>
<p>I am using the repository-pattern with the unit of work-pattern to abstract the data access. In between my controllers and the repositories I have the service-layer which handles my business logic.</p>
<p>Now my problem is: whenever I have a bigger controller with more functionality it gets cluttered up with service declarations. Here is a little example of what one of my controllers might look like:</p>
<pre><code>public class ForumController
{
private readonly ForumAnswerService _answerService;
private readonly ForumThreadService _threadService;
private readonly ReputationService _repService;
private readonly IUnitOfWork _unitOfWork;
public ForumController()
{
_unitOfWork = new EFContextUnitOfWork(new MyContext());
_threadService = new ForumThreadService(new Repository<ForumThread>(_unitOfWork));
_answerService = new ForumAnswerService(new Repository<ForumAnswer>(_unitOfWork));
_repService = new ReputationService(new ReputationRepository(_unitOfWork));
}
/* more stuff which uses the services above.. */
protected override void Dispose(bool disposing)
{
if (_unitOfWork != null)
{
_unitOfWork.Dispose();
}
base.Dispose(disposing);
}
}
</code></pre>
<p>This does not seem so bad right now but I had controllers with even more services and with growing functionality I think the list of services might grow even bigger and it does not seem clean to me.</p>
<p>Here are some ideas I have to tackle the problem:</p>
<ol>
<li><p>Only initialize services when I actually need them (i.e. in the methods)</p>
<ul>
<li>that will reduce the number of class variables but I think it might clutter up the methods and make them big and ugly</li>
</ul></li>
<li><p>Combine multiple services </p>
<ul>
<li>maybe I just have too many small services and need to combine them, for example combine <code>ForumThreadService</code> and <code>ForumAnswerService</code> to a single <code>ForumService</code></li>
<li>I don't like that though because of SRP and stuff</li>
<li>that would just move the clutter to the services because I would have to pass multiple repositories to the service</li>
</ul></li>
<li><p>Is that maybe a case where a DI framework would come in handy? Never used one and I only did constructor injection so I don't know..</p></li>
<li><p>Nope, that's it. Only got those 3 ideas..</p></li>
</ol>
<p>I hope my problem is clear and you guys can point me into the right direction.</p>
|
[] |
[
{
"body": "<p>Yes, #3 is the one - this is exactly what Dependency Injection/Inversion of Control containers are meant for - removing the assembly part of the services from the main code.</p>\n\n<p>Using an external DI framework will also give you additional benefits, such as stubbing out services while unit testing, allow future extensions to services without changing your main code, etc.</p>\n\n<p>A good start to which framework to use you can find here: <a href=\"https://stackoverflow.com/questions/4581791/how-do-the-major-c-sharp-di-ioc-frameworks-compare\">How do the major C# DI/IoC frameworks compare?</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T23:03:05.643",
"Id": "73131",
"Score": "0",
"body": "I would also look at #2. It seems like a very good possibility that there is duplicated code in those services which should be combined anyways."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T05:22:38.457",
"Id": "73174",
"Score": "0",
"body": "@JeffVanzella, since we don't know what's in these services, we can't say anything about any duplication in them. Anyway, as the system grows the number of services will eventually grow as well, and you end up with the same problem"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T07:59:01.187",
"Id": "73178",
"Score": "0",
"body": "Thanks a lot. I looked into the DI frameworks yesterday and it looks like it's what I need."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T22:26:25.260",
"Id": "73325",
"Score": "0",
"body": "@UriAgassi I was just saying it was something to look at"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T15:28:01.270",
"Id": "42426",
"ParentId": "42419",
"Score": "4"
}
},
{
"body": "<p>There is a fourth option, namely dealing with the fact your Controller has \"occasional\" dependencies.</p>\n\n<p>I'd be willing to bet your actions look something like this:</p>\n\n<pre><code>public ActionResult AddAnswer()\n{\n _answerService.DoStuff(...);\n\n return View();\n}\n\npublic ActionResult MarkThreadAsRead()\n{\n _threadService.DoStuff(...);\n return View();\n}\n</code></pre>\n\n<p>This results in your controller being instantiated, all dependencies created and then only <strong>some</strong> used depending on the action.</p>\n\n<p>Now you can just switch to using a DI framework (If you only do one thing do that) however that doesn't address what I consider the underlying problem, which is the proliferation of dependencies due to the controller not having a clear responsibility.</p>\n\n<p>Only you can really give the solution since it's heavily tied into your domain problem.\nAt a guess from the code you've shown, it looks like you need a ThreadController and possibly AnswerController too. Then do something more than the default mvc route eg:</p>\n\n<pre><code>routes.MapRoute(name: \"Forum\",\n url: \"forum/{id}\",\n defaults: new { controller = \"Forum\", action = \"Index\", id = UrlParameter.Optional });\n\nroutes.MapRoute(name: \"Thread\",\n url: \"forum/{forumid}/thread/{id}\",\n defaults: new { controller = \"Thread\", action = \"Index\", id = 0 });\n</code></pre>\n\n<hr>\n\n<p>If you do decide just to switch to a DI framework then pick one that can handle injection of lazy Dependencies for you. eg:</p>\n\n<pre><code>public class FooController\n{\n public Foo(Lazy<SomeRepo> aRepo){ ... }\n}\n</code></pre>\n\n<p>The reason for that is when you're action doesn't require a unit of work connection (For example), then one isn't created and it's dependency on something expensive like a DB connection is not also created. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T13:08:52.757",
"Id": "42868",
"ParentId": "42419",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "42426",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T14:29:16.580",
"Id": "42419",
"Score": "2",
"Tags": [
"c#",
"design-patterns",
"dependency-injection",
"asp.net-mvc"
],
"Title": "How to declutter dependencies?"
}
|
42419
|
<p>I've been doing a lot of Project Euler lately and just wanted to make sure my implementation was as good as it could be. Does anyone have any suggestions to speed this up?</p>
<pre><code>def sieve(upperlimit):
# mark off all multiples of 2 so we can use 2*p as the step for the inner loop
l = [2] + [x if x % 2 != 0 else 0 for x in range(3, upperlimit + 1)]
for p in l:
if p ** 2 > upperlimit:
break
elif p:
for i in range(p * p, upperlimit + 1, 2 * p):
l[i - 2] = 0
# filter out non primes from the list, not really that important i could work with a list full of zeros as well
return [x for x in l if x]
</code></pre>
|
[] |
[
{
"body": "<p>You have correctly implemented the optimization <code>p ** 2 > upperlimit</code>, but, there is a more efficient way to do it...</p>\n\n<p><code>p ** 2 > upperlimit</code> calculates the square of <code>p</code> for every iteration through the loop. The product is not hugely expensive, but it is also totally unnecessary....</p>\n\n<p>You can calculate the square-root of the upperlimit just once, and then reuse that calculated value as a direct comparison for <code>p</code>. Consider:</p>\n\n<pre><code>rootlimit = math.sqrt(upperlimit)\nfor p in l:\n if p > rootlimit:\n break;\n ....\n</code></pre>\n\n<p>Additionally, it is a small thing, but if you have <code>break</code>, <code>continue</code>, or <code>return</code>, inside a conditional inside a loop, then there is no need to use <code>elif</code>... It is just a small thing, but your code could be:</p>\n\n<pre><code>rootlimit = math.sqrt(upperlimit)\nfor p in l:\n if p > rootlimit:\n break;\n if p:\n ....\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T15:13:44.767",
"Id": "42424",
"ParentId": "42420",
"Score": "7"
}
},
{
"body": "<p>Your first setting of all the even numbers to 0 is not very efficient, the whole point of sieving is to avoid those costly modulo operations. Try the following:</p>\n\n<pre><code>l = range(2, upperlimit+1) # use list(range(...)) in Python 3\nl[2::2] = [0] * ((len(l) - 3) // 2 + 1)\n</code></pre>\n\n<p>You can do a similar thing for the setting of zeros of the sieve for other prime numbers, but it gets complicated to figure out how many zeros to add on the right.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T16:27:56.750",
"Id": "73007",
"Score": "0",
"body": "Oh nice catch, yea that saved me a decent chunk of time when generating the list"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T17:22:02.067",
"Id": "73019",
"Score": "2",
"body": "Note that this fails in python3 (and the question is tagged python3)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T17:59:48.837",
"Id": "73040",
"Score": "0",
"body": "Yep, Python 3 requires wrapping the `range` in a `list` for it to work, added it as a comment above."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T16:05:10.523",
"Id": "42430",
"ParentId": "42420",
"Score": "10"
}
},
{
"body": "<pre><code>for p in l:\n if p ** 2 > upperlimit:\n break\n elif p:\n ...\n</code></pre>\n\n<p>In this loop <code>p</code> is often zero, while <code>p ** 2 > upperlimit</code> is always false until the <code>break</code>. That means you evaluate both conditions always. If you put <code>if p:</code> first, only one condition is evaluated whenever <code>p</code> is not prime.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T17:03:05.593",
"Id": "42438",
"ParentId": "42420",
"Score": "7"
}
},
{
"body": "<ol>\n<li><p>Here's my starting point for computing the performance improvement due to the various revisions below: how long does it take to sieve for the prime numbers below \\$ 10^8 \\$?</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> from timeit import timeit\n>>> test = lambda f: timeit(lambda:f(10**8), number=1)\n>>> t1 = test(sieve)\n</code></pre>\n\n<p>The exact number is going to depend on how fast your computer is, so I'm going to compute performance ratios, but for the record, here it is:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> t1\n78.9875438772142\n</code></pre></li>\n<li><p>Your initialization of the list <code>l</code> takes more than half the time, so let's try a cheaper approach. Let's also give this array a better name, and make it a Boolean array while we're about it.</p>\n\n<pre><code>def sieve2(n):\n \"\"\"Return a list of the primes below n.\"\"\"\n prime = [True] * n\n for p in range(3, n, 2):\n if p ** 2 > n:\n break\n if prime[p]:\n for i in range(p * p, n, 2 * p):\n prime[i] = False\n return [2] + [p for p in range(3, n, 2) if prime[p]]\n</code></pre>\n\n<p>When optimizing a function like this, it's always worth keeping the un-optimized version around to check the correctness of the optimized version:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> sieve(10**6) == sieve2(10**6)\nTrue\n</code></pre>\n\n<p>This already runs in less than a third of the time:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> test(sieve2) / t1\n0.30390444573149544\n</code></pre></li>\n<li><p>We could avoid the test for <code>p ** 2 > n</code> by computing a tighter limit for the loop. Note that I've used <code>n ** .5</code> here as this is slightly faster than <code>math.sqrt(n)</code>.</p>\n\n<pre><code>def sieve3(n):\n \"\"\"Return a list of the primes below n.\"\"\"\n prime = [False, False, True] + [True, False] * (n // 2)\n for p in range(3, int(n ** .5) + 1, 2):\n if prime[p]:\n for i in range(p * p, n, 2 * p):\n prime[i] = False\n return [p for p in range(2, n) if prime[p]]\n</code></pre>\n\n<p>This makes little difference to the overall runtime:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> test(sieve3) / t1\n0.2971086436068156\n</code></pre></li>\n<li><p>We can accumulate the result as we go, instead of in a separate iteration at the end. Note that I've cached <code>result.append</code> in a local variable to avoid looking it up each time round the loop.</p>\n\n<pre><code>def sieve4(n):\n \"\"\"Return a list of the primes below n.\"\"\"\n prime = [False, False, True] + [True, False] * (n // 2)\n result = [2]\n append = result.append\n sqrt_n = (int(n ** .5) + 1) | 1 # ensure it's odd\n for p in range(3, sqrt_n, 2):\n if prime[p]:\n append(p)\n for i in range(p * p, n, 2 * p):\n prime[i] = False\n for p in range(sqrt_n, n, 2):\n if prime[p]:\n append(p)\n return result\n</code></pre>\n\n<p>Again, this makes very little difference:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> test(sieve4) / t1\n0.286016401170129\n</code></pre></li>\n<li><p>We can use Python's slice assignment instead of a loop when setting the sieve entries to <code>False</code>. This looks wasteful since we create a large list and then throw it away, but this avoids an expensive <code>for</code> loop and the associated Python interpreter overhead.</p>\n\n<pre><code>def sieve5(n):\n \"\"\"Return a list of the primes below n.\"\"\"\n prime = [True] * n\n result = [2]\n append = result.append\n sqrt_n = (int(n ** .5) + 1) | 1 # ensure it's odd\n for p in range(3, sqrt_n, 2):\n if prime[p]:\n append(p)\n prime[p*p::2*p] = [False] * ((n - p*p - 1) // (2*p) + 1)\n for p in range(sqrt_n, n, 2):\n if prime[p]:\n append(p)\n return result\n</code></pre>\n\n<p>This gives a small but noticeable improvement:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> test(sieve5) / t1\n0.2617646381557855\n</code></pre></li>\n<li><p>For big improvements to the performance of numerical code, we can use <a href=\"http://www.numpy.org/\" rel=\"noreferrer\">NumPy</a>.</p>\n\n<pre><code>import numpy\n\ndef sieve6(n):\n \"\"\"Return an array of the primes below n.\"\"\"\n prime = numpy.ones(n, dtype=numpy.bool)\n prime[:2] = False\n prime[4::2] = False\n sqrt_n = int(n ** .5) + 1\n for p in range(3, sqrt_n, 2):\n if prime[p]:\n prime[p*p::2*p] = False\n return prime.nonzero()[0]\n</code></pre>\n\n<p>This is more than 6 times as fast as <code>sieve5</code>, and more than 25 times as fast as your original code:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> test(sieve6) / t1\n0.03726392181902129\n</code></pre></li>\n<li><p>We could avoid allocating space for the even numbers, improving memory locality:</p>\n\n<pre><code>def sieve7(n):\n \"\"\"Return an array of the primes below n.\"\"\"\n prime = numpy.ones(n // 2, dtype=numpy.bool)\n sqrt_n = int(n ** .5) + 1\n for p in range(3, sqrt_n, 2):\n if prime[p // 2]:\n prime[p*p // 2::p] = False\n result = 2 * prime.nonzero()[0] + 1\n result[0] = 2\n return result\n</code></pre>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> test(sieve7) / t1\n0.029220096670965198\n</code></pre></li>\n<li><p>And finally, an implementation that sieves separately for primes of the form \\$ 6i − 1 \\$ and \\$ 6i + 1 \\$, <a href=\"https://stackoverflow.com/a/3035188/68063\">due to Robert William Hanks</a>:</p>\n\n<pre><code>def sieve8(n):\n \"\"\"Return an array of the primes below n.\"\"\"\n prime = numpy.ones(n//3 + (n%6==2), dtype=numpy.bool)\n for i in range(3, int(n**.5) + 1, 3):\n if prime[i // 3]:\n p = (i + 1) | 1\n prime[ p*p//3 ::2*p] = False\n prime[p*(p-2*(i&1)+4)//3::2*p] = False\n result = (3 * prime.nonzero()[0] + 1) | 1\n result[0] = 3\n return numpy.r_[2,result]\n</code></pre>\n\n<p>This is about 40 times as fast as the original <code>sieve</code>:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> test(sieve8) / t1\n0.023447068662434022\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T00:14:47.520",
"Id": "73142",
"Score": "0",
"body": "7 can be generalized using wheel factorization, which gets you another large improvement. Filling the sieve in chunks that fit into L1 or L2 cache gets another factor 5 or more according to my experience"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T17:09:36.733",
"Id": "73202",
"Score": "0",
"body": "@NiklasB.: Sounds interesting! Can you post your code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T17:27:46.703",
"Id": "73204",
"Score": "0",
"body": "@GarethRees: I wrote an implementation of it for an online judge problem once: http://pastie.org/8758862 It computes π(10^9) in under a second on my machine, but bear with me, it's highly optimized and dead ugly... It also contains some other custom optimizations than the ones I mentioned if I remember correctly. Nice job on that numpy implementation, it's blazingly fast. I guess I overestimated the speedup you can get over that. Really cool"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T17:05:56.567",
"Id": "42439",
"ParentId": "42420",
"Score": "34"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T14:41:59.543",
"Id": "42420",
"Score": "28",
"Tags": [
"python",
"performance",
"primes",
"python-3.x",
"sieve-of-eratosthenes"
],
"Title": "Sieve of Eratosthenes - Python"
}
|
42420
|
<p>This is a bidirectional map implementation that stores the values as <em>pairs on the heap</em>, and uses pointer arithmetic for efficient lookup.</p>
<p><a href="http://codepad.org/a6ozZQxd" rel="nofollow">codepad link, may be easier to read</a></p>
<pre><code>#include <iostream>
#include <set>
#include <utility>
#include <cstddef>
#include <SSVUtils/SSVUtils.hpp>
namespace Internal
{
template<typename T> struct PtrComparator
{
inline bool operator()(const T* mA, const T* mB) const noexcept { return *mA < *mB; }
};
}
template<typename T1, typename T2> class SneakyBimap
{
public:
using BMPair = std::pair<T1, T2>;
using Storage = std::vector<ssvu::Uptr<BMPair>>;
template<typename T> using PtrSet = std::set<const T*, Internal::PtrComparator<T>>;
using iterator = typename Storage::iterator;
using const_iterator = typename Storage::const_iterator;
using reverse_iterator = typename Storage::reverse_iterator;
using const_reverse_iterator = typename Storage::const_reverse_iterator;
private:
Storage storage;
PtrSet<T1> set1;
PtrSet<T2> set2;
template<typename T> inline BMPair* getPairImpl(const T* mPtr) const noexcept
{
return const_cast<BMPair*>(reinterpret_cast<const BMPair*>(mPtr));
}
inline const char* getPairBasePtr(const T2* mItem) const noexcept
{
static_assert(std::is_standard_layout<BMPair>::value, "BMPair must have standard layout");
return reinterpret_cast<const char*>(mItem) - offsetof(BMPair, second);
}
inline BMPair* getPairPtr(const T1* mItem) const noexcept { return getPairImpl(mItem); }
inline BMPair* getPairPtr(const T2* mItem) const noexcept { return getPairImpl(getPairBasePtr(mItem)); }
inline T2& getImpl(const T1* mItem) noexcept { return getPairPtr(mItem)->second; }
inline T1& getImpl(const T2* mItem) noexcept { return getPairPtr(mItem)->first; }
inline const T2& getImpl(const T1* mItem) const noexcept { return getPairPtr(mItem)->second; }
inline const T1& getImpl(const T2* mItem) const noexcept { return getPairPtr(mItem)->first; }
public:
template<typename TA1, typename TA2> inline void emplace(TA1&& mArg1, TA2&& mArg2)
{
assert(!this->has(mArg1) && !this->has(mArg2));
auto pair(std::make_unique<std::pair<T1, T2>>(std::forward<TA1>(mArg1), std::forward<TA2>(mArg2)));
set1.emplace(&(pair->first));
set2.emplace(&(pair->second));
storage.emplace_back(std::move(pair));
}
inline void insert(const BMPair& mPair)
{
this->emplace(mPair.first, mPair.second);
}
template<typename T> inline void erase(const T& mKey)
{
assert(this->has(mKey));
const auto& pairPtr(getPairPtr(&mKey));
set1.erase(&(pairPtr->first));
set2.erase(&(pairPtr->second));
ssvu::eraseRemoveIf(storage, [&pairPtr](const ssvu::Uptr<std::pair<T1, T2>>& mI){ return mI.get() == pairPtr; });
assert(!this->has(mKey));
}
inline const T2& at(const T1& mKey) const noexcept
{
const auto& itr(set1.find(&mKey));
if(itr == std::end(set1)) throw std::out_of_range{"mKey was not found in set1"};
return getImpl(*itr);
}
inline const T1& at(const T2& mKey) const noexcept
{
const auto& itr(set2.find(&mKey));
if(itr == std::end(set2)) throw std::out_of_range{"mKey was not found in set2"};
return getImpl(*itr);
}
inline T2& operator[](const T1& mKey) noexcept { assert(this->has(mKey)); return getImpl(*set1.find(&mKey)); }
inline T1& operator[](const T2& mKey) noexcept { assert(this->has(mKey)); return getImpl(*set2.find(&mKey)); }
inline const T2& operator[](const T1& mKey) const noexcept { assert(this->has(mKey)); return getImpl(*set1.find(&mKey)); }
inline const T1& operator[](const T2& mKey) const noexcept { assert(this->has(mKey)); return getImpl(*set2.find(&mKey)); }
inline void clear() noexcept { storage.clear(); set1.clear(); set2.clear(); }
inline bool empty() const noexcept { return storage.empty(); }
inline auto size() const noexcept -> decltype(storage.size()) { return storage.size(); }
inline auto count(const T1& mKey) const noexcept -> decltype(set1.count(&mKey)) { return set1.count(&mKey); }
inline auto count(const T2& mKey) const noexcept -> decltype(set2.count(&mKey)) { return set2.count(&mKey); }
inline auto find(const T1& mKey) const noexcept -> decltype(set1.find(&mKey)) { return set1.find(&mKey); }
inline auto find(const T2& mKey) const noexcept -> decltype(set2.find(&mKey)) { return set2.find(&mKey); }
inline bool has(const T1& mKey) const noexcept { return this->find(mKey) != std::end(set1); }
inline bool has(const T2& mKey) const noexcept { return this->find(mKey) != std::end(set2); }
inline auto begin() noexcept -> decltype(storage.begin()) { return storage.begin(); }
inline auto end() noexcept -> decltype(storage.end()) { return storage.end(); }
inline auto begin() const noexcept -> decltype(storage.begin()) { return storage.begin(); }
inline auto end() const noexcept -> decltype(storage.end()) { return storage.end(); }
inline auto cbegin() const noexcept -> decltype(storage.cbegin()) { return storage.cbegin(); }
inline auto cend() const noexcept -> decltype(storage.cend()) { return storage.cend(); }
inline auto rbegin() noexcept -> decltype(storage.rbegin()) { return storage.rbegin(); }
inline auto rend() noexcept -> decltype(storage.rend()) { return storage.rend(); }
inline auto crbegin() const noexcept -> decltype(storage.crbegin()) { return storage.crbegin(); }
inline auto crend() const noexcept -> decltype(storage.crend()) { return storage.crend(); }
};
SSVU_TEST(SneakyBimapTests)
{
SneakyBimap<int, std::string> sb;
SSVUT_EXPECT(sb.empty());
SSVUT_EXPECT(!sb.has(10));
SSVUT_EXPECT(!sb.has("banana"));
SSVUT_EXPECT(sb.count(10) == 0);
SSVUT_EXPECT(sb.count("banana") == 0);
sb.emplace(10, "banana");
SSVUT_EXPECT(!sb.empty());
SSVUT_EXPECT(sb.size() == 1);
SSVUT_EXPECT(sb.has(10));
SSVUT_EXPECT(sb.has("banana"));
SSVUT_EXPECT(sb.count(10) == 1);
SSVUT_EXPECT(sb.count("banana") == 1);
SSVUT_EXPECT(sb.at(10) == "banana");
SSVUT_EXPECT(sb[10] == "banana");
SSVUT_EXPECT(sb.at("banana") == 10);
SSVUT_EXPECT(sb["banana"] == 10);
sb["banana"] = 25;
SSVUT_EXPECT(!sb.empty());
SSVUT_EXPECT(sb.size() == 1);
SSVUT_EXPECT(!sb.has(10));
SSVUT_EXPECT(sb.has(25));
SSVUT_EXPECT(sb.has("banana"));
SSVUT_EXPECT(sb.count(10) == 0);
SSVUT_EXPECT(sb.count(25) == 1);
SSVUT_EXPECT(sb.count("banana") == 1);
SSVUT_EXPECT(sb.at(25) == "banana");
SSVUT_EXPECT(sb[25] == "banana");
SSVUT_EXPECT(sb.at("banana") == 25);
SSVUT_EXPECT(sb["banana"] == 25);
sb["banana"] = 15;
sb[15] = "melon";
sb.emplace(10, "cucumber");
SSVUT_EXPECT(!sb.empty());
SSVUT_EXPECT(sb.size() == 2);
SSVUT_EXPECT(sb.has(10));
SSVUT_EXPECT(sb.has(15));
SSVUT_EXPECT(!sb.has(25));
SSVUT_EXPECT(sb.has("melon"));
SSVUT_EXPECT(sb.has("cucumber"));
SSVUT_EXPECT(!sb.has("banana"));
SSVUT_EXPECT(sb.count(10) == 1);
SSVUT_EXPECT(sb.count(15) == 1);
SSVUT_EXPECT(sb.count(25) == 0);
SSVUT_EXPECT(sb.count("melon") == 1);
SSVUT_EXPECT(sb.count("cucumber") == 1);
SSVUT_EXPECT(sb.count("banana") == 0);
SSVUT_EXPECT(sb.at(10) == "cucumber");
SSVUT_EXPECT(sb[10] == "cucumber");
SSVUT_EXPECT(sb.at("cucumber") == 10);
SSVUT_EXPECT(sb["cucumber"] == 10);
SSVUT_EXPECT(sb.at(15) == "melon");
SSVUT_EXPECT(sb[15] == "melon");
SSVUT_EXPECT(sb.at("melon") == 15);
SSVUT_EXPECT(sb["melon"] == 15);
sb.clear();
SSVUT_EXPECT(sb.empty());
SSVUT_EXPECT(sb.size() == 0);
SSVUT_EXPECT(!sb.has(10));
SSVUT_EXPECT(!sb.has(15));
SSVUT_EXPECT(!sb.has(25));
SSVUT_EXPECT(!sb.has("melon"));
SSVUT_EXPECT(!sb.has("cucumber"));
SSVUT_EXPECT(!sb.has("banana"));
}
SSVU_TEST_END();
int main()
{
SSVU_TEST_RUN_ALL();
return 0;
}
</code></pre>
<p>Notes:</p>
<ul>
<li><code>ssvu::eraseRemoveIf</code> performs the <em>erase-remove</em> idiom on a container, with a predicate.</li>
<li><code>ssvu::Uptr<T></code> is just an alias for <code>std::unique_ptr<T></code>.</li>
<li><code>SSVUT_EXPECT</code> is a test macro - the test fails unless the boolean expression inside returns <code>true</code>.</li>
<li>The <em>real values</em> (pairs) are stored in <code>storage</code>, a <code>std::vector</code> of <code>std::unique_ptr<std::pair<T1, T2>></code>. </li>
<li>By performing pointer arithmetic and <code>reinterpret_cast</code> / <code>const_cast</code> magic, is it possible to obtain the base address of the pair from the <code>first</code> or <code>second</code> member. This trick is used to access the members of the pairs from a pointer to their <code>first</code> or <code>second</code> member. Is there anything dangerous about this?</li>
<li>Is there a way to avoid using <code>std::unique_ptr</code>, and improving the performance?</li>
<li>If you want to compile the code yourself, <a href="https://github.com/SuperV1234/SSVUtils" rel="nofollow">SSVUtils is available here on my GitHub page</a>.</li>
</ul>
<hr>
<p>Tested on <em>g++ 4.8</em> and <em>clang++ SVN</em>, both with <code>-O3</code> and <code>-O0</code> options. All tests passed.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-26T21:39:12.590",
"Id": "370877",
"Score": "0",
"body": "Can you please separate the test and non-test code into different segments (with separate include's), for easier copy-and-paste? Also, do you have a version of this on GitHub?"
}
] |
[
{
"body": "<p>Here you assert that the type is standard layout (for use of <code>offsetof</code>)</p>\n\n<pre><code> inline const char* getPairBasePtr(const T2* mItem) const noexcept\n {\n static_assert(std::is_standard_layout<BMPair>::value, \"BMPair must have standard layout\");\n return reinterpret_cast<const char*>(mItem) - offsetof(BMPair, second); \n }\n</code></pre>\n\n<p>For symmetry and to make sure that the first element aligns to the beginning f the class you should probably do the same here.</p>\n\n<pre><code> template<typename T> inline BMPair* getPairImpl(const T* mPtr) const noexcept\n {\n return const_cast<BMPair*>(reinterpret_cast<const BMPair*>(mPtr));\n }\n</code></pre>\n\n<p>Don't need the new syntax here:</p>\n\n<pre><code>inline auto begin() noexcept -> decltype(storage.begin()) { return storage.begin(); }\n</code></pre>\n\n<p>The types of the iterators is well defined:</p>\n\n<pre><code>iterator begin() noexcept { return storage.begin(); }\n</code></pre>\n\n<p>Also don't specify <code>inline</code> unless you have too. Members declared inside the class are automatically inline so no need to add the keyword. PS. I assume you are not doing it to force inlining because the compiler will completely ignore you.</p>\n\n<p>If you insert the same value you don't reuse a slot in storage:</p>\n\n<pre><code> typename SneakyBimap<int,int>::BMPair data(1,2);\n SneakyBimap<int,int> store;\n store.insert(data);\n store.insert(data);\n store.insert(data);\n store.insert(data);\n store.insert(data);\n store.insert(data);\n store.insert(data);\n store.insert(data);\n store.insert(data);\n store.insert(data);\n store.insert(data); // lots of storage used.\n</code></pre>\n\n<p><s>Not sure I would templatize this method:</p>\n\n<pre><code>template<typename TA1, typename TA2>\ninline void emplace(TA1&& mArg1, TA2&& mArg2)\n</code></pre>\n\n<p>The first thing you do is create a <code>BMPair</code>. </p>\n\n<pre><code>auto pair(std::make_unique<std::pair<T1, T2>>(std::forward<TA1>(mArg1), std::forward<TA2>(mArg2)))\n</code></pre>\n\n<p>And though you are forwarding the arguments to the constructor they will still need to convert the parameters as the object is constructed <code>TA1 => T1</code> and <code>TA2 => T2</code> so I don't think you gain any flexibility.</s></p>\n\n<p>OK. Worked it out. By doing this you only have to convert the parameters once as you create the object. Rather than once at the call site (which happens if you don't templatize the parameters) followed by a copy during construction. Nice but ugly.</p>\n\n<p>I would not use a vector of unique ptr.</p>\n\n<pre><code>using Storage = std::vector<ssvu::Uptr<BMPair>>;\n</code></pre>\n\n<p>As a user any dynamically allocated memory should be managed be either a smart pointer or a container. Since you are writing the container it is worth looking at writing the memory management to go with it.</p>\n\n<pre><code>using Storage = std::vector<BMPair*>;\n\n// OK just tried to re-write \n// void emplace(TA1&& mArg1, TA2&& mArg2)\n// using only pointers.\n// \n// It is possible but definitely non trivial\n// to do in an exception safe manner as you have to insert data\n// into three different containers all of which could throw during\n// insertion.\n// \n// Worth having a look at **BUT** now I think I would stick with\n// std::unique_ptr until my container showed signs that it was\n// causing efficiency problems having a good bash at it. \n</code></pre>\n\n<p>Now that I thought about it. You emplace does not provide the strong exception guarantee.</p>\n\n<pre><code> auto pair(std::make_unique<std::pair<T1, T2>>(std::forward<TA1>(mArg1), std::forward<TA2>(mArg2)));\n\n // Assume this works.\n set1.emplace(&(pair->first));\n\n // Assume this fails.\n // And throws an exception.\n set2.emplace(&(pair->second));\n\n // This is never done.\n // So `pair` still holds the value.\n storage.emplace_back(std::move(pair));\n\n // As `pair goes out of scope it deletes the object.\n // This means that `set1` holds a pointer to an invalid\n // memory location.\n</code></pre>\n\n<p>So now that I see that the same problems exist for both <code>unique_ptr</code> and <code>pointer</code> versions. I would go back to my original position of not using <code>unique_ptr</code> here. But it is non trivial and you should think about it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T17:11:49.203",
"Id": "42440",
"ParentId": "42427",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "42440",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T15:37:02.497",
"Id": "42427",
"Score": "4",
"Tags": [
"c++",
"c++11",
"collections",
"pointers",
"hash-map"
],
"Title": "Bidirectional map based on memory manipulation"
}
|
42427
|
<p>I'd like to see how to improve this code. I have a UITableView that I'm 'hiding' a section when the user taps on that section's header. I thought this was a pretty cool implementation I came up with, but it turns out when this section is hidden and the user pulls to refresh, about 1-2MB is added into memory every time they pull to refresh. If the section isn't hidden and they pull to refresh, no extra memory is allocated (the correct way/behavior).</p>
<p>I may be overlooking something, and would appreciate any help offered. Sorry for the lengthy code below:</p>
<p>Update: added cellForRowAtIndexPath method below</p>
<pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
NSString *identifier = @"cellIdentifier";
UILabel *userNameLabel = [self userNameLabel];
UIView *requestsView = [self requestsView];
UIButton *approveButton = [self approveButton];
UIButton *denyButton = [self denyButton];
UIImageView *profileImageView = [self profileImageView];
if (cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
cell.selectionStyle = UITableViewCellSelectionStyleDefault;
[requestsView addSubview:approveButton];
[requestsView addSubview:denyButton];
[cell.contentView addSubview:requestsView];
[cell.contentView addSubview:profileImageView];
[cell.contentView addSubview:userNameLabel];
}
if (indexPath.section == 0)
{
cell.selectionStyle = UITableViewCellSelectionStyleNone;
userNameLabel.frame = CGRectMake(82, 0, 167, 68);
approveButton.tag = indexPath.row;
denyButton.tag = indexPath.row;
NSArray *keys = [self.tableDataSource objectForKey:@"Requests"];
id aKey = [keys objectAtIndex:indexPath.row];
userNameLabel.text = [aKey objectForKey:@"User"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[aKey objectForKey:@"URL"]]];
request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
request.timeoutInterval = 5.0;
if ([imageCache objectForKey:aKey])
{
profileImageView.image = [imageCache objectForKey:aKey];
}
else
{
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:
^(NSURLResponse *response, NSData *data, NSError *error)
{
if (data)
{
dispatch_async(dispatch_get_main_queue(), ^
{
profileImageView.image = [UIImage imageWithData:data];
[imageCache setObject:[UIImage imageWithData:data] forKey:aKey];
});
}
else
{
profileImageView.image = [self profileImage];
}
}];
}
}
else if (indexPath.section == 1)
{
requestsView.hidden = YES;
NSArray *keys = [self.tableDataSource objectForKey:@"Friends"];
id aKey = [keys objectAtIndex:indexPath.row];
userNameLabel.text = [aKey objectForKey:@"User"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[aKey objectForKey:@"URL"]]];
request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
request.timeoutInterval = 5.0;
if ([imageCache objectForKey:aKey])
{
profileImageView.image = [imageCache objectForKey:aKey];
}
else
{
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:
^(NSURLResponse *response, NSData *data, NSError *error)
{
if (data)
{
dispatch_async(dispatch_get_main_queue(), ^
{
profileImageView.image = [UIImage imageWithData:data];
[imageCache setObject:[UIImage imageWithData:data] forKey:aKey];
});
}
else
{
profileImageView.image = [self profileImage];
}
}];
}
}
else if (indexPath.section == 2)
{
requestsView.hidden = YES;
NSArray *keys = [self.tableDataSource objectForKey:@"Blocked"];
id aKey = [keys objectAtIndex:indexPath.row];
userNameLabel.text = [aKey objectForKey:@"User"];
}
return cell;
}
- (void)displayBlockedUsers
{
if (self.isShowingBlocked == YES)
{
self.isShowingBlocked = NO;
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationNone];
}
else
{
self.isShowingBlocked = YES;
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationNone];
}
}
- (NSInteger)friendRequests
{
return [[self.tableDataSource objectForKey:@"Requests"]count];
}
- (NSInteger)friends
{
return [[self.tableDataSource objectForKey:@"Friends"]count];
}
- (NSInteger)blockedUsers
{
return [[self.tableDataSource objectForKey:@"Blocked"]count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 2 && self.isShowingBlocked == NO)
{
return 0;
}
else
{
return 68;
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
if (section == 0)
{
if ([self friendRequests] < 1)
{
return 0;
}
else
{
return 22;
}
}
else if (section == 1)
{
if ([self friends] < 1)
{
return 0;
}
else
{
return 22;
}
}
else
{
if ([self blockedUsers] < 1)
{
return 0;
}
else
{
return 22;
}
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (section == 0)
{
if ([self friendRequests] < 1)
{
return 0;
}
else
{
return [self friendRequests];
}
}
else if (section == 1)
{
if ([self friends] < 1)
{
return 0;
}
else
{
return [self friends];
}
}
else
{
if ([self blockedUsers] < 1)
{
return 0;
}
else
{
return [self blockedUsers];
}
}
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerView = [[UIView alloc]init];
headerView.backgroundColor = [UIColor colorWithRed:248.0/255.0 green:248.0/255.0 blue:248.0/255.0 alpha:1.0];
UILabel *headerLabel = [[UILabel alloc]initWithFrame:CGRectMake(12, 0, 320, 22)];
headerLabel.font = [UIFont systemFontOfSize:13.5];
[headerView addSubview:headerLabel];
if (section == 0)
{
if ([self friendRequests] < 2)
{
headerLabel.text = [NSString stringWithFormat:@"%d Request",[self friendRequests]];
}
else
{
headerLabel.text = [NSString stringWithFormat:@"%d Requests",[self friendRequests]];
}
}
else if (section == 1)
{
if ([self friends] < 2)
{
headerLabel.text = [NSString stringWithFormat:@"%d Friend",[self friends]];
}
else
{
headerLabel.text = [NSString stringWithFormat:@"%d Friends",[self friends]];
}
}
else
{
UIButton *theButton = [UIButton buttonWithType:UIButtonTypeCustom];
[theButton addTarget:self action:@selector(displayBlockedUsers) forControlEvents:UIControlEventTouchUpInside];
theButton.frame = CGRectMake(0, 0, 320, 22);
[headerView addSubview:theButton];
if (self.isShowingBlocked == YES)
{
headerLabel.text = [NSString stringWithFormat:@"%d Blocked - Tap to Hide",[self blockedUsers]];
}
else
{
headerLabel.text = [NSString stringWithFormat:@"%d Blocked - Tap to Show",[self blockedUsers]];
}
}
return headerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 0;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 3;
}
</code></pre>
|
[] |
[
{
"body": "<p>The memory leak is more on topic for StackOverflow, but while this question is here and open, I'll make some comments on the stuff that's on topic...</p>\n\n<p>Your <code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section</code> method really, really bothers me.</p>\n\n<p>It can be replaced with this:</p>\n\n<pre><code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {\n switch(section) {\n case 0:\n return [self friendRequests];\n case 1:\n return [self friends];\n default:\n return [self blockedUsers];\n }\n}\n</code></pre>\n\n<p>These 3 methods will all return a value that is either 0 or evaluates false in <code>< 1</code>. So the only time <code>< 1</code> evaluates true (and you want to return 0) is when the method itself is returning 0 (these methods can't return a negative number).</p>\n\n<hr>\n\n<p>As for the memory issue, you'd need to include the <code>cellForRowAtIndexPath:</code> method.</p>\n\n<hr>\n\n<p>Your code's readability could also be greatly enhanced by adding the following enum:</p>\n\n<pre><code>typedef NS_OPTIONS(NSInteger FriendTableSections) {\n FriendRequests = 0,\n Friends = 1,\n BlockedUsers = 2\n};\n</code></pre>\n\n<p>And then referring to the sections by their name in this enum, rather than by simply \"0\", \"1\", \"2\" (or \"else\").</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T23:52:11.173",
"Id": "73139",
"Score": "0",
"body": "Wow, thank you for the valid help with the switch statement. My previous method that I was doing definitely is not as light weight as the one you kindly provided. Also I will provide the cellForRowAtIndexPath method in a few"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T23:54:20.570",
"Id": "73140",
"Score": "0",
"body": "Just added the code in original question above"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T23:46:50.910",
"Id": "42479",
"ParentId": "42429",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "42479",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T16:05:02.267",
"Id": "42429",
"Score": "2",
"Tags": [
"objective-c",
"ios"
],
"Title": "UITableView 'hidden' section causing more memory allocations every time on pull to refresh"
}
|
42429
|
<p>The primary goal of this code is to convert a PDF file to images. I also create a directory under <code>C:/Media</code> based on a combination of the PDF name and current date and insert the uploaded PDF to the same directory as the images for safe keeping. </p>
<p>I am primarily concerned that I am over-complicating the process by initializing too many variables and the process by which I move the PDF to the newly created directory. I am looking for guidance or advice on how to improve this code.</p>
<pre><code>public class PdfService {
public static void main(String[] args) {
System.out.println("Test of Convert to PNG");
convertPDFtoImage(args[0]);
}
public static void convertPDFtoImage(String PDFFileName) {
try {
// load PDF document
PDFDocument document = new PDFDocument();
File baseFile = new File(PDFFileName);
document.load(baseFile);
//Get todays date as a String so that you can append it to the directory
String df = new SimpleDateFormat("MM-dd-yy").format(new Date());
//Get the filename without extension so that you can create a directory based on the name
Path path = Paths.get(PDFFileName);
String filenameWithExtension = path.getFileName().toString();
String filename = FilenameUtils.removeExtension(filenameWithExtension);
//add the current date to the filename to get the directory name
String dirname = filename + "-" + df;
//Create the directory
Path dir = Paths.get("C:\\Media\\" + dirname);
Files.createDirectory(dir);
//Move the pdf to the newly created directory
movePDFToDirectory(baseFile, dirname, filenameWithExtension);
// create renderer
SimpleRenderer renderer = new SimpleRenderer();
// set resolution (in DPI)
renderer.setResolution(150);
// render
List<Image> images = renderer.render(document);
// write images to files to disk as JPEG
try {
System.out.println("Begin converting PDF...");
for (int i = 0; i < images.size(); i++) {
ImageIO.write((RenderedImage) images.get(i), "jpeg", new File("C:\\Media\\" + dirname + "\\" + filename + "_" + (i + 1) + ".jpeg"));
}
System.out.println("PDF converted to image(s) successfully.");
} catch (IOException e) {
System.out.println("ERROR: " + e.getMessage());
}
} catch (Exception e) {
System.out.println("ERROR: " + e.getMessage());
}
}
public static void movePDFToDirectory(File originalFile, String directory, String filename) {
InputStream inStream = null;
OutputStream outStream = null;
try{
File newFile = new File("C:\\Media\\" + directory + "\\" + filename);
inStream = new FileInputStream(originalFile);
outStream = new FileOutputStream(newFile);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
System.out.println("Original PDF has been copied successfully!");
}catch(IOException e){
e.printStackTrace();
}
}
}
</code></pre>
<p>Notes: </p>
<ul>
<li>Eventually I plan on moving this bit of code to a web application that accepts the image as an upload. As it stands I'm just passing the file location as an argument in the <code>main</code> method. </li>
<li>I plan on making the base directory (<code>C:/Media</code>) a dynamic variable in the event we move directories.</li>
</ul>
|
[] |
[
{
"body": "<p>I see that you're using Java 7, you could use the try-with-resource for all you're IO operation. It will close the stream you're using in your application. </p>\n\n<pre><code> try{\n File newFile = new File(\"C:\\\\Media\\\\\" + directory + \"\\\\\" + filename);\n\n inStream = new FileInputStream(originalFile);\n outStream = new FileOutputStream(newFile);\n\n byte[] buffer = new byte[1024];\n\n int length;\n //copy the file content in bytes \n while ((length = inStream.read(buffer)) > 0){\n\n outStream.write(buffer, 0, length);\n\n }\n\n inStream.close();\n outStream.close();\n\n System.out.println(\"Original PDF has been copied successfully!\");\n\n }catch(IOException e){\n e.printStackTrace();\n }\n</code></pre>\n\n<p>You're not closing your streams if there is an <code>IOException</code>. This could lead to some potential problem in a future application. To get ride of the problem you could use the try-with-resource syntax. Your code could look like : </p>\n\n<pre><code>File newFile = new File(\"C:\\\\Media\\\\\");\ntry ( InputStream inStream = new FileInputStream(newFile);\n OutputStream outStream = new FileOutputStream(newFile);) {\n\n byte[] buffer = new byte[1024];\n\n int length;\n // copy the file content in bytes\n while ((length = inStream.read(buffer)) > 0) {\n\n outStream.write(buffer, 0, length);\n\n }\n\n System.out.println(\"Original PDF has been copied successfully!\");\n\n} catch (IOException e) {\n e.printStackTrace();\n}\n</code></pre>\n\n<p>Argument name should not start with an uppercase letter : <code>public static void convertPDFtoPNG(String PDFFileName)</code>. Do you need to capitalize <code>pdf</code> ?</p>\n\n<p>I would revise some of you comments. Comments should be helpful, you don't need to repeat the code. Example : </p>\n\n<pre><code> // load PDF document\n PDFDocument document = new PDFDocument();\n File baseFile = new File(PDFFileName);\n document.load(baseFile);\n</code></pre>\n\n<p>Does <code>//load PDF document</code> is really needed ? You're already using <code>document.load</code>. One liner comment are most of time just repeating what you are doing in code. Other readers don't need to know what you are doing, but rather why are you doing it. I am always wondering myself when I am adding a comment : Does my code is clear enough by itself ? Do I really to add a comment or could I change the method name or variable to better express myself. Comments are hard to maintain when the code is changing.</p>\n\n<p>I know you're not in a production environment yet, but don't forget to change all the <code>e.printStackTrace</code> for a logging of some sort.</p>\n\n<p>It is worth to know that you can use <code>/</code> for all of you path, instead of escaping <code>\\</code>. Java will manage the one you need for the OS you're using.</p>\n\n<p>You're saying that your converting a PDF to an image, but it's not quite true. In fact, you are converting a PDF to a jpeg, which is quite different IMHO. You are hard coding the creation of the image as an jpeg, you will probably want to change in the future to support more formats. You will probably extract the writing code of the image into his own method or interface so that you have multiple implementation for each format (if needed, I am not good in image at all).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T17:26:36.927",
"Id": "73022",
"Score": "1",
"body": "Thank you, your suggestions were very helpful as I had no idea about the `try-with-resource` option in Java 7."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T21:03:49.730",
"Id": "73111",
"Score": "1",
"body": "Try-with-resources is good advice, but `File` is not `Closeable`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T21:55:16.447",
"Id": "73121",
"Score": "0",
"body": "@ntoskrnl Thanks, I've overlooked this while typing the answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T16:42:34.193",
"Id": "42436",
"ParentId": "42431",
"Score": "8"
}
},
{
"body": "<p>+1 <em>@Marc-Andre</em> and some other notes:</p>\n\n<ol>\n<li><p><code>movePDFToDirectory</code>: There is a similar method in Apache Commons IO: <a href=\"http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#copyFile%28java.io.File,%20java.io.File%29\" rel=\"nofollow\"><code>FileUtils.copyFile(java.io.File, java.io.File)</code></a>. Fortunately it's a dependency of Ghost4J, so it's on the classpath already, you just need to use it and delete <code>movePDFToDirectory</code>.</p>\n\n<p>Commons IO is open-source. It's interesting to see the corner cases which it handles, like comparing the <code>destFile.length()</code> and <code>srcFile.length()</code> to make sure that everything was copied properly.</p>\n\n<p><em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> (The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)</p></li>\n<li><p>If somebody calls the program without any argument it throws an <code>ArrayIndexOutOfBoundsException</code>. A proper error message with the expected parameters would be more user-friendly and professional.</p></li>\n<li><p>I'd move the <code>main</code> method to a separate class. (For example, <code>PdfConverterMain</code>.) It's usually a good idea to separate a class from its clients.</p></li>\n<li><p>The following line is really hard to follow:</p>\n\n<pre><code>ImageIO.write((RenderedImage) images.get(i), \"jpeg\", new File(\"C:\\\\Media\\\\\" + dirname + \"\\\\\" + filename + \"_\" + (i + 1) + \".jpeg\"));\n</code></pre>\n\n<p>A few explainatory local variable would make it more readable:</p>\n\n<pre><code>RenderedImage renderedImage = (RenderedImage) images.get(i);\nString formatName = \"jpeg\";\nString outputFilePath = \"C:\\\\Media\\\\\" + dirname + \"\\\\\"\n + filename + \"_\" + (i + 1) + \".jpeg\";\nFile outputFile = new File(outputFilePath);\nImageIO.write(renderedImage, formatName, outputFile);\n</code></pre>\n\n<p>If you use them readers see immediately what kind of arguments <code>ImageIO.write</code> has, they don't have to be familiar with it and they don't have to check the API to understand the intent of the developer.</p>\n\n<p>Reference: <em>Chapter 6. Composing Methods</em>, <em>Introduce Explaining Variable</em> in <em>Refactoring: Improving the Design of Existing Code</em> by Martin Fowler:</p>\n\n<blockquote>\n <p>Put the result of the expression, or parts of the expression, \n in a temporary variable with a name that explains the purpose.</p>\n</blockquote>\n\n<p>And <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>.</p></li>\n<li><p>Actually, I'd extract out the former snippet to a named method (maybe called <code>writePage</code>) whose name summarizes the intent of that block for better readability and easier maintenance. </p></li>\n<li><p>I agree with Marc-Andre, <code>PDF</code> in variable and method names should be camelCase, it's easier to read. There is a good paragraph about it in <em>Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions</em>: </p>\n\n<blockquote>\n <p>While uppercase may be more common, \n a strong argument can made in favor of capitalizing only the first \n letter: even if multiple acronyms occur back-to-back, you can still \n tell where one word starts and the next word ends. \n Which class name would you rather see, HTTPURL or HttpUrl?</p>\n</blockquote></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T01:38:40.590",
"Id": "73475",
"Score": "1",
"body": "Thank you for the advice, I have implemented your suggestions and my code is definitely cleaner. @Marc-Andre I have accepted this answer because the `FileUtils.copyFile` eliminates the need for my second method although `try-with-resource` was definitely great advice. I've upvoted both of your posts as well. Thank you again."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T17:52:13.933",
"Id": "42444",
"ParentId": "42431",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "42444",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T16:18:07.240",
"Id": "42431",
"Score": "6",
"Tags": [
"java",
"image",
"pdf"
],
"Title": "Ghost4J PDF to image conversion"
}
|
42431
|
<p>I was tasked at work to improve a system where through a web interface a client, which eventually became us, uploads a bunch of images with descriptions (latter coming from csv files), the images are then automatically resized yada yada for the site. </p>
<p>Nowt wrong with the latter, but the upload and image description data entry is unbelievably tedious - the latter having to be filled out by hand and the uploads done through http.</p>
<p>The usual way to do this would be for me to create a more sensible interface. However, since it's us that end up doing it and me being inexperienced at *nix sysadmin type stuff and wanting to gain some experience, I thought it would be more interesting to write a shell script to do it accessed by SSH, on the basis we can upload the CSVs and image files easily enough. Have also used sed, perl, and a line of php to help me encode data as it comes from the CSV.</p>
<p>With the exception of removing my company name from the logo, here is the unaltered code:</p>
<p>How could this shell script be improved?</p>
<pre><code>#! /bin/bash
# Yes, the below is ludicrous overkill.
# B
# U
# T
# I need to become good enough at shell scripting that I don't have to look up
# elementary syntax before I write anything that is not just a collection of
# commands.
# It was fun :)
function quitTheBestShellScriptInTheWorld {
tput setaf 0
tput sgr0
if [[ $tempFile != "" ]]; then
rm $tempFile
fi
exit
}
function randomColour {
tput setaf $[ RANDOM % 8]
if [[ $1 == "e" ]]; then
echo
fi
}
function everyLineADifferentColour {
while read eachLine
do
randomColour
echo $eachLine
done
}
trap quitTheBestShellScriptInTheWorld 0 1 2 3 15 #let's be tidy
clear
tput bold
randomColour
if [[ $1 == "-l" ]]; then
echo "Er, logging feature not actually programmed. Add it yourself? Will be reasonably straightforward [y/n]"
read -n 1 dolog
if [[ $dolog == "y" ]]; then
(nano coolscript.sh)
else
echo 'Wise choice, if you change your mind then run again and answer yes, or just edit this script (which is all that pressing y would have done)'
fi
exit 0
fi
echo '
.___
| | _____ _____ ____ ____
| |/ \\__ \ / ___\_/ __ \
| | Y Y \/ __ \_/ /_/ > ___/
|___|__|_| (____ /\___ / \___ >
\/ \//_____/ \/
__________ .__
\______ \ ____ _____|__|_______ ___________
| _// __ \ / ___/ \___ // __ \_ __ \
| | \ ___/ \___ \| |/ /\ ___/| | \/
|____|_ /\___ >____ >__/_____ \\___ >__|
\/ \/ \/ \/ \/
'
randomColour
echo Enter settings, or press enter for defaults:
randomColour e
echo Loading directory paths from Perl
success=failure
cd ../www/properties/lib/
uploadDataStore=$(perl -e 'use WIMSConfig; $z = WIMSConfig->new(); print $z->{uploadDataStore}')
if [[ $? == 0 ]] && [[ $uploadDataStore != "" ]]; then
currentDataStore=$(perl -e 'use WIMSConfig; $z = WIMSConfig->new(); print $z->{currentDataStore}')
if [[ $? == 0 ]] && [[ $currentDataStore != "" ]]; then
success=success
fi
fi
if [[ $success != "success" ]]; then
randomColour
echo "Failure: Problem setting directory paths from perl code"
exit 100
fi
tput setaf 4
randomColour e
echo fyi, I have uploadDataStore of $uploadDataStore and currentDataStore of $currentDataStore
echo
success=no
while [[ $success == "no" ]]; do
randomColour
echo 'Which directory from within uploadDataStore to get files from? (default = subfolder)'
randomColour
read theDirectory
if [[ $theDirectory == "" ]]; then
theDirectory=subfolder
fi
if [[ -e $uploadDataStore$theDirectory ]]; then
success=yes
else
randomColour
echo "Can't find a folder called $uploadDataStore$theDirectory"
echo
fi
done
declare -i NameCounter
declare -A fileNameToNumberMap
declare -A numberToFileNameMap
NameBuilder='Submit=Save+and+Process'
success=no
while [[ $success == "no" ]]; do
randomColour e
echo 'What is name of CSV file? (default = csvfile.csv)'
randomColour
read CSVFilename
if [[ $CSVFilename == "" ]]; then
CSVFilename=csvfile.csv
fi
CSVFilename=$uploadDataStore$theDirectory/$CSVFilename
if [[ -e $CSVFilename ]]; then
success=yes
else
randomColour
echo Counld not find file by name of $CSVFilename, try again
fi
done
tempfile=$(mktemp)
echo -n $NameBuilder > $tempfile
cat $CSVFilename | php -r 'while(($a = fgets(STDIN))!==false) echo str_replace("---___---","\n",str_replace("-_.-_.",",",urlencode(str_replace("\n","---___---",str_replace(",","-_.-_.",$a)))));' | awk -F "," '{prefix=sprintf("%d_",NR);printf("&%s_Name=%s&%sdataStore=%s&%sbranch=%s&%sdevelopmentName=%s&%saltDevelopmentName=%s&%slocation=%s&%scompletionYear=%s&%sdevelopmentType=%s&%sdevelopmentComprises=%s&%sstageOfCompletion=%s&%sshotType=%s&%sdetail%s&%simageType=%s&%scopyright=%s&%sphotoExists=%s&%soriginalFilename=%s",prefix,$1,prefix,$3,prefix,$4,prefix,$5,prefix,$6,prefix,$7,prefix,$8,prefix,$9,prefix,$10,prefix,$11,prefix,$12,prefix,$13,prefix,$14,prefix,$15,prefix,$16,prefix,$17)}' >> $tempfile
tempfileSize=$(stat -c%s $tempfile)
echo Starting Perl Script
randomColour e
cd ../
cat $tempfile | QUERY_STRING="Folder=$theDirectory&action=doProcessUploads" CONTENT_LENGTH=$tempfileSize perl -T index.cgi 2>&1 | sed -u -n '/NEW IMAGE/ {s/\(.*\)IMAGE\(.*\)/Perl looks like it is processing image\2/p}' | everyLineADifferentColour
cd ../../upload/
randomColour e
echo 'Hope you enjoyed the ****** Image Resizer Experience!'
tput setaf 0
tput sgr0
</code></pre>
|
[] |
[
{
"body": "<p>Your code is so full of irrelevant content that distracts from the purpose of the code.</p>\n\n<p>The most <em>Beautiful</em> shell scripts are the ones that do a job, and do it well. They do it in a standard way with the least surprise. They accept input from pipes, redirects, and files, and they output in a way that is redirectable, loggable, and readable.</p>\n\n<p>The following is my long-winded-way of reviewing the superfluous fluff that makes what could otherwise be a Beautiful script (there is more serious content after that...)</p>\n\n<hr>\n\n<h2>Meant to be in Jest stuff</h2>\n\n<p><strong>O</strong> *<em>V</em>* <strong>E</strong> *<em>R</em>* <strong>K</strong> *<em>I</em>* <strong>L</strong> *<em>L</em>*</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>_________ __ \n\\_ ___ \\ ____ _____ _____ ____ _____/ |_ ______ \n/ \\ \\/ / _ \\ / \\ / \\_/ __ \\ / \\ __\\/ ___/ \n\\ \\___( <_> ) Y Y \\ Y Y \\ ___/| | \\ | \\___ \\ \n \\______ /\\____/|__|_| /__|_| /\\___ >___| /__| /____ > \n \\/ \\/ \\/ \\/ \\/ \\/ \n .__ .__ .___ ___. \n _____| |__ ____ __ __| | __| _/ \\_ |__ ____ \n / ___/ | \\ / _ \\| | \\ | / __ | | __ \\_/ __ \\ \n \\___ \\| Y ( <_> ) | / |__/ /_/ | | \\_\\ \\ ___/ \n/____ >___| /\\____/|____/|____/\\____ | |___ /\\___ > \n \\/ \\/ \\/ \\/ \\/ \n .___ ___. .__ .___\n_______ ____ _____ __| _/____ \\_ |__ | | ____ _____ ____ __| _/\n\\_ __ \\_/ __ \\\\__ \\ / __ |\\__ \\ | __ \\| | _/ __ \\ \\__ \\ / \\ / __ | \n | | \\/\\ ___/ / __ \\_/ /_/ | / __ \\| \\_\\ \\ |_\\ ___/ / __ \\| | \\/ /_/ | \n |__| \\___ >____ /\\____ |(____ /___ /____/\\___ > (____ /___| /\\____ | \n \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \n _____ .__ ._._._. \n __ __ ______ _____/ ____\\_ __| || | | | \n| | \\/ ___// __ \\ __\\ | \\ || | | | \n| | /\\___ \\\\ ___/| | | | / |_\\|\\|\\| \n|____//____ >\\___ >__| |____/|____/_____ \n \\/ \\/ \\/\\/\\/ \n</code></pre>\n\n<p>Gimmicks are fun, but, they get tiring fast.</p>\n\n<p>And, they break the 'spirit' of UNIX scripting, which is that they can do things for you in as many situations as possible.</p>\n\n<pre><code>so, what if you wanted to use this in a pipe?\n</code></pre>\n\n<blockquote>\n <p>what if you are running this from a screen terminal?</p>\n</blockquote>\n\n<p>What if you are using a small mobile device to access things?</p>\n\n<p>What if the clutter simply overwhelms the rest of it, and the point of your program is lost.</p>\n\n<p><em>That is what has happened here</em></p>\n\n<ul>\n<li>B</li>\n<li>U</li>\n<li>T</li>\n</ul>\n\n<p>Somewhere 1n th3r3 1s A re4l pr0gr4m, although... I was convinced at:</p>\n\n<pre><code>quitTheBestShellScriptInTheWorld.\n</code></pre>\n\n<p>Who am I to be critical?</p>\n\n<p>At least you spelled colour <em>correctly</em> ;-)</p>\n\n<hr>\n\n<h2>Serious stuff</h2>\n\n<p>If you cut through the crap, you have an incomplete script... Lets go through some things..</p>\n\n<p><strong>Traps</strong></p>\n\n<p>This is your trap:</p>\n\n<blockquote>\n<pre><code>function quitTheBestShellScriptInTheWorld {\n tput setaf 0\n tput sgr0\n if [[ $tempFile != \"\" ]]; then\n rm $tempFile\n fi\n exit\n}\n</code></pre>\n</blockquote>\n\n<p>And you enable 20 lines later with:</p>\n\n<blockquote>\n<pre><code>trap quitTheBestShellScriptInTheWorld 0 1 2 3 15 #let's be tidy\n</code></pre>\n</blockquote>\n\n<p>Apart from the humble function name, the system suffers because:</p>\n\n<ul>\n<li>you should set the trap in the same code-location as the method so that it is obvious they belong together</li>\n<li>there is no need for the <code>exit</code> inside the trap</li>\n<li>It is more readable to use the signal numbers instead of the names</li>\n<li>you only need to trap EXIT (which will be invoked whenever the shell exits (successful or not)</li>\n<li>you should set a the tempFile variable so it has a clear value before the trap is set.</li>\n</ul>\n\n<p>It should look like:</p>\n\n<pre><code># Setting up the exit Clean-Up trap.\n\ntempfile=\"\"\n\nfunction exiting {\n if [[ -f $tempFile ]]; then\n rm $tempFile\n fi\n}\n\ntrap exiting EXIT\n</code></pre>\n\n<p><strong>Error Handling</strong></p>\n\n<p>You have none.... and, it's really easy... do:</p>\n\n<pre><code>set -e\n</code></pre>\n\n<p>near the top of your script.</p>\n\n<p>If any command fails then your program will terminate (with a non-zero exit code).</p>\n\n<p>If you have commands that you expect to fail, you can test them with <code>if</code> statements, or put conditionals after them so that the status is handled....</p>\n\n<blockquote>\n<pre><code> set -e Exit immediately if a pipeline (which may consist of a\n single simple command), a subshell command enclosed in\n parentheses, or one of the commands executed as part of\n a command list enclosed by braces (see SHELL GRAMMAR\n above) exits with a non-zero status. The shell does not\n exit if the command that fails is part of the command\n list immediately following a while or until keyword,\n part of the test following the if or elif reserved\n words, part of any command executed in a && or || list\n except the command following the final && or ||, any\n command in a pipeline but the last, or if the command's\n return value is being inverted with !. A trap on ERR,\n if set, is executed before the shell exits. This option\n applies to the shell environment and each subshell enviâ\n ronment separately (see COMMAND EXECUTION ENVIRONMENT\n above), and may cause subshells to exit before executing\n all the commands in the subshell.\n</code></pre>\n</blockquote>\n\n<p><strong>Terminal Funkiness</strong></p>\n\n<p>You <code>clear</code> the terminal.... and you play with terminal colour and boldness, etc.</p>\n\n<p>What if you are on a simple terminal that does not support these features? Your program will either fail, or will look really ugly.</p>\n\n<p>A user operating in a terminal is looking for efficiency and usability. The trates you have added are not efficient, and ruin the usability experience the user wants... (otherwise they would be in a GUI...)</p>\n\n<p>Printing out a huge banner is also not useful... what if the user has a small screen... it's ugly,</p>\n\n<blockquote>\n<pre><code>randomColour\necho Enter settings, or press enter for defaults:\nrandomColour e\n</code></pre>\n</blockquote>\n\n<p>The above implies that you are expecting user input, but then you don't... odd.</p>\n\n<p><strong>Directory Requirements</strong></p>\n\n<p>You expect your user to be inside a specific directory, and this is not 'friendly'. It means a user cannot add the program to their <code>$PATH</code> and expect it to work:</p>\n\n<pre><code>cd ../www/properties/lib/\n</code></pre>\n\n<p>You can solve this problem by putting the script itself in a know directory, and then getting the actual directory name from there, and then using relative directories:</p>\n\n<pre><code>SCRIPT_PATH=$(cd `dirname \"${BASH_SOURCE[0]}\"` && pwd)\n</code></pre>\n\n<p>Then you can use that variable like:</p>\n\n<pre><code>cd $SCRIPT_PATH/../www/properties/lib/\n</code></pre>\n\n<p>although, that is not ideal, you should not need to be changing directories in the main part of the script.</p>\n\n<p><strong>User Input</strong></p>\n\n<p>You get a directory from the user.... inside a loop:</p>\n\n<pre><code>while [[ $success == \"no\" ]]; do\n</code></pre>\n\n<p>But, your indentation seems to die inside that loop. Makes it hard to read.</p>\n\n<p>Also, you should have a mechanism for the stript to take the argument from the commandline, and only prompt for input if there was no commandline argument...</p>\n\n<pre><code># check first argument. \ntheDirectory=$1 \nif [[ -d $theDirectory ]] ; then\n success=yes\nfi\n</code></pre>\n\n<p>Same thing for the CSVFile.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T22:41:38.710",
"Id": "73124",
"Score": "0",
"body": "`s/quitTheBestSheelScriptInTheWorld/quitTheBestShellScriptInTheWorld/`, or did I miss some joke? The question spelled `Shell` correctly ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T22:41:47.610",
"Id": "73125",
"Score": "2",
"body": "Although it can be helpful to point out flaws, it can be even more helpful to suggest changes for making things better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T11:54:29.693",
"Id": "73183",
"Score": "1",
"body": "After the edit this looks more like the monkey we all know and love! +1."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T22:34:19.590",
"Id": "42471",
"ParentId": "42432",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "42471",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T16:24:54.923",
"Id": "42432",
"Score": "9",
"Tags": [
"php",
"bash",
"linux",
"console",
"awk"
],
"Title": "Bash script - automate an upload image + description process on a server"
}
|
42432
|
<p>I would really appreciate some good advice on how to refactor a small app:</p>
<p>It basically reads a CSV (energy/heat values?), computes some stuff, and then prepares some data which should later be sent to GNUplot.</p>
<p>For example, I'm unsure about this:</p>
<p><strong>Is it good practice to send variables into a function as pointers and manipulate them within the function body?</strong> Being more familiar with OOP (specifically Ruby), I'm used to being very careful with such things and try to change variables only by sending them to some method and assigning the method's return value to the variable again, e.g. <code>x = sum(x, y)</code> (or with <code>!</code> methods).</p>
<p>I'm sure there is a lot more to optimize in the code. I would be thankful for some basic hints on how to optimize the code. It doesn't have to be perfect, but it's quite a mess at the moment, and before refactoring it into the "wrong" direction, it would be nice to get some feedback here.</p>
<pre><code>/*
============================================================================
Name : Energie.c
Author : Benjamin Pfammatter
Version : 0.1
Copyright : Your copyright notice
Description : Energy in C, Ansi-style
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include "Datenstruktur.h"
//#include "logger.h"
int main(void) {
item *myList = NULL; //Erzeugen einen Pointer vom Type item
plot *myList2 = NULL; //Erzeugen einen Pointer vom Type plot
int bar = 0;
int counter = 0;
double E_max = 0;
double E_min = 0;
double range = 0;
double width = 0;
printf("########## Dynamische Liste ##########\n\n");
printf("-- erzeuge leere Liste\n");
myList = initList(myList); //initialisiere den neuen Pointer, indem er auf NULL gesetzt wird
//LOG_PRINT("-- initList(): myList");
printf("-- pruefe auf leere Liste\n");
printIsemtyList(myList);
//LOG_PRINT("-- printIsemptyList(): myList ist leer");
printf("-- Einlesen von Daten\n");
myList = einlesensortiert(myList);
printf("########## Liste vorwaerts ausgeben ##########\n");
printListForward(myList);
//LOG_PRINT("++ printListForward()");
printf("########## Anzahl Elemente: ##########\n");
counter = countItems(myList);
printf("++%d\n", counter);
printf("########## Groesster Wert der Liste ist: ##########\n");
E_max = getEnergyMax(myList);
printf("++%lf\n", E_max);
printf("########## Kleinster Wert der Liste ist: ##########\n");
E_min = getEnergyMin(myList);
printf("++%lf\n", E_min);
printf("########## Der Messbereich betraegt: ##########\n");
range = effective_range(E_max, E_min);
printf("++%lf\n", range);
/*Wenn R¸ckgabe Wert = 0 muss neue Abfrage gemacht werden!!!!!!!*/
printf("########## Anzahl Balken: ##########\n");
bar = number_of_bars(counter);
printf("++%d\n", bar);
printf("########## Abschnittswert: ##########\n");
width = section_value(range, bar);
printf("++%lf\n", width);
printf("########## Neue Dynamische Liste ##########\n\n");
printf("-- erzeuge leere Liste\n");
myList2 = initList2(myList2);
printf("-- pruefe auf leere Liste\n");
printisemptyList2(myList2);
printf("-- sortiere Liste\n");
myList2 = sortierenfuergnu(myList2, myList, width, E_max, E_min, counter,
bar);
printf("-- Liste ausgeben\n");
printListForward2(myList2);
//printf("++test for schleife\n");
//probeforsch( E_min, width, E_max);
//printf("%lf\n",i);
return EXIT_SUCCESS;
}
</code></pre>
<p>Other file:</p>
<pre><code>/*
* Datenstruktur.c
*
* Created on: 30.12.2013
* Author: Captain Morgan
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 20
/*--------------------------------------------------*/
struct daten {
char date[MAX];
char time[MAX];
double spannung;
double strom;
double wirkfaktor;
double energie;
struct daten *next;
};
/*--------------------------------------------------*/
typedef struct daten item;
/*--------------------------------------------------*/
item *initList(item *list) {
return (list = NULL);
}
/*--------------------------------------------------*/
int isemptyList(item *list) {
return (list == NULL);
}
/*--------------------------------------------------*/
void printIsemtyList(item *list) {
item *iter_List = list;
if (isemptyList(iter_List))
printf("++ Liste ist leer\n");
else
printf("++ Liste ist nicht leer\n");
}
/*--------------------------------------------------*/
//FILE dateiOpen(void) {
// FILE *datei;
//
// datei = fopen("Maschine_02.csv","r");
// if (NULL == datei) {
// printf("Konnte Datei nicht ˆffnen!\n");
// return (*datei);
// }
// return (*datei);
//}
/*--------------------------------------------------
Sortiert einlesen und Berechnen der Energie
Sortiert nach der Energie. Von klein nach gross.
--------------------------------------------------*/
item *einlesensortiert(item *list) {
item *tmp;
FILE *datei;
item *iter_List = list;
datei = fopen("Maschine_01.csv", "r");
if (NULL == datei) {
printf("Konnte Datei nicht ˆffnen!\n");
return (0);
}
while (!feof(datei)) {
tmp = (item *) malloc(sizeof(item));
fscanf(datei, "%s \t %s \t %lf \t %lf \t %lf\n", tmp->date, tmp->time,
&tmp->spannung, &tmp->strom, &tmp->wirkfaktor);
tmp->energie = ((sqrt(3)) * (tmp->spannung) * (tmp->strom) * cos(
(tmp->wirkfaktor))) * 1; //1 f¸r Sek.
// P(Leistung) = (Wurzel3) * Strom * Spannung / W (Energie) P * t (in sek)
tmp->next = NULL;
if (isemptyList(iter_List) || tmp->energie < iter_List->energie) {
tmp->next = iter_List;
list = tmp;
} else {
while (iter_List->next != NULL && tmp->energie
> iter_List->next->energie)
iter_List = iter_List->next;
tmp->next = iter_List->next;
iter_List->next = tmp;
}
iter_List = list;
}
return (list);
}
/*--------------------------------------------------*/
void printListForward(item *list) {
item *iter_List = list;
if (iter_List) {
printf("++ %s\t", iter_List->date);
printf("++ %s\t", iter_List->time);
printf("++ %lf\t", iter_List->spannung);
printf("++ %lf\t", iter_List->strom);
printf("++ %lf\t", iter_List->wirkfaktor);
printf("++ %lf\n", iter_List->energie);
printListForward(iter_List->next);
}
}
/*--------------------------------------------------*/
int countItems(item *list) {
item *iter_List = list;
int counter = 0;
while (iter_List) {
counter++;
iter_List = iter_List->next;
}
return (counter);
}
/*--------------------------------------------------
Achtung funktioniert nur mit positiven Werten!!!
--------------------------------------------------*/
double getEnergyMax(item *list) {
item *iter_List = list;
double tmp = 0;
while (iter_List != NULL) {
if (iter_List->energie > tmp) {
tmp = iter_List->energie;
}
iter_List = iter_List->next;
}
return (tmp);
}
/*--------------------------------------------------*/
double getEnergyMin(item *list) {
item *iter_List = list;
double tmp = iter_List->energie;
while (iter_List != NULL) {
if (iter_List->energie < tmp) {
tmp = iter_List->energie;
}
iter_List = iter_List->next;
}
return (tmp);
}
/*--------------------------------------------------*/
double effective_range(double E_max, double E_min) {
double range = 0;
range = E_max - E_min;
if (range == 0) //Wenn die Differenz gleich 0 ist, wird 0 zur¸ckgegeben. Mit Kevin anschauen welchen Wert er will!!
return 0;
else
return (range);
}
/*--------------------------------------------------*/
int number_of_bars(int counter) {
if (counter < 5)
return (0);
else if (counter <= 10)
return (2);
else if (counter <= 100)
return (5);
else
return (10);
}
/*--------------------------------------------------*/
double section_value(double range, int bar) {
double width = 0;
width = range / (bar);
return (width);
}
/*--------------------------------------------------*/
struct gnuplot {
int yAchse;
double xAchse;
double prozent;
struct gnuplot *next;
};
/*--------------------------------------------------*/
typedef struct gnuplot plot;
/*--------------------------------------------------*/
plot *initList2(plot *list2) {
return (list2 = NULL);
}
/*--------------------------------------------------*/
int isemptyList2(plot *list2) {
return (list2 == NULL);
}
/*--------------------------------------------------*/
void printisemptyList2(plot *list2) {
plot *iter_List2 = list2;
if (isemptyList2(iter_List2))
printf("++Liste ist leer\n");
else
printf("++Liste ist nicht leer\n");
}
/*--------------------------------------------------*/
plot *sortierenfuergnu(plot *list2, item *list, double width, double E_max,
double E_min, int counter, int bar) {
item *iter_List = list;
plot *iter_List2 = list2;
plot *tmp2;
double i;
double b = E_min + width;
int counter2;
int z = 0;
while (z < bar) {
for (i = b; i < E_max; i += width) {
z++;
tmp2 = (plot *) malloc(sizeof(plot));
tmp2->xAchse = i;
counter2 = 0;
while (i >= iter_List->energie) {
counter2++;
//printf("%lf\t",i);
//printf("%lf\n",iter_List->energie);
iter_List = iter_List->next;
//printf("\t\t%lf\n",iter_List->energie);
}
tmp2->yAchse = counter2;
tmp2->prozent = (100 / counter) * counter2;
tmp2->next = NULL;
if (isemptyList2(iter_List2))
list2 = tmp2;
else {
while (iter_List2->next != NULL)
iter_List2 = iter_List2->next;
iter_List2->next = tmp2;
}
iter_List2 = list2;
}
}
return (list2);
}
/*--------------------------------------------------*/
void printListForward2(plot *list2) {
plot*iter_List2 = list2;
if (iter_List2) {
printf("++ %d\t", iter_List2->yAchse);
printf("++ %lf\t", iter_List2->xAchse);
printf("++ %.2lf%%\n", iter_List2->prozent);
printListForward2(iter_List2->next);
}
}
/*--------------------------------------------------*/
double probeforsch(double E_min, double width, double E_max) {
double i;
double b = E_min + width;
for (i = b; i < E_max; i += width) {
printf("%lf\n", i);
}
return (i);
}
</code></pre>
<p>Code can also be downloaded from <a href="http://speedy.sh/Vnfnw/Energie.zip" rel="nofollow">here</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T16:34:45.853",
"Id": "73009",
"Score": "2",
"body": "Please edit the question so that the code to be reviewed is embedded in the text of the question (otherwise it can't be answered); see [Can I put my code on a third party site and link to the site in my question?](http://meta.codereview.stackexchange.com/a/1309/34757)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T16:50:26.253",
"Id": "73012",
"Score": "0",
"body": "I have added the code. I'm sorry that it is really very ugly. I wanted to clean it up myself a bit, but I can't start it in Eclipse OS X, it tells me that there's no executable found (it was written on Windows). I can successfully build it but not run it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T17:24:10.703",
"Id": "73020",
"Score": "0",
"body": "I don't want to download from http://speedy.sh/Vnfnw/Energie.zip (e.g. to get the CSV data file) because that would run an EXE (\"download manager\") on my machine."
}
] |
[
{
"body": "<p>I've seen much worse C code. For the most part I think your code is reasonably well organized and your approach of manipulating data via pointers into functions is standard C practice when dealing with large data structures. </p>\n\n<p>C is not OO and you can only go so far before you re-invent C++. </p>\n\n<p>You do a good job of having a single function do a single thing. Where things can go wrong in C code is when a function has side effects that aren't apparent from \neither the function name or the calling arguments. </p>\n\n<p>This is a potential memory leak. </p>\n\n<pre><code> plot *initList2(plot *list2) {\n return (list2 = NULL);\n\n }\n</code></pre>\n\n<p>Assigning a pointer to NULL means that you are leaking whatever memory that pointer originally referenced. Generally you assign NULL at pointer creation,\nusing a subroutine like this is just asking for trouble. </p>\n\n<p>You have some helper functions that would more typically be written as C macros\nand you use numeric constants. All of these should be defined in an include file and/or put into an array/struct that you pass into the function. Best practice in C is for functions to have EVERYTHING they need passed in as arguements. In large complex codes, there is often an \"environment\" or context struct passed in as the first arguement that includes all the global variables required. </p>\n\n<p>All in all, this code is headed in the right direction. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T18:01:12.977",
"Id": "42445",
"ParentId": "42433",
"Score": "4"
}
},
{
"body": "<p>I think the code is pretty good.</p>\n\n<p>I'm not sure how to \"refactor\" (i.e. restructure) it. Does it already do everything it's supposed to, or do you want to extend it in some way? I usually <a href=\"https://stackoverflow.com/a/1275332/49942\">don't restructure something unless I need to change it</a> and the current structure seems fine: the step-by-step code in <code>main</code> is straightforward so it seems that the functions provided in <code>Datenstruktur.c</code> are adequate.</p>\n\n<p>Therefore I'll review the details (not the structure) of <code>Datenstruktur.c</code></p>\n\n<hr>\n\n<p>It's conventional to combine the typedef with the struct:</p>\n\n<pre><code>typedef struct daten {\n char date[MAX];\n char time[MAX];\n double spannung;\n double strom;\n double wirkfaktor;\n double energie;\n struct daten *next;\n} item;\n</code></pre>\n\n<hr>\n\n<p>Invoking <code>initList</code> is less readable than simply initializing the pointer to NULL.</p>\n\n<hr>\n\n<p>There's a curious mix of naming conventions:</p>\n\n<ul>\n<li>using_underscores like <code>number_of_bars</code></li>\n<li>alllowercase like <code>einlesensortiert</code></li>\n<li>camelCase like <code>printListForward</code></li>\n<li>also <code>iter_List</code></li>\n</ul>\n\n<p>It would look better if you sticked with one. If using camelCase, the 'E' in \"Empty\" should be capitalized e.g. in <code>isemptyList</code> and <code>printIsemtyList</code>. And there are spelling mistakes like missing 'p' in <code>printIsemtyList</code>.</p>\n\n<hr>\n\n<p>fscanf risks overrunning the input buffer if the data (e.g. a string) in the input CSV file is longer than <code>MAX</code>:</p>\n\n<pre><code>fscanf(datei, \"%s \\t %s \\t %lf \\t %lf \\t %lf\\n\", tmp->date, tmp->time,\n &tmp->spannung, &tmp->strom, &tmp->wirkfaktor);\n</code></pre>\n\n<hr>\n\n<p>It's strange the use recursion in the <code>printListForward</code> function. It would be more normal to use a for loop:</p>\n\n<pre><code>for (item *iter_List = list; iter_List; iter_List = iter_List->next)\n{ ...; }\n</code></pre>\n\n<p>Similarly <code>countItems</code> and similar methods could use a for loop instead of a while loop.</p>\n\n<hr>\n\n<p><code>getEnergyMax</code> will return 0 if the list is empty, but <code>getEnergyMin</code> might crash.</p>\n\n<hr>\n\n<p>I'm not sure what the point of the <code>if (range == 0)</code> statement is in the <code>effective_range</code> function.</p>\n\n<hr>\n\n<p><code>initList2</code> is a pretty bad name to distinguish it from <code>initList</code>. It would be better to use the name of the type in the function name, for example:</p>\n\n<ul>\n<li><code>initItemList</code> and <code>initPlotList</code> (sounds English-like)</li>\n<li><code>item_init_list</code> and <code>plot_init_list</code> (puts the name of the type at the beginning)</li>\n</ul>\n\n<hr>\n\n<p>You leak all the memory you allocate (there are <code>malloc</code> statements but no <code>free</code> statements). IMO that's OK for programs which run once and then exit (memory is reclaimed by the O/S).</p>\n\n<p>You also don't close the CSV file which you opened using <code>fopen</code>.</p>\n\n<hr>\n\n<p>You didn't post <code>Datenstruktur.h</code> and I don't know what's in it. Normally I'd expect to see the typedef of the structs and pointers in the header file.</p>\n\n<hr>\n\n<p>In his answer, @fred said, \"C is not OO and you can only go so far before you re-invent C++.\"</p>\n\n<p>If you want to make it more OO-like, consider the fact that a C++ class is:</p>\n\n<ul>\n<li>A data structure (i.e. member data instances)</li>\n<li>Associated methods which manipulate that data</li>\n</ul>\n\n<p>The data which you have in this program are:</p>\n\n<ul>\n<li>daten/item</li>\n<li>gnuplot/plot</li>\n<li>Lists (of item and plot nodes)</li>\n<li>The CSV file (represented by <code>FILE *datei</code>)</li>\n</ul>\n\n<p>At a minimum you could split <code>Datenstruktur.c</code> into two separate modules (where by \"module\" I mean \"a header file and a C file\"):</p>\n\n<ul>\n<li>One which defines item and functions related to item (including reading from the CSV file)</li>\n<li>One which defines plot and functions related to plot (including creating plots from items)</li>\n</ul>\n\n<p>Because C doesn't support polymorphism nor templates, I'd guess it would be overkill (too much extra, difficult code) to try to create a generic list module (a module to work with lists of an arbitrary type, including plots and items). These are a simple type of list (a \"singly-linked\" list consisting of one forward pointer) which a C programmer should be able to do easily (little or no complication that might need to be hidden inside some library module).</p>\n\n<p>I don't see a convenient way to separate the CSV from the item data: so little opportunity there for separate modules, beyond the built-in <code>FILE* fopen</code> module (family of functions) already built-in to the C run-time library.</p>\n\n<p>So as I said earlier I see little opportunity for refactoring.</p>\n\n<blockquote>\n <p>Is it good practice to send variables into a function as pointers and manipulate them within the function body?</p>\n</blockquote>\n\n<p>I don't think the code is doing that anywhere?</p>\n\n<p>But yes, that is normal practice. For example, instead of ...</p>\n\n<pre><code>item *einlesensortiert(item *list) { ... }\n</code></pre>\n\n<p>... it would also be idomatic to have ...</p>\n\n<pre><code>void einlesensortiert(item** list) { ... }\n</code></pre>\n\n<p>... where the caller passes a pointer to the list pointer, and the function uses that the change the contents of the caller's list pointer.</p>\n\n<p>C supports the <code>const</code> keyword, which can be used to specify that the thing which is passed by pointer mustn't be altered by the callee.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T18:07:00.197",
"Id": "42446",
"ParentId": "42433",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T16:28:42.250",
"Id": "42433",
"Score": "6",
"Tags": [
"c",
"csv"
],
"Title": "Read CSV, compute some stuff and prepare data to be sent to GNUPlot"
}
|
42433
|
<p>I have a <code>MouseInputHandler</code> class that registers itself to an <code>InputManager</code>. When the InputManager class receives events they are forwarded to MouseInputHandler which changes its state to reflect the state of the mouse. A mouse as an input device provides a large number of different properties that should be easy to read, but impossible to write to.</p>
<p>The problem is that C++ fails to provide a keyword otherwise similar to <code>const</code> but that grants full write access to functions in the same scope.</p>
<pre><code>class MouseInputHandler : public InputHandler
{
public:
MouseInputHandler(ResourceContext &context)
: btnLeft(btnLeft_), btnMiddle(btnMiddle_), btnRight(btnRight_),
btnX1(btnX1_), btnX2(btnX2_), absX(absX_), absY(absY_), relX(relX_),
relY(relY_), scrollX(scrollX_), scrollY(scrollY_) {}
void handleEvent(SDL_Event &mouseEvent);
void refresh();
const Signal &btnLeft, &btnMiddle, &btnRight, &btnX1, &btnX2;
const int32_t &absX, &absY, &relX, &relY, &scrollX, &scrollY;
protected:
Signal btnLeft_, btnMiddle_, btnRight_, btnX1_, btnX2_;
int32_t absX_, absY_, relX_, relY_, scrollX_, scrollY_;
};
</code></pre>
<p>Options I have identified at this point:</p>
<ol>
<li>Declaring the members private or protected and providing public const references to the non-public members that only allow read access (as in the example above). However with 11 members, the class quicly becomes a mess, with 11 const references (that also require 11 reference initializations in the constructor's initializer list).</li>
<li>Adding getter methods for every member variable. More cumbersome than the const references, but with the (marginal) added benefit that the members are now accessible as functions.</li>
<li>Placing the buttons and integers in (private or protected) arrays and adding an enum that gives indexes to the array elements meaningful names. To access the members, two (one getter for buttons, other for ints) getter functions that take the index and return a const reference are added to the class. This seems to me quite complex and error prone in comparison to the other solutions.</li>
<li>Just not caring about const correctness at all and making the member variables fully accessible.</li>
<li>Refractoring the code. I don't see how one could refractor a mouse, or simplify the interface, but any suggestions are welcome.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T19:13:52.040",
"Id": "73074",
"Score": "0",
"body": "I went with the struct + accessor method approach as suggested by ChrisW. Placing the variables separately did not come to my mind for some reason."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T22:46:34.710",
"Id": "73128",
"Score": "0",
"body": "I think the keyword you are looking for is called \"friend\", although it is often said you shouldn't make use of it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T00:11:37.037",
"Id": "73141",
"Score": "0",
"body": "@AlexisWilke \"friend\" is to get past a \"private\" barrier (i.e. no access at all); I don't see how to use it to help implement and/or get past a const-versus-non-const barrier."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T00:50:03.063",
"Id": "73143",
"Score": "0",
"body": "@ChrisW, note that this comment was in link with the OP sentence: \"The problem is that C++ fails to provide a keyword otherwise similar to const but that grants full write access to functions in the same scope.\" -- a class can allow another to write to its fields even if those are private. Of course, that doesn't remove the \"const-ness\" but marking variables as const when in reality they are not is anyway misleading."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T00:52:51.520",
"Id": "73145",
"Score": "0",
"body": "@AlexisWilke I still don't see how \"friend\" could be used in an answer to the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T00:54:30.320",
"Id": "73146",
"Score": "0",
"body": "@ChrisW, comments are not for answers, I have an answer below where I think the protected virtual function is the real solution for the const + some protected way of writing to variables. \"friend\" would be another way to bypass private which the OP seems to have missed in that specific sentence I underlined."
}
] |
[
{
"body": "<p>You could represent the mouse state using a struct:</p>\n\n<pre><code>struct MouseSettings\n{\n Signal btnLeft_, btnMiddle_, btnRight_, btnX1_, btnX2_;\n int32_t absX_, absY_, relX_, relY_, scrollX_, scrollY_;\n}\n\nclass MouseInputHandler : public InputHandler\n{\npublic:\n MouseInputHandler(ResourceContext &context)\n : mouseSettings(mouseSettings_)\n {}\n void handleEvent(SDL_Event &mouseEvent);\n void refresh();\n\n const MouseSettings& mouseSettings;\n\nprotected:\n MouseSettings mouseSettings_;\n};\n</code></pre>\n\n<p>Or a property-like get-accessor method like:</p>\n\n<pre><code>const MouseSettings& getMouseSettings() { return mouseSettings_; }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T18:26:31.910",
"Id": "42451",
"ParentId": "42447",
"Score": "7"
}
},
{
"body": "<p>As a side note, getters are fully optimized by the compiler, whereas the const references are not (read as cannot). References generate at least 2 instructions because the reference is a pointer which cannot safely be removed by the compiler (because you can change those pointers over time):</p>\n\n<pre><code>class F\n{\n int member;\npublic:\n const int& member_;\n};\n\nx = f.member; // this is a full reference, so a pointer to a value:\n // mov [%eax+4], %ebx + mov [%ebx], %ebx\n</code></pre>\n\n<p>When a simple getter as we see here is fully optimized and get one a faster program with the security you are looking for:</p>\n\n<pre><code>class G\n{\n int member_;\npublic:\n int get_member() const { return member_; }\n};\n\nx = f.get_member(); // this gets optimized to one load: mov [%eax], %ebx\n</code></pre>\n\n<p>This last example becomes exactly the same as:</p>\n\n<pre><code>x = f.member_;\n</code></pre>\n\n<p>but is read-only (and allows you to write more code in the getter as required with time.)</p>\n\n<p>Another drawback with the <code>const</code> reference, you can overrule the constness with a cast:</p>\n\n<pre><code>const_cast<int&>(f.member_) = 5;\n</code></pre>\n\n<p>So it may not be as safe as you think.</p>\n\n<p>In regard to ChrisW's answer, the last entry has the same potential problem with the <code>const_cast<>()</code> capability. Although of course, you have to work at it to want to write data in the wrong place...</p>\n\n<pre><code>const MouseSettings& getMouseSettings() { return mouseSettings_; }\nconst_cast<MouseSettings&>(f.getMouseSettings()).absX_ = 123;\n</code></pre>\n\n<p>This is rarely an issue since pretty much no one wants to do such. However, if you work with multiple threads, that issue is a problem because now you have a reference to a \"moving\" target (any thread can modify the <code>MouseSettings</code> without proper multi-CPU barrier). So a safer implementation is:</p>\n\n<pre><code>MouseSettings getMouseSettings() { return mouseSettings_; }\n</code></pre>\n\n<p>and it gets optimized like a standard getter, so:</p>\n\n<pre><code>x = f.getMouseSettings().absX_;\n</code></pre>\n\n<p>is one single <code>mov</code> instruction as if you had just one <code>get_absX() const</code> function (see above).</p>\n\n<p>Now, to answer your question some more, I'm not too sure where your problem is in your current implementation since the only thing that can modify the values defined in the class is the <code>handleEvent()</code> function and that function will have full write permissions.</p>\n\n<pre><code>void handleEvent(SDL_Event &mouseEvent)\n{\n f.member_ = 123; // this works here!\n}\n</code></pre>\n\n<p>So for the writer I would rewrite the <code>handleEvent()</code> function like this:</p>\n\n<pre><code>class InputHandler\n{\n...\nprotected:\n virtual void handleEvent(...) = 0; // force all derived class to handle events\n};\n\nclass MouseInputHandler : public InputHandler\n{\n...\nprotected:\n virtual void handleEvent(...) { ... };\n};\n</code></pre>\n\n<p>The body of the <code>handleEvent()</code> could of course be written in the .cpp file. This means on the <code>InputHandle</code> has the capability to write to the mouse input handler variables in a rather safe manner.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T23:31:20.907",
"Id": "73134",
"Score": "0",
"body": "Returning a copy of the value not only more expensive but is also insufficient protection: because a malicious caller can reinterpret_cast MouseInputHandler* to char* and then poke into private member data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T23:37:53.920",
"Id": "73136",
"Score": "0",
"body": "@ChrisW, when you return a copy, you can modify the copy. But not the content of the source in the class. A reinterpret_cast<>() won't help you on the copy returned. However if you cast the class object itself, of course. Then you can do anything anyway... C/C++ are dreadful in that sense. However, the compiler knows how to optimize a value returned by copy and transform it to a single mov instruction in assembly. (assuming the getter is written inline.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T00:50:03.820",
"Id": "73144",
"Score": "0",
"body": "+1 for implying that if the program is multi-threaded then you'd better \"lock, return a copy of the whole structure, unlock\" instead of returning a reference to volatile data: because that gives the caller a copy of a coherent set of data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T16:41:46.403",
"Id": "73198",
"Score": "0",
"body": "Your assertions about references being pointers is false. The compiler can just as easily remove them as inline getters. When writting getters, best to implement as returning a const reference to avoid the copy. Code with `const_cast<>` is dicey at best and casting it away in this situation would be undefined behavior. So you are offering a false analogy as an argument for not using them. Though I agree that getter is the way to go your arguments for doing so are mostly wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T05:24:51.763",
"Id": "73369",
"Score": "0",
"body": "I tested with a simple case and everything inline and g++ optimizes everything properly. So I guess that doesn't stand anymore."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T23:19:03.857",
"Id": "42476",
"ParentId": "42447",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>Declaring the members private or protected and providing public const references to the non-public members that only allow read access (as in the example above). However with 11 members, the class quicly becomes a mess, with 11 const references (that also require 11 reference initializations in the constructor's initializer list).</p>\n</blockquote>\n\n<p><code>protected</code> is a bad option as it does not really provide any kind of protections. It is to easy for a developer a couple of years from now deciding that he wants to have access and just inherit from your class to get the access he wants. Thus violating constraints that you probably failed to document. So prefer never to use protected. Stick with either fully <code>private</code> or fully <code>public</code>.</p>\n\n<p>Adding reference variable may potentially double the size of your class if the compiler is having a bad day and does not optimize them out. Also this adds restictions on the copy-ability of your class (the default copy constructor is not going to do the expected thing).</p>\n\n<blockquote>\n <p>Adding getter methods for every member variable. More cumbersome than the const references, but with the (marginal) added benefit that the members are now accessible as functions.</p>\n</blockquote>\n\n<p>Adding getters for each member would become cumbersome. But you could start doing some template magic to remove repetitive code.</p>\n\n<blockquote>\n <p>Placing the buttons and integers in (private or protected) arrays and adding an enum that gives indexes to the array elements meaningful names. To access the members, two (one getter for buttons, other for ints) getter functions that take the index and return a const reference are added to the class. This seems to me quite complex and error prone in comparison to the other solutions.</p>\n</blockquote>\n\n<p>I disagree. That seems like a fairly reasonable solution:</p>\n\n<pre><code>enum T {absX_, absY_, relX_, relY_, scrollX_, scrollY_};\nenum S {btnLeft_, btnMiddle_, btnRight_, btnX1_, btnX2_};\nclass LotsOfPrivateMembers\n{\n int intData[6];\n double signalData[5];\n\n public:\n\n template<T i>\n int const& get() { return intData[i];}\n template<S i>\n int const& get() { return signalData[i];}\n};\n</code></pre>\n\n<blockquote>\n <p>Just not caring about const correctness at all and making the member variables fully accessible.</p>\n</blockquote>\n\n<p>Not a good idea.<br>\nMake sure your code is const correct is a big part of modern C++.</p>\n\n<blockquote>\n <p>Refractoring the code. I don't see how one could refractor a mouse, or simplify the interface, but any suggestions are welcome.</p>\n</blockquote>\n\n<p>Suggestion above.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T17:05:01.563",
"Id": "42518",
"ParentId": "42447",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "42451",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T18:13:28.153",
"Id": "42447",
"Score": "6",
"Tags": [
"c++",
"object-oriented",
"c++11",
"event-handling",
"sdl"
],
"Title": "Mouse input handler which exposes read-only mouse state data"
}
|
42447
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.