body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I'd like to know how to optimize this by shadowing symbols 'lo and 'hi inside nested function f. I guess CPS conversion would solve this but how?</p> <pre><code>;; chess engine - early development ;; Alist: (cons 'piece xy-coordinates) (define whites) (define blacks) (begin (define setup     (let ([lo `(p0 p1 p2 p3 p4 p5 p6 p7)]            [hi `(r0 n0 b0 q k b1 n1 r1)])       (define f         (let ([xs (iota 8)])           (lambda (ls y)             (map (lambda (i x) (cons i (cons x y))) ls xs))))       (lambda (l h) (concatenate (f lo l) (f hi h)))))   (set! whites (setup 1 0)) (set! blacks (setup 6 7))) </code></pre>
[]
[ { "body": "<p>Your question and code are both confusing to me, but I'll give it a shot.</p>\n\n<p><code>(define whites)</code> doesn't compile with my standard definition of <code>define</code>. <code>define</code> usually needs to bind the identifier to something, even if it is just <code>'()</code> or <code>#f</code>. Since it seems like they (blacks and whites) are meant to hold a-lists, I've initialized them to <code>'()</code>.</p>\n\n<p>I don't know what dialect of scheme you're running, but you may be able to drop the outer <code>begin</code> form, and your <code>concatenate</code> function is usually called append in most schemes. Finally, you may have a <code>list*</code> function so to replace <code>(cons i (cons x y))</code> with <code>(list* i x y)</code></p>\n\n<p>Next, in order to call setup, it wasn't immediately clear that setup was a function that took two arguments, the first being an integer intended to be the row to place the pieces onto, and the second being the row to set the pawns. I would make setup into a thunk since the initial placement of the pieces is pretty intrinsic to chess unless you're planning to support rectangular boards or something. Also, being a thunk emphasizes that it's being called for its side effect, and not it's value. You could really bring home that point by calling the function <code>setup!</code> instead.</p>\n\n<p>I would give more descriptive names to your identifiers. I would create a function that put a list of pieces together with their coordinates, called <code>make-row</code>, and a function that setup both the pieces and pawns given the rows to place them on, called <code>setup-color</code></p>\n\n<p>With regard to your concern about optimizing: readability and extensibility are usually more important than a few instructions. There are exceptions, and those exceptions will kill performance if you don't optimize when they occur. There are no rules about where performance bottlenecks lie, except for they are usually not where you think they are ;-). That's why it is important to MEASURE your performance as you go. The bottlenecks of most chess engines are usually NOT in the method used to setup the board. They are usually in the search methods, so when you get there, time spent optimizing will yield a much better ROI.</p>\n\n<p>Also, when you go to optimize, before starting down the path of flipping your program inside -out to CPS it, consider easier wins first, like using a vector instead of a list as your primary data structure. </p>\n\n<p>As for shadowing symbols, it seems you may have a misunderstanding. Shadowing doesn't buy you anything in performance. It's not the identifier that takes up space, it's whatever that identifier is bound to. When you shadow a variable, the old value still has to be stored for when it is unshadowed later. </p>\n\n<p>In fact, shadowing variables can actually be harmful to performance in some cases. Since you can shadow primitive operations like <code>+</code>, the compiler is unable to safely inline those operations. If you can tell the compiler that you promise not to shadow <code>+</code>, it can inline addition operations. If your implementation has a decent module system, wrapping you code in modules may help the compiler make these deductions, otherwise there may be flags to encourage inlining.</p>\n\n<p>Here is my suggested refactoring.</p>\n\n<pre><code>;; Alist: (cons 'piece xy-coordinates)\n(define whites '())\n(define blacks '())\n\n;;Set!s whites and blacks to the initial chessboard setup\n(define (setup!)\n (define (make-row pieces row)\n (map (lambda (piece x) (list* piece x row)) \n pieces\n (iota 8)))\n\n (define (setup-color pawn-row piece-row)\n (let ((pawns '(p0 p1 p2 p3 p4 p5 p6 p7))\n (pieces '(r0 n0 b0 q k b1 n1 r1)))\n (append\n (make-row pawns pawn-row)\n (make-row pieces piece-row))))\n\n (set! whites (setup-color 1 0))\n (set! blacks (setup-color 6 7)))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T15:59:28.323", "Id": "13247", "ParentId": "13236", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-01T19:59:41.617", "Id": "13236", "Score": "1", "Tags": [ "optimization", "scheme", "functional-programming" ], "Title": "Optimize this Scheme-written chess engine module" }
13236
<p>Please review the two code snippets below and let me know if the second snippet is better than the first one.</p> <p>In code snippet 2 I have added an inline function. According to my peers, using inline functions can help improve performance, since context switch will occur less often. </p> <p>But I am not able to verify this claim. Is there any perfomance difference in the two code snippets?</p> <p><strong>Snippet 1</strong> </p> <pre><code>foreach (var item in requestPayLoad.UserData) { UserItem userItem = UserItemHelper.CreateItem(item, jobID); if (userItem != null) { lstUserItems.Add(userItem); } } </code></pre> <p><strong>Snippet 2</strong></p> <pre><code>var GetUserItem = new Func&lt;UserItem , UserJob , UserItemStruct&gt;((custItemStruct, syncJob) =&gt; { return UserItemHelper.CreateItem(custItemStruct, syncJob); }); foreach (var item in requestPayLoad.UserData) { UserItem userItem = GetUserItem(item,job); if (userItem != null) { lstUserItems.Add(userItem); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T08:11:51.557", "Id": "21410", "Score": "2", "body": "Have you tried profiling these code snippets to find any performance differences?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T09:09:29.783", "Id": "21411", "Score": "1", "body": "The jit compiler will inline for you when it can. Don't write your code in such a way to hinder its functionality." } ]
[ { "body": "<p>You seem to be confusing several concepts, some completely unrelated.</p>\n\n<p>First, the second snippet is less readable, because it adds quite a lot of complexity that's not necessary. Unless you have a good reason to do something like this (for example, significant <em>measurable</em> performance improvements), don't do it.</p>\n\n<p>Now to the confusions: what you're doing could be called an inline function. But the performance improvements your peers were most likely talking about are from inlining functions. Inlining functions is an optimization made by the jitter, which sometimes inlines the machine code of one function into another function. This optimization is completely unrelated to creating a local delegate from lambda. And actually, by doing this you are <em>preventing</em> that optimization. Also, invoking a delegate has some small cost, so your second snippet will be actually slower.</p>\n\n<p>To sum up, the second snippet is less readable and less efficient: I don't see any reason why should you ever write code like that. In any case, trying to optimize code like this is pointless: optimize only the code that's worth optimizing (identified by profiling) and then use empirical data to see which version is actually faster. Don't guess, measure.</p>\n\n<p>You also seem to be confused about what context switch is. Context switch happens when your CPU is executing code from one thread, and then switches to executing code from another thread. This is completely unrelated to your question.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T11:55:32.643", "Id": "13241", "ParentId": "13239", "Score": "13" } }, { "body": "<p>For what it's worth, you could re-write this as </p>\n\n<pre><code>lstUserItems.AddRange(requestPayLoad.UserData\n .Select(item =&gt; UserItemHelper.CreateItem(item, jobID))\n .Where(userItem =&gt; userItem != null));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T16:32:15.517", "Id": "13249", "ParentId": "13239", "Score": "10" } }, { "body": "<p>The second code snippet is a really dirty one becouse you loose the control over your code (reuseability, unit test (for this you should rethink the concept of UserItemHelper), readability).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T09:42:58.307", "Id": "13441", "ParentId": "13239", "Score": "0" } } ]
{ "AcceptedAnswerId": "13241", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T07:16:33.887", "Id": "13239", "Score": "2", "Tags": [ "c#", "performance" ], "Title": "Inline Functions C#" }
13239
<p>I am quite new to ASP.net and am currently trying to implement my data access layers of my application. I have so far implemented a generic repository pattern as follows:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Data; using System.Data.Entity; using PayPlate.Models; using System.Linq.Expressions; namespace PayPlate.DAL { public class GenericRepository&lt;TEntity&gt; where TEntity : class { internal PayPlateContext context; internal DbSet&lt;TEntity&gt; dbSet; public GenericRepository(PayPlateContext context) { this.context = context; this.dbSet = context.Set&lt;TEntity&gt;(); } public virtual IEnumerable&lt;TEntity&gt; Get( Expression&lt;Func&lt;TEntity, bool&gt;&gt; filter = null, Func&lt;IQueryable&lt;TEntity&gt;, IOrderedQueryable&lt;TEntity&gt;&gt; orderBy = null, string includeProperties = "") { IQueryable&lt;TEntity&gt; query = dbSet; if (filter != null) { query = query.Where(filter); } foreach (var includeProperty in includeProperties.Split (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { query = query.Include(includeProperty); } if (orderBy != null) { return orderBy(query).ToList(); } else { return query.ToList(); } } public virtual TEntity GetByID(object id) { return dbSet.Find(id); } public virtual void Insert(TEntity entity) { dbSet.Add(entity); } public virtual void Delete(object id) { TEntity entityToDelete = dbSet.Find(id); Delete(entityToDelete); } public virtual void Delete(TEntity entityToDelete) { if (context.Entry(entityToDelete).State == EntityState.Detached) { dbSet.Attach(entityToDelete); } dbSet.Remove(entityToDelete); } public virtual void Update(TEntity entityToUpdate) { dbSet.Attach(entityToUpdate); context.Entry(entityToUpdate).State = EntityState.Modified; } } } </code></pre> <p>I have also implemented a UnitOfWork pattern to perform actions against the database as follows:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using PayPlate.Models; namespace PayPlate.DAL { public class UnitOfWork : IDisposable { private PayPlateContext context = new PayPlateContext(); private GenericRepository&lt;User&gt; userRepository; private GenericRepository&lt;Permission&gt; permissionRepository; private GenericRepository&lt;Payroll&gt; payrollRepository; private GenericRepository&lt;Function&gt; functionRepository; private GenericRepository&lt;PayrollIndexData&gt; payrollIndexDataRepository; private GenericRepository&lt;PayrollSelection&gt; payrollSelectionRepository; private GenericRepository&lt;GLRule&gt; gLRuleRepository; private GenericRepository&lt;Contract&gt; contractRepository; private GenericRepository&lt;CostGrp&gt; costGrpRepository; private GenericRepository&lt;AnalysisGrp&gt; analysisGrpRepository; private GenericRepository&lt;Job&gt; jobRepository; private GenericRepository&lt;Division&gt; divisionRepository; private GenericRepository&lt;AuthChain&gt; authChainRepository; private GenericRepository&lt;JobCode&gt; jobCodeRepository; private GenericRepository&lt;Pension&gt; pensionRepository; public GenericRepository&lt;GLRule&gt; GLRuleRepository { get { if (this.gLRuleRepository == null) { this.gLRuleRepository = new GenericRepository&lt;GLRule&gt;(context); } return gLRuleRepository; } } public GenericRepository&lt;Contract&gt; ContractRepository { get { if (this.contractRepository == null) { this.contractRepository = new GenericRepository&lt;Contract&gt;(context); } return contractRepository; } } public GenericRepository&lt;CostGrp&gt; CostGrpRepository { get { if (this.costGrpRepository == null) { this.costGrpRepository = new GenericRepository&lt;CostGrp&gt;(context); } return costGrpRepository; } } public GenericRepository&lt;AnalysisGrp&gt; AnalysisGrpRepository { get { if (this.analysisGrpRepository == null) { this.analysisGrpRepository = new GenericRepository&lt;AnalysisGrp&gt;(context); } return analysisGrpRepository; } } public GenericRepository&lt;Job&gt; JobRepository { get { if (this.jobRepository == null) { this.jobRepository = new GenericRepository&lt;Job&gt;(context); } return jobRepository; } } public GenericRepository&lt;Division&gt; DivisionRepository { get { if (this.divisionRepository == null) { this.divisionRepository = new GenericRepository&lt;Division&gt;(context); } return divisionRepository; } } public GenericRepository&lt;AuthChain&gt; AuthChainRepository { get { if (this.authChainRepository == null) { this.authChainRepository = new GenericRepository&lt;AuthChain&gt;(context); } return authChainRepository; } } public GenericRepository&lt;JobCode&gt; JobCodeRepository { get { if (this.jobCodeRepository == null) { this.jobCodeRepository = new GenericRepository&lt;JobCode&gt;(context); } return jobCodeRepository; } } public GenericRepository&lt;Pension&gt; PensionRepository { get { if (this.pensionRepository == null) { this.pensionRepository = new GenericRepository&lt;Pension&gt;(context); } return pensionRepository; } } public GenericRepository&lt;PayrollSelection&gt; PayrollSelectionRepository { get { if (this.payrollSelectionRepository == null) { this.payrollSelectionRepository = new GenericRepository&lt;PayrollSelection&gt;(context); } return payrollSelectionRepository; } } public GenericRepository&lt;Permission&gt; PermissionRepository { get { if (this.permissionRepository == null) { this.permissionRepository = new GenericRepository&lt;Permission&gt;(context); } return permissionRepository; } } public GenericRepository&lt;User&gt; UserRepository { get { if (this.userRepository == null) { this.userRepository = new GenericRepository&lt;User&gt;(context); } return userRepository; } } public GenericRepository&lt;Payroll&gt; PayrollRepository { get { if (this.payrollRepository == null) { this.payrollRepository = new GenericRepository&lt;Payroll&gt;(context); } return payrollRepository; } } public GenericRepository&lt;Function&gt; FunctionRepository { get { if (this.functionRepository == null) { this.functionRepository = new GenericRepository&lt;Function&gt;(context); } return functionRepository; } } public GenericRepository&lt;PayrollIndexData&gt; PayrollIndexDataRepository { get { if (this.payrollIndexDataRepository == null) { this.payrollIndexDataRepository = new GenericRepository&lt;PayrollIndexData&gt;(context); } return payrollIndexDataRepository; } } public void Save() { context.SaveChanges(); } private bool disposed = false; protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { context.Dispose(); } } this.disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } } </code></pre> <p>This is my database context:</p> <pre><code>using System; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using PayPlate.Models; namespace PayPlate.DAL { public class PayPlateContext : DbContext { public DbSet&lt;User&gt; Users { get; set; } public DbSet&lt;Permission&gt; Permissions { get; set; } public DbSet&lt;Payroll&gt; Payrolls { get; set; } public DbSet&lt;Function&gt; Functions { get; set; } public DbSet&lt;JobCode&gt; JobCodes { get; set; } public DbSet&lt;Division&gt; Divisions { get; set; } public DbSet&lt;AuthChain&gt; AuthChains { get; set; } public DbSet&lt;Job&gt; Jobs { get; set; } public DbSet&lt;Pension&gt; Pensions { get; set; } public DbSet&lt;AnalysisGrp&gt; AnalysisGrps { get; set; } public DbSet&lt;CostGrp&gt; CostGrps { get; set; } public DbSet&lt;Contract&gt; Contracts { get; set; } public DbSet&lt;GLRule&gt; GLRules { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove&lt;PluralizingTableNameConvention&gt;(); } } } </code></pre> <p>And these are my models:</p> <pre><code>using System; using System.ComponentModel.DataAnnotations; using System.Text; using System.Collections.Generic; using System.Linq; using System.Web; namespace PayPlate.Models { public class PayrollSelection { public IEnumerable&lt;Payroll&gt; Payrolls { get; set; } public IEnumerable&lt;User&gt; Users { get; set; } public IEnumerable&lt;Permission&gt; Permissions { get; set; } } public class PayrollIndexData { public IEnumerable&lt;Payroll&gt; Payrolls { get; set; } public IEnumerable&lt;User&gt; Users { get; set; } public IEnumerable&lt;Function&gt; Functions { get; set; } public IEnumerable&lt;Permission&gt; Permissions { get; set; } } public class Payroll { public int PayrollID { get; set; } [Required(ErrorMessage = "Payroll title is required.")] [Display(Name = "Payroll")] [MaxLength(20)] public string Title { get; set; } [Required(ErrorMessage = "C21 description is required.")] [Display(Name = "C21 Name")] [MaxLength(20)] public string C21Name { get; set; } [Required(ErrorMessage = "Server name is required.")] [Display(Name = "Server Name")] [MaxLength(20)] public string Server { get; set; } [Required(ErrorMessage = "Port is required.")] [Display(Name = "Port")] [MaxLength(5)] public string Port { get; set; } [Required(ErrorMessage = "Connection string is required.")] [Display(Name = "Connection String")] [MaxLength(200)] public string Connection { get; set; } public virtual ICollection&lt;Permission&gt; Permissions { get; set; } } public class SelectedPayroll { public string UserName { get; set; } public int UserID { get; set; } public int PayrollID { get; set; } public string Title { get; set; } } public class PermissionsPayrollGrp { public string Payroll { get; set; } public int UserCount { get; set; } } public class Function { public int FunctionID { get; set; } [Required(ErrorMessage = "Function description is required.")] [Display(Name = "Function")] [MaxLength(20)] public string Title { get; set; } public virtual ICollection&lt;Permission&gt; Permissions { get; set; } } public class Permission { public int PermissionID { get; set; } public int PayrollID { get; set; } public int FunctionID { get; set; } public int UserID { get; set; } [Range(typeof(double), "1", "5")] public double? Level { get; set; } public virtual Payroll Payroll { get; set; } public virtual Function Function { get; set; } public virtual User User { get; set; } } public class User { public int UserID { get; set; } public string NetLogin { get; set; } [Required(ErrorMessage = "Employee number is required.")] [Display(Name = "Employee Number")] [MaxLength(6)] public string EmpNumber { get; set; } [Required(ErrorMessage = "First name is required.")] [Display(Name = "First Name")] [MaxLength(50)] public string Forename { get; set; } [Required(ErrorMessage = "Last name is required.")] [Display(Name = "Last Name")] [MaxLength(50)] public string Surname { get; set; } public bool Active { get; set; } public virtual ICollection&lt;Permission&gt; Permissions { get; set; } } } using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PayPlate.Models { public class JobCode { public int JobCodeID { get; set; } public string Jobcode { get; set; } public int DivisionID { get; set; } public int AuthChainID { get; set; } public int JobID { get; set; } public int PensionID { get; set; } public int AnalysisGrpID { get; set; } public int CostGrpID { get; set; } public int ContractID { get; set; } public bool AuthJob { get; set; } public virtual Division Division { get; set; } public virtual AuthChain AuthChain { get; set; } public virtual Job Job { get; set; } public virtual Pension Pension { get; set; } public virtual AnalysisGrp AnalysisGrp { get; set; } public virtual CostGrp CostGrp { get; set; } public virtual Contract Contract { get; set; } public int Author { get; set; } public DateTime Created { get; set; } public string Action { get; set; } } public class Division { public int DivisionID { get; set; } public string Code { get; set; } public string Title { get; set; } public int Author { get; set; } public DateTime Created { get; set; } public string Action { get; set; } } public class AuthChain { public int AuthChainID { get; set; } public string RL01 { get; set; } public int RL01Emp { get; set; } public string RL02 { get; set; } public int RL02Emp { get; set; } public string RL03 { get; set; } public int RL03Emp { get; set; } public string RL04 { get; set; } public int RL04Emp { get; set; } public string RL05 { get; set; } public int RL05Emp { get; set; } public string RL06 { get; set; } public int RL06Emp { get; set; } public string RL07 { get; set; } public int RL07Emp { get; set; } public string RL08 { get; set; } public int RL08Emp { get; set; } public string RL09 { get; set; } public string RL09Emp { get; set; } public string RL10 { get; set; } public string RL10Emp { get; set; } public int Author { get; set; } public DateTime Created { get; set; } public string Action { get; set; } } public class Job { public int JobID { get; set; } public string Title { get; set; } public int Author { get; set; } public DateTime Created { get; set; } public string Action { get; set; } } public class Pension { public int PensionID { get; set; } public string Code { get; set; } public string Title { get; set; } public int Author { get; set; } public DateTime Created { get; set; } public string Action { get; set; } } public class AnalysisGrp { public int AnalysisGrpID { get; set; } public string Value { get; set; } public string Name { get; set; } public int Author { get; set; } public DateTime Created { get; set; } public string Action { get; set; } } public class CostGrp { public int CostGrpID { get; set; } public string Value { get; set; } public string Name { get; set; } public int Author { get; set; } public DateTime Created { get; set; } public string Action { get; set; } } public class Contract { public int ContractID { get; set; } public string Code { get; set; } public string Name { get; set; } public double Hours { get; set; } public double Weeks { get; set; } public int Author { get; set; } public DateTime Created { get; set; } public string Action { get; set; } } } </code></pre> <p>As I have said I am a beginner and I really need some help, I have been looking arround for a few weeks now and can't seem to find a full answer to help show me how to get this working.</p> <p>My ultimate aim is to implement some of the Extended EF 4.3 fucntions, I have done unitOfWork with Generic repository pattern, how ever I need to be able to audit and be able to view an archived history of changes.</p> <p>So for exmaple someone adds a new user in, then 5 changes are made by various people and finally the user is deleted. I want to be able to see who did something, what they did, the action they performed (create, update, delete) and finally the date/time they did this.</p> <p>Additionally I need to know the best way to implement a Business logic layer and where and how I can make functions to return data.</p> <p>So for example in a student records system, you might want to get the students for a specific Tutor in a specific course. Is it best to keep repeating these queries for every action or sub action e.g. another query could be grades for all students taught by a tutor on a particular course. Or is there a way the I should impletement a GetStudents(TutorID,CourseID) and if so where should these functions go? Would these be generic or is it common you have some generic and some entity specific and if so where do you put them, do they all go in the same class in your DAL folder or do they go in seperate clases or in fact is this what make up your business logic layer?</p> <p>I know there are a lot of questions here but I have a deadline coming up very soon and need to find a solution to achieve the above.</p> <p>I really apprciate any help and examples you can offer and here is a link to the nuget package <a href="http://efpatterns.codeplex.com/" rel="nofollow">http://efpatterns.codeplex.com/</a>,</p> <p>Andy</p>
[]
[ { "body": "<p>Your UnitOfWork class is unnessesary complicated and untestable, unreadable. If you are working with Entity Framework then you don't need to create your own UnitOfWork implementation because EF has its own.</p>\n\n<p>What you really need it is a container (<code>IRepositorContainer</code> with a generic Get method for example) which can instantiate (and maybe keep the instance for the lifetime of the AppDomain) the repository. You can use a generic Dictionary (<code>Dictionary&lt;Type, IEntityRepository&gt;</code>) for this and you will not need to hardcode all of your repository into your classes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T09:48:23.803", "Id": "21930", "Score": "0", "body": "Hi Peter, thanks for the advice, I am really new to all this please can you direct me towards an example or provide me with an example of what I need to change and how to use the suggested, based on my example code above?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T17:04:40.007", "Id": "21945", "Score": "0", "body": "Something like this: https://dl.dropbox.com/u/15497521/Repo.zip" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-19T15:34:27.657", "Id": "22322", "Score": "0", "body": "Thanks Peter that was very helpful, I am looking through my database patterns to see where I can clean things up a little. Also you have an IObjectRepository, do you have any examples of the type of thing you would put in here? And how would you recommend working with both generic and specific database actions. E.g. like you get() action, how would you structure having specifics like maybe GetUserEmail(int UserID)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-19T18:38:39.857", "Id": "22328", "Score": "0", "body": "The IObjectRepository interface only needed to store the repositories in the dictionary nothing more.\nIf you want a GetUserEmail(int uid) method you have the create a specific repo like the ProductRepository in my example." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T09:50:52.463", "Id": "13442", "ParentId": "13240", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T11:29:48.090", "Id": "13240", "Score": "2", "Tags": [ "c#", "asp.net", "entity-framework" ], "Title": "IAuditable and IArchivable Repository with Repository Pattern and UnitOfWork" }
13240
<p>I'm curious what people think about this little bit of logging code. It seems to work ok. Is there anything I'm missing?</p> <pre><code>public static class Logger { private static readonly object Locker = new object(); private static readonly StreamWriter Writer = new StreamWriter("c:\\temp\\logtester.log", true) ; public static void Log(string message) { Action&lt;string&gt; action = MessageWriter; action.BeginInvoke(message, null, null); } private static void MessageWriter(string message) { lock(Locker) { Writer.WriteLine(message); } } } </code></pre> <p>Using Jesse's code, but with <code>QueueUserWorkItem</code> instead of <code>BeginInvoke</code>.</p> <pre><code>public sealed class Logger : IDisposable { private static readonly object Locker = new object(); private static readonly StreamWriter Writer = new StreamWriter("c:\\temp\\logtester.log", true); private static bool _disposed; public static void Log(string message) { ThreadPool.QueueUserWorkItem(MessageWriter, message); } private static void MessageWriter(object message) { if (!(message is string)) return; lock (Locker) { Writer.WriteLine(message); } } ~Logger() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { lock (Locker) { if (_disposed) return; if (disposing) { if (Writer != null) Writer.Dispose(); } _disposed = true; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-16T11:56:09.563", "Id": "276620", "Score": "0", "body": "When do you actually call writer.Dispose so the writer writes?" } ]
[ { "body": "<p>Here's a slightly different version. It implements <code>IDisposable</code> so that the <code>StreamWriter</code> can eventually be closed and disposed properly and also uses a typed <code>delegate</code> for asynchronous invocation and properly calls <code>EndInvoke</code> upon completion.</p>\n\n<pre><code>public sealed class Logger : IDisposable\n{\n private delegate void WriteMessage(string message);\n private static readonly Logger Instance = new Logger(\"c:\\\\temp\\\\logtester.log\");\n private readonly object Locker = new object();\n private readonly StreamWriter Writer;\n private bool Disposed;\n\n private Logger(string logFileName)\n {\n Writer = new StreamWriter(logFileName, true);\n }\n\n ~Logger()\n {\n Dispose(false);\n }\n\n public static void Log(string message)\n {\n WriteMessage action = Instance.MessageWriter;\n action.BeginInvoke(message, MessageWriteComplete, action);\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n private static void MessageWriteComplete(IAsyncResult iar)\n {\n ((WriteMessage)iar.AsyncState).EndInvoke(iar);\n }\n\n private void Dispose(bool disposing)\n {\n lock (Locker)\n {\n if (Disposed)\n {\n return;\n }\n\n if (disposing)\n {\n if (Writer != null)\n {\n Writer.Dispose();\n }\n }\n\n Disposed = true;\n }\n }\n\n private void MessageWriter(string message)\n {\n lock (Locker)\n {\n if (!Disposed &amp;&amp; (Writer != null))\n {\n Writer.WriteLine(message);\n }\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T20:54:25.907", "Id": "21426", "Score": "0", "body": "Maybe using the threadpool would be more appropriate than using begininvoke? Since I don't care about a return value. I'll update the original question with this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T21:05:40.977", "Id": "21428", "Score": "0", "body": "`BeginInvoke` already uses the thread pool behind the scenes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T00:49:25.763", "Id": "21435", "Score": "0", "body": "Maybe using Tasks is a better approah?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T01:13:45.537", "Id": "21436", "Score": "0", "body": "That was going to be my first choice, but I need to use .net 3.5." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T06:34:33.543", "Id": "21437", "Score": "0", "body": "How to do this using tasks? http://codereview.stackexchange.com/questions/13263/file-async-writer-using-tasks-or-new-features-of-net-4-5" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-15T11:34:41.963", "Id": "52299", "Score": "0", "body": "Its a really really bad idea to close static Writer in the instance Dispose method and you're using instance Locker for locking static field!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-15T12:23:08.043", "Id": "52300", "Score": "0", "body": "The Writer is not static, you may be mistaken." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-15T12:30:29.817", "Id": "52301", "Score": "0", "body": "@jeremywho You should not be using Threads to do this sort of work. The write operation is a blocking operation and can keep threads from doing other important work. Async is the prefered method when working with I/O bound operations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-15T13:13:06.457", "Id": "52304", "Score": "0", "body": "@JesseC.Slicer My bad, in your implementation is not static but in jeremywho is static." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T16:44:52.467", "Id": "13250", "ParentId": "13248", "Score": "2" } }, { "body": "<p>There is a lot of issues in this code from my point of view.</p>\n\n<ul>\n<li>No error handling.</li>\n</ul>\n\n<p>Your writing operation could fail (insufficient space, security issues etc). In this case your log would bring down entire application.</p>\n\n<p>If you'll have an error in the following line of code:</p>\n\n<pre><code> private static readonly StreamWriter Writer = \n new StreamWriter(\"c:\\\\temp\\\\logtester.log\", true) ;\n</code></pre>\n\n<p>Your type would be marked as unsuable and client of your code will receive TypeLoadExpetion.</p>\n\n<ul>\n<li>Performance and responsiveness</li>\n</ul>\n\n<p>Usually loggers are build using some sort of queue. I can suggest to implement something like <a href=\"http://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem\" rel=\"nofollow\">Producer-Consumer queue</a>; In this case you can write or flush all the data in more paritucar times, because currently we can exhaust thread pool threads by calling Write method too many times.</p>\n\n<p>And as I mentioned at the comment it's not a good idea to close in Dispose method some static resources. In this case you can easily faced a situation when one instance would use already closed stream.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-18T06:54:44.080", "Id": "52548", "Score": "0", "body": "I purposefully left error handling out for readability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-18T07:01:27.030", "Id": "52550", "Score": "0", "body": "I purposefully left error handling out for readability. You're correct about everything mentioned. I was mostly curious about feedback on using the TPL/threadpool in that manner. If I was implementing something now in .Net 4.5, I would probably use a BlockingCollection and do async file i/o operations." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-15T11:43:41.047", "Id": "32707", "ParentId": "13248", "Score": "1" } } ]
{ "AcceptedAnswerId": "13250", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T16:03:11.080", "Id": "13248", "Score": "4", "Tags": [ "c#", ".net", "asynchronous" ], "Title": "Async file writer in .Net 3.5" }
13248
<p>I thought about the best way to implement localisation with runtime in Swing.</p> <p>I currently solve the problem like that:</p> <pre><code>JMenu menuData = new JMenu("Data"); menuData.setName("mainframe.menu.data"); // property key localeChangedListener.add(menuData); </code></pre> <p>The <code>LocaleChangedListener</code>:</p> <pre><code>public class SwingLocaleChangedListener implements LocaleChangedListener { private ArrayList&lt;AbstractButton&gt; abstractButtons; @Override public void localeChanged(ResourceBundle rb) { logger.info("Locale changed to '" + rb.getLocale() + "'"); for (AbstractButton b : abstractButtons) { b.setText(rb.getString(b.getName())); b.setComponentOrientation(ComponentOrientation.getOrientation(rb.getLocale())); //EDIT: Line added } } public boolean add(AbstractButton b) { initAbstractButtons(); return abstractButtons.add(b); } private void initAbstractButtons() { if (abstractButtons == null) { this.abstractButtons = new ArrayList&lt;AbstractButton&gt;(); } } } </code></pre> <p>And the registration of the <code>Listener</code>:</p> <pre><code>public class GuiBundleManager { private String filePrefix = "language.lang"; private ResourceBundle rb = null; private LocaleChangedListener listener = null; private static GuiBundleManager instance = null; private GuiBundleManager() { setLocale(Locale.getDefault()); } public String getString(String key) { return rb.getString(key); } public String[] getStringArray(String key) { return rb.getStringArray(key); } public Locale getLocale() { return rb.getLocale(); } public void setLocale(Locale l) { rb = ResourceBundle.getBundle(filePrefix, l); if (listener != null) { listener.localeChanged(rb); } } public LocaleChangedListener getLocaleChangedListener() { return listener; } public void setLocaleChangedListener(LocaleChangedListener listener) { this.listener = listener; if (listener != null) { listener.localeChanged(rb); } } public static GuiBundleManager get() { if (instance == null) { instance = new GuiBundleManager(); } return instance; } } </code></pre> <p>Another way I'm thinking of is using <code>Component.setLocale()</code> combined with an <code>PropertyChangedListener</code>:</p> <pre><code>public abstract class GUIComponentFactory { public JLabel createLocalisedJLabel(final String key) { final JLabel label = new JLabel(GuiBundleManager.get().getString(key)); label.addPropertyChangeListener("locale", new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { label.setText(GuiBundleManager.get().getString(key)); label.setComponentOrientation(ComponentOrientation.getOrientation(e.getNewValue())); //Edit: Line added for(Component c : getComponents()){ c.setLocale(e.getNewValue()); } } }); return label; } . . . } </code></pre>
[]
[ { "body": "<p>Consider <a href=\"http://docs.oracle.com/javase/7/docs/api/java/awt/Component.html#applyComponentOrientation%28java.awt.ComponentOrientation%29\" rel=\"nofollow noreferrer\"><code>applyComponentOrientation()</code></a>, which recursively \"Sets the <code>ComponentOrientation</code> property of this component and all components contained within it.\" Examples may be found <a href=\"https://stackoverflow.com/questions/6475320\">here</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T18:39:37.510", "Id": "21464", "Score": "0", "body": "I think I'll implement the PropertyChangedListener structure. This way seems more flexible to me" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T19:29:42.840", "Id": "21470", "Score": "0", "body": "Agree; it's included in every `Component`. Do you have any `i18n` plans?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T19:40:46.983", "Id": "21471", "Score": "0", "body": "I have a method in GuiBundleManager that list all locates with existing properties File (and you can change at runtime) - is this what you mean?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T19:42:06.317", "Id": "21472", "Score": "0", "body": "Yes; skimmed right past it! :-)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T18:36:40.817", "Id": "13253", "ParentId": "13251", "Score": "3" } }, { "body": "<p>Whatever approach you finally decide upon: you don't have to handle the resourceBundles yourself. Instead, add them to the UIManager and query that for the localized values:</p>\n\n<pre><code>// edited: it's the defaults which take the bundle, my bad I didn't check core api\n// SwingX has a UIManagerExt which takes it directly :-)\nUIManager.getDefaults().addResourceBundle(\"com.xypackage.resources.MyBundle\");\n...\nlabel.setText(UIManager.get(key, label.getLocale());\n</code></pre>\n\n<p>There used to be (didn't check if it's fixed) a bug which prevented this to work reliably in webstartables. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T10:59:52.503", "Id": "21543", "Score": "0", "body": "UIManager.addResourceBundle() does not exist in my Java version (1.7) |||| but UIManager.getDefaults().addResourceBundle(bundleName) does" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T11:13:09.530", "Id": "21544", "Score": "0", "body": "And this is also a problem: public Object get(Object key, Locale l) {\n Object value = getFromHashtable( key );\n return (value != null) ? value : getFromResourceBundle(key, l);\n }" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T11:21:29.257", "Id": "21545", "Score": "0", "body": "this means that it only returns the message of the first .properties and ignores the given Locale" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T11:48:59.620", "Id": "21547", "Score": "0", "body": "darn, you are right with your first comment (will edit). Don't understand your conclusion: the lookup will return the most fitting value for the given locale, falling down from the most specific to the base." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T12:50:11.413", "Id": "21549", "Score": "0", "body": "UIManager.get(key, Locale.GERMAN) and UIManager.get(key, Locale.ENGLISH) return the same value (the German one)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T13:56:17.083", "Id": "21556", "Score": "0", "body": "do you have a _en properties file (assuming your default locale is German)? If not, you have to add it: the \"second-last-resort\" fallback is the default locale's property, not the base. For a complete description, see ResourceBundle.get(..). If you have one, something else goes wrong, the lookup in the UIManager should work (haha, optimistic me :-) Best show a SSCCE so we can reproduce the problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T16:11:38.657", "Id": "21567", "Score": "0", "body": "the problem was that my .propertis had names like 'lang_de_DE.properties' and I used Loclale.GERMAN. I changed the filenames to 'lang_de.properties' and now it works" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T13:55:46.963", "Id": "13314", "ParentId": "13251", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T18:00:25.847", "Id": "13251", "Score": "4", "Tags": [ "java", "swing", "localization" ], "Title": "Working with Locales in Swing (with change at runtime)?" }
13251
<p>I am new to PHP so this is largely compiled from examples around the web. It seems to work fine. Are there any ways in which it can be improved upon? Is it secure?</p> <pre><code>&lt;?php mysql_connect("localhost", "myusername", "mypassword"); mysql_select_db("companyDB"); function user_login($username, $password) { ob_start(); $username = mysql_real_escape_string($username); $password = md5($password); $sql = "select * from users where username='$username' and password ='$password' LIMIT 1"; $result = mysql_query($sql) or die('Please change your mysql query !'); if(mysql_num_rows($result) &gt; 0) { $_SESSION['username'] = $username; $_SESSION['loggedin'] = true; $row = mysql_fetch_row($result); $access_level = $row[4]; $_SESSION['accessLevel'] = $access_level; while (ob_get_status()) { ob_end_clean(); } header("Location: /index.php"); } else { } } ?&gt; </code></pre>
[]
[ { "body": "<p>Well, <code>mysql()</code> is being deprecated, so be aware of that. <code>mysqli()</code> and <code>pdo()</code> are the new standards. I'd say continue learning on the old one, everything you learn can be translated to the new.</p>\n\n<p>When connecting to a database, it is best to give that connection a name, such as <code>$conn</code> so that it can be referenced later. This is so that you can specify which connection you wish to use when selecting databases, or if you need to check if the connection is successful. Same for selecting the database. So...</p>\n\n<pre><code>$conn = mysql_connect(\"localhost\", \"myusername\", \"mypassword\");\nif( ! $conn ) {\n //handle error and exit script...\n}\n\n$companyDB = mysql_select_db(\"companyDB\", $conn);\nif( ! $companyDB ) {\n //handle error and exit script...\n}\n</code></pre>\n\n<p>You've started output buffering (<code>ob_start()</code>), but not done anything with it except clear it. Usually you'll want to examine the output for errors, or dump it directly onto the page before clearing it. But for a \"first\" script this is fine. Just be aware that there is more to it than just starting and clearing.</p>\n\n<p>Try to avoid <code>or die()</code> short circuiting. It works but was not intended for this purpose. <code>die()</code> shouldn't even be in live environments, its meant as a debugging tool. Instead you should handle any errors more elegantly, such as displaying what happened, logging errors, etc...</p>\n\n<p>Be careful of magic numbers. You've told us that <code>$row[4]</code> is the access level, but why? What if it changes? This should probably be grabbed with a more specific SQL statement. I'm not much of SQL guy, so I can't help you out here, but I imagine there should be a better way.</p>\n\n<p>Location headers should be terminated with <code>exit</code> afterwards to prevent the rest of the script from running.</p>\n\n<p>If you don't have anything to put in an else block, then there is no need to declare one.</p>\n\n<p>You also need to close connections to your mysql using <code>mysql_close()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T19:19:26.920", "Id": "13254", "ParentId": "13252", "Score": "1" } } ]
{ "AcceptedAnswerId": "13254", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T18:23:45.900", "Id": "13252", "Score": "0", "Tags": [ "php", "beginner", "mysql", "security" ], "Title": "Connect and login to MySQL database" }
13252
<p>I have read about it at a few places and tried to write my own version. I would like to get it reviewed. </p> <pre><code>class Node { private int value; private Node left; private Node right // getters and setters } </code></pre> <hr> <pre><code>public class DeleteNodeBST { Node parent = null; boolean deleteNodeBST(Node node, int value) { if (node == null) { return false; } if (node.getValue() == value) { if ((node.getLeft() == null) &amp;&amp; (node.getRight() == null)) { // leaf node node = null; return true; } if ((node.getLeft() != null) &amp;&amp; (node.getRight() != null)) { // node with two children node.setValue(findMinimumAndReturnWithDelete(node.getRight())); return true; } // either left child or right child if (node.getLeft() != null) { parent.setLeft(node.getLeft()); node = null; return true; } if (node.getRight() != null) { parent.setRight(node.getRight()); node = null; return true; } } parent = node; if (node.getValue() &gt; value) { return deleteNodeBST(node.getLeft(), value); } else { return deleteNodeBST(node.getRight(), value); } } int findMinimumAndReturnWithDelete(Node node) { if (node.getLeft() == null) { int v = node.getValue(); node = null; return v; } return findMinimumAndReturnWithDelete(node.getLeft()); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T21:00:38.717", "Id": "21427", "Score": "1", "body": "there are compile errors... missing a semicolon `;` after `right`... missing a return type (`boolean`) before `deleteNodeBST(Node node, int value)`... `node == null;` is a condition so it can't be used as a statement, did you mean `node = null;`? and the last line has to be `return findMinimumAndReturnWithDelete(node.getLeft());` because **all code paths have to return a value**. And what the hell is `node.setValue() = findMinimumAndReturnWithDelete(node.getRight());`? you're assigning a value to a method? surely you meant node.setValue(findMinimumAndReturnWithDelete(node.getRight()));" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T21:12:14.623", "Id": "21429", "Score": "0", "body": "ahh @codesparkle, this is just a pesudo code, I am sorry not being specific" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T21:14:04.113", "Id": "21430", "Score": "0", "body": "the [faq] requires real code as opposed to pseudo-code. And even as pseudo-code, leaving out the returns makes no sense. If you like I'll paste in a compiling version of your code..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T21:14:57.693", "Id": "21431", "Score": "0", "body": "sure, would like to see the version" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T21:19:58.027", "Id": "21432", "Score": "0", "body": "I've [proposed an edit](http://codereview.stackexchange.com/suggested-edits/1148), but that still needs to be accepted by a mod. Note that though this satisfies the compiler, I by no means have any idea whether it actually runs properly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T21:28:11.350", "Id": "21433", "Score": "0", "body": "correctness of program is what I am interested in :). thnks for your edit" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-12T05:04:54.533", "Id": "196659", "Score": "0", "body": "nicely explained: http://javabypatel.blogspot.in/2015/08/delete-a-node-from-binary-search-tree-in-java.html" } ]
[ { "body": "<p>Here is how I would do this. I've sprinkled comments throughout the code, so hopefully this will be helpful.</p>\n\n<pre><code>//generalize the node to work for types other than just int\npublic class Node&lt;T extends Comparable&lt;? super T&gt; &gt;\n{\n private T value; //get; set;\n private Node&lt;T&gt; left; //get; set;\n private Node&lt;T&gt; right; //get; set;\n\n /**\n * construct a Node with value\n *\n * @param val value for this node\n */\n public Node(T val)\n {\n value = val;\n left = null;\n right = null;\n }\n\n /**\n * copy constructor\n * \n * @param n node to copy from\n */\n public Node(Node&lt;T&gt; n)\n {\n value = n.value;\n left = n.left;\n right = n.right;\n }\n\n /**\n * @return true if this node has no children\n */\n public boolean isLeaf()\n {\n return (left == null &amp;&amp; right == null);\n }\n\n public Node&lt;T&gt; getLeft() { return left; }\n public Node&lt;T&gt; getRight() { return right; }\n public T getValue() { return value; }\n public void setLeft(Node&lt;T&gt; n) { left = n; }\n public void setRight(Node&lt;T&gt; n) { right = n; }\n public void setValue(T v) { value = v; }\n}\n</code></pre>\n\n<p>And the BST. Since it doesn't really make sense to delete without being able to add nodes to the tree first, I've put in adding as well.</p>\n\n<pre><code>public class DeleteNodeBST&lt;T extends Comparable&lt;? super T&gt; &gt;\n{\n private Node&lt;T&gt; root = null;\n private int nodes = 0; //get;\n\n /**\n * add a node to the tree\n *\n * @param n node to add\n * @return true if add is successful\n */\n public boolean add(final Node&lt;T&gt; n)\n {\n //null guard\n if (n == null || n.getValue() == null)\n {\n return false;\n }\n\n boolean isSuccessful;\n if (root == null)\n {\n root = n;\n ++nodes;\n isSuccessful = true;\n }\n else\n {\n isSuccessful = findHome(root, n);\n }\n\n return isSuccessful;\n }\n\n /**\n * create a node containing input value and add it to the tree\n * \n * @param val value for new node\n * @return true if add is successful\n */\n public boolean add(final T val)\n {\n return add( new Node&lt;T&gt;(val) );\n }\n\n /**\n * attempt to place a node under another\n * \n * @param adoptor node to look under\n * @param adoptee child node looking for a home\n * @return true if child node finds a place, otherwise false\n */\n private boolean findHome(Node&lt;T&gt; adoptor, final Node&lt;T&gt; adoptee)\n {\n int comp = adoptor.getValue().compareTo( adoptee.getValue() );\n\n if (comp &gt; 0) //adoptor comps greater than adoptee, so go left\n {\n if (adoptor.getLeft() == null)\n {\n adoptor.setLeft(adoptee);\n ++nodes;\n return true;\n }\n //recurse until we find somewhere to place the adoptee node\n return findHome(adoptor.getLeft(), adoptee);\n }\n else if (comp &lt; 0) //adoptor comps less than adoptee, so go right\n {\n if (adoptor.getRight() == null)\n {\n adoptor.setRight(adoptee);\n ++nodes;\n return true;\n }\n //recurse until we find somewhere to place the adoptee node\n return findHome(adoptor.getRight(), adoptee);\n }\n\n return false;\n }\n\n /**\n * attempts to delete a node from the tree\n * \n * @param n node to delete\n * @return true if node is deleted, otherwise false\n */\n public boolean delete(Node&lt;T&gt; n)\n {\n //null guard\n if (n == null || n.getValue() == null)\n {\n return false;\n }\n\n return delete( n.getValue() );\n }\n\n /**\n * attempts to delete a node from the tree containing the value\n * \n * @param val value of node to delete\n * @return true if node is deleted, otherwise false\n */\n public boolean delete(final T val)\n {\n //the node to be deleted\n Node&lt;T&gt; target = null;\n //to keep track of parent node\n Node&lt;T&gt; parent = null;\n //variable node reference\n Node&lt;T&gt; node = root;\n\n while (node != null)\n {\n if (val.compareTo( node.getValue() ) == 0) //eureka!\n {\n target = node;\n break;\n }\n else if (val.compareTo( node.getValue() ) &gt; 0) //target greater, so go right\n {\n parent = node;\n node = node.getRight();\n }\n else //target less, so go left\n {\n parent = node;\n node = node.getLeft();\n }\n }\n\n if (target == null)\n {\n //target not found\n return false;\n }\n\n boolean isLeft = (target == parent.getLeft() );\n\n if (target == root) //the node that's baleeting is in fact the root node\n {\n //get last house on the left on the right!\n //it becomes the new root\n node = getLastHouseOnTheLeft( parent.getRight() );\n if (node != null)\n {\n node.setLeft( parent.getLeft() );\n node.setRight( parent.getRight() );\n root = node;\n }\n }\n else if ( target.isLeaf() )\n {\n if (isLeft)\n {\n parent.setLeft(null);\n }\n else\n {\n parent.setRight(null);\n }\n }\n else if (target.getLeft() != null &amp;&amp; target.getRight() != null) //two children, some shuffling\n {\n if (isLeft)\n {\n parent.setLeft( target.getRight() );\n parent.getLeft().setLeft( target.getLeft() );\n }\n else\n {\n parent.setRight( target.getRight() );\n parent.getRight().setLeft( target.getLeft() );\n }\n }\n else //one child is simpler\n {\n if (target.getLeft() == null)\n {\n if (isLeft)\n {\n parent.setLeft( target.getLeft() );\n }\n else\n {\n parent.setRight( target.getLeft() );\n }\n }\n else\n {\n if (isLeft)\n {\n parent.setLeft( target.getRight() );\n }\n else\n {\n parent.setRight( target.getRight() );\n }\n }\n }\n\n return true; //baleeted\n }\n\n /**\n * extract the last house on the left\n * \n * @param start the node to start on\n * @return the last house on the left\n */\n private Node&lt;T&gt; getLastHouseOnTheLeft(final Node&lt;T&gt; start)\n {\n Node&lt;T&gt; candidate = null;\n Node&lt;T&gt; parent = null;\n Node&lt;T&gt; node = start;\n\n while (node != null)\n {\n if ( node.getLeft() != null )\n {\n parent = node;\n candidate = node.getLeft();\n }\n\n node = node.getLeft();\n }\n\n if (parent != null)\n {\n parent.setLeft(null);\n }\n\n return candidate;\n }\n\n /**\n * get a node from the value it's associated with\n * \n * @param v value as a key to finding the node containing it\n * @return node associated with the value\n */\n public Node&lt;T&gt; getNode(T v)\n {\n //null guard\n if (v == null)\n {\n return null;\n }\n\n Node&lt;T&gt; node = root;\n int comp;\n while (root != null)\n {\n comp = node.getValue().compareTo(v);\n if (comp == 0)\n {\n return node;\n }\n if (comp &gt; 0)\n {\n node = node.getLeft();\n }\n else\n {\n node = node.getRight();\n }\n }\n\n return node;\n }\n</code></pre>\n\n<p>Finally, some simple test cases, plus an example graph:</p>\n\n<pre><code>import static org.junit.Assert.*;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\npublic class TestDeleteNodeBST\n{\n DeleteNodeBST&lt;Integer&gt; delBst;\n Node&lt;Integer&gt; node;\n\n @Before\n public void init()\n {\n delBst = new DeleteNodeBST&lt;Integer&gt;();\n\n assertTrue(delBst.getNumberOfNodes() == 0);\n }\n\n @Test\n public void testAddNode()\n {\n node = new Node&lt;Integer&gt;(1);\n assertTrue(node.getValue() == 1);\n assertTrue(node.getLeft() == null);\n assertTrue(node.getRight() == null);\n\n delBst.add(node);\n assertTrue(delBst.getNumberOfNodes() == 1);\n\n Integer two = 2;\n assertTrue( two &gt; node.getValue() );\n assertTrue( two.compareTo(node.getValue() ) &gt; 0 );\n\n delBst.add(two);\n assertTrue(delBst.getNumberOfNodes() == 2);\n assertTrue( delBst.getNode(2).getValue().equals(2) );\n }\n\n @Test\n public void testCorrectness()\n {\n delBst.add(5);\n delBst.add(4);\n delBst.add(3);\n delBst.add(2);\n delBst.add(1);\n delBst.add(0);\n assertTrue(delBst.getNumberOfNodes() == 6);\n\n node = delBst.getNode(3);\n assertTrue(node.getValue() == 3);\n }\n\n @Test\n public void testDeleteNode()\n {\n delBst.add(5);\n delBst.add(4);\n delBst.add(6);\n delBst.add(7);\n delBst.add(2);\n delBst.add(3);\n delBst.add(1);\n /*\n * tree should look like this now\n * 5\n * 4 6\n * 2 7\n * 1 3\n */\n assertTrue( delBst.delete(2) ); //3 should take 2's place\n assertFalse( delBst.delete(2) );//nothing to delete now\n node = delBst.getNode(3);\n assertTrue(node.getValue() == 3);\n assertTrue(node.getRight() == null);\n assertTrue(node.getLeft().getValue() == 1);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-24T17:04:49.353", "Id": "45541", "Score": "2", "body": "I think it would be good if `Node` class doesn't have a `Node`, rather make a `Tree` class which contains `Node`s." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T07:02:27.020", "Id": "13386", "ParentId": "13255", "Score": "8" } }, { "body": "<p>I discovered a bug: your code failed when I tried to delete the node for the root (<code>value=5</code>).\nIn the delete function, the <code>parent.getLeft()</code> method causes a <code>NullPointerException</code> since <code>parent</code> is null. This is the offending line:</p>\n\n<pre><code>boolean isLeft = (target == parent.getLeft());\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T18:50:42.810", "Id": "39291", "Score": "0", "body": "This is not a suggestion on how to improve the code in question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T02:07:47.187", "Id": "39308", "Score": "1", "body": "@svick, isn't it? It's poorly written yes, but it is trying to point a bug I think." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T18:24:11.623", "Id": "25347", "ParentId": "13255", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T20:43:13.363", "Id": "13255", "Score": "4", "Tags": [ "java", "algorithm", "interview-questions", "tree", "binary-search" ], "Title": "Deleting a node from a binary search tree" }
13255
<p>There is a function with bunch of a redundant <code>let</code>s and <code>←</code>s inside a list monad. </p> <pre><code>example ∷ (Int, Int, Int, Int, Int) example = head $ do let list1 = [0,1] e1 ← list1 let list2 = φ list1 e1 e2 ← list2 let list3 = φ list2 e2 e3 ← list3 let list4 = φ list3 e3 e4 ← list4 let list5 = φ list4 e4 e5 ← list5 return (e1,e2,e3,e4,e5) where φ ∷ [Int] → Int → [Int] </code></pre> <p>So, all <code>list#</code> values are unusable. How can <code>example</code> could be rewritten with <code>&gt;&gt;=</code> or maybe with something else to get <code>(e1,e2,e3,e4,e5)</code> without any <code>let</code>s?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-16T19:38:41.083", "Id": "240324", "Score": "0", "body": "I'm not quite sure why this question was closed with such a reason, the code looks pretty real and it could be compiled" } ]
[ { "body": "<p>Hm, this could probably be done using <code>foldM</code> or similar, but that would require you to convert to and from lists. My first impulse would be to try to write the top-level of <code>example</code> using Applicative style:</p>\n\n<pre><code>import Control.Applicative\n\nexample = head $ (,,,,) &lt;$&gt; m &lt;*&gt; m &lt;*&gt; m &lt;*&gt; m &lt;*&gt; m\n</code></pre>\n\n<p>But that doesn't work directly here, as you want each <code>m</code> to know the <code>list#</code> of the last action.</p>\n\n<p>One way to realize this without breaking up the above structure would be to have a <code>StateT</code> monad transformer take care of passing around the current <code>list#</code>:</p>\n\n<pre><code>import Control.Monad.State\n\nexample = head $ flip evalStateT [0,1] $\n (,,,,) &lt;$&gt; m &lt;*&gt; m &lt;*&gt; m &lt;*&gt; m &lt;*&gt; m\n</code></pre>\n\n<p>This allows us to write <code>m</code> as a list monad with state:</p>\n\n<pre><code> where m :: StateT [Int] [] Int\n m = do list &lt;- get\n e &lt;- lift list\n put (phi list e)\n return e\n</code></pre>\n\n<p>Now admittedly, this is a bit advanced. It might be easier to try to restructure <code>phi</code> or use a <code>foldM</code> type solution.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T15:35:09.707", "Id": "13286", "ParentId": "13256", "Score": "6" } } ]
{ "AcceptedAnswerId": "13286", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T22:07:44.040", "Id": "13256", "Score": "9", "Tags": [ "haskell" ], "Title": "Redundant `let`s in list monadic code" }
13256
<p>Is this JavaScript code robust? It is for an interactive book about a card game. When the reader clicks on the checkbox, an answer is revealed and related text is highlighted. I need to get this right before I write <a href="http://keepcount.net/ebook/01-09/02_tricks.html" rel="nofollow noreferrer">more chapters</a>.</p> <p><a href="http://jsbin.com/ojukox/2/edit#javascript,html,live" rel="nofollow noreferrer">JSBin</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Quiz&lt;/title&gt; &lt;script&gt; function hlt_showhide(EEE){ "use strict"; var xxx = EEE.getAttribute('answer'); var win_num = "win" + xxx; var e2 = document.getElementsByName(win_num); var countE2 = e2.length; for (var i = 0; i &lt; countE2; i++) { e2[i].style.backgroundColor = (EEE.checked) ? "#FFCC66" : "#FFFFFF"; } var ans_num = "ans" + xxx; var AAA = document.getElementById(ans_num); if (AAA !== null) { AAA.style.visibility = (EEE.checked) ? "visible" : "hidden"; } } &lt;/script&gt; &lt;style type="text/css"&gt; .ansText {visibility: hidden} &lt;/style&gt; &lt;/head&gt; &lt;form name="form1"&gt; &lt;!-- Question 1 --&gt; Q1: 3 &lt;span id="win1" name="win1"&gt; 5 &lt;/span&gt; &lt;span id="win1" name="win1"&gt; 10 &lt;/span&gt; &lt;span class="click"&gt; Click&lt;/span&gt; &lt;input onclick="hlt_showhide(this)" type="checkbox" name="" answer="1"&gt; &lt;!-- Answer 1 --&gt; A1: &lt;span id="ans1" class="ansText"&gt; revealed text refers to 2nd &amp; 3rd highlighted numbers &lt;/span&gt; &lt;hr id="q_a"&gt; &lt;!-- Question 2 --&gt; Q2: &lt;span id="win2" name="win2"&gt; 7 &lt;/span&gt; 28 &lt;span id="win2" name="win2"&gt; 37 &lt;/span&gt; &lt;span class="click"&gt; Click&lt;/span&gt; &lt;input onclick="hlt_showhide(this)" type="checkbox" name="" answer="2"&gt; &lt;!-- Answer 2 --&gt; A2: &lt;span id="ans2" class="ansText"&gt; revealed text refers to 1st &amp; 3rd highlighted numbers&lt;/span&gt; &lt;hr id="q_a"&gt; &lt;/form&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>Here are my thoughts:</p>\n\n<ol>\n<li><p>Most importantly from the first look at the code: Use proper variable names. No one knows what you mean with <code>EEE</code>, <code>xxx</code> or <code>e2</code>. And while you are at it: in JavaScript it's a convention to start variable names with a lower case letter.</p></li>\n<li><p>Don't make up attributes such as \"answer\" - you can't say if an unknown browser can work with them. At least you should adhere to <a href=\"http://www.w3.org/TR/html5/global-attributes.html#embedding-custom-non-visible-data-with-the-data-attributes\" rel=\"nofollow\">HTML5 and prefix the custom attribute with <code>data-</code></a>. </p></li>\n<li><p><code>name</code> is not a valid attribute for <code>span</code> (or any other object other than form elements). Unfortunately there is no simple, cross-browser alternative for selecting multiple elements. The easiest soltuion with be to use a <code>class</code> and <a href=\"https://developer.mozilla.org/en/DOM/document.getElementsByClassName\" rel=\"nofollow\"><code>getElementsByClassName</code></a>, however the latter isn't supported by all browsers yet, but there are implementations for the non-supporters easily available on the web.</p></li>\n<li><p>The \"Click\" text is bad for two reasons: A) You can't actually click on it and B) texts such as \"click here\" is bad UI. Instead wrap the text together with the checkbox in a <code>&lt;label&gt;</code> element, such allows the user to click on the text to activate the checkbox and use a text such as \"Show solution\" instead.</p></li>\n<li><p>Finally, there are more elegant ways to switch on the answers. Instead of looking of a specifc ID, set (or remove) a class on an element surrounding the question and use CSS to highlight/show the sub elements. Example: <a href=\"http://jsbin.com/ayoqem/7/edit\" rel=\"nofollow\">http://jsbin.com/ayoqem/7/edit</a></p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T13:46:39.280", "Id": "13274", "ParentId": "13257", "Score": "2" } } ]
{ "AcceptedAnswerId": "13274", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T22:20:11.777", "Id": "13257", "Score": "2", "Tags": [ "javascript", "css" ], "Title": "Click textbox to show answer and highlight related text" }
13257
<p>Below are the bunch of functions which I wrote to determine paths between give coordinates of a square tile-based game. It permits paths between tiles in 4 directions (i.e. not 8 directions/diagonal paths).</p> <p>It can be pretty resource-intensive when the path is long, especially if the target is unreachable (on large maps (~10,000 tiles) it literally causes Firefox to hang for several seconds in this case).</p> <p>So far I'm very happy with the results it yields but not so much its performance. One aspect I'd like to try to improve is the repeated sorting of the closed_tile array.</p> <pre><code>// Some example variables: var terrain_tile_types = [ ["",[0,0,0,0]], // Not really a tile (invisible/unselectable) ["Flat grass",[1,0,0,1]], // ID: 1 ["Water",[0,1,1,1]] // ID: 2 ]; var unit_types = [ ["Unit type 1",[10,0.1,null],0,1] ]; var terrain_map = [[2,2,2,2,2],[1,1,1,2,2],[1,1,2,2,2],[1,2,2,1,1]]; function calc_h(start,end){ // start,end: [locI,locJ] // Estimates the cost of moving from given tile to end return Math.abs(end[0]-start[0])+Math.abs(end[1]-start[1]); } function is_in_array(needleCoords,haystack){ // Where haystack is an array of randomly-arranged coordinate arrays, (e.g. [[1,1,28.72,...],[0,2,43.2,...]]) // And needleCoords is an array with coords to find (e.g. [0,1]). // Returns index if found for(n in haystack){ if(haystack[n][0]==needleCoords[0] &amp;&amp; haystack[n][1]==needleCoords[1]) return n; } return false; } function reconstruct_path(end,closed_tiles){ var path=[]; var current_tile=closed_tiles[is_in_array(end,closed_tiles)]; while(current_tile[5][0]!=current_tile[0] || current_tile[5][1]!=current_tile[1]){ path=path.concat([ [current_tile[0],current_tile[1]] ]); current_tile=closed_tiles[is_in_array(current_tile[5],closed_tiles)]; } path.reverse(); return path; } function pathfind(start,end,mobility_type,substitute_map){ // start = start coords array, end = end coords array // mobility_type = determines which type of tiles are "walkable" based on the moving unit's type - will be an integer index o // substitute_map = optional map array to use instead of the default (terrain_map) pathfind_map = typeof substitute_map !== 'undefined' ? substitute_map : terrain_map; mobility_type = typeof mobility_type !== 'undefined' ? mobility_type : 0; // Able to walk on end tile? If not return false if(terrain_tile_types[terrain_map[end[0]][end[1]]][1][mobility_type]!=1) return false; // Validate start and end arrays if(start.length!=2 || end.length!=2 || start[0]!==+start[0] || start[0]!==(start[0]|0) || start[1]!==+start[1] || start[1]!==(start[1]|0) || end[0]!==+end[0] || end[0]!==(end[0]|0) || end[1]!==+end[1] || end[1]!==(end[1]|0)) return false; // Add g, h and f values (and parent = start) start=start.concat([0,calc_h(start,end)]); start=start.concat([(start[2]+start[3])]); start=start.concat([start]); var open_tiles=[start]; // Structure: [[locI,locJ,g,h,f,[parent]]] var closed_tiles=[]; // Structure: [[locI,locJ,g,h,f,[parent]]] while(open_tiles.length&gt;0){ // Order open_tiles by f value (smallest) open_tiles.sort(function(a,b){return a[4]-b[4];}); // Add tile to closed list closed_tiles[closed_tiles.length]=open_tiles[0]; if(end[0]==open_tiles[0][0] &amp;&amp; end[1]==open_tiles[0][1]){ // Path found, finish. return reconstruct_path(end,closed_tiles); } // 4-surrounding tiles: var surrounding_tiles=[[open_tiles[0][0]-1,open_tiles[0][1],false],[open_tiles[0][0],open_tiles[0][1]-1,false],[open_tiles[0][0],open_tiles[0][1]+1,false],[open_tiles[0][0]+1,open_tiles[0][1],false]]; for (q in surrounding_tiles){ if(pathfind_map[surrounding_tiles[q][0]]!=undefined &amp;&amp; pathfind_map[surrounding_tiles[q][0]][surrounding_tiles[q][1]]!=undefined &amp;&amp; terrain_tile_types[pathfind_map[surrounding_tiles[q][0]][surrounding_tiles[q][1]]]!=undefined &amp;&amp; is_in_array(surrounding_tiles[q],closed_tiles)===false){ // Not able to cross this terrain? if(terrain_tile_types[pathfind_map[surrounding_tiles[q][0]][surrounding_tiles[q][1]]][1][mobility_type]!=1) continue; var status=is_in_array(surrounding_tiles[q],open_tiles); if(status!==false){ // Tile already found in open list if((open_tiles[0][2]+(surrounding_tiles[2]?14:10))&lt;open_tiles[status][2]){ // This new path is better. Update open list entry open_tiles[status][2]=(open_tiles[0][2]+(surrounding_tiles[2]?14:10)); open_tiles[status][4]=open_tiles[status][2]+open_tiles[status][3]; open_tiles[status][5]=[open_tiles[0][0],open_tiles[0][1]]; } }else{ // Tile wasn't found in open list, so add it now var tile_info_to_add=[surrounding_tiles[q][0],surrounding_tiles[q][1],(open_tiles[0][2]+(surrounding_tiles[2]?14:10)),calc_h(surrounding_tiles[q],end)]; tile_info_to_add=tile_info_to_add.concat([tile_info_to_add[2]+tile_info_to_add[3],[open_tiles[0][0],open_tiles[0][1]]]); open_tiles=open_tiles.concat([tile_info_to_add]); } } } // Remove tile from list (shift removes first element from array) open_tiles.shift(); } // No valid path found from start to end return false; } </code></pre> <p>Here's a question I asked earlier about optimising the is_in_array() function: <a href="https://stackoverflow.com/questions/11300249/javascript-return-position-index-of-matched-array-within-array">https://stackoverflow.com/questions/11300249/javascript-return-position-index-of-matched-array-within-array</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T18:58:16.863", "Id": "21687", "Score": "0", "body": "I'm intrigued too, and would love to work on this as well. But without slightly more readable source or a somewhat more instructive problem description, I'm not willing to put in the work to understand exactly what you're working on. Any chance you could draw us some pictures that would help explain and post them somewhere?" } ]
[ { "body": "<p>I know you are asking about performance but I'd like to suggest some readability changes.<br>\nLists are good for lists of things not for keeping properties in. </p>\n\n<p>for example:</p>\n\n<pre><code> var terrain_tile_types = [\n [\"\",[0,0,0,0]], // Not really a tile (invisible/unselectable)\n [\"Flat grass\",[1,0,0,1]], // ID: 1\n [\"Water\",[0,1,1,1]] // ID: 2\n ];\n</code></pre>\n\n<p>could be an object/list of objects:</p>\n\n<pre><code> var terrain_tile_types = {\n \"INV\" : { \"description\" : \"invisible/unselectable\", \"other_property\": 0, \"another_property\": 0, \"mobility_type\": {\"walking\": false, \"swimming\":false, \"flying\":false} } // ID = \"INV\"\n \"FLATGRASS\" : { \"description\": \"Flat Grass\", \"other_property\": 1, \"another_property\": 0\", mobility_type\": {\"walking\": true, \"swimming\":false, \"flying\":true} } // ID = \"FLATGRASS\"\n \"H2O\": { \"description\": \"Water\", \"other_property\": 0, \"another_property\": 1, \"mobility_type\": {\"walking\": false, \"swimming\":true, \"flying\":true} } // ID = \"H2O\"}\n };\n</code></pre>\n\n<p>This way when you read the code it actually makes sense what you are accessing. Less need for magic numbers? </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T16:36:05.957", "Id": "21461", "Score": "0", "body": "I would like to do this, but do you think it will cause a noticeable impact on performance? Most Google results for \"javascript object vs array performance\" show objects manipulation as being orders of magnitude slower than array manipulation, although I don't know how much this would matter in the scheme of things." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T23:48:46.253", "Id": "21481", "Score": "1", "body": "@Alex I would suggest that readability is a bigger issue." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T01:28:07.467", "Id": "13260", "ParentId": "13258", "Score": "4" } }, { "body": "<p>Also not necessarily concerning performance:</p>\n\n<ul>\n<li>First off: Never use <code>for..in</code> on arrays, it doesn't do what you think it does.</li>\n<li>The code isn't really readable. The \"magic arrays\" aren't nice (see James' suggestion), and the long, long lines don't really help either.</li>\n<li>A working example (eg with jsfiddle) with some explanation how to call your code would be helpfull,</li>\n<li>To speed up the array search, it may be worth trying implementing coordinates as objects with an integer hash value, which should help comparisons.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T18:46:19.147", "Id": "21467", "Score": "0", "body": "Thanks for these suggestions. Just replaced the two `for..in` loops with `for ..;..;..` ones and am noticing a very significant performance increase (Firefox 13 at least)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T14:09:47.287", "Id": "13277", "ParentId": "13258", "Score": "6" } }, { "body": "<p>I have made the <code>current_tile</code> arrays into objects so that it this is easier to edit. I doubt it makes enough of a difference to be noticeable. That is, I replaced <code>[[i, j], g, h, f, [parent]]</code> with a structure <code>{i, g, h, f, p}</code>. It may be worthwhile to change them back though.</p>\n\n<h2>Reduce comparisons by navigating a 1 dimensional model of the map instead.</h2>\n\n<p>When you call <code>pathfind</code> you can generate a set of <code>mobility_tiles</code> for a given map.\nFor the terrain_map provided and a mobility index of 0, this would be the following array:</p>\n\n<pre><code>[\n 0, 0,0,0,0,0 ,0,\n\n 0, 0,0,0,0,0 ,0,\n 0, 1,1,1,0,0 ,0,\n 0, 1,1,0,0,0 ,0,\n 0, 1,0,0,1,1 ,0,\n\n 0, 0,0,0,0,0 ,0\n]\n</code></pre>\n\n<p>(spacing to demonstrate relationship to terrain_map)</p>\n\n<p>With this array you can start with any coordinate <code>[i,j]</code> and convert it into an index in this array via a the <code>coord_to_int</code> function and back with its inverse function.</p>\n\n<p>Once you have that you can move up or down by adding/subtracting <code>map[0].length + 2</code> and left or right by adding/subtracting <code>1</code> from the index.</p>\n\n<p>Since this array is a padded version of the map, you never have to worry about wrapping around because you cannot move to these fake coordinates that make up the padding.</p>\n\n<p>This may or may not wind up actually being faster (it depends on how big your maps actually are and how easy the set of paths were to compute in the first place).</p>\n\n<p>code:</p>\n\n<pre><code>function coord_to_int(coord, map) {\n return (coord[0] + 1) * (map[0].length + 2) + (coord[1] + 1);\n}\n\nfunction int_to_coord(i, map) {\n return [\n Math.floor((i - 1) / (map[0].length + 2) - 1),\n (i - 1) % (map[0].length + 2)\n ];\n}\nfunction newArray(size, value) {\n var arr=[];\n while(size--) {\n arr.push(value);\n }\n return arr;\n}\nfunction generate_mobility_tiles(mobility, map) {\n var i, \n j,\n ii = map.length, \n jj = map[0].length,\n o = newArray((ii + 2) * (jj + 2), false);\n for (i = 0; i &lt; ii; i += 1) {\n for (j = 0; j &lt; jj; j += 1) {\n if(terrain_tile_types[map[i][j]][1][mobility]) {\n o[coord_to_int([i, j]] = true;\n }\n }\n }\n return o;\n}\n</code></pre>\n\n<p>In <code>pathfind</code>:</p>\n\n<pre><code>//near start\nvar mobility_tiles = generate_mobility_tiles(mobility_type, pathfind_map),\n down = pathfind_map[0].length+2, \n right = 1;\n\nclosed_tiles = new Array((pathfind_map.length + 2) * down); // sparse array matching mobility_tiles\n\n//later\n var surrounding = [\n [current_tile.i + down, false],\n [current_tile.i - down, false],\n [current_tile.i + right, false],\n [current_tile.i - right, false]\n ];\n surrounding.forEach(function (t) { //IE &lt; 9 compat is up to you\n if (!mobility_tiles[t[0]] || //cannot move here\n closed_tiles[t[0]]) { //visited already\n return;\n }\n\n var index = open_tiles.map(function (x) { return x.i; }).indexOf(t[0]);\n ...\n</code></pre>\n\n<p>and changed <code>reconstruct_path</code> accordingly (and remove <code>is_in_array</code>).</p>\n\n<h2>Instead of <code>sort</code> and <code>shift</code>, <code>splice</code> out the smallest element</h2>\n\n<p>I have no idea how big of an affect this will have (if any), but I think it would be faster to just splice out the smallest element rather than sort every time (again depends on size of your map). In the meantime there is no benefit to having <code>open_tiles.shift()</code> at the end of the loop rather than right after the sort and caching the lookup into a local variable:</p>\n\n<pre><code>while (open_tiles.length &gt; 0) {\n // remove smallest tile, faster than sort+shift?\n f = Number.MAX_VALUE;\n open_index = open_tiles.length;\n smallest = 0;\n while (open_index--) {\n if (f &gt; open_tiles[open_index].f) {\n f = open_tiles[open_index].f;\n smallest = open_index;\n }\n }\n current_tile = open_tiles.splice(smallest, 1);\n</code></pre>\n\n<h2>The completely raw untested result:</h2>\n\n<pre><code>// Some example variables:\nvar terrain_tile_types = [\n [\"\",[0,0,0,0]], // Not really a tile (invisible/unselectable)\n [\"Flat grass\",[1,0,0,1]], // ID: 1\n [\"Water\",[0,1,1,1]] // ID: 2\n];\n\nvar unit_types = [\n [\"Unit type 1\",[10,0.1,null],0,1]\n];\n\nvar terrain_map = [ // [x][y] = key to terrain_tyle_types\n [2,2,2,2,2],\n [1,1,1,2,2],\n [1,1,2,2,2],\n [1,2,2,1,1]\n];\n\nfunction coord_to_int(coord, map) {\n return (coord[0] + 1) * (map[0].length + 2) + (coord[1] + 1);\n}\n\nfunction int_to_coord(i, map) {\n return [\n Math.floor((i - 1) / (map[0].length + 2) - 1),\n (i - 1) % (map[0].length + 2)\n ];\n}\n\nfunction newArray(size, value) {\n var arr = [];\n while (size--) {\n arr.push(value);\n }\n return arr;\n}\n\nfunction generate_mobility_tiles(mobility, map) {\n var i,\n j,\n ii = map.length,\n jj = map[0].length,\n o = newArray((ii + 2) * (jj + 2), false);\n for (i = 0; i &lt; ii; i += 1) {\n for (j = 0; j &lt; jj; j += 1) {\n if (terrain_tile_types[map[i][j]].mobility[mobility]) {\n o[coord_to_int([i, j]] = true;\n }\n }\n }\n return o;\n}\nfunction calc_h(start, end){ // start,end: [locI,locJ]\n // Estimates the cost of moving from given tile to end\n return Math.abs(end[0] - start[0]) + Math.abs(end[1] - start[1]);\n}\n\nfunction reconstruct_path(end, map, closed_tiles){\n var path = [],\n current_tile = closed_tiles[coord_to_int(end, map)];\n\n while (current_tile.p != current_tile.i) {\n path.push(int_to_coord(current_tile.i, map));\n current_tile = closed_tiles[current_tile.p];\n if (!current_tile) { return false; }\n }\n path.reverse();\n return path;\n}\n\nfunction pathfind(start, end, mobility_type, substitute_map) {\n // start = start coords array, end = end coords array\n // mobility_type = determines which type of tiles are \"walkable\" based on the moving unit's type - will be an integer index o\n // substitute_map = optional map array to use instead of the default (terrain_map)\n\n var pathfind_map = typeof substitute_map !== 'undefined' ? substitute_map : terrain_map;\n mobility_type = typeof mobility_type !== 'undefined' ? mobility_type : 0;\n var mobility_tiles = generate_mobility_tiles(mobility_type, pathfind_map),\n down = pathfind_map[0].length+2, \n right = 1;\n\n // Able to walk on end tile? If not return false\n var end_i = coord_to_int(end, pathfind_map);\n if (!mobility_tiles[end_i]) return false;\n\n // Validate start and end arrays\n if (start.length != 2 || end.length != 2 ||\n start[0] !== +start[0] || start[0] !== (start[0]|0) || // note: bit-ors ???\n start[1] !== +start[1] || start[1] !== (start[1]|0) || // think that is wrong\n end[0] !== +end[0] || end[0] !== (end[0]|0) ||\n end[1] !== +end[1] || end[1] !== (end[1]|0)) { return false; }\n\n var start_obj = {\n i: coord_to_int(start, pathfind_map),\n g: 0,\n h: calc_h(start,end)\n };\n start_obj.p = start_obj.i;\n start_obj.f = start_obj.g + start_obj.h;\n\n\n var open_tiles = [start_obj];\n var closed_tiles = new Array((pathfind_map.length + 2) * down); // sparse array matching mobility_tiles\n var current_tile, f, open_index, smallest;\n while (open_tiles.length &gt; 0) {\n // remove smallest tile, faster than sort+shift?\n f = Number.MAX_VALUE;\n open_index = open_tiles.length;\n smallest = 0;\n while (open_index--) {\n if (f &gt; open_tiles[open_index].f) {\n f = open_tiles[open_index].f;\n smallest = open_index;\n }\n }\n current_tile = open_tiles.splice(smallest, 1);\n\n // Add tile to closed list\n closed_tiles[current_tile.i] = current_tile;\n\n if(end_i === current_tile.i){\n // Path found, finish.\n return reconstruct_path(end, map, closed_tiles);\n }\n\n // 4-surrounding tiles:\n var surrounding = [\n [current_tile.i + down, false],\n [current_tile.i - down, false],\n [current_tile.i + right, false],\n [current_tile.i - right, false]\n ];\n surrounding.forEach(function (t) {\n if (!mobility_tiles[t[0]] || //cannot move here\n closed_tiles[t[0]]) { //visited already\n return;\n }\n\n var index = open_tiles.map(function (x) { return x.i; }).indexOf(t[0]);\n var t_g = (curr.g + (t[1] ? 14 : 10));\n if (index &gt; -1) {\n // Tile already found in open list\n var old = open_tiles[index];\n if (t_g &lt; old.g) {\n // This new path is better. Update open list entry\n old.g = t_g;\n old.f = t_g + old.h;\n old.p = curr.i;\n }\n } else {\n // Tile wasn't found in open list, so add it now\n var coord = int_to_coord(current_tile.i, map);\n var potential = {\n i: t[0],\n g: t_g,\n h: calc_h(coord, end),\n p: curr.i\n };\n potential.f = potential.g + potential.h;\n open_tiles.push(potential);\n }\n });\n }\n // No valid path found from start to end\n return false;\n}\n</code></pre>\n\n<h2>Another change you could do to make this appear smoother to the UI would be to make it async.</h2>\n\n<p>Instead of the <code>while (open_tiles</code> loop (reminder this will require changes elsewhere):</p>\n\n<pre><code>var iterations = 10;\n(function iter() {\n while (iterations--) {\n if (!open_tiles.length) {\n failed_callback();\n return;\n }\n ...\n if(end_i === current_tile.i){\n // Path found, finish.\n found_callback(reconstruct_path(end, map, closed_tiles));\n return;\n }\n ...\n\n }\n iterations = 10;\n window.setTimeout(iter, 1);\n}());\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T09:36:04.747", "Id": "21497", "Score": "1", "body": "Thanks for such a comprehensive answer. I've implemented your \"raw untested result\" and with a small amount of fixing had it working several times faster than the original code!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T22:59:07.017", "Id": "13297", "ParentId": "13258", "Score": "8" } }, { "body": "<p>please check out this : </p>\n\n<p><a href=\"http://jsfiddle.net/konijn_gmail_com/bndxD/\" rel=\"nofollow\">http://jsfiddle.net/konijn_gmail_com/bndxD/</a></p>\n\n<p>Main features are : </p>\n\n<ul>\n<li>Named properties instead of indexed properties</li>\n<li>JS naming convention nameStuffLikeThis not name_stuff_like_this</li>\n<li>Not using for..in</li>\n<li>Extract getting a tile into a function which returns nothing when bounds are wrong</li>\n</ul>\n\n<p>It is more memory intensive then your version, but it should be much faster, let me know if it actually is on large maps. It also easily allows for 8 directional searching and monsters that go over multiple terrain types. It does not put this in a nice object, even though this really should contain a map object with a function that does path-finding.</p>\n\n<p>Code : </p>\n\n<pre><code>//which directions can be taken,\n//only cardinal in this case, you can be creative with this\nvar directions = [{ x: -1, y: 0},\n { x: 1, y: 0},\n { x: 0, y: 1},\n { x: 0, y: -1}];\n\n//What can be traversed ? \nvar PASS_FLOOR = 0x1; // 0001 \nvar PASS_WATER = 0x2; // 0010 \n\n// Some terrain types:\n// Feel free to embellish with other properties\nvar terrainTypes = [\n { type: \"\", canPass: 0},\n { type: \"grass\", canPass: PASS_FLOOR},\n { type: \"water\", canPass: PASS_WATER},];\n\n//map should really be a class..\nvar testMap = [[2, 2, 2, 2, 2],\n [1, 1, 1, 2, 2],\n [1, 1, 2, 2, 2],\n [1, 2, 2, 1, 1]];\n\n/* Get a tile at a location, ideally this should be a function of the map object.. \ndont trust map at all, trust that location has .x and .y */\nfunction getTile(map, location) {\n if (map &amp;&amp; map[location.x] &amp;&amp; map[location.x][location.y])\n return terrainTypes[map[location.x][location.y]];\n return false;\n}\n\n/* This could be cleaner.. */\nfunction getNeighbours(map, location, directions_optional) {\n var i;\n var neighbours = [];\n //make sure we start with something\n location.trace = location.trace || [];\n //This code still has far too many globals, that should all get fixed\n var vectors = directions_optional || directions;\n for (i = 0; i &lt; vectors.length; i++) {\n var newX = location.x + vectors[i].x;\n var newY = location.y + vectors[i].y;\n if (!map[newX]) map[newX] = [];\n if (!map[newX][newY])\n {\n map[newX][newY] = {\n x: newX,\n y: newY, \n //distance from origin\n d: (location.d || 0) + 1,\n //how did we get here\n trace: location.trace.slice(0)\n } \n }\n else\n {\n continue;\n }\n map[newX][newY].trace.push({ x: newX, y: newY });\n neighbours.push(map[newX][newY]);\n }\n return neighbours;\n}\n\n\nfunction findPath(start, end, mobility_optional, map_optional) {\n // start = start coords array { x, y }, note this could be a monster or an item with these properties!\n // end = end coords array { x, y }, see above\n // mobility_optional = which type of tiles are \"walkable\" based on the moving unit's type, see var PASS_*\n // map_optional = optional map array to use instead of the default (terrain_map)\n var map = map_optional || testMap;\n var mobility = mobility_optional || start.mobility || PASS_FLOOR;\n var shadowMap = [];\n var location, neighbours, i;\n\n // Validate start and end\n if (!getTile(map, start) || !getTile(map, end)) return false;\n\n // Able to walk on start and end tile? If not return false\n if (!(getTile(map, start).canPass &amp; mobility) || !(getTile(map, end).canPass &amp; mobility)) return false;\n\n //Start with the start ( we only look there hence the last parameter )\n var todo = getNeighbours(shadowMap, start, [{ x: 0, y: 0}]);\n\n //While we have places to check\n while (todo.length &gt; 0) {\n location = todo.shift();\n console.log( \"Looking at\" , location );\n neighbours = getNeighbours(shadowMap, location);\n console.log( \"Neighbours\" , neighbours ); \n //Find neighbours and iterate over them\n for (i = 0; i &lt; neighbours.length; i++) {\n //check whether we can go there with mobility\n if (!(getTile(map, neighbours[i]).canPass &amp; mobility)) continue;\n //did we find the place ? \n if (neighbours[i].x == end.x &amp;&amp; neighbours[i].y == end.y) return neighbours[i].trace;\n //did we find a new spot further away from start ?\n if (neighbours[i].d &gt; location.d) todo.push(neighbours[i]);\n //did we find an old spot closer to the start ?\n //if (neighbours[i].d &lt; location.d)\n //Save some memory\n //delete neighbours[i].trace\n }\n }\n return false;\n}\n\nvar start = { x: 0, y: 0 , mobility : PASS_WATER };\nvar end = { x: 3, y: 1 };\n\nconsole.log(findPath(start, end));​\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T09:18:04.857", "Id": "21681", "Score": "1", "body": "would you mind posting the most important bits of code inline?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T13:38:07.063", "Id": "21686", "Score": "0", "body": "@codesparkle The code is relatively short, I had a hard time deciding what was most important, so I put it all here, hope that is okay." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T02:57:43.540", "Id": "13412", "ParentId": "13258", "Score": "1" } } ]
{ "AcceptedAnswerId": "13297", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T23:09:09.977", "Id": "13258", "Score": "4", "Tags": [ "javascript", "pathfinding" ], "Title": "Javascript A* pathfinding function for tile-based game optimisation" }
13258
<p>I'm a few months into learning C++ programming and I want to know if I'm moving generally in the right direction or not with the following code. This is the most advanced thing I've created so far, but it doesn't contain any pointers or references so I'm worried I'm not doing things properly on the memory level. I especially want advice regarding moving this type of code to templates and virtual functions.</p> <pre><code>//This program's purpose is a simple battle simulator and a simple lotto simulator //This requires two classes and a bit of procedural main game logic that can repeat //The first class is a Randomizer class that allows the user to generate //random numbers by inputting the desired amount of numbers, and the max //range for those numbers. The default start value is 1. //The second class is a Battler class that contains two Randomizer objects. //It also contains a method to compare the second integer of each of the vector //arrays contained in each of those objects, and returns -1, 0, or 1 depending //on which value is greater, or 0 if they are tied. #include &lt;iostream&gt; //Necessary for cout and endl #include &lt;ctime&gt; //Necessary for time_t variable #include &lt;cstdlib&gt; //Necessary for rand and srand #include &lt;vector&gt; //Necessary for vector&lt;type&gt; /*HEADER OF RANDOMIZER CLASS*/ class Randomizer //The preferred syntax is to start with a capital letter for classes { private: time_t timevalue; //time_t member variable that will be set later void randomTimeInit(); //called by constructor (runs once) public: Randomizer() //Class constructor { srand(time(NULL)); //This is JUST necessary here to get new results every time //Caution: Only run once per program execution! (per object?) void randomTimeInit(); //This function sets time_t value and seeds rand() with it std::cout &lt;&lt; "construct randomizer" &lt;&lt; std::endl; //UNCOMMENT FOR DEBUG } ~Randomizer() //Class deconstructor { std::cout &lt;&lt; "destruct randomizer" &lt;&lt; std::endl; //UNCOMMENT FOR DEBUG } std::vector&lt;int&gt; randomIntArray; //The vector array for the random numbers int getRandomNumber(int); //Function to return one random number of max int void createRandomIntArray(int, int); //Function to create random number array void printRandomIntArray(); //Function to print created random number array }; /*IMPLEMENTATION OF RANDOMIZER CLASS*/ void Randomizer::randomTimeInit() { time_t timevalue; //time_t is a special value (usually number of seconds since 00:00) time(&amp;timevalue); //Sets a reference timevalue to the time (requires the special time_t value) srand(timevalue); //Seeds the random generator with timevalue } int Randomizer::getRandomNumber(int max) { return rand() % max +1; //Returns random int %modulo (max value) + 1 (to eliminate 0) } void Randomizer::createRandomIntArray(int count, int max) { for(int i=1;i&lt;=count;i++) //Iterates up to the count value { int randomInt = getRandomNumber(max); //Sets randomInt to 1-to-max randomIntArray.insert(randomIntArray.begin(), randomInt); //Inserts randomInt at start of vector } } void Randomizer::printRandomIntArray() { for(unsigned int j=0;j&lt;randomIntArray.size();j++) //Iterates up to previously created vector size { std::cout &lt;&lt; randomIntArray[j] &lt;&lt; " "; //Outputs number value at [j] followed by a space } } /*HEADER OF BATTLER CLASS*/ class Battler { private: Randomizer random1, random2; //Two Randomizer objects that will each have different values int numOne, maxOne, numTwo, maxTwo; //Four variables for setting up the battle public: Battler() //Class constructor { std::cout &lt;&lt; "con battler" &lt;&lt; std::endl; //UNCOMMENT FOR DEBUG } ~Battler() //Class destructor { std::cout &lt;&lt; "decon battler" &lt;&lt; std::endl; //UNCOMMENT FOR DEBUG } int doBattler(); //Function that compares values between the Randomizer objects }; /*IMPLEMENTATION OF BATTLER CLASS*/ int Battler::doBattler() { numOne = 5; //Five numbers to choose from for the battle (arbitrary) maxOne = 100; //Value up to 100 for the "damage" number (arbitrary) numTwo = 5; //Five numbers to choose from for the battle (arbitrary) maxTwo = 100; //Value up to 100 for the "damage" number (arbitrary) random1.createRandomIntArray(numOne, maxOne); //Generates Player 1s numbers random2.createRandomIntArray(numTwo, maxTwo); //Generates Player 2s numbers std::cout &lt;&lt; "Here the two scores:" &lt;&lt; std::endl; random1.printRandomIntArray(); //Prints Player 1s numbers std::cout &lt;&lt; std::endl; random2.printRandomIntArray(); //Prints Player 2s numbers std::cout &lt;&lt; std::endl; //This begins the logic to test which player won the round //I decided to use a simple return here instead of a switch statement //One definite downside of the following code is having to repeat two of the lines //in each of the three different statements in order to clear the vector array between rounds if(random1.randomIntArray[2] == random2.randomIntArray[2]) //NOTE: this looks at the second integer //of the member arrays and compares //them ((arbitrary) but it has to be a value //inside the array or it crashes) { std::cout &lt;&lt;"It was a draw!" &lt;&lt; std::endl &lt;&lt; std::endl; random1.randomIntArray.clear(); //This is necessary to clear the vector array between rounds random2.randomIntArray.clear(); //If it's not present then the array continues to expand forever return 0; //Return immediately stops the function and returns this value } else if(random1.randomIntArray[2] &gt; random2.randomIntArray[2]) //See NOTE above { std::cout &lt;&lt; "Player 1 hits!" &lt;&lt; std::endl &lt;&lt; std::endl; random1.randomIntArray.clear(); //This is necessary to clear the vector array between rounds random2.randomIntArray.clear(); //If it's not present then the array continues to expand forever return -1; //Return immediately stops the function and returns this value } else { std::cout &lt;&lt; "Player 2 hits!" &lt;&lt; std::endl &lt;&lt; std::endl; random1.randomIntArray.clear(); //This is necessary to clear the vector array between rounds random2.randomIntArray.clear(); //If it's not present then the array continues to expand forever return 1; //Return immediately stops the function and returns this value } } /*START OF FUTURE MAIN.CPP*/ /*PROTOTYPE DECLARATIONS*/ void inputAndPrintRandomIntArray(); //This function takes inputs for amount of numbers and //their max value and prints out the created array void lottoLoop(); //This function allows the repetition of the above function //if the user inputs char 'Y' void battleLoop(); //This function creates a Battler object and player life //variables and repeats the doBattler function until one player is dead void chooseBattleOrLotto(); //This function allows user input to control which of the two //main functions of the program to run /*START OF MAIN FUNCTION*/ int main(int argc, char* args[]) //These arguments for main allow command line access? { chooseBattleOrLotto(); //Allows user to choose which function program will perform return 0; //Here because int main expects a return value } /*DEFINITION OF MAIN.CPP FUNCTIONS*/ void inputAndPrintRandomIntArray() { Randomizer myRandomizer; //Instantiates an object of the Randomizer class int number, maximum; //These are the variables that will go into Randomizer method std::cout &lt;&lt; "Enter the amount of numbers for the Lotto Ticket (1-100):"; std::cin &gt;&gt; number; std::cout &lt;&lt; "Enter the maximum number from which they will be chosen(1-1000):"; std::cin &gt;&gt; maximum; std::cout &lt;&lt; "Here are your Lotto Numbers:" &lt;&lt; std::endl; myRandomizer.createRandomIntArray(number, maximum); //This activates Randomizer method with input values myRandomizer.printRandomIntArray(); //This prints the created random int array std::cout &lt;&lt; std::endl; } void lottoLoop() { char gameRunning = 'Y'; //This char value will control whether the game continues to loop do { //system("cls"); //apparently dangerous to use, simply clears console //alternative is cout &lt;&lt; string( 100, '\n' ). Remove to see all outputs inputAndPrintRandomIntArray(); //Function that takes input and outputs vector array std::cout &lt;&lt; "Would you like to play again? (must enter Y):"; std::cin &gt;&gt; gameRunning; } while(gameRunning == 'Y'); //For some reason I couldn't get || 'y' to work } void battleLoop() { Battler doSimpleBattle; //Instantiates an object of the Battler class char battleAgain = 'Y'; //Creates a char that controls whether to repeat the battle //Begins the battle logic do/while loops do { int player1HP = 10; //Setting the variables here resets them between games int player2HP = 10; //Placing them where the char is above will not work do { int battleResult; //Creates a variable to control the if statements battleResult = doSimpleBattle.doBattler(); //Sets the variable to the return value of the function if(battleResult == -1) //Looks at the return of the doBattler method { player2HP--; //Decrements Player 2 health based on this result } if(battleResult == 1) //Continues looking at return of doBattler method { player1HP--; //Decrements Player 1 health based on this result } } while(player1HP &gt; 0 || player2HP &gt; 0); //Continue the game until one player has no health left if(player1HP == 0) //Checks if Player 1's health is zero { std::cout &lt;&lt; "Player 2 wins!" &lt;&lt; std::endl; } else if(player2HP == 0) //Checks if Player 2's health is zero { std::cout &lt;&lt; "Player 1 wins!" &lt;&lt; std::endl; } std::cout &lt;&lt; "Game over!" &lt;&lt; std::endl; std::cout &lt;&lt; "Play again? (Must be Y to work)"; std::cin &gt;&gt; battleAgain; //This is the char input to control repeating the game std::cout &lt;&lt; std::endl; } while(battleAgain == 'Y'); //For some reason I can't get || 'y' to work } void chooseBattleOrLotto() { char modeSelect = 'L'; //Creates a char that controls mode choice and exit std::cout &lt;&lt; "Press 'L' for the lottery or 'B' for battle! ('Q' to exit):"; std::cin &gt;&gt; modeSelect; if(modeSelect == 'L') { lottoLoop(); //Contains a do while loop that allows game repeat } if(modeSelect == 'B') { battleLoop(); //Contains a do while loop that runs the battle game with //Player 1 vs Player 2 each having 10 HP that allows repeat } if(modeSelect == 'Q') { modeSelect = 'Q'; } else { std::cout &lt;&lt; "Value must match L or B. Q to Exit." &lt;&lt; std::endl; if(modeSelect != 'Q') { chooseBattleOrLotto(); //Repeats entire function unless input char equals 'Q' } } } </code></pre>
[]
[ { "body": "<p>I suggest the following: </p>\n\n<ul>\n<li><p>Member variables should be private.Do you really need </p>\n\n<pre><code>std::vector&lt;int&gt; randomIntArray\n</code></pre>\n\n<p>to be public in Randomizer?</p></li>\n<li><p>Be const correct. Declare variables to be const whenever possible. The ff.</p>\n\n<pre><code>int getRandomNumber(int); \nvoid createRandomIntArray(int, int); \n</code></pre>\n\n<p>can be rewritten to:</p>\n\n<pre><code>int getRandomNumber(const int);\nvoid createRandomIntArray(const int, const int); \n</code></pre></li>\n<li><p>In terms of OOP design, I think it would be better if you could create another class named BattleGame ( or any other name ) where you will put your game logic.</p>\n\n<pre><code>class BattleGame \n{\npublic:\n void chooseBattleOrLotto();\n\nprivate:\n void inputAndPrintRandomIntArray();\n void lottoLoop(); \n void battleLoop();\n } \n</code></pre></li>\n</ul>\n\n<p>You can then call it using:</p>\n\n<pre><code>int main(int argc, char* args[]) \n{\n BattleGame b;\n b.chooseBattleOrLotto();\n return 0;\n}\n</code></pre>\n\n<p>This encapsulates the methods that the caller does not need to know.</p>\n\n<p>There are probably more things you can do to improve your program. I will post some more suggestions when I get more time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T07:11:53.150", "Id": "21438", "Score": "0", "body": "FAQ about const correctness: http://www.parashift.com/c++-faq-lite/const-correctness.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T14:37:44.523", "Id": "21446", "Score": "0", "body": "The concept of const correctness is a new one for me. The C++ Faq was extremely helpful. Thanks a lot for the feedback!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T06:25:48.823", "Id": "13262", "ParentId": "13261", "Score": "6" } }, { "body": "<p>A couple quick observations:</p>\n\n<h1>class Randomizer</h1>\n\n<p>You're seeding your random number generator several times. <code>srand</code> is a global resource. You could create a single Randomizer object that passed by reference into the constructor of all objects -- that way only one is ever created. Or you could use a singleton. (Beware: Over-use of singletons is a common trap. Don't pretend they're not global variables. <a href=\"http://gameprogrammingpatterns.com/singleton.html\">Read more here</a>.)</p>\n\n<p>In order to do the above, Randomizer should have no state. It's create and print functions should take a <code>std::vector&lt;int&gt;&amp;</code> (reference) that they fill in or print.</p>\n\n<h1>class Battler</h1>\n\n<p>It's better style to declare multiple variables on multiple lines. (Because it sometimes doesn't do what you expect: <code>char * a,b;</code> declares one pointer and one char -- not two pointers.)</p>\n\n<p>You have a lot of unnecessary member variables. Try to use local variables where possible to limit the shared data in your code. (More shared data means more opportunities for values you didn't expect.) </p>\n\n<h1>Battler::doBattler</h1>\n\n<p>It's better style to return enum or const values instead of \"magic numbers\".</p>\n\n<p>Often when you have a function called \"doSomething\", it doesn't have precisely defined functionality (so it's hard to name). It looks like you want this to getBattleResult (and then the calling code could do the prints). Then your Battler is your model and the calling code is the UI.</p>\n\n<h1>Design</h1>\n\n<p>In terms of your design, instead of having an array of random numbers, you could just call getRandomNumber. If you're trying to add complexity (so you have a chance to use vectors), then you could use a series of randoms and average the top two.</p>\n\n<p>Also, the <a href=\"http://www.parashift.com/c++-faq-lite/newbie.html\">C++ FAQ</a> may be helpful. (It's one of my favourite resource for C++. Especially, the const correctness entry.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T14:50:16.480", "Id": "21447", "Score": "0", "body": "I appreciate the feedback. The C++ Faq is indeed an amazing resource. Const correctness seems important as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T22:27:15.137", "Id": "21477", "Score": "0", "body": "The C++FAQ is awful. The author is opinionated and biased. Also some of the examples are just plain wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T22:39:00.207", "Id": "21479", "Score": "0", "body": "See: http://stackoverflow.com/tags/c%2b%2b/info for better references." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T07:05:54.280", "Id": "13264", "ParentId": "13261", "Score": "6" } }, { "body": "<p>Some thoughts:</p>\n\n<ol>\n<li><p>I'm not sure why you need a randomizer class. The random number stream is a global resource, so <code>srand()</code> needs to be done only once. It may be better to rename this as a Player class, since that's what it's usually used for. I can see a use for a <code>RandomStream</code> class for your damage and lotto numbers, something like:</p>\n\n<pre><code>class RandomStream\n{\npublic:\n RandomStream( int max ) : m_max(max) {}\n virtual ~RandomStream() = 0;\n int Next() { return rand() % m_max + 1; }\nprivate:\n int m_max;\n};\nstruct DamageGenerator: public RandomStream\n{\n DamageGenerator(): RandomStream(c_MaxDamage) {}\n};\nstruct LottoGenerator: public RandomStream\n{\n LottoGenerator( int max ): RandomStream(max) {}\n};\n</code></pre>\n\n<p>So your numbers can be generated as:</p>\n\n<pre><code>LottoGenerator gen( maximum );\nfor ( int i = 0; i &lt; number; i++ ) {\n\n std::cout &lt;&lt; gen.Next() &lt;&lt; \" \";\n}\nstd::cout &lt;&lt; std::endl;\n</code></pre>\n\n<p>and your battle damage as:</p>\n\n<pre><code>DamageGenerator m_gen;\nvoid GenerateScores( int num ) {\n\n m_scores.clear();\n for ( int i = 0; i &lt; num; i++ ) {\n\n m_scores.push_back( m_gen.Next() );\n }\n}\n</code></pre></li>\n<li><p>For writing out \"constructor/destructor messages\", try guarding them with a #ifdef</p>\n\n<pre><code>#idef _DEBUG // or equivalent\nstd::cout &lt;&lt; \"...\" &lt;&lt; std::endl;\n#endif\n</code></pre>\n\n<p>That way, you don't need to remove them in \"proper use\".</p></li>\n<li><p>You have a loop running from <code>1</code> to <code>&lt;= count</code> in one function and <code>0</code> to <code>&lt; size()</code> in the other. Make the first one <code>0</code> to <code>&lt; count</code> as well - more consistent.</p></li>\n<li><p>for </p>\n\n<pre><code>randomIntArray.insert(randomIntArray.begin(), randomInt);\n</code></pre>\n\n<p>you could do</p>\n\n<pre><code>randomIntArray.push_back( randomInt );\n</code></pre>\n\n<p>for simplicity - the order isn't significant.</p></li>\n<li><p>For printing them out, you could use an iterator:</p>\n\n<pre><code>for ( std::vector&lt;int&gt;::iterator it = randomIntArray.begin(); it != randomIntArray.end(); it ++ ) {\n std::cout &lt;&lt; *it &lt;&lt; \" \"\n}\n</code></pre>\n\n<p>Note that you're printing out a space at the end, which doesn't matter in this case. See <a href=\"https://codereview.stackexchange.com/questions/13176/infix-iterator-code\">C++ infix iterator</a> for something rather more complex!</p></li>\n<li><p>Note that in your <code>Randomizer::createRandomIntArray</code>, there's nothing to stop you first doing </p>\n\n<pre><code>randomIntArray.clear();\n</code></pre>\n\n<p>This will remove the need for the annoying clears after the hit or draw messages.</p></li>\n<li><p>Don't use magic numbers 50, 100 and -1, 0, 1 etc. You can use</p>\n\n<pre><code>const int c_Rounds = 5;\nconst int c_MaxDamage = 100;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>enum BattlerResult { PLAYER1_WINS, DRAW, PLAYER2_WINS };\n</code></pre>\n\n<p>This is to aid readability (and also ease of change), rather than wondering what it means in the future.</p></li>\n<li><p><code>numOne</code>, <code>maxOne</code> etc are only used once, so there's no need to \"remember\" them in the class definition - move them from there into the function (and actually, they're covered by the definition in 7) anyway).</p></li>\n<li><p>Try to keep Class/variable names in the realm of what they mean rather than what they do/are. <em>e.g.</em>, <code>Randomizer</code> is probably better named as <code>Player</code>, <code>random1</code> as <code>player1</code>, <code>Battler</code> as <code>BattlerRound</code>, <code>doBattler</code> as <code>GetBattlerResult</code> etc.</p>\n\n<ul>\n<li>I know they're really notes to yourself, but in general keep comments explaining how/why, rather than just echoing the code they're commenting.</li>\n</ul></li>\n<li><p>The \"who wins\" code is repeated, possibly giving rise to inconsistent behaviour if one part is changed. Separate out that decision into a separate function, something like:</p>\n\n<pre><code>BattlerResult result = DecideWinner( player1, player2 );\n</code></pre></li>\n<li><p>Similarly, the hit or draw messages can be separated out into a function as well:</p>\n\n<pre><code>GiveResultMessage( result );\n</code></pre>\n\n<p>Doing these will simplify the overall <code>doBattler</code> function, making it easier to read and understand what's going on.</p></li>\n<li><p>When you receive input from an unvalidated source, validate it. It doesn't make sense to have -5 lotto numbers. Also, consider allowing e.g. b as well as B as input.</p></li>\n<li><p>The lotto loop termination should be:</p>\n\n<pre><code>while ( ( gameRunning == 'Y' ) || ( gameRunning == 'y' ) )\n</code></pre>\n\n<p>or perhaps even</p>\n\n<pre><code>while ( ::toupper( gameRunning ) == 'Y' )\n</code></pre></li>\n<li><p>The <code>battleLoop</code> loop could be a for, rather than a do...while; and it may be better as a boolean value (again, separating out the \"play again\" message as another function):</p>\n\n<pre><code>for ( bool battleAgain = true; battleAgain; battleAgain = QueryAnotherGame() )...\n</code></pre></li>\n<li><p>You may wish to introduce a <code>BattleGame</code> class to contain a single game, so that <code>battleLoop</code> just consists of:</p>\n\n<pre><code>void battleLoop()\n{\n for ( bool battleAgain = true; battleAgain; battleAgain = QueryAnotherGame() )\n {\n BattleGame game;\n BattleResult result = game.Play();\n game.GiveWinnerMessage( result );\n std::cout &lt;&lt; \"Game over!\" &lt;&lt; std::endl;\n }\n}\n</code></pre></li>\n<li><p><code>chooseBattleOrLotto</code> may be better as a switch (such as):</p>\n\n<pre><code>while ( true )\n{\n // ask L or B\n switch ( ::toupper( modeSelect ) )\n {\n case 'Q': return;\n case 'L': playLotto; break;\n case 'B': playBattle; break;\n default: \"only L/B message\"; break;\n }\n}\n</code></pre>\n\n<p>Note that your function is recusive - it probably won't matter for this, but a person could crash the game if they were determined by repeatedly pressing an invalid key.</p>\n\n<p>I think templates and virtual functions are a bit too complex for this at the moment...</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T12:07:59.500", "Id": "13268", "ParentId": "13261", "Score": "4" } } ]
{ "AcceptedAnswerId": "13268", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T04:37:04.610", "Id": "13261", "Score": "3", "Tags": [ "c++", "beginner", "random", "generator" ], "Title": "Simple randomization program" }
13261
<p>This code was posted as answer to <a href="https://codereview.stackexchange.com/questions/13248/async-file-writer-in-net-3-5">Async file writer in .Net 3.5</a>.</p> <p>How would it be done better using Tasks or new features in .Net 4.5?</p> <pre><code>public sealed class Logger : IDisposable { private delegate void WriteMessage(string message); private static readonly Logger Instance = new Logger(); private static object Locker = new object(); private static readonly StreamWriter Writer = new StreamWriter("c:\\temp\\logtester.log", true); private static bool Disposed; private Logger() { } ~Logger() { Dispose(false); } public static void Log(string message) { WriteMessage action = Instance.MessageWriter; action.BeginInvoke(message, MessageWriteComplete, action); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private static void Dispose(bool disposing) { lock (Locker) { if (Disposed) { return; } if (disposing) { if (Writer != null) { Writer.Dispose(); } } Disposed = true; } } private static void MessageWriteComplete(IAsyncResult iar) { ((WriteMessage)iar.AsyncState).EndInvoke(iar); } private void MessageWriter(string message) { lock (Locker) { Writer.WriteLine(message); } } } </code></pre>
[]
[ { "body": "<p>Before I explain how would I improve that code, I'll first mention two problems I will not try to fix (because I'm not sure how to do it properly):</p>\n\n<ol>\n<li><p>Disposable singleton is a really weird combination. If something should be available anytime and anywhere, it should be a singleton. On the other hand, if something has a limited lifetime and holds an expensive resource (like an open file), it should be disposable. Those two don't go together very well.</p></li>\n<li><p>Finalizer should execute as fast as possible. It certainly shouldn't take a lock that may not be released for quite some time (because there may be many threads also holding the lock).</p></li>\n</ol>\n\n<p>The problems my solution will solve:</p>\n\n<ol>\n<li>Writing to the log may not be in the correct order, <code>lock</code> doesn't guarantee any ordering.</li>\n<li><code>Dispose()</code> may not write all outstanding messages. This is again because <code>lock</code> doesn't guarantee ordering.</li>\n<li>If a write attempt happens after <code>Dispose()</code> (either because <code>Log()</code> was called after <code>Dispose()</code>, or because of the ordering problems mentioned above), an exception will be thrown on the <code>ThreadPool</code>. This exception can't be caught from outside of <code>Logger</code> and will bring down the whole application. (More reason not to have disposable singletons.)</li>\n<li>If there are many calls to <code>Log()</code> at the same time, or if the writing takes too long, there may be many threads, all waiting on the same lock.</li>\n<li>While the message is being written, there is a thread blocking until it finishes.</li>\n</ol>\n\n<p>My solution using TPL Dataflow (which uses .Net 4.5 extensively, available from NuGet) solves the issues so that:</p>\n\n<ol>\n<li>Writing to the log will be always in the correct order.</li>\n<li><code>Dispose()</code> will first write all outstanding messages before returning.</li>\n<li>If <code>Log()</code> is called after <code>Dispose()</code>, it will directly throw an exception.</li>\n<li>There will be at most one thread doing the writing, at any time.</li>\n<li>While the message is being written, no thread is waiting for it to finish.</li>\n</ol>\n\n\n\n<pre><code>public sealed class Logger : IDisposable\n{\n private static readonly Logger Instance = new Logger();\n\n private readonly ActionBlock&lt;string&gt; m_writerBlock;\n\n private static bool Disposed;\n\n private Logger()\n {\n var writer = new StreamWriter(\"c:\\\\temp\\\\logtester.log\", true);\n m_writerBlock = new ActionBlock&lt;string&gt;(s =&gt; writer.WriteLineAsync(s));\n m_writerBlock.Completion.ContinueWith(_ =&gt; writer.Dispose());\n }\n\n public static void Log(string message)\n {\n if (!Instance.m_writerBlock.Post(message))\n throw new ObjectDisposedException(\"Logger\");\n }\n\n public void Dispose()\n {\n if (Disposed)\n return;\n\n m_writerBlock.Complete();\n m_writerBlock.Completion.Wait();\n\n Disposed = true;\n }\n}\n</code></pre>\n\n<p>This works correctly, because the <code>ActionBlock</code> will take care of almost anything needed here, like ordering, synchronization and scheduling <code>Task</code>s when necessary. <code>WriteLineAsync()</code> returns a <code>Task</code> and the block will use this <code>Task</code> to asynchronously wait for it to finish.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T18:06:24.197", "Id": "21553", "Score": "0", "body": "Very nice, I would upvote, but I don't yet have the reputation (almost there). I was not aware of the ActionBlock, I briefly looked at the MSDN entry for it and I'm curious how this will preserve ordering? Is it due to the \"degree of parallelism\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T08:24:33.000", "Id": "21555", "Score": "0", "body": "`ActionBlock` maintains a queue that takes care of the ordering. Because of that, it preserves the order *unless* you specify `MaxDegreeOfParallelism` other than 1. But you certainly don't want to do that here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T15:02:14.083", "Id": "51578", "Score": "0", "body": "@svick, I like this solution and if message parsing prior to writing is needed one could setup a transformblock prior to the actionblock, link the two and perform all parsing in the transformblock. With this even maxdegreeofparallelism set to other than 1 will still preserve order within the transformblock. But agree that maxdegreeofparallelism in the actionblock should always be set to 1 or ignored (then default 1 applies) to preserve write order." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-11T11:08:48.267", "Id": "86976", "Score": "2", "body": "has anyone tested this? Some specflow that i did with 100 tasks being set up for log a string fail at about 75 very consistently. I suspect its to do with disposal" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-11T11:30:02.340", "Id": "86979", "Score": "0", "body": "It also doesnt store the data until disposal ... not great if you want to log to debug." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-11T11:38:22.047", "Id": "86980", "Score": "0", "body": "yeah, if this is the quality of code review someone needs to seriously question not the guy who answered with this but all the people who upvoted. The code looks reasonable until you actually REVIEW and test it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-11T11:54:29.763", "Id": "86982", "Score": "0", "body": "bunging a writer.flush in the action kind of hides the issue." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T21:58:56.923", "Id": "87187", "Score": "0", "body": "@JohnNicholas Yeah, you need to `Dispose()` the logger before the program terminates, otherwise it won't work correctly. I explained I'm not trying to fix the “disposable singleton” issue. And the finalizer is useless here, I'll remove that." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T13:38:24.567", "Id": "13273", "ParentId": "13263", "Score": "13" } }, { "body": "<p><a href=\"https://codereview.stackexchange.com/a/13273/20883\">The above code</a> doesn't flush the buffer. So if you use it in a high load / parallel situation and run into an exception the program can terminate and lose the file handle for the writer before all the logs have been written. That's a bit of speculation - it could be that the writer can only write about 3k at once.</p>\n\n<p>Some clarification of the issues as in comments seems like a discussion started:\nA for loop writing 100 messages will reveal the following issues</p>\n\n<ol><li>the output log file maxes out at 3k</li>\n<li>putting a sleep for an arbitrary length of time doesnt help it still stalls at around 75 messages for me (presumably message length or some kind of buffer setting influences this) - the point being a running program with logging in a loop would find this solution broken.</li>\n<li> only writes on termination of program - which is probably why it runs into a max buffer and truncates the rest of the messages.</li>\n<li> Who cares about ordering? thats what a timestamp is for. Ordering is very un-asynchronous</li>\n</ol>\n\n<p>I didn't sit down and figure out precisely what the problem was, however, I did use a dirty hack to somewhat compensate. Namley - dispose of the logger regularly. I do not recommend this as a solution in production code but seeing as i am merely using it for dirty debugging it suffices for my purposes. The flush of the buffer is a good solution for myself.</p>\n\n<p>The flush adjustment</p>\n\n<pre><code>this.mWriterBlock = new ActionBlock&lt;string&gt;(\n s =&gt;{\n writer.WriteLineAsync(s);\n writer.Flush();\n });\n</code></pre>\n\n<p>There are other patterns for singletons in multithreaded environments. Given it is an async logger it should probably create itself in a thread safe manner.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ff650316.aspx\" rel=\"nofollow noreferrer\">This</a> for example - needs modernising.</p>\n\n<p>The singleton on the microsoft site</p>\n\n<pre><code>using System;\n\npublic sealed class Singleton\n{\n private static volatile Singleton instance;\n private static object syncRoot = new Object();\n\n private Singleton() {}\n\n public static Singleton Instance\n {\n get \n {\n if (instance == null) \n {\n lock (syncRoot) \n {\n if (instance == null) \n instance = new Singleton();\n }\n }\n\n return instance;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T22:04:37.363", "Id": "87188", "Score": "0", "body": "You using `WriteLineAsync()` incorrectly, you have to `await` the `Task` it returns (my answer does that implicitly by returning the `Task` to the block). And if you're using `WriteLineAsync()`, there is no reason not to use `FLushAsync()` too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T22:08:13.390", "Id": "87189", "Score": "0", "body": "Also, I don't understand what does the singleton code you included here have to do with anything." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-13T08:02:53.913", "Id": "87238", "Score": "0", "body": "You are probably right about the singleton given that i am flushing the buffer. The singleton idea came before that as reinstantiating the writer also had the side effect of flushing and keeping it able to successfully write." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-13T08:28:26.707", "Id": "87244", "Score": "0", "body": "can you gurantee order of calls with flushasync though? calling it synchronously in the async block doesn't seem so bad and safer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-13T13:56:51.417", "Id": "87286", "Score": "0", "body": "Yeah, you can guarantee order of calls if you `await` `FlushAsync()` too." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-11T15:39:06.093", "Id": "49472", "ParentId": "13263", "Score": "1" } } ]
{ "AcceptedAnswerId": "13273", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T06:32:59.707", "Id": "13263", "Score": "7", "Tags": [ "c#", "asynchronous" ], "Title": "File Async writer using Tasks or new features of .Net 4.5?" }
13263
<p>I'm building a typo correction program. This is the function, which compute the levenshtein distance between two words (a dictionnary word and an input word). I will call this function many times, so it should be fast. I'm looking for therefore some optimizations. I've seen some faster algorithms, but I don't know how to implement them correctly.</p> <pre><code>static size_t compute_levenshtein_distance (char const *const s, size_t const ns, char const *const t, size_t const nt) { #define swap(d1, d2) \ size_t *tmp = (d1); \ (d1) = (d2); \ (d2) = tmp #define max(a, b) \ ((a) &gt; (b) ? (a) : (b) \ #define min2(a, b) \ ((a) &lt; (b) ? (a) : (b)) \ #define min3(a, b, c) \ (min2(min2(a, b), c)) size_t t1[ns+1], t2[ns+1]; size_t *d1 = t1, *d2 = t2; for (size_t i = 1UL; i &lt;= ns; ++i) d1[i] = i; for (size_t i = 1UL; i &lt;= nt; ++i) { char const cCol = t[i-1]; d2[0UL] = i; for (size_t j = 1UL; j &lt;= ns; ++j) { int const nCost = s[j-1] != cCol; size_t const i1 = d1[j ] + 1; size_t const i2 = d2[j-1] + 1; size_t const i3 = d1[j-1] + nCost; d2[j] = min3(i1, i2, i3); } swap(d1, d2); } return d1[ns]; #undef swap #undef max #undef min2 #undef min3 } </code></pre> <p>Do you have any ideas ? Thanks.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T15:36:17.743", "Id": "21877", "Score": "0", "body": "One problem I see is that you very often call the minimum macro. Try using bit twiddling this part. There is an excellent article about how to obtain the minimum of two numbers without branching on http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-16T09:30:45.643", "Id": "22145", "Score": "0", "body": "Thanks for your comment, I've already read this article, but the given version run slower down than the ternary version." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-16T10:18:55.177", "Id": "22149", "Score": "0", "body": "You're welcome. Well then I only see the problem of a too big dictionary. Can you reduce the number of calls of the distance function by e.g. only checking against words with similar length?" } ]
[ { "body": "<p>I see very little space for improvements.</p>\n\n<p>First, your <code>min3</code> macro (btw, <code>max</code> is missing a closing bracket) will, in some cases, execute inside branching more than needed (i.e., if <code>c &gt; min2(a,b)</code>). I'd write it directly:</p>\n\n<pre><code>#define min3(a, b, c) \\\n((a) &lt; (b) ? ((a) &lt; (c) ? (a) : (c)) : ((b) &lt; (c) ? (b) : (c)))\n</code></pre>\n\n<p>Second, this part:</p>\n\n<pre><code>for (size_t i = 1UL; i &lt;= nt; ++i) {\n char const cCol = t[i-1];\n d2[0UL] = i;\n</code></pre>\n\n<p>can save one subtraction:</p>\n\n<pre><code>for (size_t i = 0UL; i &lt; nt; ) {\n char const cCol = t[i];\n d2[0UL] = ++i;\n</code></pre>\n\n<p>Maybe the inside loop can be made faster by using pointer arithmetic instead of indexing, but I'm not sure. So, you can try replacing</p>\n\n<pre><code> for (size_t j = 1UL; j &lt;= ns; ++j) {\n int const nCost = s[j-1] != cCol;\n size_t const i1 = d1[j ] + 1;\n size_t const i2 = d2[j-1] + 1;\n size_t const i3 = d1[j-1] + nCost; \n d2[j] = min3(i1, i2, i3);\n }\n</code></pre>\n\n<p>with</p>\n\n<pre><code> size_t *d1j = d1+1, *d2j1 = d2, *d1j1 = d1;\n for (size_t j = 1UL; j &lt;= ns; ++j) {\n int const nCost = s[j-1] != cCol;\n size_t const i1 = *d1j + 1;\n size_t const i2 = *d2j1 + 1;\n size_t const i3 = *d1j1 + nCost; \n *d2j = min3(i1, i2, i3);\n d1j1 = d1j++;\n d2j1++;\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-21T02:33:19.110", "Id": "37859", "ParentId": "13267", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T12:02:00.437", "Id": "13267", "Score": "2", "Tags": [ "c", "edit-distance" ], "Title": "Write a typo correction program with Levenshtein distance algorithm" }
13267
<p>This is my first go at genetic algorithms, using PyGame for the visual representation. Is there a way to improve the speed of the code? Click to place a point, press <kbd>↑</kbd> to start looking for the shortest route, or press <kbd>c</kbd> to clear all. </p> <pre><code>import pygame, time, random #Size of next generation, change number at the end if needed resize_rate = 1.005 #Controls crossover appearence cross_rate = 0.7 #Controls number of chromosomes created at the start, exponential exponent = 4 black = (0, 0, 0) white = (255, 255, 255) red = (255, 0, 0) genes = [] def draw_background(screen): screen.fill(white) def draw_connection(screen, pointlist): pygame.draw.lines(screen, black, True, pointlist, 1) def draw_best_connection(screen, pointlist): pygame.draw.lines(screen, red, True, pointlist, 2) def create_random_chromosomes(genes): temp_chromosomes = [] chromosomes = [] for i in range(len(genes)**exponent): genes_copy = genes[:] random.shuffle(genes_copy) temp_chromosomes.append(genes_copy) for element in temp_chromosomes: if element not in chromosomes: chromosomes.append(element) print(str(len(chromosomes)) + " random chromosomes created") return chromosomes def calculate_distance(chromosome): distances = [] total_distance = 0 for i in range(len(chromosome)): if i &lt; (len(chromosome)-1): distance_A_B = (((chromosome[i+1][0]-chromosome[i][0])**2)+(chromosome[i+1][1]-chromosome[i][1])**2)**0.5 distances.append(distance_A_B) else: distance_A_B = (((chromosome[i][0]-chromosome[0][0])**2)+(chromosome[i][1]-chromosome[0][1])**2)**0.5 distances.append(distance_A_B) for i in range(len(distances)): total_distance += distances[i] return total_distance def calculate_fitness(chromosomes): fitness_scores = [] for i in range(len(chromosomes)): fitness = 0 fitness = 1/calculate_distance(chromosomes[i]) fitness_scores.append(fitness) return fitness_scores def build_chromosome_fitness_dict(chromosomes, fitness_scores): chrom_fit_dict = {} for i in range(len(chromosomes)): chrom_fit_dict[fitness_scores[i]] = chromosomes[i] return chrom_fit_dict def roulette_selection(chromosomes, fitnesses, new_size): sum_fitness = sum(fitnesses) rel_fitness = [fitness/sum_fitness for fitness in fitnesses] #Generate probability intervals for each chromosome probabilities = [sum(rel_fitness[:i+1]) for i in range(len(rel_fitness))] #Select chromosomes selected_chromosomes = [] for n in range(new_size): r = random.random() for (i, chromosome) in enumerate(chromosomes): if r &lt;= probabilities[i]: selected_chromosomes.append(chromosome) break return selected_chromosomes def find_closest(cities): dist_a = (((cities[0][0]-cities[1][0])**2)+(cities[0][1]-cities[1][1])**2)**0.5 dist_b = (((cities[0][0]-cities[2][0])**2)+(cities[0][1]-cities[2][1])**2)**0.5 if dist_a &lt; dist_b: return cities[1] else: return cities[2] #Greedy crossover selects the first city of one parent, #compares the cities leaving that city in both parents, #and chooses the closer one to extend the tour. #If one city has already appeared in the tour, we choose the other city. #If both cities have already appeared, we randomly select a non-selected city. def crossover(chromosomes, rate): new_chromosomes = [] #len -1 because index out of range error might occur otherwise for i in range(len(chromosomes)-1): #Crossover T/F if random.random() &lt; rate: #Take 2 chromosomes a = chromosomes[i] b = chromosomes[i+1] #Randomly select crossover location cross_location = random.randint(1, len(chromosomes[i])) #Create parts c = a[:cross_location] for i in range((len(a)-len(c))): #City to start from start_pos = c[-1] #2 most plausible targets target_0 = a[cross_location+i] target_1 = b[cross_location+i] #Determine if targets already appear in c and add correct city if target_0 in c: if target_1 in c: not_yet_selected = [] for city in genes: if city not in c: not_yet_selected.append(city) c.append(not_yet_selected[random.randint(0,(len(not_yet_selected)-1))]) else: c.append(target_1) elif target_1 in c: c.append(target_0) else: cities = [start_pos, target_0, target_1] closest = find_closest(cities) c.append(closest) new_chromosomes.append(c) else: new_chromosomes.append(chromosomes[i]) return new_chromosomes pygame.init() screen = pygame.display.set_mode((640,340)) clock = pygame.time.Clock() done = False first = True while done == False: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: if genes != []: #Start Genetic Algorithm print('Creating initial solutions') chromosomes = create_random_chromosomes(genes) #Draw most possible solutions for i in range(len(chromosomes)): draw_connection(screen, chromosomes[i]) #Main Logic Loop print('Starting calculations') while len(chromosomes) &gt; 10: print(str(len(chromosomes)) + ' chromosomes left') new_size = int(len(chromosomes)/resize_rate) #Calculate fitness scores fitness_scores = calculate_fitness(chromosomes) #Build dictionary to preserve order chrom_fit_dict = build_chromosome_fitness_dict(chromosomes, fitness_scores) #Roulette selection - select chromosomes for next generation selected_chromosomes = roulette_selection(chromosomes, fitness_scores, new_size) #Adopt newly selected chromosomes as population chromosomes = selected_chromosomes #Apply crossover mutation mutated_chromosomes = crossover(chromosomes, cross_rate) #Adopt mutated chromosomes as population chromosomes = mutated_chromosomes best_chrom = fitness_scores.index(max(chrom_fit_dict)) draw_best_connection(screen, chromosomes[best_chrom]) if event.key == pygame.K_c: draw_background(screen) genes = [] if first == True: draw_background(screen) first = False #Get points if pygame.mouse.get_pressed() == (1, 0, 0): mouse_pos = pygame.mouse.get_pos() genes.append(mouse_pos) pygame.draw.rect(screen, black, [mouse_pos[0], mouse_pos[1], 2, 2], 1) genes = list(set(genes)) pygame.display.flip() clock.tick(30) pygame.quit() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T20:54:02.953", "Id": "21474", "Score": "0", "body": "How many vertexes (cities) do you want to process? Do you need a genetic algorithm only, not an exact one?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T12:57:23.253", "Id": "21507", "Score": "0", "body": "It isn't meant for real-world application so it doesn't really matter how many cities/points it can process, largest test I ran was with 30 different points, it executed in about 7-8 minutes and was most of the times I ran it 90% - 100% correct. I'm only interested in the genetic algorithm, this was a test project to learn how these work, so an exact result is not requiered." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T15:14:07.433", "Id": "21509", "Score": "0", "body": "Ok, I see. If you need the exact TSP solution (may be in order to check you genetic algorithm solution) let me know. It solves 30 points TSP in about 0.5 second." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T17:13:28.190", "Id": "21512", "Score": "0", "body": "oh, to check solutions that would be interesting indeed." } ]
[ { "body": "<p>Ok, so here is <strong>exact</strong> ATSP solver, just in order to check your genetic algorithm solution. It's based on pascal code implementing the branch-and- bound algorithm by Little, Murty, Sweeney, and Karel. It's very very fast (30 points in 0.5 sec!).</p>\n\n<pre><code>'''\n\nBranch and bound Algorithm for Travelling Salesman Problem\n\nbased on\n\nhttp://www.cs.sunysb.edu/~algorith/implement/syslo/distrib/processed/babtsp.p\n\n'''\n\nimport time\n\nINF = 100000000\n\nbest_cost = 0\n\ndef reduce(size, w, row, col, rowred, colred):\n rvalue = 0\n for i in xrange(size):\n temp = INF\n for j in xrange(size):\n temp = min(temp, w[row[i]][col[j]])\n if temp &gt; 0:\n for j in xrange(size):\n if w[row[i]][col[j]] &lt; INF:\n w[row[i]][col[j]] -= temp\n rvalue += temp\n rowred[i] = temp\n for j in xrange(size):\n temp = INF\n for i in xrange(size):\n temp = min(temp, w[row[i]][col[j]])\n if temp &gt; 0:\n for i in xrange(size):\n if w[row[i]][col[j]] &lt; INF:\n w[row[i]][col[j]] -= temp\n rvalue += temp\n colred[j] = temp\n return rvalue\n\n\ndef bestEdge(size, w, row, col):\n mosti = -INF\n ri = 0\n ci = 0\n for i in xrange(size):\n for j in xrange(size):\n if not w[row[i]][col[j]]:\n minrowwelt = INF\n zeroes = 0\n for k in xrange(size):\n if not w[row[i]][col[k]]:\n zeroes += 1\n else:\n minrowwelt = min(minrowwelt, w[row[i]][col[k]])\n if zeroes &gt; 1: minrowwelt = 0\n mincolwelt = INF\n zeroes = 0\n for k in xrange(size):\n if not w[row[k]][col[j]]:\n zeroes += 1\n else:\n mincolwelt = min(mincolwelt, w[row[k]][col[j]])\n if zeroes &gt; 1: mincolwelt = 0\n if minrowwelt + mincolwelt &gt; mosti:\n mosti = minrowwelt + mincolwelt\n ri = i\n ci = j\n return mosti, ri, ci\n\n\ndef explore(n, w, edges, cost, row, col, best, fwdptr, backptr):\n global best_cost\n\n colred = [0 for _ in xrange(n)]\n rowred = [0 for _ in xrange(n)]\n size = n - edges\n cost += reduce(size, w, row, col, rowred, colred)\n if cost &lt; best_cost:\n if edges == n - 2:\n for i in xrange(n): best[i] = fwdptr[i]\n if w[row[0]][col[0]] &gt;= INF:\n avoid = 0\n else:\n avoid = 1\n best[row[0]] = col[1 - avoid]\n best[row[1]] = col[avoid]\n best_cost = cost\n else:\n mostv, rv, cv = bestEdge(size, w, row, col)\n lowerbound = cost + mostv\n fwdptr[row[rv]] = col[cv]\n backptr[col[cv]] = row[rv]\n last = col[cv]\n while fwdptr[last] != INF: last = fwdptr[last]\n first = row[rv]\n while backptr[first] != INF: first = backptr[first]\n colrowval = w[last][first]\n w[last][first] = INF\n newcol = [INF for _ in xrange(size)]\n newrow = [INF for _ in xrange(size)]\n for i in xrange(rv): newrow[i] = row[i]\n for i in xrange(rv, size - 1): newrow[i] = row[i + 1]\n for i in xrange(cv): newcol[i] = col[i]\n for i in xrange(cv, size - 1): newcol[i] = col[i + 1]\n explore(n, w, edges + 1, cost, newrow, newcol, best, fwdptr, backptr)\n w[last][first] = colrowval\n backptr[col[cv]] = INF\n fwdptr[row[rv]] = INF\n if lowerbound &lt; best_cost:\n w[row[rv]][col[cv]] = INF\n explore(n, w, edges, cost, row, col, best, fwdptr, backptr)\n w[row[rv]][col[cv]] = 0\n\n for i in xrange(size):\n for j in xrange(size):\n w[row[i]][col[j]] = w[row[i]][col[j]] + rowred[i] + colred[j]\n\n\ndef atsp(w):\n global best_cost\n size = len(w)\n col = [i for i in xrange(size)]\n row = [i for i in xrange(size)]\n best = [0 for _ in xrange(size)]\n route = [0 for _ in xrange(size)]\n fwdptr = [INF for _ in xrange(size)]\n backptr = [INF for _ in xrange(size)]\n best_cost = INF\n\n explore(size, w, 0, 0, row, col, best, fwdptr, backptr)\n\n index = 0\n for i in xrange(size):\n route[i] = index\n index = best[index]\n index = []\n cost = 0\n\n for i in xrange(size):\n if i != size - 1:\n src = route[i]\n dst = route[i + 1]\n else:\n src = route[i]\n dst = 0\n cost += w[src][dst]\n index.append([src, dst])\n return cost, index\n\n\ndef main():\n # adjasted matrix\n\n m = [\n [INF, 514, 230, 92, 172, 201, 320, 205, 329, 285, 404, 128, 352, 357, 190, 269, 484, 237, 567, 209, 413, 404,\n 333, 480, 371, 175, 470, 281, 423, 328],\n [452, INF, 359, 410, 450, 401, 315, 293, 244, 200, 275, 446, 469, 143, 278, 362, 399, 344, 544, 644, 335, 381,\n 248, 457, 626, 375, 551, 258, 397, 305],\n [414, 360, INF, 90, 170, 42, 90, 46, 282, 238, 186, 126, 320, 198, 31, 267, 437, 190, 358, 623, 246, 345, 286,\n 271, 267, 16, 326, 222, 421, 119],\n [324, 427, 269, INF, 80, 109, 359, 113, 263, 233, 312, 36, 260, 265, 98, 177, 418, 257, 475, 533, 321, 312, 281,\n 388, 279, 83, 378, 189, 331, 236],\n [244, 382, 312, 226, INF, 335, 402, 246, 197, 153, 334, 262, 486, 466, 231, 315, 352, 297, 670, 453, 241, 538,\n 201, 583, 505, 309, 298, 415, 350, 431],\n [448, 318, 355, 216, 268, INF, 445, 111, 240, 196, 288, 252, 385, 156, 96, 358, 395, 148, 691, 640, 348, 528,\n 244, 455, 373, 299, 566, 405, 393, 452],\n [330, 437, 126, 216, 280, 119, INF, 123, 206, 315, 312, 252, 348, 275, 108, 324, 361, 267, 268, 539, 372, 255,\n 242, 181, 393, 93, 236, 132, 478, 29],\n [495, 557, 521, 539, 313, 563, 469, INF, 406, 444, 543, 575, 274, 700, 440, 524, 442, 506, 729, 633, 554, 716,\n 442, 642, 788, 537, 611, 593, 641, 490],\n [208, 256, 115, 168, 206, 157, 205, 49, INF, 148, 137, 204, 323, 313, 34, 118, 155, 100, 473, 417, 197, 460, 36,\n 386, 382, 131, 441, 337, 272, 234],\n [252, 229, 159, 212, 250, 201, 249, 93, 44, INF, 181, 248, 367, 357, 78, 162, 199, 144, 517, 444, 241, 398, 48,\n 430, 426, 175, 485, 275, 197, 278],\n [534, 568, 363, 453, 411, 250, 237, 254, 326, 344, INF, 225, 449, 406, 239, 366, 481, 398, 505, 547, 60, 375,\n 362, 418, 623, 224, 473, 252, 520, 266],\n [445, 507, 334, 389, 469, 332, 393, 336, 413, 369, 276, INF, 224, 488, 321, 141, 392, 321, 659, 583, 336, 496,\n 417, 572, 601, 306, 629, 373, 295, 420],\n [221, 283, 313, 313, 393, 314, 195, 263, 214, 170, 351, 349, INF, 426, 248, 325, 168, 314, 455, 359, 411, 442,\n 218, 368, 580, 288, 431, 319, 367, 216],\n [309, 286, 216, 269, 307, 258, 306, 150, 101, 57, 132, 305, 326, INF, 135, 219, 256, 201, 574, 501, 192, 455,\n 105, 487, 483, 232, 542, 332, 254, 335],\n [416, 554, 484, 398, 172, 507, 484, 15, 369, 325, 506, 434, 289, 638, INF, 487, 457, 469, 717, 625, 413, 554,\n 373, 359, 677, 481, 470, 431, 522, 478],\n [514, 509, 193, 283, 352, 191, 252, 195, 306, 387, 379, 319, 469, 347, 180, INF, 461, 339, 518, 723, 249, 355,\n 342, 431, 460, 165, 488, 232, 154, 279],\n [53, 115, 278, 145, 225, 254, 368, 212, 163, 119, 300, 181, 405, 258, 197, 281, INF, 263, 620, 262, 360, 457,\n 167, 533, 424, 228, 523, 334, 316, 381],\n [300, 277, 207, 68, 148, 177, 297, 141, 92, 48, 229, 104, 328, 333, 126, 210, 247, INF, 543, 492, 289, 380, 96,\n 456, 347, 151, 446, 257, 245, 304],\n [758, 471, 620, 710, 754, 593, 710, 597, 550, 671, 687, 746, 571, 614, 582, 668, 705, 650, INF, 930, 747, 599,\n 586, 404, 887, 567, 915, 476, 822, 523],\n [39, 434, 269, 131, 211, 240, 359, 227, 178, 324, 315, 167, 391, 396, 212, 296, 333, 276, 452, INF, 375, 439,\n 214, 365, 410, 214, 509, 316, 450, 213],\n [526, 513, 443, 496, 534, 485, 533, 377, 328, 284, 441, 165, 389, 641, 362, 306, 483, 428, 698, 487, INF, 535,\n 332, 611, 710, 459, 769, 412, 460, 459],\n [784, 654, 691, 552, 604, 336, 781, 447, 576, 532, 624, 588, 721, 492, 432, 694, 731, 484, 1027, 976, 684, INF,\n 580, 791, 709, 635, 902, 741, 729, 788],\n [435, 220, 576, 527, 607, 569, 450, 513, 464, 420, 495, 563, 689, 363, 498, 582, 619, 564, 718, 396, 555, 601,\n INF, 631, 806, 543, 686, 478, 617, 479],\n [354, 402, 216, 306, 350, 189, 306, 193, 146, 294, 283, 342, 167, 345, 178, 264, 301, 246, 358, 526, 343, 195,\n 182, INF, 483, 163, 511, 72, 418, 119],\n [311, 288, 218, 79, 159, 188, 308, 152, 103, 59, 240, 115, 113, 344, 137, 221, 258, 11, 554, 472, 300, 391, 107,\n 462, INF, 162, 457, 268, 256, 315],\n [431, 344, 186, 242, 187, 26, 276, 30, 266, 222, 314, 278, 304, 182, 15, 384, 421, 174, 544, 640, 374, 531, 270,\n 374, 399, INF, 348, 408, 419, 305],\n [477, 454, 384, 437, 475, 426, 474, 318, 269, 225, 300, 473, 494, 168, 303, 387, 424, 369, 742, 669, 360, 623,\n 273, 655, 651, 400, INF, 500, 422, 503],\n [282, 330, 144, 234, 280, 186, 234, 123, 74, 222, 211, 270, 366, 342, 108, 192, 229, 174, 286, 491, 271, 123,\n 110, 199, 411, 160, 470, INF, 346, 47],\n [360, 399, 39, 129, 209, 81, 98, 85, 152, 277, 225, 165, 359, 237, 70, 270, 307, 229, 364, 569, 95, 201, 188,\n 277, 306, 55, 334, 78, INF, 125],\n [301, 433, 97, 187, 267, 139, 187, 143, 177, 325, 283, 223, 319, 295, 128, 295, 332, 277, 239, 510, 343, 226,\n 213, 152, 364, 113, 423, 103, 449, INF]\n ]\n\n start_time = time.time()\n cost, path = atsp(m)\n print \"Cost = \", cost\n print \"Path = \", path\n print \"Time (s)\", time.time() - start_time\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T09:26:34.127", "Id": "13340", "ParentId": "13272", "Score": "1" } } ]
{ "AcceptedAnswerId": "13340", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T13:30:17.397", "Id": "13272", "Score": "1", "Tags": [ "python", "algorithm", "pygame" ], "Title": "Tackling the TSP with a genetic algorithm" }
13272
<p>Doing graphics in Java, I find myself writing lines like these regularly:</p> <pre><code>Vector3f b = mid.add( a.mult(yOffset + length / 2) ).add( up.cross(a).mult(xOffset) ); </code></pre> <p>It gets even worse when I'm reusing objects.</p> <pre><code>Vector3f vTemp = VarPool.getVector3f(); Vector3f b = VarPool.getVector3f(); b.set(mid).addMutable( a.multAndStore(yOffset + length / 2, vTemp) ).addMutable( up.crossAndStore(a, vTemp).multMutable(xOffset) ); //...do some useful computation... VarPool.recycle(vTemp, b); </code></pre> <p>I've tried coping using a combination of these two methods:</p> <h2>1. Place 'translations' in comments above dense lines</h2> <pre><code>//i.e. Vector3f b = ( mid + a * (yOffset + length / 2) + (up X a) * xOffset ); //this calculates such and such b.set(mid).addMutable( a.multAndStore(yOffset + length / 2, vTemp) ).addMutable( up.crossAndStore(a, vTemp).multMutable(xOffset) ); </code></pre> <p>Disadvantages: Extra noise. 'Translation' comments can look like actual code that's been commented out. There's no getting around the real code being hard to read.</p> <h2>2. Break dense chains into more readable lines</h2> <pre><code>b .set(mid) .addMutable( a.multAndStore(yOffset + length / 2, vTemp) ) .addMutable( ( vTemp = up.crossAndStore(a, vTemp) .multMutable(xOffset) ) ); </code></pre> <p>Disadvantages: Some calculations don't chain up quite as nicely. When different return types are involved (e.g. matrices, quaternions, scalars), chaining is not always logical or possible.</p> <p>Any other suggestions? Switching language is not really viable.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T23:59:37.730", "Id": "21443", "Score": "0", "body": "Use an EL? Still Java, can be extended if you need specialized types, etc. Otherwise... Java is Java, and it's Java." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T03:26:19.287", "Id": "21444", "Score": "0", "body": "@David B: I wouldn't say I'm looking for code review, as I'm really after solutions others may have come up with while staying Java-interoperable -- as a random example, a source processor that can translate between operator-overloaded/method-call notation." } ]
[ { "body": "<p>@DaveNewton Not necessarily, sometimes it's Groovy :-)</p>\n\n<p>Advantage</p>\n\n<ul>\n<li>code/syntax compatible with java.</li>\n<li>Operator overrides allow you to write your code so it looks more like your comment i.e. operators rather than methods</li>\n</ul>\n\n<p>Disadvantage</p>\n\n<ul>\n<li>Groovy is slower than java (but this can be reduced with Groovy++)</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T03:34:43.520", "Id": "21445", "Score": "0", "body": "I've looked at some JVM alternatives like Scala/Groovy/Stab. Still considering, although leaning heavily toward Xtend..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T02:54:26.583", "Id": "13276", "ParentId": "13275", "Score": "3" } } ]
{ "AcceptedAnswerId": "13276", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T23:43:30.703", "Id": "13275", "Score": "3", "Tags": [ "java" ], "Title": "Improving readability of 3d math in Java" }
13275
<p>I'm reading a book called <em>JavaScript Web Applications</em>. In first chapter, it introduces an implementation of class library. Here's an intermediate version:</p> <pre><code>var Class = function () { var klass = function () { this.init.apply(this, arguments); } klass.prototype.init = function (args) {}; // Adding class properties klass.extend = function (obj) { var extended = obj.extended; for (var i in obj) { klass[i] = obj[i]; } if (extended) extended(klass); }; // Adding instance propertied klass.include = function (obj) { var included = obj.included; for (var i in obj) { klass.prototype[i] = obj[i]; } if (included) include(klass) }; return klass; } </code></pre> <p>Then it can be used like this:</p> <pre><code>var Person = new Class; Person.extend({ find: function (id) { /* ... */ } }); var person = Person.find(1); var Person = new Class; Person.include({ save: function () { /* ... */ } }); var person = new Person; person.save(); </code></pre> <p>I modified it to that it support non-shared instance properties, and here's my version:</p> <pre><code>var Class = function (properties) { var klass = function () { this.init.apply(this, arguments); } klass.prototype.init = function (args) { var self = this; if (properties instanceof Array &amp;&amp; typeof args === 'object') { properties.forEach(function (p) { if (typeof args[p] !== 'undefined') { self[p] = args[p]; } }); } }; // extend and include return klass; } </code></pre> <p>So it can be used like this:</p> <pre><code>var Person = new Class(['name', 'age']; var person = new Person({ name: 'bob', age: '30' }); </code></pre> <p>Is my approach ok? I also wonder that why <code>Person.name</code> was <code>""</code> in my approach? I expected it to be <code>undefined</code>.</p>
[]
[ { "body": "<p>There is nothing fundamentally wrong about your class strategy, it is a matter of personal style really. The only suggestion I would have is to add Object.prototype.hasOwnProperty guards in the for-in loops, to avoid extending your classes with bogus properties if someone adds things to Object.prototype.</p>\n\n<pre><code>for (var i in obj) {\n if(Object.prototype.hasOwnProperty.call(obj, i)){\n // ...\n }\n}\n</code></pre>\n\n<p>As for the <code>name === ''</code> thing, its just a coincidence since Javascript functions (and therefore your class) always have this property defined:</p>\n\n<pre><code>(function(){}).name // \"\"\n(function foo(){}).name // \"foo\"\n</code></pre>\n\n<p>Some other properties such as \"prototype\" or \"length\" should also always be defined and there is nothing you can do about them.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T14:37:55.630", "Id": "13280", "ParentId": "13278", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T06:01:40.667", "Id": "13278", "Score": "2", "Tags": [ "javascript", "properties" ], "Title": "My implementation of javascript class library" }
13278
<p>I'd like to ask if this PHP/HTML code has any flaws which can be exploited by the potential aggressor:</p> <pre><code>&lt;form method='post' action='&lt;?php echo $_SERVER['PHP_SELF']; ?&gt;'&gt; &lt;input type='text' name='foo' value='&lt;?php echo htmlspecialchars($_POST['foo']); ?&gt;' /&gt; &lt;input type='submit' value='bar' /&gt; &lt;/form&gt; </code></pre> <p>I'm aware that it can be exploited by calling script like this <a href="http://foo.bar/baz.php/" rel="nofollow">http://foo.bar/baz.php/</a>'&gt;&lt;script&gt;alert('xss')&lt;/script&gt;&lt;foo' and </p> <pre><code>&lt;?php echo $_SERVER['PHP_SELF']; ?&gt; </code></pre> <p>should be replaced with </p> <pre><code>&lt;?php echo htmlentities($_SERVER['PHP_SELF']); ?&gt; or &lt;?php echo htmlspecialshars($_SERVER['PHP_SELF']); ?&gt; </code></pre> <p>Are there any other possible ways to conduct XSS attack on this piece of code? If so, how can I secure this form?</p> <p>@Update: Ok, I've just found another possible attack - entering code like ' onmouseover='alert(String.fromCharCode(88,83,83,33)); (with the apostrophe in the beginning) into the text field, which causes simple 'XSS!' alert. It can be avoided by changing <code>&lt;?php echo htmlspecialchars($_POST['foo']); ?&gt;</code> to <code>&lt;?php echo str_replace('\'', '&amp;#39;', htmlspecialchars($_POST['foo'])); ?&gt;</code></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T15:50:10.583", "Id": "21459", "Score": "2", "body": "You've answered your own question... Though I think `__FILE__` is the preferred way, rather than `$_SERVER[ 'PHP_SELF' ]` although I may be mistaken. Only other thing I can think to suggest is that you take a look at `filter_input()` for that post variable that you also never verified was set." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T15:57:58.610", "Id": "21460", "Score": "0", "body": "Amendment: `$_SERVER[ 'SCRIPT_NAME' ]` is the preferred way, not `__FILE__`, not sure what I was thinking... Though the latter should work too." } ]
[ { "body": "<p>For single-quoted attributes, use <code>htmlspecialchars($text, ENT_QUOTES)</code>.</p>\n\n<p>Depending on what this does, you might want to implement some sort of protection against CSRF attacks.</p>\n\n<p>You might also want to check <code>$_SERVER['SCRIPT_NAME']</code>.</p>\n\n<p>Other than that, this code seems reasonable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-27T22:27:13.007", "Id": "15998", "ParentId": "13282", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T14:55:10.813", "Id": "13282", "Score": "3", "Tags": [ "php", "security" ], "Title": "PHP form XSS vulnerability" }
13282
<h3>The (real life) problem</h3> <p>Following <a href="https://stackoverflow.com/questions/11294307/convert-java-date-to-utc-string">my question on SO</a>, I found out that printing a Java <code>Date()</code> in a custom format is quite tedious:</p> <pre class="lang-java prettyprint-override"><code>final Date date = new Date(); final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS zzz"; final SimpleDateFormat sdf = new SimpleDateFormat(ISO_FORMAT); final TimeZone utc = TimeZone.getTimeZone("UTC"); sdf.setTimeZone(utc); System.out.println(sdf.format(date)); </code></pre> <p>I was looking for a one-liner without object initialization:</p> <pre class="lang-java prettyprint-override"><code>System.out.println(magic(date, "yyyy-MM-dd'T'HH:mm:ss.SSS zzz", "UTC")); </code></pre> <h3>My Solution</h3> <p><code>PrettyDate</code> class, which formats <code>Date()</code> objects using <code>TimeZones</code> and <code>Formats</code> given as <em>strings</em>, sans any external object creation. There are some convenience methods for popular timezone\format combinations.</p> <h3>Alternatives to Consider (please comment on these, too!)</h3> <ul> <li>Extending <code>Date()</code> with better toString()</li> <li>Using non-static methods: Initializing <code>PrettyDate</code> with a <code>Format</code> and a <code>TimeZone</code>, and feeding it with <code>Date</code> objects to get a string representation</li> </ul> <h3>Usage</h3> <pre class="lang-java prettyprint-override"><code>// The problem - not UTC Date.toString() "Tue Jul 03 14:54:24 IDT 2012" // ISO format, now PrettyDate.now() "2012-07-03T11:54:24.256 UTC" // ISO format, specific date PrettyDate.toString(new Date()) "2012-07-03T11:54:24.256 UTC" // Legacy format, specific date PrettyDate.toLegacyString(new Date()) "Tue Jul 03 11:54:24 UTC 2012" // ISO, specific date and time zone PrettyDate.toString(moonLandingDate, "yyyy-MM-dd hh:mm:ss zzz", "CST") "1969-08-20 03:17:40 CDT" // Specific format and date PrettyDate.toString(moonLandingDate, "yyyy-MM-dd") "1969-08-20" // ISO, specific date PrettyDate.toString(moonLandingDate) "1969-08-20T20:17:40.234 UTC" // Legacy, specific date PrettyDate.toLegacyString(moonLandingDate) "Wed Aug 20 08:17:40 UTC 1969" </code></pre> <h3>Code</h3> <pre><code>import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; /** * Formats dates to sortable UTC strings in compliance with ISO-8601. * * @author Adam Matan &lt;adam@matan.name&gt; * @see https://stackoverflow.com/questions/11294307/convert-java-date-to-utc-string/11294308 */ public class PrettyDate { public static String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS zzz"; public static String LEGACY_FORMAT = "EEE MMM dd hh:mm:ss zzz yyyy"; private static final TimeZone utc = TimeZone.getTimeZone("UTC"); private static final SimpleDateFormat legacyFormatter = new SimpleDateFormat(LEGACY_FORMAT); private static final SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT); static { legacyFormatter.setTimeZone(utc); isoFormatter.setTimeZone(utc); } /** * Formats the current time in a sortable ISO-8601 UTC format. * * @return Current time in ISO-8601 format, e.g. : * "2012-07-03T07:59:09.206 UTC" */ public static String now() { return PrettyDate.toString(new Date()); } /** * Formats a given date in a sortable ISO-8601 UTC format. * * &lt;pre&gt; * &lt;code&gt; * final Calendar moonLandingCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); * moonLandingCalendar.set(1969, 7, 20, 20, 18, 0); * final Date moonLandingDate = moonLandingCalendar.getTime(); * System.out.println("UTCDate.toString moon: " + PrettyDate.toString(moonLandingDate)); * &gt;&gt;&gt; UTCDate.toString moon: 1969-08-20T20:18:00.209 UTC * &lt;/code&gt; * &lt;/pre&gt; * * @param date * Valid Date object. * @return The given date in ISO-8601 format. * */ public static String toString(final Date date) { return isoFormatter.format(date); } /** * Formats a given date in the standard Java Date.toString(), using UTC * instead of locale time zone. * * &lt;pre&gt; * &lt;code&gt; * System.out.println(UTCDate.toLegacyString(new Date())); * &gt;&gt;&gt; "Tue Jul 03 07:33:57 UTC 2012" * &lt;/code&gt; * &lt;/pre&gt; * * @param date * Valid Date object. * @return The given date in Legacy Date.toString() format, e.g. * "Tue Jul 03 09:34:17 IDT 2012" */ public static String toLegacyString(final Date date) { return legacyFormatter.format(date); } /** * Formats a date in any given format at UTC. * * &lt;pre&gt; * &lt;code&gt; * final Calendar moonLandingCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); * moonLandingCalendar.set(1969, 7, 20, 20, 17, 40); * final Date moonLandingDate = moonLandingCalendar.getTime(); * PrettyDate.toString(moonLandingDate, "yyyy-MM-dd") * &gt;&gt;&gt; "1969-08-20" * &lt;/code&gt; * &lt;/pre&gt; * * * @param date * Valid Date object. * @param format * String representation of the format, e.g. "yyyy-MM-dd" * @return The given date formatted in the given format. */ public static String toString(final Date date, final String format) { return toString(date, format, "UTC"); } /** * Formats a date at any given format String, at any given Timezone String. * * * @param date * Valid Date object * @param format * String representation of the format, e.g. "yyyy-MM-dd HH:mm" * @param timezone * String representation of the time zone, e.g. "CST" * @return The formatted date in the given time zone. */ public static String toString(final Date date, final String format, final String timezone) { final TimeZone tz = TimeZone.getTimeZone(timezone); final SimpleDateFormat formatter = new SimpleDateFormat(format); formatter.setTimeZone(tz); return formatter.format(date); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T18:31:28.057", "Id": "58816", "Score": "1", "body": "What about [FastDateFormat](http://commons.apache.org/lang/api/org/apache/commons/lang3/time/FastDateFormat.html) in Commons Lang? And [DateFormatUtils](http://commons.apache.org/lang/api/org/apache/commons/lang3/time/DateFormatUtils.html) with a set of static methods for formatting dates using FastDateFormat" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T16:40:53.440", "Id": "58817", "Score": "0", "body": "I will take a look - seems like I've been trying to reinvent the wheel." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T06:08:09.437", "Id": "58818", "Score": "0", "body": "FastDateFormat uses the default Java Date String format as a default, but thanks again for the idea." } ]
[ { "body": "<p>The thing about <code>Date</code> is that there are so many different time zones, so many different \"standard\" ways of representing the date and even, in some places, completely different calendar systems. As a result, Sun designed <code>Date</code> to not make any assumptions about anything and let application developers write whatever implementation best suited them.</p>\n\n<p>So, if you find your implementation for PrettyDate works well for you, that's ok. My only comment about that is that heavy use of static methods smells of procedural, rather than object oriented thinking, and that's not a good thing. Embrace the objects.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T05:35:35.470", "Id": "21484", "Score": "0", "body": "+1 Thanks for your answer, Perhaps I will refactor my code to comply with OOP design, although it is procedural in nature. Do you have any feedback regarding code style and readability?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T08:02:02.330", "Id": "21491", "Score": "0", "body": "I thought the style and readability were fine - otherwise I would have said something. You might try trimming the comments a little - not to remove any of the information, but just to try and shrink them a little. They make it hard to see the actual code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T03:21:00.310", "Id": "13301", "ParentId": "13283", "Score": "6" } }, { "body": "<p>Also be aware that SimpleDateFormat is not thread-safe. In a Multithreading Environment users should create a separate instance for each thread. For more information how to achieve it check this <a href=\"http://www.javacodegeeks.com/2010/07/java-best-practices-dateformat-in.html\">link</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T02:34:47.377", "Id": "13527", "ParentId": "13283", "Score": "7" } }, { "body": "<p>You've called strings like <code>2012-07-03T11:54:24.256 UTC</code> \"ISO\" and the doc on your code says that it produces strings <em>\"...in compliance with ISO-8601.\"</em> It does not. The only valid <a href=\"https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators\" rel=\"nofollow\">timezone specifiers in ISO-8601</a> are <code>Z</code> (for UTC) or numeric offsets (or nothing, meaning \"local\" time). Abbreviations like <code>UTC</code>, <code>CDT</code>, etc. are not part of the ISO-8601 format.</p>\n\n<p>It's not a code problem, but it's a documentation and interoperation problem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-29T19:10:15.643", "Id": "187194", "Score": "0", "body": "More specifically, to get valid ISO-8601 compliant output, you should change your `ISO_FORMAT` string to either `yyyy-MM-dd'T'HH:mm:ss.SSSZ` or `yyyy-MM-dd'T'HH:mm:ss.SSSXX`. (The difference, a bit perversely, is that [the `XX` pattern outputs `Z` for a zero offset from UTC, whereas `Z` outputs `+0000` in that case.](http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html) AFAICT, [both are valid.](https://en.wikipedia.org/wiki/ISO_8601#Time_offsets_from_UTC))" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-27T17:30:02.493", "Id": "102105", "ParentId": "13283", "Score": "1" } } ]
{ "AcceptedAnswerId": "13301", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T14:59:59.580", "Id": "13283", "Score": "10", "Tags": [ "java", "strings", "datetime" ], "Title": "Java Date formatter" }
13283
<p>I've been writing some smaller jQuery plugins lately, and I've been thinking of writing up some boilerplate that I can use when writing new ones. I have code that works (for now), but I want to share it and get feedback on things I may be missing as I move to larger plugins.</p> <pre><code>/** * jQuery Plugin Boilerplate * - find and replace the following variable names * - utilities : namespace for shared utility functions * - PluginClass : class name for plugin object * - pluginName : the name of your plugin function, e.g. $('.foo').myPlugin() **/ (function($) { /** * Utility function object * - namespace wrapper for variables or functions shared between all plugin instances **/ var utilities = { // example utility function getInt: function(i) { i = parseInt(i, 10); return isNaN(i) ? 0 : i; } }, /** * Main plugin class * - encapsulate each instance of plugin as an object **/ PluginClass = { // other instance-specific functions get defined here init: function(el,options) { var _t = this; // for maintaining reference to plugin class in callbacks this.options = $.extend({}, $.fn.pluginName.defaults, options); this.el = el; this.$el = $(el); // do your plugin stuff }, callFn: function(fn) { switch(fn) { // case statements matching allowable function aliases // which execute the appropriate plugin functions } } }; /** * Plugin function * - for each element passed to the plugin, create a new class instance **/ $.fn.pluginName = function () { var arg = arguments[0]; var fn, options; // if the argument passed is a string, then the user // is calling a function. Otherwise, it's an options object if(typeof arg === 'string') { fn = arg; } else { options = arg; } if (this.length &gt; 0) { return this.each(function(i) { var el = $(this), p; // if plugin instance already exists, use it if(el.data('pluginName')) { p = el.data('pluginName'); if(fn) { p.callFn(fn); } else { p.init(this,options); } } else { p = Object.create(PluginClass); el.data('pluginName', p); p.init(this,options); } }); } }; /** * Plugin default options * - created outside of plugin function for easier overriding by user **/ $.fn.pluginName.defaults = { some: thing, foo: 'bar' }; })(jQuery);​ </code></pre> <p>Here's an example I created using this boilerplate. It's nothing fancy, it simply takes the text of an element and paints each character with a different color.</p> <p><a href="http://jsfiddle.net/jackwanders/ggBaP/" rel="nofollow"><strong>jQuery Plugin Demo - $.paintText()</strong></a></p> <p>My main concern here is with the functionality of using <code>$('#foo').paintText('fnAlias')</code> to call a function on an existing plugin instance. My way seems to work, but part of me feels there may be a more efficient way.</p> <p>Thanks for any help.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T15:17:27.550", "Id": "21455", "Score": "0", "body": "Do you mean `p = new PluginClass.init(this,options)`? You can't `new` the `PluginClass` itself because it's not a function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T15:23:25.953", "Id": "21456", "Score": "0", "body": "Oh, that's a typo, that should be `Object.create(PluginClass)`. I'll edit" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T10:35:37.120", "Id": "21684", "Score": "0", "body": "If you haven't come across this one, there is already a [jQuery boilerplate](http://jqueryboilerplate.com/) that I tend to use when making plugins." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T15:54:46.153", "Id": "68726", "Score": "1", "body": "As you're writing boiler you should follow the jQuery style guide's [directions on spacing](http://contribute.jquery.org/style-guide/js/#spacing)" } ]
[ { "body": "<p>From a once over:</p>\n\n<ul>\n<li>I like how you store both <code>el</code> and <code>$el</code> </li>\n<li>I also like how you expose your defaults</li>\n<li>Not sure about <code>_t</code>, I think generally <code>self</code> is considered to a better name for <code>this</code></li>\n<li>You should have a spot in your boilerplate to define the <code>prototype</code> of your plugin class</li>\n<li>Lint finds nothing worth mentioning</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T14:17:47.020", "Id": "40742", "ParentId": "13284", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T15:08:59.027", "Id": "13284", "Score": "2", "Tags": [ "javascript", "jquery", "design-patterns", "plugin" ], "Title": "Creating boilerplate for jQuery plugins" }
13284
<p>This code is intended to take input as a string, do a SHA-256 hash on the string, and return the result.</p> <p>It works correctly for the standard test vectors (test code included at the bottom). I'm particularly interested in your thoughts about whether it would be a good idea for it to accept input in forms other than a string (e.g., be able to work directly with a <code>std::ifstream</code>).</p> <p>Another possibility that has occurred to me (but I'm not sure if it's worthwhile) would be to have it accept a pair of iterators. The (somewhat) unusual part about that is that even though we don't care about the form of the source, we do care about assuring that the iterator's value_type is <code>char</code> (or possibly a signed/unsigned variant).</p> <p>First the header:</p> <pre><code>// sha256.h #ifndef SHA_256_H_INCLUDED #define SHA_256_H_INCLUDED // This is a relatively straightforward implementation of SHA-256. It makes no particular // attempt at optimization, instead aiming toward easy verification against the standard. // To that end, many of the variable names are identical to those used in FIPS 180-2 and // FIPS 180-3. // // The code should be fairly portable, within a few limitations: // 1. It requires that 'char' have 8 bits. In theory this is avoidable, but I don't think // it's worth the bother. // 2. It only deals with inputs in (8-bit) bytes. In theory, SHA-256 can deal with a number of // bits that's not a multiple of 8, but I've never needed it. Since the padding always results // in a byte-sized stream, the only parts that would need changing would be reading and padding // the input. The main hashing portion would be unaffected. // // Originally written in February 2008 for SHA-1. // Converted to SHA-256 sometime later (sorry, I don't remember exactly when). // // You can use this software any way you want to, with following limitations // (shamelessly stolen from the Boost software license): // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // // If you put this to real use, I'd be happy to hear about it. If you find a bug, // I'd be interested in hearing about that too. There's even a pretty good chance // that I'll try to fix it, though I certainly can't guarantee that. // #include &lt;algorithm&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;assert.h&gt; #include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;iomanip&gt; #if defined(_MSC_VER) &amp;&amp; _MSC_VER &lt; 1600 typedef unsigned int uint32_t; typedef unsigned __int64 uint64_t; #else #include &lt;stdint.h&gt; #endif namespace crypto { namespace { struct ternary_operator { virtual uint32_t operator()(uint32_t x, uint32_t y, uint32_t z) = 0; }; } class sha256 { static const size_t hash_size = 8; static const size_t min_pad = 64; static const size_t block_bits = 512; static const size_t block_bytes = block_bits / 8; static const size_t block_words = block_bytes / 4; std::vector&lt;uint32_t&gt; K; std::vector&lt;uint32_t&gt; H; std::vector&lt;uint32_t&gt; W; std::vector&lt;ternary_operator *&gt; fs; std::vector&lt;uint32_t&gt; temp; static const size_t block_size = 16; static const size_t bytes_per_word = 4; size_t total_size; // hash a 512-bit block of input. // void hash_block(std::vector&lt;uint32_t&gt; const &amp;block); // Pad the input to a multiple of 512 bits, and add the length // in binary to the end. static std::string pad(std::string const &amp;input); // Turn 64 bytes into a block of 16 uint32_t's. std::vector&lt;uint32_t&gt; make_block(std::string const &amp;in); public: // Construct a SHA-256 object. More expensive that typical // ctor, but not expected to be copied a lot or anything // like that, so it should be fairly harmless. sha256(); // The two ways to provide input for hashing: as a stream or a string. // Either way, you get the result as a vector&lt;uint32_t&gt;. It's a fairly // small vector, so even if your compiler doesn't do return-value // optimization, the time for copying isn't like to be significant. // std::vector&lt;uint32_t&gt; operator()(std::string const &amp;input); friend std::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, sha256 const &amp;s); }; } #endif </code></pre> <p>And then the implementation:</p> <pre><code>#include "sha256.h" namespace crypto { namespace { uint32_t word(int a, int b, int c, int d) { a &amp;= 0xff; b &amp;= 0xff; c &amp;= 0xff; d &amp;= 0xff; int val = a &lt;&lt; 24 | b &lt;&lt; 16 | c &lt;&lt; 8 | d; return val; } uint32_t ROTR(uint32_t number, unsigned bits) { return (number &gt;&gt; bits) | (number &lt;&lt; (32-bits)); } uint32_t f1(uint32_t x, uint32_t y, uint32_t z) { return (x &amp; y) ^ (~x &amp; z); } uint32_t f2(uint32_t x, uint32_t y, uint32_t z) { return (x &amp; y) ^ (x&amp;z) ^ (y&amp;z); } uint32_t f3(uint32_t x) { return ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22); } uint32_t f4(uint32_t x) { return ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25); } uint32_t f5(uint32_t x) { return ROTR(x, 7) ^ ROTR(x, 18) ^ (x &gt;&gt; 3); } uint32_t f6(uint32_t x) { return ROTR(x, 17) ^ ROTR(x, 19) ^ (x &gt;&gt; 10); } uint32_t add(uint32_t a, uint32_t b) { return a+b; } } // Pad the input to a multiple of 512 bits, and add the length // in binary to the end. std::string sha256::pad(std::string const &amp;input) { uint64_t length = input.size() * 8 + 1; size_t remainder = length % block_bits; size_t k = (remainder &lt;= 448) ? 448 - remainder : 960 - remainder; std::string padding("\x80"); padding.append(std::string(k/8, '\0')); --length; for (int i=sizeof(length)-1; i&gt;-1; i--) { unsigned char byte = length &gt;&gt; (i*8) &amp; 0xff; padding.push_back(byte); } std::string ret(input+padding); return ret; } // Turn 64 bytes into a vector of 16 uint32_t's. std::vector&lt;uint32_t&gt; sha256::make_block(std::string const &amp;in) { assert(in.size() &gt;= block_bytes); std::vector&lt;uint32_t&gt; ret(block_words); for (size_t i=0; i&lt;block_words; i++) { size_t s = i*4; ret[i] = word(in[s], in[s+1], in[s+2], in[s+3]); } return ret; } sha256::sha256() : H(hash_size), W(64), temp(10) { static const uint32_t H0[hash_size] = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 }; std::copy(H0, H0+hash_size, H.begin()); } void sha256::hash_block(std::vector&lt;uint32_t&gt; const &amp;block) { static const uint32_t K[] = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; assert(block.size() == 16); std::copy(block.begin(), block.end(), W.begin()); for (int t=16; t&lt;64; ++t) W[t] = f6(W[t-2]) + W[t-7] + f5(W[t-15]) + W[t-16]; std::copy(H.begin(), H.end(), temp.begin()); for (int t=0; t&lt;64; ++t) { temp[8] = temp[7]+f4(temp[4]) + f1(temp[4],temp[5],temp[6])+K[t]+W[t]; temp[9] = f3(temp[0]) + f2(temp[0], temp[1], temp[2]); temp[7] = temp[6]; temp[6] = temp[5]; temp[5] = temp[4]; temp[4] = temp[3] + temp[8]; temp[3] = temp[2]; temp[2] = temp[1]; temp[1] = temp[0]; temp[0] = temp[8] + temp[9]; } std::transform(H.begin(), H.end(), temp.begin(), H.begin(), add); } // Take a `std::string` as input, produce a SHA-256 hash as a vector of 16 uint32_ts'. // std::vector&lt;uint32_t&gt; sha256::operator()(std::string const &amp;input) { std::string temp(pad(input)); std::vector&lt;uint32_t&gt; block(block_size); size_t num = temp.size()/block_bytes; for (unsigned block_num=0; block_num&lt;num; block_num++) { size_t s; for (size_t i=0; i&lt;block_size; i++) { s = block_num*block_bytes+i*4; block[i] = word(temp[s], temp[s+1], temp[s+2], temp[s+3]); } hash_block(block); } return H; } std::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, sha256 const &amp;s) { // Display hash result in hex. for (size_t i=0; i&lt;(s.H).size(); i++) os &lt;&lt; std::fixed &lt;&lt; std::setprecision(8) &lt;&lt; std::hex &lt;&lt; std::setfill('0') &lt;&lt; (s.H)[i] &lt;&lt; " "; return os &lt;&lt; std::dec &lt;&lt; std::setfill(' ') &lt;&lt; "\n"; } } #ifdef TEST #include &lt;iostream&gt; #include &lt;iomanip&gt; #include &lt;string&gt; #include &lt;sstream&gt; // A minimal test harness to check that it's working correctly. Strictly black-box // testing, with no attempt at things like coverage analysis. Nonetheless, I believe // it should cover most of the code -- the core hashing code all gets used for every // possible value. The padding code should be tested fairly thoroughly as well -- the // first test is a fairly simple case, and the second the more complex one (where the // padding requires adding another block). class tester { bool verify(uint32_t *test_val, std::vector&lt;uint32_t&gt; const &amp;hash, std::ostream &amp;os) { // Verify that a result matches a test value and report result. for (size_t i=0; i&lt;hash.size(); i++) if (hash[i] != test_val[i]) { os &lt;&lt; "Mismatch. Expected: " &lt;&lt; test_val[i] &lt;&lt; ", but found: " &lt;&lt; hash[i] &lt;&lt; "\n"; return false; } os &lt;&lt; "Message digest Verified.\n\n"; return true; } public: bool operator()(uint32_t *test_val, std::string const &amp;input) { std::cout &lt;&lt; "Testing hashing from string:\n\"" &lt;&lt; input &lt;&lt; "\"\n"; crypto::sha256 hasher1; std::vector&lt;uint32_t&gt; hash = hasher1(input); std::cout &lt;&lt; "Message digest is:\n\t" &lt;&lt; hasher1; return verify(test_val, hash, std::cerr); } }; int main() { char const *input1 = "abc"; uint32_t result1[] = {0xba7816bf, 0x8f01cfea, 0x414140de, 0x5dae2223, 0xb00361a3, 0x96177a9c, 0xb410ff61, 0xf20015ad}; char const *input2 = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; uint32_t result2[] = {0x248d6a61, 0xd20638b8, 0xe5c02693, 0x0c3e6039, 0xa33ce459, 0x64ff2167, 0xf6ecedd4, 0x19db06c1}; bool correct = tester()(result1, input1); correct &amp;= tester()(result2, input2); if (correct) std::cerr &lt;&lt; "All Tests passed!\n"; else std::cerr &lt;&lt; "Test Failed!\n"; } #endif </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T21:19:15.643", "Id": "21475", "Score": "3", "body": "Reinventing the wheel. While it may be fun I do think I would ever use any crypto software that has not come from authoritative crypto site validated by lots of people in the field." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-12T07:42:37.803", "Id": "347068", "Score": "0", "body": "@Loki Lost in negation? ;)" } ]
[ { "body": "<p>Virtual operator?</p>\n\n<pre><code>struct ternary_operator { \n virtual uint32_t operator()(uint32_t x, uint32_t y, uint32_t z) = 0;\n };\n</code></pre>\n\n<p>Personally I thinks this obfuscates the meaning and makes it harder to see that the call is using virtual dispatch (but that is just an opinion there is nothing technically wrong here).</p>\n\n<p>I have a hard time following the logic here:</p>\n\n<pre><code>std::string sha256::pad(std::string const &amp;input) {\n</code></pre>\n\n<p>Also the comment does not accurately reflect what it does:</p>\n\n<pre><code>// Pad the input to a multiple of 512 bits, and add the length\n// in binary to the end.\n</code></pre>\n\n<p>After decoding this I find that you are adding the length to the end. <strong>BUT</strong> the length takes it upto the 512 bit byte boundary. It is not added after the string has been padded.</p>\n\n<p>I assume this:</p>\n\n<pre><code>for (int i=sizeof(length)-1; i&gt;-1; i--) {\n unsigned char byte = length &gt;&gt; (i*8) &amp; 0xff;\n padding.push_back(byte);\n}\n</code></pre>\n\n<p>Is trying to compensate for endianeess. I would rather see a standard function here. Something like <code>htonl()</code> or an equivalent.</p>\n\n<p>I assume there is a reason that the padding starts with: '\\x80`. It would be nice that is in the comment. There must be a technical reason you are not '\\0' padding the string.</p>\n\n<pre><code>std::string padding(\"\\x80\");\npadding.append(std::string(k/8, '\\0'));\n</code></pre>\n\n<p>I prefer to always use {} in sub-statements. That way my code looks consistent:</p>\n\n<pre><code>for (int t=16; t&lt;64; ++t) \n W[t] = f6(W[t-2]) + W[t-7] + f5(W[t-15]) + W[t-16];\n</code></pre>\n\n<p>It always worries my bare statement inside an if. Especially with function calls that potentially look like macros.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T22:19:33.103", "Id": "13294", "ParentId": "13288", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T16:32:42.577", "Id": "13288", "Score": "5", "Tags": [ "c++", "cryptography" ], "Title": "Perform SHA-256 on input" }
13288
<p>Here is my attempt at a PHP class to be used as a base class for typed collections. My goals with this are:</p> <ul> <li>to be able to access collection members with foreach</li> <li>to be able to access collection members using indices (array-like)</li> <li>to ensure that all collection members are objects of the same type</li> </ul> <p>I have implemented the appropriate interfaces. Here is the code:</p> <pre><code>&lt;?php /** * A class to hold a collection of objects of the same type. * * There are tow purposes: * - to ensure that all elements are of the same type * - to be enumerable by the foreach loop */ abstract class TypedCollection implements Countable, Iterator, ArrayAccess { /** * Child classes pass the collection type to this constructor * * @param string $typeName The name of the underlying class * @throws InvalidArgumentException If the class can't be found by reflection */ public function __construct($typeName) { if(class_exists($typeName)) { $this-&gt;_type = new ReflectionClass($typeName); } else { throw new InvalidArgumentException( "The class $typeName does not exist."); } } /* Implement Countable */ /** * Returns the count of the elements in the collection * @return int */ public function count() { return count($this-&gt;_innerArray); } /* Implement Iterator */ /** * Returns the current element of the collection * @return Object */ public function current() { return current($this-&gt;_innerArray); } /** * Return the key of the current element * @return int */ public function key() { return key($this-&gt;_innerArray); } /** * Move forward to next element */ public function next() { next($this-&gt;_innerArray); } /** * Rewind to its first element */ public function rewind() { reset($this-&gt;_innerArray); } /** * Checks if the current position is valid * @return bool */ public function valid() { return $this-&gt;current() !== false; } /* Implement ArrayAccess */ /** * Whether an offset exists * @param int $offset * @return bool */ public function offsetExists($offset) { return isset($this-&gt;_innerArray[$offset]); } /** * Returns the value at the specified offset * @param int $offset * @return int */ public function offsetGet($offset) { if(isset($this-&gt;_innerArray[$offset])) { return $this-&gt;_innerArray[$offset]; } else { return null; } } /** * Assigns a value to the specified offset * @param int $offset * @param mixed $object * @throws InvalidArgumentException If $object is not of the underlying type */ public function offsetSet($offset, $object) { if ($object instanceof $this-&gt;_type-&gt;name) { if (is_null($offset)) { $this-&gt;_innerArray[] = $object; } else { $this-&gt;_innerArray[$offset] = $object; } } else { throw new InvalidArgumentException( "Object needs to be a $this-&gt;_type-&gt;name instance."); } } /** * Unsets an offset * @param int $offset */ public function offsetUnset($offset) { unset($this-&gt;_innerArray[$offset]); $this-&gt;_innerArray = array_values($this-&gt;_innerArray); } /* TypedCollection functions */ /** * Adds an object to the collection. * @param mixed $object The object to add to the collection */ public function add($object) { $this-&gt;offsetSet(null, $object); } /** * Removes all elements from the collection */ public function clear() { $this-&gt;_innerArray = array(); } /** * Checks if an object belongs to the collection * @param mixed $object * @return bool */ public function contains($object) { return in_array($object, $this-&gt;_innerArray, true); } /** * Return an object index * @param mixed $object * @return int */ public function indexOf($object) { return array_search($object); } /** * Inserts an object at the specified offset in the collection * @param int $offset * @param mixed $object * @throws InvalidArgumentException If the object is not of the underlying type * @throws OutOfRangeException If the offset does not exist */ public function insert($offset, $object) { if(array_key_exists($offset, $this-&gt;_innerArray)) { if($object instanceof $this-&gt;_type-&gt;name) { $tempArray = array($object, $this-&gt;offsetGet($offset)); array_splice($this-&gt;_innerArray, $offset, 1, $tempArray); $this-&gt;_innerArray = array_values($this-&gt;_innerArray); } else { throw new InvalidArgumentException( "Object needs to be a $this-&gt;_type-&gt;name instance."); } } else { throw new OutOfRangeException( "The index $offset does not exist in the collection."); } } /** * Removes the specified object from the collection * @param mixed $object */ public function remove($object) { if($this-&gt;contains($object)) { $this-&gt;offsetUnset(array_search($object, $this-&gt;_innerArray)); $this-&gt;_innerArray = array_values($this-&gt;_innerArray); } } /** * Removes the object at the specified offset in the collection * @param int $offset */ public function removeAt($offset) { $this-&gt;offsetUnset($offset); $this-&gt;_innerArray = array_values($this-&gt;_innerArray); } /** * The array that contains collection elements * @var array */ protected $_innerArray = array(); /** * The collection type * @var ReflectionClass */ protected $_type; } ?&gt; </code></pre> <p>A child class:</p> <pre><code>&lt;?php include_once 'TypedCollection.php'; include_once 'Statement.php'; class StatementCollection extends TypedCollection { public function __construct() { parent::__construct('Statement'); } } ?&gt; </code></pre> <p>How I use it:</p> <pre><code>$for2-&gt;Statements[0]-&gt;TrueStatements-&gt;add($break); $for2-&gt;Statements-&gt;add($echo1); </code></pre> <p>Any thoughts on the code are welcome.</p>
[]
[ { "body": "<p>Instead of recreating methods that perform functions that already exist ( <code>count()</code>, <code>current()</code>, etc...), have you thought of using PHP's magic <code>__toString()</code> method? I've not had much need to play around with it myself, but from my understanding you can use that magic method then just call functions such as <code>count()</code> and <code>current()</code> outside of the class with the class instance as its argument and it will accomplish the same thing. This will reduce your code considerably.</p>\n\n<p>In my opinion <code>offsetGet()</code> should either return the found offset, or FALSE. Usually when I see NULL that means an error occurred that made performing that task impossible and so it was silently handled. FALSE on the other hand says clearly that \"no this doesn't exist\". At least to me... This may just be a preference thing, I just thought it looked extremely odd.</p>\n\n<p>A better way to declare <code>offsetSet()</code> would be to reverse the arguments. If you expect that you aren't always going to use an argument it should be declared after those arguments that aren't ever going to be empty. That way calling that method will not begin with empty arguments.</p>\n\n<pre><code>$this-&gt;offsetSet( $object ); // Equivalent to $this-&gt;offsetSet( $object, '' );\n//Compared to...\n$this-&gt;offsetSet( '', $object );\n</code></pre>\n\n<p>When using PHP to process strings with variables, it is important to remember that PHP only expects simple variables such as <code>$name</code>. More complex variables, such as class properties or arrays will not work as expected. So <code>$this-&gt;_type-&gt;name</code> will not display what you are expecting. In fact, what PHP sees here is <code>$this</code> which can not be processed without <code>var_dump()</code> or <code>print_r()</code>. This is good, otherwise you'd have your entire class dumped onto the screen. Instead, what you will have to do is use PHP's escape identifiers <code>{}</code> (not right term, not sure what they're called) to wrap those more complex variables. Or you could abstract it by simplifying it before using it, but that means creating an unnecessary variable. So...</p>\n\n<pre><code>throw new InvalidArgumentException(\n \"Object needs to be a {$this-&gt;_type-&gt;name} instance.\");\n</code></pre>\n\n<p>I stopped here because most of what remained appeared to be things that could be fixed/removed with my first suggestion. Hopefully I didn't miss anything. I'll take another look at it if you want, just let me know. Hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T17:51:40.390", "Id": "21515", "Score": "0", "body": "I implemented count() and current() (and most of the other methods) as required by the implemented interfaces. I haven't used __toString() before, I'll have to test it to see if PHP complains if I don't define the methods explicitly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T17:56:39.010", "Id": "21516", "Score": "0", "body": "Same for offsetSet(), it is declared by ArrayAccess and the first argument as $offset and the second as $value (which I renamed to $object). I'll try to reverse the order to see if it works." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T18:05:54.380", "Id": "21517", "Score": "0", "body": "Thanks for that last tip on referencing _type->name, good explanation. I hope this site gets out of beta soon, I only stumbled upon it by chance. I like the concept, I think it could be very useful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T00:14:08.173", "Id": "21522", "Score": "0", "body": "@anonimista: I didn't think about that... If it comes down to it you might be able to extend the classes rather than implement them to bypass this need." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T19:23:26.230", "Id": "13291", "ParentId": "13290", "Score": "3" } } ]
{ "AcceptedAnswerId": "13291", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T18:27:38.273", "Id": "13290", "Score": "1", "Tags": [ "php", "object-oriented", "collections" ], "Title": "PHP Class to Represent a Type Collection" }
13290
<p>I have the following code that converts a couple of bash commands into Windows <code>cmd</code> commands, as well as adding some commands. This is only my second day programming in C++, so any and all suggestions would be helpful.</p> <pre><code>#include "stdafx.h" #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;regex&gt; #include &lt;fstream&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; #include &lt;conio.h&gt; using namespace std; using namespace std::tr1; class Parser { regex ls_regex, mkdir_regex, sleep_regex, rand_regex, rm_regex, touch_regex, cat_regex, open_regex, cp_regex, lat_regex; string touch_match, sleep_match, mkdir_match, ls_match, rm_match, open_match, cp_match; public: void SetRegexes(); void RunCommand(string); string ParseCommand(string); string SearchString(int, string); }; void Parser::SetRegexes() { // Regex is the bash command, match is the cmd command ls_regex = "^ls$"; ls_match = "dir"; mkdir_regex = "^mkdir"; mkdir_match = "md"; sleep_regex = "^sleep$"; sleep_match = "pause"; rand_regex = "^timerand$"; rm_regex = "^rm"; rm_match = "del"; touch_regex = "^touch"; cat_regex = "^cat"; open_regex = "^open"; open_match = "notepad"; cp_regex = "^cp"; cp_match = "copy"; lat_regex = "^lat"; } string Parser::ParseCommand(string unparsed) { // Checks if the regex can be found in the unparsed string if (regex_search(unparsed, ls_regex)) { // Unparsed now is actually parsed unparsed = unparsed.replace(0, 3, ls_match); } else if (regex_search(unparsed, mkdir_regex)) { unparsed = unparsed.replace(0, 5, mkdir_match); } else if (regex_search(unparsed, sleep_regex)) { unparsed = unparsed.replace(0, 4, sleep_match); } else if (regex_search(unparsed, rand_regex)) { srand(time(NULL)); cout &lt;&lt; rand() &lt;&lt; endl; return " "; } else if (regex_search(unparsed, rm_regex)) { unparsed = unparsed.replace(0, 2, rm_match); } else if (regex_search(unparsed, touch_regex)) { string tfile; for (int i = 0; i &lt; unparsed.length(); i++) { if (i &gt; 5) { tfile += unparsed[i]; } } ofstream create_file(tfile); return " "; } else if (regex_search(unparsed, cat_regex)) { string op_line; string catfile; for (int i = 0; i &lt; unparsed.length(); i++) { if (i &gt; 3) { catfile += unparsed[i]; } } ifstream input_file(catfile); while (input_file.good()) { getline(input_file, op_line); cout &lt;&lt; op_line; } cout &lt;&lt; endl; return " "; } else if (regex_search(unparsed, open_regex)) { unparsed = unparsed.replace(0, 5, open_match + " "); } else if (regex_search(unparsed, cp_regex)) { unparsed = unparsed.replace(0, 4, cp_match + " "); } else if (regex_search(unparsed, lat_regex)) { string latfile; string op_line; char holder; for (int i = 0; i &lt; unparsed.length(); i++) { if (i &gt; 3) { latfile += unparsed[i]; } } cout &lt;&lt; latfile &lt;&lt; endl &lt;&lt; endl; ifstream input_file(latfile); while (input_file.good()) { getline(input_file, op_line); cout &lt;&lt; op_line &lt;&lt; endl; // getch() makes it so the letters are not echoed to the keyoard holder = getch(); } return " "; } return unparsed; } void Parser::RunCommand(string parsed) { // Converts to a different type so it can be used in the system method const char *cparsed = parsed.c_str(); system(cparsed); } void _tmain(int argc, _TCHAR* argv[]) { string name; int line_counter = 0; Parser main_parser; main_parser.SetRegexes(); string command; // Provides a never-ending command line interface while (true) { line_counter++; cout &lt;&lt; "&lt;" &lt;&lt; line_counter &lt;&lt; name &lt;&lt; "-&gt; "; //cin &gt;&gt; command; getline(cin, command); command = main_parser.ParseCommand(command); main_parser.RunCommand(command); } } </code></pre>
[]
[ { "body": "<p>Some quick suggestions:</p>\n\n<ul>\n<li><p>Since SetRegexes() does not change the values of your data members, better make the data members constant and initialize them in the constructor's initializer list. Thus you save some runtime in setting the values at initialization.</p>\n\n<pre><code>private:\n const regex ls_regex ...\npublic:\n Parser() : ls_regex(\"^ls$\"),\n mkdir_regex(\"^mkdir\"), ...\n</code></pre></li>\n<li><p>The function <code>string Parser::ParseCommand(string unparsed)</code> can be\nconverted to <code>void Parser::ParseCommand(string&amp; unparsed)</code> since what\nyou are doing is modifying the input <code>unparsed</code>. You don't need to return the input when it is a reference.</p></li>\n<li><p>I would suggest breaking the function <code>ParseCommand(string unparsed)</code> into two parts. First parts converts the input to a corresponsing enum. The second part switches this enum to the appropriate step. This way it is easier to read. Refer to this for the benefits of using switch over if-else: <a href=\"https://stackoverflow.com/questions/1028437/why-switch-case-and-not-if-else-if\">https://stackoverflow.com/questions/1028437/why-switch-case-and-not-if-else-if</a>.</p>\n\n<pre><code>typedef enum Ens {\n enLSRegex = 0,\n enLSMatch = 1, \n ...\n enInvalid\n} Ens;\n\nEns Parser::getEns( const string unparsed )\n{\n Ens en = enInvalid;\n if (regex_search(unparsed, ls_regex))\n en = enLSRegex ;\n else if(regex_search(unparsed, mkdir_regex))\n en = enLSMatch ;\n ...\n return en;\n}\n\nvoid Parser::ParseCommand(string&amp; unparsed)\n{\n switch( getEns(unparsed) )\n {\n case enLSRegex:\n unparsed = unparsed.replace(0, 3, ls_match);\n break;\n case enLSMatch:\n unparsed = unparsed.replace(0, 5, mkdir_match);\n break;\n ...\n }\n}\n</code></pre></li>\n<li><p>Use updated versions of the libraries. Use cstdlib, ctime, conio for stdlib.h, time.h and conio.h respectively.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T09:35:30.273", "Id": "13310", "ParentId": "13296", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T22:54:45.493", "Id": "13296", "Score": "1", "Tags": [ "c++", "parsing", "beginner", "shell", "windows" ], "Title": "Converting Bash commands into Windows cmd commands" }
13296
<p>I wrote this script to collect evidence of the number of days worked for the purpose of claiming some government tax credits.</p> <p>I'm looking for some ways to clean it up. I'm especially wondering if there is a cleaner way to uniqueify a list than <code>list(set(my_list)</code> and maybe a better way to do:</p> <blockquote> <pre><code>d = dict(zip(commiters, [0 for x in xrange(len(commiters))])) </code></pre> </blockquote> <pre><code>import os from pprint import pprint lines = os.popen('git log --all').read().split('\n') author_lines = filter(lambda str: str.startswith('Author'), lines) date_lines = filter(lambda str: str.startswith('Date'), lines) author_lines = map(lambda str: str[8:], author_lines) date_lines = map(lambda str: str[8:18].strip(), date_lines) lines = zip(author_lines, date_lines) lines = sorted(list(set(lines)), key = lambda tup: tup[0]) commiters = list(set(map(lambda tup: tup[0], lines))) d = dict(zip(commiters, [0 for x in xrange(len(commiters))])) for item in lines: d[item[0]] += 1 pprint(d) </code></pre>
[]
[ { "body": "<p>For this part:</p>\n\n<pre><code>author_lines = filter(lambda str: str.startswith('Author'), lines)\ndate_lines = filter(lambda str: str.startswith('Date'), lines)\nauthor_lines = map(lambda str: str[8:], author_lines)\ndate_lines = map(lambda str: str[8:18].strip(), date_lines)\n</code></pre>\n\n<p>This might be clearer, not that I have anything against map or filter, but list comprehensions do combine them nicely when you need both:</p>\n\n<pre><code>author_lines = [line[8:] for line in lines if line.startswith('Author')]\ndate_lines = [line[8:18].strip() for line in lines if line.startswith('Date')]\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>lines = sorted(list(set(lines)), key = lambda tup: tup[0])\n</code></pre>\n\n<p>Can become:</p>\n\n<pre><code>lines = sorted(set(lines), key = lambda tup: tup[0])\n</code></pre>\n\n<p>for slightly less repetition (<code>sorted</code> automatically converts to a list).<br>\nAnd are you sure the <code>key</code> is even necessary? Tuples get sorted by elements just fine, the only reason to sort specifically by only the first element is if you want to preserve the original order of lines with the same author, rather than sorting them by the date line.<br>\n... Actually, why are you even sorting this at all? I don't see anything in the rest of the code that will work any differently whether it's sorted or not.</p>\n\n<p>For this:</p>\n\n<pre><code>commiters = list(set(map(lambda tup: tup[0], lines)))\n</code></pre>\n\n<p>Why are you zipping author_lines and date_lines and then unzipping again? Just do:</p>\n\n<pre><code>commiters = set(author_lines)\n</code></pre>\n\n<p>or am I missing something?</p>\n\n<p>And this:</p>\n\n<pre><code>d = dict(zip(commiters, [0 for x in xrange(len(commiters))]))\nfor item in lines:\n d[item[0]] += 1\n</code></pre>\n\n<p>You're just getting commit counts, right? Use <code>Counter</code>:</p>\n\n<pre><code>import collections\nd = collections.Counter([author_line for author_line,_ in lines])\n</code></pre>\n\n<p>Or, if your python version doesn't have <code>collections.Counter</code>:</p>\n\n<pre><code>import collections\nd = collections.defaultdict(lambda: 0)\nfor author_line,_ in lines:\n d[author_line] += 1\n</code></pre>\n\n<p>... Wait, are you even using date_lines anywhere? If not, what are they there for?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T14:32:51.740", "Id": "21508", "Score": "1", "body": "date_lines is there so that list(set(lines)) will leave behind only the lines that have a unique author and day of commit. I'm trying to count the number of days that a particular author made a commit.\n\nIts true that they don't need to be sorted, that was left over from when I changed my algorithm slightly. I also like your version of collecting the author_lines and date_lines.\n\nI'll look into the collections library more, I'm not sure if I like Counter, but I definitely like the `for author_line,_ in lines` syntax." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T15:25:13.317", "Id": "21510", "Score": "0", "body": "@Drew - Oh, right! That makes sense. In that case I'd probably do the `list(set(lines))` as you did and then just do a list comprehension to discard all the date lines, since you no longer need them and they only seem to get in the way later. (Also I'd probably rename some of your variables, like `lines`, to make it more obvious what they're doing, like `author_day_pairs` or something)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T21:13:28.907", "Id": "21521", "Score": "0", "body": "Oooh, getting rid of the date_lines afterwards is a great idea. Thanks!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T06:08:29.767", "Id": "13303", "ParentId": "13298", "Score": "2" } } ]
{ "AcceptedAnswerId": "13303", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T23:29:15.943", "Id": "13298", "Score": "4", "Tags": [ "python", "git" ], "Title": "Counting the number of days worked for all commiters to a git repo" }
13298
<p>I am using wordpress to allow a client to enter a curriculum vitae and have it output the correct and consistent html formatting:</p> <p><img src="https://i.stack.imgur.com/U4N0S.png" alt="enter image description here"></p> <p>So I have a plain text box custom field and am having them enter in the content in the following way:</p> <pre><code>[section "Solo Exhibitions"] [year 2011] Inner Space January 11 Peter Pan February 11 [section "Group Shows"] [year 2009] Group Show January 09 Big Group Show February 09 </code></pre> <p>So on and so forth. I wrote the following to parse that text field and output the correct HTML formatting, but I think it is pretty brute force-- not very much finesse.</p> <pre><code>$cv = get('cv_text'); $cv = strip_tags($cv); // Remove empty line breaks $cv = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "", $cv); // Explode line breaks $cv = explode("\n", $cv); $i = 0; foreach($cv as $line) { if( preg_match('/\[section \"(.*)\"\]/', $line) ) { echo preg_replace('/\[section \"(.*)\"\]/', '&lt;h2&gt;$1&lt;/h2&gt;', $line); } elseif( preg_match('/\[year (\d*)\]/', $line) ) { echo preg_replace('/\[year (\d*)\]/', '&lt;h3&gt;$1&lt;/h3&gt;', $line); } else { // Count every two lines and wrap in a &lt;p&gt; tag if($i === 1) { echo '&lt;em&gt;'.$line.'&lt;/em&gt;&lt;/p&gt;'; $i = 0; continue; } else { echo '&lt;p&gt;'.$line.'&lt;/br&gt; '; $i++; } } } </code></pre> <p>Can anyone recommend a way to improve my present code or present a better approach?</p> <p>Thanks!</p>
[]
[ { "body": "<p>Why are you having them write that all in one box? And with custom tags no less!</p>\n\n<p>I'd just create a form with each of these fields in it (section, year, event), with a JS \"add\" button below the event to add additional events to the DOM. Then if you want to give them the option of adding multiple sections at a time, then you can add another \"add\" button below the section that will duplicate an unmodified version of the original form so that they can do it all over again.</p>\n\n<p>This is much better than having your client learn your custom tags for your program. And if you were to continue this route you'd end up recreating BB code, which there are plenty enough out there that you'd be better off downloading one instead. Not to mention that the above method is also easier on you. No need to create a custom parser at that point, just extract the proper keys from the POST data. I'm not going to put the code here, simply because a simple google search will find what you're looking for easier and faster than I could write it all here.</p>\n\n<p>As for improvement to your code, I'd steer clear of Regex, but that's just me. I wasn't born on whatever planet that language came from.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T22:11:05.453", "Id": "21670", "Score": "0", "body": "I had tried it your way originally and it was just so clunky... they are going to have 50 entries, and 50 duplicate forms is not readable or usable, while using a simple shortcode scheme and being able to just cut and paste makes alot more sense for them." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T14:30:39.507", "Id": "13356", "ParentId": "13300", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T02:04:04.210", "Id": "13300", "Score": "1", "Tags": [ "php", "regex" ], "Title": "Improving a shortcode replacement routine PHP and regex" }
13300
<p>Linq already has a set of <a href="http://msdn.microsoft.com/en-us/library/bb534501">GroupBy methods for enumerable</a>, which returns <code>IEnumerable&lt;IGrouping&lt;TKey, TSource&gt;&gt;</code>. I dislike this return type because it means I have to do a where query everytime I want to find a group. I try to make something that returns a dictionary instead, as below:</p> <pre><code> public static class GroupByExtension { public static Dictionary&lt;TKey, List&lt;TSource&gt;&gt; GroupToDictionary&lt;TSource, TKey&gt;( this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, TKey&gt; keySelector) { return source.GroupBy(keySelector).ToDictionary (grouping =&gt; grouping.Key, grouping =&gt; grouping.ToList()); } } </code></pre> <p>I can test it like this</p> <pre><code>List&lt;int&gt; list = new List&lt;int&gt;() { 1, 2, 33, 4, 20, 43, 21, 93, 26, 31, 113 }; Dictionary&lt;int, List&lt;int&gt;&gt; numbersGroup = list.GroupToDictionary(i =&gt; i / 10); //group number by result of division by ten. </code></pre> <p>So, I can call numbersGroup[1], numbersGroup[3], etc. as opposed to the more clumsy and less efficient <code>Where</code>'s clauses if I only have <code>IEnumerable&lt;IGrouping&lt;TKey, TSource&gt;&gt;</code></p> <pre><code>IEnumerable&lt;IGrouping&lt;int, int&gt;&gt; numbersGroup2 = list.GroupBy(i =&gt; i / 10); IGrouping&lt;int, int&gt; group = numbersGroup2.Where(grouping =&gt; grouping.Key == 3).First(); //and this only returns an IGrouping, not a proper list, //and where can be expensive for large list because it uses O(n) IIRC //the first() could have also been avoided because we know that the keys are unique </code></pre> <p>What do you think of this code? What drawback do you see? And what is the reason Microsoft use <code>IEnumerable&lt;IGrouping&lt;TKey, TSource&gt;&gt;</code></p>
[]
[ { "body": "<p>Returning an interface type makes the software very future proof.</p>\n\n<p>Even now, LINQ is works with any number of different providers, and each can implement the grouping in different ways, as long as the interface requirements are met. One example is that a LINQ provider can implement a lazy loaded grouping, which is not how the dictionary works.</p>\n\n<p>Another option would be to create a class that implements IGrouping and gives you access through the this[] accessor.</p>\n\n<p>Anyway, your solution is also quite good in my opinion. Just change the function return type to IDictionary instead of Dictionary, so you can change the implementation in the future.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T07:36:03.823", "Id": "21486", "Score": "1", "body": "But that doesn't explain why doesn't `GrouBy()` return something like `IDictionary<TKey, IList<TSource>>`, that's an interface type and could work with any provider." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T07:38:25.960", "Id": "21488", "Score": "0", "body": "Well, a LINQ provider could e.g. implement the grouping with lazy loading. That wouldn't work with a dictionary. IDictionary and IGrouping represent different things and should be represented differently" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T07:40:52.037", "Id": "21489", "Score": "0", "body": "ah I see.. what do you mean by \"providers\"? Also do you think I should change `List` to `IList` too?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T11:24:46.140", "Id": "21501", "Score": "0", "body": "Provider I mean that the LINQ could be interfacing with XML, SQL, objects, or anything else.\nIt's always a good idea to use the interfaces indeed, IList is a good example." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T07:34:16.433", "Id": "13306", "ParentId": "13305", "Score": "6" } }, { "body": "<p>I think the reason it's done this way is to make <code>GroupBy()</code> consistent with the rest of LINQ: everything is as lazy as possible, so that following queries can be efficient.</p>\n\n<p>And there already is a method that does almost the same thing as your <code>GroupToDictionary()</code>, it's called <a href=\"http://msdn.microsoft.com/en-us/library/bb549073.aspx\"><code>ToLookup()</code></a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T07:42:18.620", "Id": "21490", "Score": "0", "body": "ah, never heard of that, is look up similar to `IDictionary<TKey, List<TValue>>`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T08:20:42.893", "Id": "21493", "Score": "0", "body": "Yes, thanks to [its indexer](http://msdn.microsoft.com/en-us/library/bb549314.aspx), it behaves close to `Dictionary<TKey, IEnumerable<TValue>>` (it doesn't actually implement that interface)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T08:24:53.013", "Id": "21495", "Score": "1", "body": "nice.. does it have deferred/lazy loading? (just curious, not that it matters for me)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T08:28:41.323", "Id": "21496", "Score": "4", "body": "No, all of the `ToXxx()` methods don't use lazy loading or deferred execution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-11T04:39:06.027", "Id": "287566", "Score": "0", "body": "Also, `GroupBy` uses `Lookup` to get the groupings https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,60e7f83f7c37000f" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T07:39:11.870", "Id": "13308", "ParentId": "13305", "Score": "18" } }, { "body": "<p>The main reason for using <code>IEnumerable&lt;IGrouping&lt;TKey, TValue&gt;&gt;</code> would be defered loading/calculation, meaning that:</p>\n\n<pre><code>list.GroupBy(i =&gt; i / 10)\n</code></pre>\n\n<p>Would be almost instant, as no calculation and grouping are performed.<br>\nIn your <code>GroupToDictionary</code> method the groupings are calculated when the method is called. So basically you are waiting in another place in the code.</p>\n\n<p>The difference between your <code>GroupToDictionary</code> and the <code>IEnumerable</code> is that when a where is performed on the <code>IEnumerable</code> the calculation is performed when iterating over the value, and this is done each time the value is used as the result aren't cached. A common way to get around this is to either do <code>ToDictionary</code>, <code>ToList</code>, <code>ToArray</code> or any other \"conversion\" which enumerates a saves the result. This also gives you the performance you expect.</p>\n\n<p>So basically I don't think there is anything wrong with you code, it the example provided you don't need defered loading, and that is one of the cases where I would do the same.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T09:40:26.973", "Id": "21499", "Score": "0", "body": "interesting.. But how could group by be yielded one by one? the grouper code will need to iterate one by one before returning the first value anyway right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T10:47:02.270", "Id": "21500", "Score": "0", "body": "@LouisRhys That is correct, the groups are created before returning the values. The difference is when the groups are created." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T08:14:10.517", "Id": "13309", "ParentId": "13305", "Score": "4" } } ]
{ "AcceptedAnswerId": "13308", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T07:17:01.957", "Id": "13305", "Score": "13", "Tags": [ "c#", ".net", "linq" ], "Title": "What do you think of this improvement of Linq's GroupBy method?" }
13305
<p>I am a newbie programmer learning some C++. One of the exercises in my book asked me to write a basic console calculator that takes 2 numbers and an operation as input. I have done so and the program compiles (both with clang++ and g++) and runs fine.</p> <p>I would like to know if:</p> <ul> <li>I am making mistakes in my code that the compiler is allowing me to get away with</li> <li>If my code can be made more resource efficient and/or shorter in length</li> </ul> <p></p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { char operation; double first_number; double second_number; double solution = 0; cout &lt;&lt; "This is a basic calculator program, enter the first number.\n"; cout &lt;&lt; "First number:"; cin &gt;&gt; first_number; cout &lt;&lt; "Enter second number:"; cin &gt;&gt; second_number; cout &lt;&lt; "\nEnter an operation to perform, choose one from this list: +,-,/,*\n"; cout &lt;&lt; "Enter your operation:"; cin &gt;&gt; operation; cin.ignore(); if (operation != '+' &amp;&amp; operation != '-'&amp;&amp; operation != '/'&amp;&amp; operation != '*') { cout &lt;&lt; "\nInvalid operation! Aborting!"; cout &lt;&lt; "\nPress Enter to exit."; cin.get(); return 1; }//end if if (operation == '+') { solution = first_number + second_number; cout &lt;&lt; "\nYour answer is: " &lt;&lt; solution &lt;&lt; "\nPress Enter to exit.\n"; cin.get(); return 0; }//end if if (operation == '-') { solution = first_number - second_number; cout &lt;&lt; "\nYour answer is: " &lt;&lt; solution &lt;&lt; "\nPress Enter to exit.\n"; cin.get(); return 0; }//end if if (operation == '*') { solution = first_number * second_number; cout &lt;&lt; "\nYour answer is: " &lt;&lt; solution &lt;&lt; "\nPress Enter to exit.\n"; cin.get(); return 0; }//end if if (operation == '/') { if ( second_number == 0 ) { cout &lt;&lt; "\nYou can't divide by zero! Aborting!"; cout &lt;&lt; "\nPress Enter to exit."; cin.get(); return 2; }//end if solution = first_number / second_number; cout &lt;&lt; "\nYour answer is: " &lt;&lt; solution &lt;&lt; "\nPress Enter to exit.\n"; cin.get(); return 0; }//end if return 0; }//end main </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T04:58:13.680", "Id": "21502", "Score": "0", "body": "You can use enum to indicate the status, and move all the duplicate code to output and return to one place." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T04:58:16.980", "Id": "21503", "Score": "0", "body": "Great, it's always a nice approach to get code running first, then refine it. For starters, you might investigate use of a 'switch' statement instead of your multiple 'if' statements. Also, take a look at code you duplicate in several places. Such code might make up a function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T05:29:16.827", "Id": "21504", "Score": "0", "body": "If you'd like to see if the compiler is \"letting you get away with things\", you can try increasing the strictness / warning level on compiler (most likely via command-line options)..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-23T18:56:52.190", "Id": "22532", "Score": "0", "body": "since the operators are `char`, you can use a switch case instead of if's" } ]
[ { "body": "<p>You might want to check that your two numbers coming in are in fact numbers, if someone were to enter a letter, your program will crash. You might also want to split the operations up into other functions, it makes code more readable/ debug-able.\nLastly, when using <code>cout</code> and <code>cin</code>, don't create new lines using the backslash n character <code>\\n</code>, use <code>&lt;&lt; endl;</code> which simply ends the line.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T05:34:29.227", "Id": "21505", "Score": "4", "body": "Actually `std::endl` does more than just ending the line. By default it flushes the output buffer, so it may be better to avoid overusing it. See [here](http://stackoverflow.com/questions/213907/c-stdendl-vs-n)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T05:03:02.023", "Id": "13312", "ParentId": "13311", "Score": "2" } }, { "body": "<p>You are duplicating a lot of code. You might want to put </p>\n\n<pre><code>cout &lt;&lt; \"\\nYour answer is: \" &lt;&lt; solution &lt;&lt; \"\\nPress Enter to exit.\\n\";\n cin.get();\n return 0;\n</code></pre>\n\n<p>after all if conditions, so you will save a lot of space, since these three lines are repeated for each 'if'. In that case, however, you might want to replace your \"if\"s with \"else if\". \nYou can also output more than 1 line at a time like this:</p>\n\n<pre><code>cout &lt;&lt; \"some text\" &lt;&lt; \"some more text\" &lt;&lt; \"and some more\";\n</code></pre>\n\n<p>To end the line, you can also use 'endl' instead of \"\\n\":</p>\n\n<pre><code>cout &lt;&lt; \"some text\" &lt;&lt; endl;\n</code></pre>\n\n<p>So your code can look like this:</p>\n\n<pre><code> #include &lt;iostream&gt;\n using namespace std;\n int main()\n {\n //it is always a good idea to initialize variables right away. \n char operation = 0;\n double first_number = 0;\n double second_number = 0;\n double solution = 0;\n\n cout &lt;&lt; \"This is a basic calculator program, enter the first number.\" &lt;&lt; endl;\n cout &lt;&lt; \"First number:\";\n cin &gt;&gt; first_number;\n\n cout &lt;&lt; endl &lt;&lt; \"Enter second number:\";\n cin &gt;&gt; second_number;\n\n cout &lt;&lt; endl &lt;&lt; \"Enter an operation to perform, choose one from this list: +,-,/,*\\n\";\n cout &lt;&lt; \"Enter your operation:\";\n cin &gt;&gt; operation;\n cin.ignore();\n\n if (operation != '+' &amp;&amp; operation != '-'&amp;&amp; operation != '/' &amp;&amp; operation != '*')\n {\n cout &lt;&lt; endl &lt;&lt; \"Invalid operation! Aborting!\" &lt;&lt; endl &lt;&lt; \"Press Enter to exit.\";\n cin.get();\n return 1;\n }//end if\n\n if (operation == '+')\n solution = first_number + second_number;\n\n else if (operation == '-')\n solution = first_number - second_number;\n\n else if (operation == '*')\n solution = first_number * second_number;\n\n else if (operation == '/')\n {\n if ( second_number == 0 )\n {\n cout &lt;&lt; endl &lt;&lt; \"You can't divide by zero! Aborting!\";\n cout &lt;&lt; endl &lt;&lt; \"Press Enter to exit.\";\n cin.get();\n return 2;\n }//end if\n solution = first_number / second_number;\n }//end if\n\n ///Output starts here\n cout &lt;&lt; endl &lt;&lt; \"Your answer is: \" &lt;&lt; solution &lt;&lt; endl &lt;&lt; \"Press Enter to exit.\" &lt;&lt; endl;\n cin.get();\n return 0;\n }//end main\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T05:37:32.447", "Id": "13313", "ParentId": "13311", "Score": "4" } }, { "body": "<p>I'd try something like this. This is more robust as it checks for a 0 as the denominator and an invalid operation character.</p>\n\n<p>Checking the former before attempting a calculation would be best, though you can still have it ask again for a proper denominator instead of just terminating the program right away. I did the latter here anyway for simplicity.</p>\n\n<p>Checking the latter would involve either terminating the program right away or by throwing an exception since <code>calculate()</code> <em>must</em> return something (<code>throw</code> would replace <code>return</code> here, but should only be used in case of an error).</p>\n\n<pre><code>#include &lt;cstdlib&gt; // EXIT_FAILURE\n#include &lt;iostream&gt;\n#include &lt;stdexcept&gt; // std::logic_error\n\nfloat calculate(const char operation, const float left, const float right)\n{\n switch (operation)\n {\n case '+': return left + right;\n case '-': return left - right;\n case '*': return left * right;\n case '/': return left / right;\n default: throw std::logic_error(\"unsupported operator\");\n }\n}\n\nint main()\n{\n std::cout &lt;&lt; \"Enter your two numbers: \\n\\n\";\n float left, right;\n std::cin &gt;&gt; left &gt;&gt; right;\n\n std::cout &lt;&lt; \"\\nEnter your operation (+, -, *, /): \";\n char operation;\n std::cin &gt;&gt; operation;\n\n // terminate right away if dividing by zero\n if (operation == '/' &amp;&amp; right == 0)\n {\n std::cerr &lt;&lt; \"Cannot divide by 0\";\n return EXIT_FAILURE;\n }\n\n float result;\n\n // attempt the calculation (will throw if failed)\n try\n {\n result = calculate(operation, left, right);\n }\n // if it fails - catch exception, display it, then terminate\n catch (std::logic_error const&amp; e)\n {\n std::cerr &lt;&lt; \"Error: \" &lt;&lt; e.what();\n return EXIT_FAILURE;\n }\n\n std::cout &lt;&lt; \"\\nResult = \" &lt;&lt; result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T02:04:03.843", "Id": "45362", "Score": "1", "body": "`#include <cstdlib>` for EXIT_FAILURE. Rename the number variables to `left` and `right` or something. And throw an exception in the `default` clause instead of silently swallowing an error. Apart from that, much cleaner than the other approaches." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T02:16:38.907", "Id": "45363", "Score": "0", "body": "@Lstor: I had a feeling I didn't do enough in my `default`. Could you please tell me how it should be done inside a `switch` statement? I can't seem to find a firm answer anywhere." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T02:23:22.567", "Id": "45364", "Score": "0", "body": "I would've just `default: throw std::logic_error(\"unsupported operator\");` or something along those lines." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T02:32:14.477", "Id": "45365", "Score": "0", "body": "@Lstor: Ah. I've never seen that one before. I'm still getting an _unhandled exception_ error, though. Could that be compiler-specific?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T02:35:24.237", "Id": "45366", "Score": "1", "body": "A warning, surely? A program is not required to catch exceptions, but if an exception leaves `main`, `std::terminate()` will be called, which by default will `abort()` the program. The cleanest approach is to `catch` the exception somewhere as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T02:43:07.810", "Id": "45367", "Score": "0", "body": "@Lstor: No warnings, either. Would it be best to handle those errors in `main()`, then? I would still need a `default`, otherwise I'll be warned about not having enough `return`s." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T02:47:53.767", "Id": "45368", "Score": "0", "body": "I [answered in chat](http://chat.stackexchange.com/rooms/9728/c-code-reviews) to avoid a long comments thread here." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T23:27:08.643", "Id": "28852", "ParentId": "13311", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T04:50:12.213", "Id": "13311", "Score": "7", "Tags": [ "c++", "beginner", "console", "calculator" ], "Title": "Console calculator" }
13311
<pre><code>public static function find_user_tracks($id) { global $mySQL; $sql = "SELECT * FROM `tracks` WHERE account_id = {$id}"; $result_set = $mySQL-&gt;query($sql); $ret = array(); while($row = $result_set-&gt;fetch_assoc()) { $ret[] = $row; } return $ret; } </code></pre> <p>The above code contains the result of a database query. The database looks like this:</p> <p><img src="https://i.stack.imgur.com/q6vrg.png" alt="database screenshot"></p> <p>So, basically, it will return a set of fields with values and then those values will be used for a certain page:</p> <pre><code>$row = Track::find_user_tracks($id); if(!empty($row)) { $track_paths = array(); $track_names = array(); $track_desc = array(); $track_ids = array(); $track_artist = array(); for($i = 0 ;$i&lt;count($row);$i++) { $track_paths[] = $row[$i]['track_path']; $track_ids[] = $row[$i]['track_id']; $track_names[] = $row[$i]['track_name']; $track_desc[] = $row[$i]['track_desc']; $track_artist[] = $row[$i]['artist']; } echo "&lt;h1&gt; {$screename}'s Beats&lt;/h1&gt;"; } </code></pre> <p>The <code>$row</code> variable contains the result from the previous queries. I loop over <code>$row</code> to extract every single bit of data like <code>track_id</code>, <code>track_name</code>, etc. </p> <p>Is there any way to make this cleaner or improve it?</p>
[]
[ { "body": "<p>I think this will work. You'll have to have PHP version 5.3 though, otherwise you'll have to remove the lambda functions and define actual functions in their place. Disclaimer, not to say that this is easier to read or easier to understand, but I think it fits the \"cleaner\" request.</p>\n\n<pre><code>$track_paths = array_map( function ( $array ) { return $array[ 'track_path' ]; }, $row );\n$track_ids = array_map( function ( $array ) { return $array[ 'track_id' ]; }, $row );\n$track_names = array_map( function ( $array ) { return $array[ 'track_name' ]; }, $row );\n$track_desc = array_map( function ( $array ) { return $array[ 'track_desc' ]; }, $row );\n$track_artist = array_map( function ( $array ) { return $array[ 'track_artist' ]; }, $row );\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T14:06:19.410", "Id": "13355", "ParentId": "13316", "Score": "1" } } ]
{ "AcceptedAnswerId": "13355", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T15:47:20.100", "Id": "13316", "Score": "1", "Tags": [ "php", "array", "mysqli" ], "Title": "Extracting Multiple Associative arrays in PHP" }
13316
<p>What is the common practice to implement attributes that have side effects in Python? I wrote the following class which supposed to save singletons when a variable is going to get a certain value. The background is that my program had sparse data, meaning that there were a lot of objects having empty sets in their attributes which wasted a lot of memory. (my actual class is slightly more complex). Here is the solution I took:</p> <pre><code>class DefaultAttr: void="Void" def __init__(self, var_name, destroy, create): self.var_name=var_name self.destroy=destroy self.create=create def __get__(self, obj, owner=None): result=getattr(obj, self.var_name) if result is DefaultAttr.void: result=self.create() return result def __set__(self, obj, value): if value==self.destroy: value=DefaultAttr.void setattr(obj, self.var_name, value) class Test: a=DefaultAttr("_a", set(), set) def __init__(self, a): self._a=None self.a=a t=Test(set()) print(t._a, t.a) </code></pre> <p>Do you see a way to make it neater? I was wondering if I can avoid the hidden attribute <code>_a</code>. Also the <code>"Void"</code> solution seems dodgy. What would you do?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T18:47:29.497", "Id": "21518", "Score": "1", "body": "Python 2 or Python 3?" } ]
[ { "body": "<p>If you are using python 2, your code doesn't work at all. I'll assume you are using python 3.</p>\n\n<p>There a few cases where this will do unexpected things:</p>\n\n<pre><code>t=Test(set())\nt.a.add(2)\nprint t.a\n</code></pre>\n\n<p>The set will empty.</p>\n\n<pre><code>b = set()\nt = Test(b)\nb.add(2)\nprint t.a\n</code></pre>\n\n<p>The set will again be empty.</p>\n\n<p>These issues are caused because set are mutable. They go away if you only use immutable objects, such as <code>frozenset()</code>, or if you just never use the mutable operations on the sets.</p>\n\n<blockquote>\n <p>I was wondering if I can avoid the hidden attribute _a</p>\n</blockquote>\n\n<p>Instead of providing the name as a parameter, have DefaultAttr make one up such as <code>'_' + str(id(self))</code>. That'll provide a unique attribute to store data on.</p>\n\n<blockquote>\n <p>Also the \"Void\" solution seems dodgy</p>\n</blockquote>\n\n<p>Instead of <code>\"Void\"</code> use <code>object()</code>. It'll avoid a string comparison and be guaranteed unique.</p>\n\n<p>Alternately, delete the attribute using <code>delattr</code> instead of storing anything there. Absence of the attribute indicates that you should use the default value.</p>\n\n<p>Alternately, if you restrict the use of the object to immutable objects, just store a reference to the immutable object there. There is no need to use a special sentinel value. Here is my code to implement that idea:</p>\n\n<pre><code>class DefaultAttr(object):\n def __init__(self, empty):\n self._empty = empty\n self._name = '_' + str(id(self))\n\n def __get__(self, obj, owner=None):\n return getattr(obj, self._name)\n\n def __set__(self, obj, value):\n if value == self._empty:\n value = self._empty\n setattr(obj, self._name, value)\n</code></pre>\n\n<blockquote>\n <p>The background is that my program had sparse data, meaning that there\n were a lot of objects having empty sets in their attributes which\n wasted a lot of memory.</p>\n</blockquote>\n\n<p>Actually, your probably shouldn't be doing this at all. Instead, use <code>frozenset()</code>. Whenever you call <code>frozenset()</code> it returns the same set, so the empty sets won't take up excess memory. If you rework your app to use them, you should use much less memory.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T20:06:48.307", "Id": "21520", "Score": "0", "body": "Thanks! That's many great comments :) I think for the Void I will actually write a class which throws meaningful exceptions on most operations performed on it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T19:22:28.533", "Id": "13319", "ParentId": "13318", "Score": "3" } } ]
{ "AcceptedAnswerId": "13319", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T16:57:18.133", "Id": "13318", "Score": "1", "Tags": [ "python" ], "Title": "Attributes with special behaviour in Python" }
13318
<p>The common lisp function copy-tree is often implemented in a recursive way, and thus is prone to <a href="https://bugs.launchpad.net/sbcl/+bug/998926">stack overflow</a>.</p> <p>Here is my attempt at writing an iterative version, one-pass, no stack, no unnecessary consing, version of copy-tree in common-lisp, working with nested, perhaps dotted, lists.</p> <pre><code> (defun my-copy-tree (tree) (do* ((result (list tree)) (node result) (next)) ((null node) result) (cond ((and (consp (cdar node))(atom (caar node))) (setf (cdr node) (cons (cdar node) (cdr node)) (car node) (caar node) node (cdr node))) ((consp (cdar node)) (setf (cdr node) (cons (cdar node) (cdr node)) (car node) (cons (caar node) (cdr node)) node (car node))) ((consp (caar node)) (setf (car node) (cons (car node) (cdr node)) (cdr node) (cdaar node) node (car node) (car node) (caar node))) (t (setf next (cdr node) (cdr node) (cdar node) (car node) (caar node) node next))))) </code></pre> <p>The performance is ok. In fact, on sbcl it is faster than the native implementation, and almost as fast as copy-list for proper lists. It also has no problem making copies of "reversed" lists like the one given by</p> <pre><code>(reduce 'cons (make-list 1000000 :initial-element 0)) </code></pre> <p>(by the way, are there any lisp implementation with a native copy-tree that does not stack-overflow on these kind of deep lists ?)</p> <p>Unfortunately, my code is unreadable, and I must say I can't really understand it now without drawing a whole page of cons cells. Also it is not very flexible, e. g. there is no obvious way to turn it into a reduce-tree, in contrast to the recursive version.</p> <p>How to rewrite the code above in a more readable and flexible way, and so to speak in a more lispy way, without losing performance ?</p> <p>Writing an efficient implementation of copy-tree in lisp should be a standard exercice but google didn't bring anything relevant.</p>
[]
[ { "body": "<h2>RE: how to rewrite to make it more readable</h2>\n\n<ol>\n<li>Stop using <code>c[a,d]*r</code>. While I have a soft spot for them your code may be more readable via <code>first</code>, <code>second</code> etc.</li>\n<li>Name the predicates of the <code>cond</code> statement. What are they testing for? Use <code>flet</code> or <code>labels</code>.</li>\n<li>Perhaps name the <code>setf</code> blocks to make it more clear what they are doing.</li>\n<li>Perhaps split the <code>setf</code> blocks into separate <code>setf</code> lines. I had to check the hyperspec to verify that in fact each one was evaluated sequentially. It would be clearer if they were explicitly sequential.</li>\n</ol>\n\n<p>To summarize: </p>\n\n<ul>\n<li>improve naming </li>\n<li>make things explicit</li>\n</ul>\n\n<h2>Re: performance</h2>\n\n<p>Without having performance benchmarks I cannot tell how the above changes would change the performance of the code. I also noticed that you didn't specify a <code>optimize</code> declaration. That could be used to change performance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-27T13:22:05.727", "Id": "148824", "Score": "0", "body": "I disagree on the `setf` splitting (I see the distinction of `setf`/`psetf` as quite clear)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T02:08:55.063", "Id": "38805", "ParentId": "13321", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T19:48:15.673", "Id": "13321", "Score": "5", "Tags": [ "lisp", "common-lisp" ], "Title": "iterative copy-tree in lisp" }
13321
<p>I have a couple of jQuery animations running in a sequence after certain resources are loaded:</p> <pre><code>$(".loading").delay(2600).fadeOut({ useTranslate3d: true, }); $(".zip").delay(1900).slideDown({ useTranslate3d: true, }); $("#zip").delay(2800).slideDown({ useTranslate3d: true, }); </code></pre> <p>Is there a better way to combine all of these animations? It feels superfluous having to write them all out like this...</p>
[]
[ { "body": "<p>You can use the same <code>options</code> object for all three animations.</p>\n\n<pre><code>var opts = {\n useTranslate3d: true,\n}\n$(\".loading\").delay(2600).fadeOut(opts);\n$(\".zip\").delay(1900).slideDown(opts);\n$(\"#zip\").delay(2800).slideDown(opts);\n</code></pre>\n\n<p>Having <code>.zip</code> and <code>#zip</code> pointing to different elements might also be a bit confusing - but that depends on your DOM structure.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T01:06:50.673", "Id": "21523", "Score": "0", "body": "Yeah, I'll worry about the naming later." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T00:56:35.530", "Id": "13326", "ParentId": "13325", "Score": "2" } } ]
{ "AcceptedAnswerId": "13326", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T00:44:50.810", "Id": "13325", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Combining multiple jQuery animations?" }
13325
<p>I develop an android native application using phonegap and jquery mobile. I've made a function to create a listview style dynamically using looping <code>for..</code>. When I run the function for the first time, it works, the listview style is working, and match with the content. but when I press back button and run the function again, the style change (the listview style is gone) but the content still there. is my function wrong? how to solve this problem?<br/></p> <p>the screenshoot for more explanation:<br/></p> <ul> <li><a href="https://i.stack.imgur.com/WIS2Y.jpg" rel="nofollow noreferrer">this is the result when I press the back button and run the function again</a></li> </ul> <p>the codes for more detail:<br/></p> <pre><code>function detail(kodenegara, koderesult) { $.ajax({ type: "GET", contentType: "application/json; charset=utf-8", url: "http://10.80.3.73/webservice/Service1.svc/json/weeklyflash/"+kodenegara, dataType: "json", success:function(data){ var result = koderesult; maks = -1; for(i = 0; i &lt; data[result].length; i++) { if(data[result][i].bulan &gt; maks) maks = data[result][i].bulan; } var loop_tipe = countTypesForBulan(data[result], maks); var innerHtml = ""; for (i = 0; i &lt; loop_tipe; i++){ a=i+loop_tipe; b=a+loop_tipe; innerHtml += "&lt;div data-role='collapsible' data-collapsed='true'&gt;"+ "&lt;h3&gt;"+data[result][i].type+"&lt;/h3&gt;"+ "&lt;table width='100%' border='1'&gt;"+ "&lt;tr&gt;"+ "&lt;td&gt;&amp;nbsp;&lt;/td&gt;"+ "&lt;td style='text-align: center'&gt;"+data[result][i].bulan+"/2012&lt;/td&gt;"+ "&lt;td style='text-align: center'&gt;"+data[result][a].bulan+"/2012&lt;/td&gt;"+ "&lt;td style='text-align: center'&gt;"+data[result][b].bulan+"/2012&lt;/td&gt;"+ "&lt;/tr&gt;"+ "&lt;tr&gt;"+ "&lt;td&gt;Cash&lt;/td&gt;"+ "&lt;td style='text-align: right'&gt;"+data[result][i].uang+"&lt;/td&gt;"+ "&lt;td style='text-align: right'&gt;"+data[result][a].uang+"&lt;/td&gt;"+ "&lt;td style='text-align: right'&gt;"+data[result][b].uang+"&lt;/td&gt;"+ "&lt;/tr&gt;"+ "&lt;tr&gt;"+ "&lt;td&gt;Qty&lt;/td&gt;"+ "&lt;td style='text-align: right'&gt;"+data[result][i].total+"&lt;/td&gt;"+ "&lt;td style='text-align: right'&gt;"+data[result][a].total+"&lt;/td&gt;"+ "&lt;td style='text-align: right'&gt;"+data[result][b].total+"&lt;/td&gt;"+ "&lt;/tr&gt;"+ "&lt;/table&gt;"+ "&lt;/div&gt;"; } $('#tipe').html(innerHtml); $.mobile.changePage("#detail", "slide", false, true); //show the page }, error: function () { alert("ERROR"); } }); } function countTypesForBulan(resultArray, bulanVal) { var i, types, count = 0; for (i=0, types = {}; i &lt; resultArray.length; i++) if (resultArray[i].bulan === bulanVal &amp;&amp; !types[resultArray[i].type]) { types[resultArray[i].type] = true; count++; } return count; } </code></pre> <ul> <li><a href="http://jsfiddle.net/seXmc/9/" rel="nofollow noreferrer">here is for simulation my project with jsfiddle</a></li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T02:01:33.910", "Id": "21525", "Score": "0", "body": "Where is the code for review? If this is more of a problem of broken code I'd suggest [SO] otherwise please help us by adding some code. Thanks. EDIT:- I should have prefaced that with .... \"I'm too lazy to go to paste bins for code\" ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T02:28:17.387", "Id": "21526", "Score": "0", "body": "@JamesKhoury well, my code is working but I think there is some bugs in my code and need to be review. I've update my thread now, thank you..sorry :p" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T03:02:44.757", "Id": "21527", "Score": "0", "body": "thanks its easier to read code when its in the thread. I'm not sure whats wrong with this. Could you also provide a sample response from that url?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T03:29:51.977", "Id": "21528", "Score": "0", "body": "here is the url result:\n`{\"GetReportIdResult\":[{\"bulan\":\"4\",\"total\":\"1728\",\"type\":\"CHEESE1K\",\"uang\":\"8796383\"},{\"bulan\":\"4\",\"total\":\"572476\",\"type\":\"ESL\",\"uang\":\"5863408410\"},{\"bulan\":\"5\",\"total\":\"4761\",\"type\":\"CHEESE1K\",\"uang\":\"134877865\"},{\"bulan\":\"5\",\"total\":\"648663\",\"type\":\"ESL\",\"uang\":\"6645764498\"},{\"bulan\":\"6\",\"total\":\"5762\",\"type\":\"CHEESE1K\",\"uang\":\"293393832\"},{\"bulan\":\"6\",\"total\":\"594942\",\"type\":\"ESL\",\"uang\":\"6088671790\"},]}`" } ]
[ { "body": "<p>I can't see anything wrong with your code in terms of why it gives you different styles. I would however ensure you have a consistent coding standard.</p>\n\n<p>For example my coding standards usually include:</p>\n\n<ol>\n<li><p>Always declare variables. Variable <code>maks</code> is never declared here (I'm going to assume it is never declared.) Change it to <code>var maks = -1;</code></p></li>\n<li><p>Always use <code>{</code> and <code>}</code>. This will ensure you don't screw up a block. </p>\n\n<pre><code>if(data[result][i].bulan &gt; maks) \n maks = data[result][i].bulan;\n</code></pre>\n\n<p>would become:</p>\n\n<pre><code>if(data[result][i].bulan &gt; maks)\n{\n maks = data[result][i].bulan;\n}\n</code></pre>\n\n<p>Its just proofing for us who make mistakes from time to time.</p></li>\n<li><p>make local variables where possible</p>\n\n<pre><code>if (resultArray[i].bulan === bulanVal &amp;&amp; !types[resultArray[i].type]) {\n types[resultArray[i].type] = true;\n count++;\n}\n</code></pre>\n\n<p>could be:</p>\n\n<pre><code> var current = resultArray[i];\n if (current.bulan === bulanVal &amp;&amp; !types[current.type]) {\n types[current.type] = true;\n count++;\n}\n</code></pre>\n\n<p>It means less look ups. Most of the time its easier to read. </p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T05:01:58.433", "Id": "21530", "Score": "0", "body": "okay, I'll update my code as your advice. Thank you very much :))" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T06:00:00.980", "Id": "21531", "Score": "0", "body": "@blankon91 It might help to see the outer for loop that calls this code. There might be something there that is the root of your problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T06:12:44.007", "Id": "21533", "Score": "0", "body": "here is the outer that call this code http://pastie.org/4201837" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T06:14:27.580", "Id": "21534", "Score": "0", "body": "@blankon91 Your original post seemed to suggest this was created dynamically in a `for..` loop" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T06:18:59.740", "Id": "21535", "Score": "0", "body": "yes, I want it created dynamically listview" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T06:31:36.843", "Id": "21536", "Score": "0", "body": "or maybe you can review my new code http://jsfiddle.net/seXmc/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T06:34:31.220", "Id": "21537", "Score": "0", "body": "@blankon91 ... you can't do cross domain Ajax requests. I can't give you any more review on it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T06:40:32.920", "Id": "21538", "Score": "0", "body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/3995/discussion-between-blankon91-and-james-khoury)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T06:45:00.890", "Id": "21540", "Score": "0", "body": "well, what if we ignore that cross domain ajax request, and assume that the json string is hard coded, can you review whats wrong with my function and maybe somethiong wrong with my way to call the function?" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T04:54:21.387", "Id": "13329", "ParentId": "13328", "Score": "1" } } ]
{ "AcceptedAnswerId": "13329", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T01:18:29.460", "Id": "13328", "Score": "1", "Tags": [ "javascript", "html" ], "Title": "Why my listview style change when I loop the javascript twice?" }
13328
<p>I have constructed a function that checks whether an element has a scrollbar or not, and can also check individual axes.</p> <p>I don't know if this works in all major browsers and am unsure about the performance. </p> <p>Is there any way to improve upon the code, did I miss anything?<br> How would a javascript equivalent look like?</p> <p><sub>Note: I first asked this question on <a href="https://stackoverflow.com/q/11338611/944301">Stack Overflow</a>, but someone suggested I should post it here instead.</sub></p> <hr> <p>Code | <a href="http://jsfiddle.net/u69dU/" rel="nofollow noreferrer">Example</a></p> <pre class="lang-js prettyprint-override"><code>$.fn.hasScroll = function(axis){ var sX = this.css("overflow-x"), sY = this.css("overflow-y"); if(typeof axis == "undefined"){ //Check both x and y declarations if( (sX == "hidden" &amp;&amp; sY == "hidden") || (sX == "visible" &amp;&amp; sY == "visible") ){ return false; } if(sX == "scroll" || sY == "scroll"){ return true; } }else{ //Check individual axis declarations switch(axis){ case "x": if(sX == "hidden" || sX == "visible") return false; if(sX == "scroll") return true; break; case "y": if(sY == "hidden" || sY == "visible") return false; if(sY == "scroll") return true; break; } } //Compare client and scroll dimensions to see if a scrollbar is needed var bVertical = this[0].clientHeight &lt; this[0].scrollHeight, bHorizontal = this[0].clientWidth &lt; this[0].scrollWidth; return bVertical || bHorizontal; }; </code></pre>
[]
[ { "body": "<p><img src=\"https://i.stack.imgur.com/8Rpkl.jpg\" alt=\"=== everywhere\"></p>\n\n<p><a href=\"https://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use\"><code>=== &gt; ==</code></a> (Not that it really matters in this case, but it's still better.)</p>\n\n<p>Also, IIRC <code>clientHeight</code> etc are not cross-browser, this is why jQuery provides <a href=\"http://api.jquery.com/position/\" rel=\"nofollow noreferrer\"><code>.position()</code></a>, <a href=\"http://api.jquery.com/offset/\" rel=\"nofollow noreferrer\"><code>.offset()</code></a>, <a href=\"http://api.jquery.com/scrollTop/\" rel=\"nofollow noreferrer\"><code>.scrollTop()</code></a> and <a href=\"http://api.jquery.com/height/\" rel=\"nofollow noreferrer\"><code>.height()</code></a> (whichever one best suits your needs).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-07-05T09:42:55.323", "Id": "13341", "ParentId": "13338", "Score": "8" } }, { "body": "<p>I would write this as an extension to the Sizzle engine rather than a jQuery plugin; I've made a few other minor changes as well:</p>\n\n<pre><code>function hasScroll(el, index, match) {\n var $el = $(el),\n sX = $el.css('overflow-x'),\n sY = $el.css('overflow-y'),\n hidden = 'hidden', // minifiers would like this better\n visible = 'visible',\n scroll = 'scroll',\n axis = match[3]; // regex for filter -&gt; 3 == args to selector\n\n if (!axis) { // better check than undefined\n //Check both x and y declarations\n if (sX === sY &amp;&amp; (sY === hidden || sY === visible)) { //same check but shorter syntax\n return false;\n }\n if (sX === scroll || sY === scroll) { return true; }\n } else if (axis === 'x') { // don't mix ifs and switches on the same variable\n if (sX === hidden || sX === visible) { return false; }\n if (sX === scroll) { return true; }\n } else if (axis === 'y') {\n if (sY === hidden || sY === visible) { return false; }\n if (sY === scroll) { return true };\n }\n\n //Compare client and scroll dimensions to see if a scrollbar is needed\n\n return $el.innerHeight() &lt; el.scrollHeight || //make use of potential short circuit\n $el.innerWidth() &lt; el.scrollWidth; //innerHeight is the one you want\n}\n$.expr[':'].hasScroll = hasScroll;\n</code></pre>\n\n<p>You can then use this in any jQuery selector, such as:</p>\n\n<pre><code>$('div:hasScroll') //all divs that have scrollbars\n$('div').filter(':hasScroll') //same but better\n$(this).closest(':hasScroll(y)') //find the parent with the vert scrollbar\n$list.is(':hasScroll(x)') //are there any horizontal scrollbars in the list?\n</code></pre>\n\n<p>If you must have an instance method to do this check then you could write this to keep your semantics:</p>\n\n<pre><code>$.fn.hasScroll = function(axis) {\n var el = this[0];\n if (!el) { return false; }\n return hasScroll(el, 0, [0, 0, 0, axis]);\n};\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/u69dU/1/\">Updated JsFiddle</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T09:17:53.920", "Id": "21680", "Score": "1", "body": "Most impressive. I didn't consider having it as a selector function. Very nice. You wrote in the comments \"don't mix ifs and switches on the same variable\", \"minifiers would like this better\" and \"better check than undefined\". Could you explain these comments or point to some documentation that does? :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T22:22:16.707", "Id": "13378", "ParentId": "13338", "Score": "8" } } ]
{ "AcceptedAnswerId": "13378", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T09:08:17.283", "Id": "13338", "Score": "5", "Tags": [ "javascript", "jquery", "optimization", "performance" ], "Title": ".hasScroll function, checking if a scrollbar is visible in an element" }
13338
<p>Below is the class which I am using to fill multiple DropDowns on ASP.NET Page Load event:</p> <pre><code>public sealed class getBlocks { public getBlocks(DropDownList dropDownName, string districtId) { returnBlocks(dropDownName, districtId); } public void returnBlocks(DropDownList DropDownName, string DistrictId) { var DB = new PetaPoco.Database("cnWebDems"); string Query = "SELECT distinct blockname, blockid FROM hab_master WHERE distid = '" + DistrictId + "' ORDER BY blockname"; var result = DB.Fetch&lt;hab_master&gt;(Query); DropDownName.DataSource = result; DropDownName.DataTextField = "blockname"; DropDownName.DataValueField = "blockid"; DropDownName.DataBind(); DropDownName.Items.Insert(0, "-- Select --"); DB.Dispose(); } </code></pre> <p>Suggest further improvements.</p>
[]
[ { "body": "<p>Firstly, data access should be separate from your UI logic. Certainly create a new layer, where you'll manage CRUD operations.</p>\n\n<p>Secondly, I'm not really fond of your naming convention of classes. Even though it may be a subjective matter, many people tend to use capitalized names for classes and certainly not using words like \"getBlocks\". This isn't a name for a class, that's a name for a getter method.</p>\n\n<p>Thirdly, you're dealing with your parameters the wrong way, at least in my opinion. I believe it would be more appropriate to have private fields of type DropDownList and String, populate them in the constructor and then just use these private variables (and/or properties, depends on your needs) instead of specifying parameters for the method itself. Seems more OOP to me that way. Otherwise I don't really see a reason why not just create a helper class with a static method you'll call whenever needed, without the need to instantiate the class itself.</p>\n\n<p>Another thing to consider - usually it's better to use an <code>using</code> statement instead of manually calling <code>Dispose</code> method.</p>\n\n<p><strong>Edit</strong> based on the comment:</p>\n\n<p>1.) example using private fields</p>\n\n<pre><code>public sealed class Blocks\n{\n private DropDownList _ddList;\n private int _districtId;\n\n public Blocks(DropDownList dropDownList, int districtId)\n {\n _ddList = dropDownList;\n _districtId = districtId;\n }\n\n public void PopulateDropDownList()\n { \n var results = MyDbAccessClass.GetBlocks(_districtId); \n\n _ddList.DataSource = results;\n _ddList.DataTextField = \"blockname\";\n _ddList.DataValueField = \"blockid\";\n _ddList.DataBind();\n _ddList.Items.Insert(0, \"-- Select --\");\n }\n}\n</code></pre>\n\n<p>2.) example using static method</p>\n\n<pre><code>public sealed class MyHelperMethods\n{\n public static void PopulateWithBlocks(DropDownList ddList, int districtId)\n {\n var results = MyDbAccessClass.GetBlocks(districtId); \n\n ddList.DataSource = results;\n ddList.DataTextField = \"blockname\";\n ddList.DataValueField = \"blockid\";\n ddList.DataBind();\n ddList.Items.Insert(0, \"-- Select --\");\n }\n}\n</code></pre>\n\n<p>Hope you get the idea...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T08:40:58.460", "Id": "21637", "Score": "0", "body": "I appreciate your comments. Can you please illustrate third point with little code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T12:01:56.790", "Id": "21643", "Score": "0", "body": "@RPK, please see the updated answer with examples. Hope it helps." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T16:56:35.970", "Id": "21657", "Score": "0", "body": "I avoid static methods because they create problems in a concurrent environment. Will your static method work in such environment?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T17:33:48.203", "Id": "21661", "Score": "0", "body": "Static variables are dangerous in asp.net, that's true, but static methods should be perfectly ok, especially helper methods like this. I've been using similar methods in asp.net on various shared webhostings without any issue for quite some time. If you're working with some kind of multi-thread application or with an application with its data being constantly edited by multiple users, you still need to apply some lock mechanism that will prevent possible problems with deleting, inserting and updating the data." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T17:37:04.900", "Id": "21662", "Score": "0", "body": "To be honest though, the shown method is used just for retrieving some data and populating the dropdownlist with some values. I'm not sure how would that be a problem in any asp.net environment, because every request creates a new aspx page, with a new set of controls etc, so instances won't affect each other like it would be in the scenario with static variables. Either way, you don't have to do it if it causes you any problems or discomfort, you can use the first approach with instance variables and adapt that code to your needs. ;-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T07:31:58.710", "Id": "21676", "Score": "0", "body": "I faced an issue with static methods used to populate GridView. At certain intervals, the GridView started showing results of another user's DropDownList. I didn't get any solution yet. SQL Server service needs to be restarted to correct the problem. This problem occurred each time many users were connected." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T14:46:29.427", "Id": "21689", "Score": "1", "body": "@RPK, not sure what caused your problems back then, maybe you should post that code in another question, but I've made some research on the Google and made some tests by myself, resulting in the same answer - `static methods` aren't a problem unless you use `static variables`. Static methods are thread-safe. The biggest issue about static methods is unit testing, but that's a different matter... If your GW started to show results of another user's ddlist, it implies you used static members/variables/properties, but the method itself probably wasn't the problem..." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T18:28:34.373", "Id": "13368", "ParentId": "13342", "Score": "3" } } ]
{ "AcceptedAnswerId": "13368", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T09:49:38.157", "Id": "13342", "Score": "2", "Tags": [ "c#", ".net", "asp.net" ], "Title": "What improvements are needed in this class to fill DropDown using PetaPoco?" }
13342
<p>What I've been working on is some kind of function that can take basically any well constructed multi-dimensional array and remove any and all duplicates within matching key sets.</p> <p>The particular function I've designed provides convenience and functionality but it is far from pretty and seemingly slow compared to a possibly more optimized function.</p> <p><strong>Sample Data</strong></p> <pre><code>$echo['level-one'][] = '1'; $echo['level-one'][] = '1'; $echo['level-one'][] = '1'; $echo['level-one'][] = '1'; $echo['level-one']['level-two'][] = '1'; $echo['level-one']['level-two'][] = '1'; $echo['level-one']['level-two'][] = '1'; $echo['level-one']['level-two'][] = '1'; $echo['level-one']['level-two']['level-three'][] = '1'; $echo['level-one']['level-two']['level-three'][] = '2'; $echo['level-one']['level-two']['level-three'][] = '3'; $echo['level-one']['level-two']['level-three'][] = '4'; </code></pre> <p><strong>Function Declaration and Execution</strong></p> <pre><code>function array_unique_multidimensional($name=null,$tv=null,$tk=null,$ta=null){ if(!isset($ta)){$ta = ''.$name.'';}else{$ta .= '['.$tk.']';} if(!isset($tv)){$tv = '$v';}else{$tv .= 'v';} if(!isset($tk)){$tk = '$k';}else{$tk .= 'k';} return(' foreach('.$ta.' as '.$tk.' =&gt; '.$tv.'){ if(is_array('.$tv.')){ eval(array_unique_multidimensional(\'\',\''.$tv.'\',\''.$tk.'\',\''.$ta.'\')); }else{ '.$ta.' = array_unique('.$ta.'); } } '); //end return } eval(array_unique_multidimensional('$echo')); //Yes this function returns a foreach loop so it must be eval'd //then it recursively calls itself until the entire array is traversed //This will ensure every segment of the array is unique individually </code></pre> <p>Alright so I spaced it out a lot more then it probably needs to be and it is probably best viewed in some kind of program editor. Anyway after running the script as it is shown above you should get level's one and two reduced to a single entry and level three should have all four of it's entries (since their values are unique and one and two's are not).</p> <p>I've seen a lot of answers using array_map to serialize and unique but I've found that they do not work for multidimensional arrays of varying calibers. Ultimately this function will accept any size and depth of array, compare every single key set to itself, remove any duplicates, and preserve every array name/key contained within.</p> <p>Does anyone know of a better way to go about this? If not enjoy the working code above, if you do please share :)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T14:12:14.863", "Id": "21558", "Score": "0", "body": "I'd only add that your variables are not very descriptive (ta, tv, tk), which makes reading the function difficult at places. And also that `eval()` is evil. I'd use either of the other two functions before this one just for that alone." } ]
[ { "body": "<p>This is probably better than using <code>eval</code>. This solution touches only keys which are numeric, leaving string keys unchanged:</p>\n\n<pre><code>&lt;?php\n\n$echo['level-one'][] = '1';\n$echo['level-one'][] = '1';\n$echo['level-one'][] = '1';\n$echo['level-one'][] = '1';\n$echo['level-one']['level-two'][] = '1';\n$echo['level-one']['level-two'][] = '1';\n$echo['level-one']['level-two'][] = '1';\n$echo['level-one']['level-two'][] = '1';\n$echo['level-one']['level-two']['level-three'][] = '1';\n$echo['level-one']['level-two']['level-three'][] = '2';\n$echo['level-one']['level-two']['level-three'][] = '3';\n$echo['level-one']['level-two']['level-three'][] = '4';\n\nfunction makeUnique(array $arr) {\n $seen = array();\n foreach (array_keys($arr) as $key) {\n if (is_array($arr[$key])) {\n $arr[$key] = makeUnique($arr[$key]);\n } else {\n if (is_numeric($key)) {\n $v = (string)$arr[$key];\n if (isset($seen[$v])) {\n unset($arr[$key]);\n } else {\n $seen[$v] = true;\n }\n }\n }\n }\n return $arr;\n}\n\nprint_r(makeUnique($echo));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T10:24:07.950", "Id": "13344", "ParentId": "13343", "Score": "1" } }, { "body": "<p>Shortest solution I can come up with:</p>\n\n<pre><code>function array_unique_recursive ($array) {\n\n // First loop the array and call self on any sub arrays\n // Note that $value is referenced\n foreach ($array as &amp;$value) {\n if (is_array($value)) {\n $value = array_unique_recursive($value);\n }\n }\n\n // Now unique this level\n return array_unique($array, SORT_REGULAR);\n\n}\n\nprint_r(array_unique_recursive($echo));\n</code></pre>\n\n<p><a href=\"http://codepad.viper-7.com/wkeSri\" rel=\"nofollow\">See it working</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T10:27:50.417", "Id": "13345", "ParentId": "13343", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T10:14:22.120", "Id": "13343", "Score": "2", "Tags": [ "php" ], "Title": "Can anyone improve my multidimensional array more distinctive?" }
13343
<p>I'm creating a Backbone App, and although everything seems to work i'm afraid i might need to refactor very soon if I keep adding functionalities and views with this approach. I'm using Parse in the backend, meaning that the object Parse is equivalent to the Backbone.Model. I can't control my models since they've been optimized for mobile and here i need to display only certain key values of 3 different models.</p> <p>Although there's nothing "wrong" (it works) it's only a matter of time until i start doing 'bigger' mistakes.</p> <p>Here's my Router:</p> <pre><code>App.Controllers.Documents = Backbone.Router.extend({ routes:{ "story/:id" : "fullStory", "" : "index" }, // ... fullStory: function(id){ var self = this; var query = new Parse.Query(Steps); query.equalTo("story", id) var steps = query.collection(); steps.fetch({ success: function() { new App.Views.Steps({ collection: steps }); var title = new Story({ objectId: id }); title.fetch({ success: function(model, resp) { new App.Views.Title({ model: title}); var idUser = title.toJSON().idUser; var user = new Parse.User({ objectId: idUser }); user.fetch({ success: function(){ // I just need the username key here... new App.Views.Username({model:user,el:$("#user")}); }, error: function(){ new Error({ message: 'Could not find the user you requested.' }); } }) }, error: function() { new Error({ message: 'Could not find that story.' }); } }) }, error: function() { new Error({ message: "Error loading story." }); } }); } </code></pre> <p>Given the way objects have been created in Parse I need to access 3 different objects, that's why i'm rendering the View in "parts". I'd like this function to render just a FullStory View with these 'sub views' inside of it but i'm unsure on how to do it 'cause the Parse.Objects need a reference to the other object -> var user = new Parse.User({ objectId: idUser }); where idUser is a key from another object.</p> <p>Finally my Views:</p> <pre><code>App.Views.Steps = Backbone.View.extend({ tagName : "ul", className: "steps", initialize: function() { this.render(); }, render: function() { this.$el.html(_.template($("#story_steps").html())({ collection: this.collection })); $('#steps_wrapper').html(this.el); }, }); App.Views.Title = Backbone.View.extend({ initialize: function() { this.render(); }, render: function() { this.$el.html(_.template($("#story_title").html())({ model: this.model })); $('#title').html(this.el); } }); App.Views.Username = Backbone.View.extend({ initialize: function() { this.render(); }, template: _.template('&lt;%= name %&gt;'), render: function() { this.$el.html(this.template(this.model.toJSON())); } }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T13:32:21.310", "Id": "21551", "Score": "0", "body": "Why is `title` inside the response from `steps.fetch`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T14:04:14.140", "Id": "21557", "Score": "0", "body": "Does `fetch` return a [Promise-like object](http://wiki.commonjs.org/wiki/Promises/A)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T14:14:00.960", "Id": "21559", "Score": "0", "body": "I'm not sure how to go about rendering one view with two models since they have relations." } ]
[ { "body": "<p>The success function for the user.fetch statement is annoying. Just messing around, I am not sure this is any better as a whole (or if it even works):</p>\n\n<pre><code>var Util = {\n error: function (msg) {\n return function () { new Error({ message: msg }); };\n }\n};\n\nvar controllers = {};\n\n_.extend(controllers, Backbone.Events);\n\nvar events = {\n fullStory: 'fullStory',\n user: 'user'\n};\n\ncontrollers.on(events.fullStory, function (id) {\n var query = new Parse.Query(Steps),\n steps;\n query.equalTo(\"story\", id);\n steps = query.collection();\n\n steps.fetch({\n success: function () {\n new App.Views.Steps({ collection: steps });\n },\n error: Util.error(\"Error loading story.\")\n }\n });\n});\n\ncontrollers.on(events.fullStory, function (id) {\n var title = new Story({ objectId: id });\n title.fetch({\n success: function(model, resp) {\n var idUser;\n new App.Views.Title({ model: title });\n idUser = title.toJSON().idUser;\n controllers.trigger(events.user, idUser);\n },\n error: Util.error('Could not find that story.')\n });\n});\n\ncontrollers.on(events.user, function (idUser) {\n var user = new Parse.User({ objectId: idUser });\n user.fetch({\n success: function () {\n // I just need the username key here...\n new App.Views.Username({model:user, el:$(\"#user\")});\n },\n error: Util.error('Could not find the user you requested.')\n });\n});\n\nApp.Controllers.Documents = Backbone.Router.extend({\n routes: {\n \"story/:id\" : \"fullStory\",\n \"\" : \"index\"\n },\n\n fullStory: function (id) {\n controllers.trigger(events.fullStory, id);\n }\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T14:17:27.507", "Id": "21560", "Score": "0", "body": "I know that function is annoying, that actually why I posted the question lol.\nI'm not sure how to go about rendering one view with two models since they have relations. I need to look more into this. Thanks for the answer! +1" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T13:58:50.823", "Id": "13353", "ParentId": "13346", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T10:05:21.210", "Id": "13346", "Score": "1", "Tags": [ "javascript", "jquery", "backbone.js" ], "Title": "Backbone.js App approach not very scalable - nested views" }
13346
<p>This libray was written quite some time ago, and it has so far been used in all sorts of small-ish projects.</p> <p>I'm about to base a more complex, security (Access Control) related, open-source project on this library, so I thought it would be a good moment to ask for a code review.</p> <p><strong>Source:</strong> DbHandler</p> <pre><code>&lt;?php /** * @package DbHandler * @version 1.04 * @date 2010-09-27 * @copyright (c) 2010-2012 Netslik (http://netsilik.nl) * @license EUPL (European Union Public Licence, v.1.1) * * Example of usage: * * // Object creation * $dbPointer = new DbHandler('localhost', 'user', 'secret', 'testDatabase'); * * // Executing queries * $resultSet = $dbPointer-&gt;doQuery('SELECT * FROM test WHERE id = %i, 1); * $records = $resultSet-&gt;fetch(); * * var_dump( $records ); */ require('class.dbResult.php'); /** * Database Access abstraction object */ class DbHandler { protected $_connection = null; protected $_inTransaction; /** * @param string $dbHost Either a host name or the IP address for the MySQL database server * @param string $dbUser The MySQL user name * @param string $dbPass The MySQL password for this user * @param string $dbName The optional name of the database to select * @throws Exception * @return object instance */ public function __construct ($dbHost, $dbUser, $dbPass, $dbName = false) { $this-&gt;_connection = new mysqli($dbHost, $dbUser, $dbPass); $this-&gt;_inTransaction = false; /* This is the correct OO way to do setup a connection, BUT $connect_error is broken up till PHP 5.3.1. if ( null !== ($errorMsg = $this-&gt;_connection-&gt;connect_error) ) { $this-&gt;_connection = null; throw new Exception('Could not connect to DB-server: '.$errorMsg); } */ // So, let's use a backward compatible check if (mysqli_connect_error()) { $this-&gt;connection = null; throw new Exception('Could not connect to DB-server: '.mysqli_connect_error()); } // Select specified database (if any) if ( $dbName !== false) { $this-&gt;selectDb( $dbName ); } } /** * Commit a transaction * @return bool true on success, false on failure */ public function commit() { if ( ! $this-&gt;_inTransaction) { error('No transaction started', E_USER_NOTICE, 1); return false; } $this-&gt;_inTransaction = false; return $this-&gt;_connection-&gt;query('COMMIT'); } /** * Execute a prepared query * @param string $query the query with zero or more parameter marker characters at the appropriate positions. * Parameter markers are defined as a literal % followed by either * i : corresponding variable will be interpreted as an integer * d : corresponding variable will be interpreted as a double * s : corresponding variable will be interpreted as a string * b : corresponding variable will be interpreted as a blob and should be sent in packets (but this has not yet been implemented) * @param mixed $params An optional set of variables, matching the parameter markers in $query. if an array is given, each element * of the array will be interpreted as being of the type specified by the placeholder * @throws Exception * @return DbResult Object holding the result of the executed query */ public function doQuery($query) { $query = trim($query); $params = array_slice(func_get_args(), 1); array_unshift($params, $this-&gt;_parse($query, $params)); if (strlen($params[0]) &lt;&gt; count($params) - 1) { throw new Exception((count($params) - 1).' parameters specified, '.strlen($params[0]).' expected'); } $statement = $this-&gt;_connection-&gt;prepare($query); if ( ! $statement || $statement-&gt;errno &gt; 0) { throw new Exception('Query preparation failed: '.$this-&gt;_connection-&gt;error); } $startTime = microtime(true); if ( (strlen($params[0]) &gt; 0 &amp;&amp; ! call_user_func_array(array($statement, 'bind_param'), $this-&gt;_referenceValues($params)) ) || $statement-&gt;errno &gt; 0) { throw new Exception('Parameter binding failed'); } $statement-&gt;execute(); $queryTime = microtime(true) - $startTime; if ($statement-&gt;errno &gt; 0) { throw new Exception('Query failed: '.$statement-&gt;error); } return new DbResult( $statement, $queryTime ); } /** * Fetch connection resource for this db connection * @return resource mysqli connection */ public function getConnectionPtr() { return $this-&gt;_connection; } /** * Parse the query for parameter placeholders and, if appropriate, match them to the number of elemnts in the parameter * @param string &amp;$query a reference to the query string * @param array &amp;$params a reference to the array with * @throws Exception * @return string all tokens found by the parser * @note both the original variables $query and $params passed to this method will be modified by reference! */ private function _parse(&amp;$query, &amp;$params) { $s = $d = false; // quoted string quote type $n = 0; // parameter index $tokenString = ''; $queryLength = strlen($query); for ($i = 0; $i &lt; $queryLength; $i++) { switch( $query{ $i } ) { case '\\': $i++; break; case '\'': if (!$d) { $s = !$s; } break; case '"': if (!$s) { $d = !$d; } break; case '%': if (!$s &amp;&amp; !$d &amp;&amp; $i+1 &lt; $queryLength) { if ('i' === $query{$i+1} || 'd' === $query{$i+1} || 's' === $query{$i+1} || 'b' === $query{$i+1}) { if ($n &gt;= count($params)) { throw new Exception('The number of parameters is not equal to the number of placeholders'); } if (is_array($params[$n])) { $elmentCount = count($params[$n]); array_splice($params, $n, 1, $params[$n]); $tokenString .= str_repeat($query{$i+1}, $elmentCount); $query = substr_replace($query, implode(',', array_fill(0, $elmentCount, '?')), $i, 2); $queryLength += $elmentCount * 2 - 3; $n += $elmentCount; } else { $tokenString .= $query{$i+1}; $query = substr_replace($query, '?', $i, 2); $queryLength--; $n++; } } } break; // case: check for the various comment start chars (not implemented yet) } } return $tokenString; } /** * PHP &gt;= 5.3 expects the parametrs passed to mysqli_stmt::bind_param to be references. However, we will do the binding after query execution * So, this functions quickly solves the issues by wrapping the arguments in an associative array. * @param $array * @return associative array for PHP &gt;= 5.3, unchanged array otherwise */ private function _referenceValues($array){ if (strnatcmp(phpversion(),'5.3') &gt;= 0) { // References are required for PHP 5.3+ (and noone knows why) $references = array(); foreach($array as $key =&gt; $value) { $references[$key] = &amp;$array[$key]; } return $references; } return $array; } /** * Rollback a transaction * @return bool true on success, false on failure */ public function rollback() { if ( ! $this-&gt;_inTransaction) { error('No transaction started', E_USER_NOTICE, 1); return false; } $this-&gt;_inTransaction = false; return $this-&gt;_connection-&gt;query('ROLLBACK'); } /** * Select a database to use on current connection * @param string $dbName name of the database to select * @return true on success, false otherwise */ public function selectDb ( $dbName ) { return $this-&gt;_connection-&gt;select_db( $dbName ); } /** * Start a transaction * @return bool true on success, false on failure * @note 'advanced' features such as WITH CONSISTENT SNAPSHOT are not supported */ public function startTransaction() { if ($this-&gt;_inTransaction) { error('Implicit commit for previous transaction', E_USER_NOTICE, 1); } $this-&gt;_inTransaction = true; return $this-&gt;_connection-&gt;query('START TRANSACTION'); } /** * Close current db connection on object destruction */ public function __destruct() { if ($this-&gt;_connection !== null) { $this-&gt;_connection-&gt;close(); $this-&gt;_connection = null; } } } </code></pre> <p><strong>Source:</strong> DbResult</p> <pre><code>&lt;?php /** * @package DbHandler * @version 1.04 * @date 2010-09-27 * @copyright (c) 2010-2012 Netslik (http://netsilik.nl) * @license EUPL (European Union Public Licence, v.1.1) * */ /** * Result object, returned by the DbHandler whenever a valid query is executed */ class DbResult { protected $_statement = null; protected $_result = null; // holds a bound record as fieldname =&gt; value pairs; modified by reference protected $_queryTime = 0; /** * @param MySQLi $statement Statement the statement for this result set * @param int $queryTime the time in seconds the statement took to execute * @return object instance */ public function __construct ($statement, $queryTime) { $this-&gt;_statement = $statement; $this-&gt;_queryTime = $queryTime; if ( false !== ($metaData = $statement-&gt;result_metadata()) ) { $statement-&gt;store_result(); while ($field = $metaData-&gt;fetch_field()) { $params[] = &amp;$this-&gt;_result[$field-&gt;name]; } call_user_func_array(array($this-&gt;_statement, 'bind_result'), $params); $metaData-&gt;close(); } } /** * get the results for an SELECT statement * @return array an associative array per record, containing all fields (columns) */ public function fetch() { if (is_null($this-&gt;_result)) { // No result data available return false; } $records = array(); while ($this-&gt;_statement-&gt;fetch()) { foreach($this-&gt;_result as $name =&gt; $value) { $column[$name] = $value; } $records[] = $column; } $this-&gt;_statement-&gt;data_seek(0); return $records; } /** * get the results for an SELECT statement * @param int $column optional name of the column to fetch * @return array an indexed array containing all fields for specified column or the first column if none specified */ public function fetchColumn($column = null) { $records = $this-&gt;fetch(); $values = array(); foreach ($records as $record) { foreach ($record as $key =&gt; $val) { if ( ! is_null($column) &amp;&amp; $column &lt;&gt; $key) { continue; } $values[] = $val; break; } } return $values; } /** * get the results for an SELECT statement * @param int $field name of the column of the first record to fetch * @return scalar the value of the specified field */ public function fetchField($field, $recordNum = 0) { $records = $this-&gt;fetch(); return isset($records[$recordNum][$field]) ? $records[$recordNum][$field] : null; } /** * get the results for an SELECT statement * @param int $recordNum return the num-th record from the set to get * @return array an associative array containing all fields (columns) for specified record */ public function fetchRecord($recordNum = 0) { $records = $this-&gt;fetch(); return isset($records[$recordNum]) ? $records[$recordNum] : array(); } /** * get the total number of records changed, deleted, or inserted by the last executed statement * @return int number of records affected by this statement */ public function getAffectedRecords() { return $this-&gt;_statement-&gt;affected_rows; } /** * get the number of fields (columns) in the result set * @return int number of fields (columns) in the result set */ public function getFieldCount() { return $this-&gt;_statement-&gt;field_count; } /** * get the primary for this inserted record * @return int the value of the primary for this inserted record, or 0 if nothing was inserted */ public function getInsertedId() { return $this-&gt;_statement-&gt;insert_id; } /** * get the query execution time * @return int time in seconds for this query */ public function getQueryTime() { return number_format($this-&gt;_queryTime, 4); } /** * get the total number of records in this result set * @return int number of records in this result set */ public function getRecordCount() { return $this-&gt;_statement-&gt;num_rows; } /** * dump query result to std-out as an html table * @return void */ public function dump() { echo "&lt;div class=\"debug\"&gt;\n"; if (is_null($this-&gt;_result)) { echo "&lt;strong&gt;Query OK, ".$this-&gt;getAffectedRecords()." rows affected (".$this-&gt;getQueryTime()." sec.)&lt;/strong&gt;\n"; } elseif ( 0 == ($recordCount = $this-&gt;getRecordCount()) ) { echo "&lt;strong&gt;empty set (".$this-&gt;getQueryTime()." sec.)&lt;/strong&gt;\n"; } else { $records = $this-&gt;fetch(); echo "&lt;table cellspacing=\"0\" cellpadding=\"3\" border=\"1\"&gt;\n"; for ($i = 0; $i &lt; $recordCount; $i++) { if ($i == 0) { $fieldnames = array_keys($records[0]); echo "\t&lt;tr&gt;\n"; foreach ($fieldnames as $fieldname) { echo "\t\t&lt;th&gt;".$fieldname."&lt;/th&gt;\n"; } echo "\t&lt;/tr&gt;\n"; } echo "\t&lt;tr&gt;\n"; foreach ($records[$i] as $field) { echo "\t\t&lt;td&gt;"; echo (is_null($field)) ? '&lt;em&gt;NULL&lt;/em&gt;' : htmlspecialchars($field, ENT_NOQUOTES); echo "&lt;/td&gt;\n"; } echo "\t&lt;/tr&gt;\n"; } echo "&lt;/table&gt;\n"; echo "&lt;strong&gt;$recordCount row in set (".$this-&gt;getQueryTime()." sec.)&lt;/strong&gt;\n"; } echo "&lt;/div&gt;\n"; } /** * cleanup any unused memory */ public function __destruct () { $this-&gt;_statement-&gt;close(); } } </code></pre> <p>Any and all feedback is welcome.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T14:39:34.877", "Id": "21561", "Score": "0", "body": "Glad to see you have it commented, especially since you mentioned going to OS, they'd eat you alive otherwise :) I went ahead and edited this so that your sources were separated, makes it easier to read. Working on a response now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T15:59:17.030", "Id": "21566", "Score": "0", "body": "Looking forward to your response." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-16T18:38:43.260", "Id": "22175", "Score": "0", "body": "Updated dbHandler class" } ]
[ { "body": "<p>Alright, here we go. There's quite a bit so grab a drink, go to the bathroom, etc...</p>\n\n<p><strong>Unsetting Variables</strong></p>\n\n<p>I don't think unsetting the <code>$dbPass</code> was necessary as it only exists in the local scope of the constructor method, so a <code>var_dump()</code> shouldn't reveal it unless you have a <code>var_dump()</code> in the actual constructor. But I've been known to be wrong. Would be curious to see what others think.</p>\n\n<p><strong>Comments</strong></p>\n\n<p>Your comments are pretty good, maybe not too descriptive, but better than none. So internal comments should not be necessary and will only clutter your code. Trust in your PHPDoc comments and if you need to explicitly explain something, do so there.</p>\n\n<p><strong>Validating Variables</strong></p>\n\n<p>When calling methods to set certain properties or perform certain tasks based on the value of a specific variable, it is better, in my opinion, to perform any validation inside that method rather than before calling it. This has one major advantage. No repetition. Sure, you're probably not going to change your <code>$dbName</code> again, but if you wanted to, or if you found yourself reusing this code, such as extending it, then you'd have to write that check over again. Better to have the method perform its own validation.</p>\n\n<p><strong>Public vs Private</strong></p>\n\n<p>I'm not sure that your <code>selectDb()</code> method should be public. I would think that the database should not change in the middle of an operation, so it should be private to prevent accidental, or malicious, changes. If you need to access another database, then you should create a new instance, not change the existing one.</p>\n\n<p><strong>Diamond Operators * UPDATE</strong></p>\n\n<p>I don't think this is supported... Never seen it in any PHP code before, though I do remember seeing it somewhere before, which is the only reason I knew to call it a diamond operator.</p>\n\n<pre><code>if (strlen($params[0]) &lt;&gt; count($params) - 1) {\n</code></pre>\n\n<p><strong>EDIT:</strong> You've proven it is supported, and I swear I looked at that page, but anyways, still looks odd, but to each their own.</p>\n\n<p><strong>Long Statements</strong></p>\n\n<p>Its best to either separate long statements, or abstract their arguments. In other words, if the statement is too long break it up into multiple statements or for those arguments that aren't already variables, make them so.</p>\n\n<pre><code>$length = strlen( $params[ 0 ] );\n$bindParams = call_user_func_array(\n array( $statement, 'bind_param' ),\n $this-&gt;referenceValues( $params )\n);\nif ( $length &gt; 0 &amp;&amp; ! $bindParams || $statement-&gt;errno &gt; 0) {\n</code></pre>\n\n<p><strong>Repetitive Tasks</strong></p>\n\n<p>Best to create functions for those repetitive tasks. Serves two purposes. First, less typing. Second, should you ever want to change how that task is performed, best to only have to change it once. So everywhere you call the <code>error()</code> function, which seems odd after all those exceptions, could be more easily written with a function similar to so.</p>\n\n<pre><code>function throwError( $method ) { error( \"$method: No transaction started\", E_USER_NOTICE, 1); }\n//example usage\n$this-&gt;throwError( __METHOD__ );\n</code></pre>\n\n<p><strong>_parse() * UPDATE</strong></p>\n\n<p>This function is <strong>way</strong> too busy. There's too much going on. Why is the query being trimmed? That has nothing to do with parsing and should have been done prior to calling this function. Doing so will also remove the need to assign that argument by reference. Speaking of which reference assignments make troubleshooting a nightmare. If you don't know this code, you aren't going to realize, without tracking it down, that the variable changed. What is <code>$s</code>? What is <code>$d</code>? Why did you assign them that way? Sure it means you can do them both on the same line, but for legibility they should definitely both be defined separately. Why are there two iterators in one array? If you separate these into different loops, you'll be halfway to separating this into two different functions.</p>\n\n<p>I'm not really sure how I feel about the string position array syntax. But why are you using braces \"{}\" instead of brackets \"[]\"? I didn't even know that was possible. Also, is it really necessary to go over every character in that string? From the looks of it you only want to perform certain actions based on the first couple of characters and the rest are empty spaces. I'd locate those few characters, set them as variables, then proceed to loop over the <code>$params</code>. This seems like entirely too much effort was put into a simple task.</p>\n\n<p><strong>EDIT:</strong> I still think some of the above is valid, which is why I'm leaving it, that and to give a reference to the earlier discussions. Here's the update, which is about as long as the entire first update.</p>\n\n<p>Still not sure what <code>$s</code> and <code>$d</code> are. They are too vague. I can tell they are switches that are toggled based on the others value, but what are they switches for? If you can explain their purpose, you'll have a better idea what to call them. Self documenting code is easily read and easily understood and should be something everyone strives for in my opinion. You've mostly done this, this is just one of the few times you didn't. And as a consequence, I have no idea what's supposed to be going on here. I just noticed your comment, which appears to give me my answer, but I still think the above is valid, it shouldn't need a comment to tell me what a variable is.</p>\n\n<p>I'd use a switch instead of if/else statements. One its cleaner, in my opinion, and two its faster, though that's negligible and isn't a reason to do anything. This is one of those preference things, but one many agree with me on. I've only ever heard one, maybe two people say that switches were harder to read, and I think it probably had more to do with inexperience, or from too much experience with drop cases, for which I understand. In case you're curious, drop cases are where one case purposefully does not break and drops to the next case.</p>\n\n<pre><code>switch( $query{ $i } ) {\n case '\\\\': $i++; break;\n case '\\'':\n if( ! $d ) { $s = ! $s; }\n break;\n case '\"':\n if( ! $s ) { $d = ! $d; }\n break;\n case '%':\n if( ! $s &amp;&amp; ! $d ) {\n }\n break;\n}\n</code></pre>\n\n<p>Another point for (DRY (Don't Repeat Yourself). You are looking up the next character for the <code>$query</code> string quite frequently. I'd consider making a new variable to hold it instead of typing the same equation again and again to retrieve it. This way you'll reduce the overhead, small as it is, increase the legibility, and should this equation ever change, say you need to skip two places instead of one, you'll be able to do so without needing to change it multiple times.</p>\n\n<pre><code>$nextChar = $query{ $i + 1 };\n</code></pre>\n\n<p>While I'd still use <code>$nextChar</code> for the rest of the program, I wouldn't use that if statement with all those <code>$nextChar</code> comparisons. You can keep the first part that compares the length, but it would be better to create a whitelist array and use <code>in_array()</code> to determine if the next character is one you want. And best to use two if statements rather than just one, since they check for different things.</p>\n\n<pre><code>$whitelist = array(\n 'i',\n 'd',\n 's',\n 'b',\n);\nif( $i + 1 &lt; $queryLength ) {\n $nextChar = $query{ $i + 1 };\n if( in_array( $nextChar, $whitelist ) ) {\n</code></pre>\n\n<p>And one more point for DRY. When performing an if/else statement that will change the same variable(s) in both instances, it is much easier to perform similar changes only once. So...</p>\n\n<pre><code>$tokenString .= $nextChar;\n$filler = '?';\n\n$contents = $params[ $n ];\nif( is_array( $contents ) ) {\n $elmentCount = count( $contents ) - 1;\n\n $filler = str_repeat( $nextChar, $elmentCount );\n $tokenString .= $filler;\n\n $queryLength += $elmentCount * 2 - 2;\n $n += $elmentCount;\n}\n\n$prevChars = substr( $query, 0, $i );\n$restOfQuery = substr( $query, $i + 2 );\n$query = $prevChars . $filler . $restOfQuery;\n\n$queryLength--;\n\n$n++;\n</code></pre>\n\n<p>I moved all of the common bits out of the if/else statements. As such, you'll now notice that the else statement is gone. This is because you did the same thing in the if statement that you did in the else statement, only more so. I had to change some things within the if statement to compensate, but now you only need to change the values once if you ever need to change the base value. The <code>$elementCount</code> now needs to be decremented because everything that uses it has already been incremented. I removed the <code>array_splice()</code> as I could not fathom the reason for it. Correct me if I'm wrong, but doesn't this just remove <code>$params[ $n ]</code> then replace it with the same value? Anyways, after that I created a <code>$filler</code>, using the <code>str_repeat()</code> method you were already using. The other used two functions to accomplish the same thing instead of just one. And I could find no reason for there to be different contents, so I simplified it and just removed the other. After creating the filler, I added it to the <code>$tokenString</code> and later to the <code>$query</code>. I then had to adjust the <code>$queryLength</code> because of the adjustment to <code>$elementCount</code>. BTW: what does this equation mean? I understand the need for doubling, but why the subtraction? I then added the length of <code>$elementCount</code> to <code>$n</code>, which will be incremented once more by default.</p>\n\n<p>Last comment, I think that because you are doing two iterations in one loop, it is better to have both <code>$i</code> and <code>$n</code> declared in the arguments, as you had before, that way everyone knows its purpose.</p>\n\n<p><strong>MAJOR UPDATE</strong></p>\n\n<p>Alright, I've done a bit of research to try and better understand MySQLi and subsequently better answer your questions. As I said before I had no experience with MySQLi. I still have no practical experience with it, but now at least I've got a better understanding of it. So here are a few updates. First some improvements I missed due to lack of understanding.</p>\n\n<p>When creating a new instance of the MySQLi object, you can also immediately select the database. From what I gather, there is no reason to separate this and all the reason to incorporate it. This makes it so that when you check for connection errors you are also ensuring that you are able to select the appropriate database, which you were not doing before. This means a few less lines, one less function to call, and extra protection. I think its a good tradeoff. All you have to do is change the default value of <code>$dbName</code> to an empty string and pass it as the final parameter for the MySQLi constructor. The MySQLi already expects the <code>$dbName</code> to be an empty string by default, so passing an empty string to it shouldn't make a difference.</p>\n\n<pre><code>public function __construct ( $dbHost, $dbUser, $dbPass, $dbName = '' ) {\n $this-&gt;_connection = new mysqli( $dbHost, $dbUser, $dbPass, $dbName );\n</code></pre>\n\n<p>I think its also important to note that, until recently (5.2.9), the <code>connect_error</code> property of the MySQLi object was not working properly and the only way to get this information was to use <code>mysqli_connect_error()</code>. Because it does seem like you are dealing with multiple versions, this could definitely pose a problem.</p>\n\n<p>Now to your last two comments and updated advice.</p>\n\n<p>I'm not sure I understand how the switch breaks the code... The switch is essentially one big if statement that checks the current character. Additional if statements inside the switch serve as AND checking. And all AND checking does is ensure that both sides are TRUE. One side before the other of course, but from what I can see, the order does not appear to make a difference here because you aren't checking for the same character twice, but even if you were, a second if statement in the appropriate case would settle any issues there. The value of the current character is not going to change, so seeing what it is first will not make a difference, so long as we still perform the appropriate checks against it before doing anything with it. Its backwards from how you are currently checking it, but it still follows the same flow. If the current character is a single quote it will still only flip the \"quoted string\" switch only if the \"quoted type\" switch has already been flipped. Same for the double quote, and same for the percent sign. They all still rely on those two switches. So, what is different that causes this to break? Is there something I missed? This next bit might actually render this point moot, but I'm still interested.</p>\n\n<p>I don't see how your current <code>array_splice()</code> does anything. Let's take a look at it. First the function in question.</p>\n\n<pre><code>array_splice( $input, $offset, $length, $replacement );\n</code></pre>\n\n<p>The <code>$input</code> specifies the array, and the <code>$offset</code> specifies index of the desired element to be removed. This is identical to <code>$input[ $offset ]</code>. The <code>$length</code> determines how many elements are going to be removed after the offset. And of course, the <code>$replacement</code> is the replacement element that will take residence in the hole we just chopped out of the array. You give the function an array, an offset, and then a range of offsets, then a replacement element. Pretty simple. So lets look at yours.</p>\n\n<pre><code>array_splice( $params, $n, 1, $params[ $n ] );\n</code></pre>\n\n<p>We are removing <code>$n</code> from the <code>$params</code> array, or <code>$params[ $n ]</code>. The length is only set to 1 so, this will be the only element that is removed. We are also replacing the element we just removed (<code>$params[ $n ]</code>) with <code>$params[ $n ]</code>. Which is equivalent to saying <code>$params[ $n ] = $params[ $n ]</code> BTW, so the function isn't even necessary here. But do you see how this is redundant? One of us is missing something here. I've had the PHP documentation opened along side me the whole time, so I'm fairly confident in this answer. I don't think this is actually doing anything except taking up overhead, and more overhead than is actually necessary for this task. If you are going to replace a single element of an array, there is no need to use <code>array_splice()</code> to do it. Just reassign the key a new value. But again, even that is unnecessary as it is.</p>\n\n<p>If your program is so expensive that it bogs down with even basic PHP functionality, then there is definitely something wrong. You're either doing too much, or doing something extremely inefficiently. Either way, I would suggest reviewing your code and asking yourself if it can be done better. Of course, that's why you're here. When I originally answered this question I mentioned another way to parse your query, but you shot it down saying what you were doing was necessary. I didn't pursue it further at the time because I didn't understand what you were doing well enough to argue the point. After much examination, and a better understanding, I still think that other way is possible, and better. I've included a snippet of it below. Are you sure you can't do something similar to this? It seems identical to what you are currently doing, but vastly simpler and quicker and would reduce a lot of your overhead. Of course this isn't complete and might require some fine tuning, but it gets the idea across.</p>\n\n<pre><code>while( $pos = strpos( $query, '%' ) ) {\n if( $pos + 1 &lt; $queryLength ) {\n $nextChar = $query{ $pos + 1 };\n if( in_array( $nextChar, $whitelist ) ) {\n $tokenString .= $nextChar;\n $query = substr_replace($query, '?', $i, 2);\n }\n }\n}\n</code></pre>\n\n<p>Also, can't believe I missed this before, but, instead of using two <code>substr()</code> functions to replace a part of a string, why not just use <code>substr_replace()</code> like I have shown above?</p>\n\n<p><strong>referenceValues()</strong></p>\n\n<p>You've broken from your standard practice for private/protected properties/methods. All your other private/protected elements are prepended with an underscore \"_\". Not everyone does this, each person has their own methods. However I noticed that you were following it up to this point. Why did you stop? Speaking of private/protected. Why are you using protected? Not saying you can't, just that its an odd choice unless you are extending classes.</p>\n\n<p><strong>Getter Methods</strong></p>\n\n<p>I'd personally set up my magic getter method rather than call so many different/specific getter methods. If you want to prevent the certain variables from being retrieve you can create a blacklist for them.</p>\n\n<pre><code>public function __get( $name ) { return isset( $this-&gt;_statement-&gt;$name ) ? $this-&gt;_statement-&gt;$name : FALSE; }\n</code></pre>\n\n<p><strong>dump()</strong></p>\n\n<p>I'd personally remove the HTML from the PHP. It looks very cluttered in this code. Take a look at MVC. You're mostly there already, so adding this bit for HTML output won't take too much effort.</p>\n\n<p><strong>Error Suppressing</strong></p>\n\n<p>You should never suppress errors. Your code should ALWAYS be 100% error free. If something doesn't work without that suppressor, find out why and fix it.</p>\n\n<p><strong>Setting Variables in Statements</strong></p>\n\n<p>I would avoid setting variables in if statements, or any similar statement. They can be a debugging nightmare. For example, I'm not going to tell you what variable you defined, or where, only that its in an if statement, good luck finding it :) Of course, you're probably familiar enough with this program so that finding it probably wont be an issue, but others won't be as fortunate.</p>\n\n<p>Answer:</p>\n\n<blockquote class=\"spoiler\">\n <p> There are actually multiples of these, but the first is in the first if statement of the DbHandler constructor method.</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T16:58:59.253", "Id": "21570", "Score": "0", "body": "first: thanks for the long answer! On supported PHP syntax: 1) The diamond operator is supported by PHP. As always the language allows you to do even the most basic operation in several ways. I think (=my opinion) this syntax is clearer than the equivalent `!=`. 2) The `{}` is (once again, it has been `[]` for a while) the prefered method of string position referencing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T17:35:59.873", "Id": "21573", "Score": "0", "body": "The `_parse()` method has been cleaned up to remove the trimming. It needs to itterates over every character because it is actually parsing the string. This is the common pattern to support quoted strings, escape sequences and actual control characters. If I would try to locate the required characters in any other way, they would be out of context and thus could have another meaning. (Why does it look different? It is older, it came from my previous, procedural `mysql_*`-based handler)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T17:41:00.027", "Id": "21574", "Score": "0", "body": "On the `'dump()'` method. You are absolutely correct, it does not belong here. However, during debugging and development, this method is so usefull, that I go grumpy without it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T17:48:04.917", "Id": "21575", "Score": "0", "body": "On why the trigger_error, instead of throwing exception. In my code, I use Exceptions for (fatal) errors. The E_USER_WARNING and E_USER_NOTICE are less severe than an Error, they point to things that might be other-than-expected, but could also be intended behaviour. Notices are commonly suppressed in a production environment, Exceptions will always need catching." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T18:09:11.543", "Id": "21577", "Score": "2", "body": "@Jacco: I did not know that the diamond operator was supported. I knew what it did, but not that it was supported. Not sure about it being clearer, especially since it is not even documented in the PHP manual (at least not that I could find), but that's a preference thing. Also did not know that about the strings. Knew what you were doing was possible, but not that braces were interchangeable. I have to admit, that I do prefer this method. Removes ambiguity from them being mistaken as arrays..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T18:09:27.410", "Id": "21578", "Score": "0", "body": "@Jacco: It looks different because of those reasons I gave in the answer. Also this method is less specialized than all the rest. The other methods do one thing, and their method name describes them very well. In fact I was impressed with that, usually I'm having to tell people to do that. This one method, as I mentioned, is doing too much. I'll admit, I don't have any experience with MySQLi at all, and very little with any of the others, but if this is the standard way, it just seems odd and cluttered." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T18:09:45.663", "Id": "21579", "Score": "0", "body": "@Jacco: You can have the `dump()` method there, I completely agree that such methods are lifesavers, I just wasn't happy with the mingling of PHP and HTML. Its very messy. I'd set up all the variables and arrays you need and then create and include the HTML page to lightly use PHP to parse over the variables and arrays there. I don't like HTML touching my PHP, though I don't mind a bit of PHP touching my HTML." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T18:10:08.737", "Id": "21580", "Score": "1", "body": "@Jacco: I guess I can understand that distinction for error reporting. Much better than mine anyways. Need to work on that :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T18:59:15.147", "Id": "21583", "Score": "0", "body": "(a reference to the [diamond operator](http://www.php.net/manual/en/language.operators.comparison.php)). I've cleaned up the `_parse()` method and would like to invite you to review it again. It is by far the most complex method in the whole package as it is responsible for the actual syntax change between this library and the vanilla MySQLi syntax." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T21:21:18.393", "Id": "21599", "Score": "0", "body": "@Jacco: I added an update to the \"Diamond Operator\" and \"_parser()\" sections. I left most of the original text for reference." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T09:33:06.993", "Id": "21638", "Score": "0", "body": "Thanks for looking at it again. The `array_splice()` replaces an element by an array of elements in this case. The Switch vs. The `_parse()` method does a lot of work. Because of this, it has been optimized for computational efficiency and to minimize the amount of assignments and function calls. By introducing for example an `in_array()` function call, you introduce a function call for every character in the query string, something I considered unacceptably costly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T16:44:24.167", "Id": "21656", "Score": "0", "body": "@Jacco: Add a major update to the \"_parser()\" section" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T21:50:13.863", "Id": "21667", "Score": "0", "body": "the `substr_replace()` is a nice catch, implemented it. The array_splice is doing it's job: it changes `array('a', array('b','c'),'d')` into `array('a','b','c','d')`, try it out :) (and, stackexchange site functionality is far-from-optimal for code-review)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T22:07:09.420", "Id": "21669", "Score": "0", "body": "if I do the `while( $pos = strpos( $query, '%' ) ) {`, the code would never know when to skip a character because of a preceding escape character or not to return the position of %-characters inside a quoted string. The pattern used is a common one for parsing strings; you can't get around examining every character in sequence. I'm looking at your `switch()` point again, looks like I mistakenly claimed it would break the code, it looks like it should indeed work as intended. (will try later)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-16T18:39:45.367", "Id": "22177", "Score": "0", "body": "I've updated dbHandler class, mostly the `_parse()` method, but also the connect mechanism in the `__construct()` method." } ], "meta_data": { "CommentCount": "15", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T16:41:01.730", "Id": "13360", "ParentId": "13352", "Score": "10" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T13:28:46.370", "Id": "13352", "Score": "7", "Tags": [ "php", "security", "mysqli" ], "Title": "MySQLi DB library - quality/security review?" }
13352
<p>I knocked this up quickly to allow delayed <code>Invoke</code> on the dispatcher. Along with canceling the existing invocation and replacing with a new one, this allows throttling an action.</p> <pre><code>public static class DispatcherExtensions { private static Dictionary&lt;string, DispatcherTimer&gt; timers = new Dictionary&lt;string, DispatcherTimer&gt;(); private static object syncRoot = new object(); public static void DelayInvoke(this Dispatcher dispatcher, string namedInvocation, Action action, TimeSpan delay, DispatcherPriority priority = DispatcherPriority.Normal) { lock (syncRoot) { DispatcherTimer timer = null; if (timers.TryGetValue(namedInvocation, out timer)) { timer.Stop(); timer.IsEnabled = false; timers.Remove(namedInvocation); } timer = new DispatcherTimer(priority,dispatcher) { Interval = delay }; timer.Tick += (s, e) =&gt; { action(); }; timers.Add(namedInvocation, timer); timer.IsEnabled = true; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T17:02:13.687", "Id": "21571", "Score": "0", "body": "What kind of improvements are you looking for? Do you think there's something wrong with your code? Also, do you really want to always invoke the actions repeatedly (that's what `DispatcherTimer` does) and have no direct way of truly canceling the invocation (without replacement)?" } ]
[ { "body": "<p>I'm not an expert on multithreading at all, but I've attempted refactoring your code a bit.\nFirst of all, to code defensively, I suggest adding the <code>readonly</code> modifier to your lock object. It's not required but will prevent accidental assignments:</p>\n\n<pre><code>private static readonly object syncRoot = new object();\n</code></pre>\n\n<p>I'm against incurring the complexity of an <code>out</code> argument: let's just check if the timer exists. We can stop it and remove it if it does; setting <code>DispatcherTimer.IsEnabled</code> isn't necessary because <code>DispatcherTimer.Stop()</code> <a href=\"https://stackoverflow.com/a/3163314/1106367\">sets it to false anyway</a>:</p>\n\n<pre><code>if (timers.ContainsKey(namedInvocation))\n{\n timers[namedInvocation].Stop();\n timers.Remove(namedInvocation);\n}\n</code></pre>\n\n<p>We can get rid of the object initializer because <code>DispatcherTimer</code> has the perfect constructor for us anyway; this has the added benefit of inlining the lambda: </p>\n\n<pre><code>var timer = new DispatcherTimer(delay, priority, (s, e) =&gt; action(), dispatcher);\ntimer.Start();\ntimers.Add(namedInvocation, timer);\n</code></pre>\n\n<p>Again, remember we don't need to set <code>IsEnabled</code> because <code>DispatcherTimer.Start()</code> sets it to true for us (alternatively, you can leave it in place but remove the call to <code>Start()</code>. But the method call seems more intuitive to me; setting a property doesn't make it obvious that the timer has been started).</p>\n\n<p>You may have noticed I used <code>var</code> wherever it seemed appropriate; it's just as type safe as using the actual type but takes up less space, both on the page in in my brain.</p>\n\n<p>That leaves us with the following end result:</p>\n\n<pre><code>public static class DispatcherExtensions\n{\n private static Dictionary&lt;string, DispatcherTimer&gt; timers = \n new Dictionary&lt;string, DispatcherTimer&gt;();\n private static readonly object syncRoot = new object();\n\n public static void DelayInvoke(this Dispatcher dispatcher, string namedInvocation,\n Action action, TimeSpan delay, \n DispatcherPriority priority = DispatcherPriority.Normal)\n {\n lock (syncRoot)\n {\n if (timers.ContainsKey(namedInvocation))\n {\n timers[namedInvocation].Stop();\n timers.Remove(namedInvocation);\n }\n var timer = new DispatcherTimer(delay, priority, (s,e) =&gt; action(), dispatcher);\n timer.Start();\n timers.Add(namedInvocation, timer);\n }\n }\n}\n</code></pre>\n\n<p>In case I introduced a bug or if you have improvements, let me know in the comments.</p>\n\n<hr>\n\n<h1>Edit: supporting cancellation</h1>\n\n<p><em>(@svick's suggestion)</em></p>\n\n<p>To provide the possibility of cancelling your timers, you would factor out the timer removing logic (I inverted the condition to reduce nesting...) into a new method that is called at the beginning of <code>DelayInvoke</code>.</p>\n\n<pre><code>private static void RemoveTimer(string namedInvocation)\n{\n if (!timers.ContainsKey(namedInvocation)) return;\n timers[namedInvocation].Stop();\n timers.Remove(namedInvocation);\n}\n</code></pre>\n\n<p>Then, you'd create another extension method (first parameter is useless, but calling the method via the Dispatcher is consistent and convenient, so I left it there). Something like this:</p>\n\n<pre><code>public static void CancelNamedInvocation(this Dispatcher dispatcher, string namedInvocation)\n{\n lock(syncRoot)\n {\n RemoveTimer(namedInvocation);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T17:15:18.503", "Id": "13363", "ParentId": "13354", "Score": "3" } }, { "body": "<p>The only thing I'd add to codesparkle's answer is that I find it better to move the action to the end, so that when you call the method, an anonymous method doesn't come before other parameters.</p>\n\n<p>So instead of this:</p>\n\n<pre><code>MyDispatcher.DelayInvoke(\"SomeKey\", () =&gt; {\n // ..\n // ..\n // ..\n}, TimeSpan.FromSeconds(5), DispatcherPriority.Normal);\n</code></pre>\n\n<p>You have this, which I think is more pleasant on the eye:</p>\n\n<pre><code>MyDispatcher.DelayInvoke(\"SomeKey\", TimeSpan.FromSeconds(5), DispatcherPriority.Normal, () =&gt; {\n // ..\n // ..\n // ..\n});\n</code></pre>\n\n<p>Although the downside is that the priority can no longer be a defaulted parameter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-27T21:28:19.813", "Id": "225900", "Score": "0", "body": "You should post this as a comment to the answer, because it's not an answer in itself. But do you think it's wise to trade a feature for looks?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-03T08:49:51.783", "Id": "226790", "Score": "0", "body": "You can't post code in comments, and I felt it was a visual thing. Also, isn't this valid as an answer to a call for refactoring? I don't see it as a trade - what feature is being traded in? Also, it's not just looks. If that anonymous method gets long enough, anyone reading that code could miss that there are further parameters at the end. It's for transparency more than anything." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-27T20:39:25.747", "Id": "121318", "ParentId": "13354", "Score": "0" } }, { "body": "<p>In my experience there is rarely a need for delayed invokes on the dispatcher, what problem are you solving?</p>\n\n<p>If you do something in a constructor that you want deferred until loaded there is already an overload for that:</p>\n\n<pre><code>Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(...));\n</code></pre>\n\n<p>For delayed invokes why not use:</p>\n\n<pre><code>public static async Task InvokeAsync(\n this Dispatcher dispatcher,\n TimeSpan delay,\n Action action)\n{\n await Task.Delay(delay).ConfigureAwait(false);\n await dispatcher.InvokeAsync(action).Task.ConfigureAwait(false);;\n}\n</code></pre>\n\n<p>I would probably not have this as an extension method as it doesn't mean any real reuse of code.</p>\n\n<p>For cancellation you can use this:</p>\n\n<pre><code>public static async Task InvokeAsync(\n this Dispatcher dispatcher,\n TimeSpan delay,\n CancellationToken cancellationToken,\n Action action)\n{\n await Task.Delay(delay, cancellationToken).ConfigureAwait(false);\n await dispatcher.InvokeAsync(action, DispatcherPriority.Normal, cancellationToken)\n .Task.ConfigureAwait(false);;\n}\n</code></pre>\n\n<p>Passing in cancellation token is more consistent with how it is done in the framework.</p>\n\n<p>With this design there is no risk for deadlocks and leaks.</p>\n\n<p>I omitted the overload permutations with <code>DispatcherPriority</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-28T01:07:12.837", "Id": "121330", "ParentId": "13354", "Score": "0" } } ]
{ "AcceptedAnswerId": "13363", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T13:59:24.037", "Id": "13354", "Score": "3", "Tags": [ "c#", "multithreading", "wpf" ], "Title": "Delayed dispatcher invoke" }
13354
<p>I came up with the idea of a small utility class that will poll <em>some delegate</em> until the response received meets <em>some condition</em>, upon which it will notify the main thread which can take the appropriate action.</p> <p>This is the first time I've ever done something like this, and I know that in general, polling is a bad idea, so I want to do this in a way that consumes minimal resources, and is really easy to use.</p> <pre><code>using System; using System.Threading; using System.Windows.Threading; namespace WPF.Utilities.Common { /// &lt;summary&gt;This class allows a user to easily set up a seperate thread to poll some state, /// and set up an event that will fire if the state meets some condition.&lt;/summary&gt; /// &lt;typeparam name="T"&gt;The type of the value returned by the polling delegate.&lt;/typeparam&gt; public class ConditionMonitor&lt;T&gt; { #region Private Properties protected bool Halted = false; protected Dispatcher originThread = null; protected Thread monitorThread = null; #endregion #region Delegates /// &lt;summary&gt;A delegate provided by the user of this class which returns the current state, /// to be tested against a certain condition in the IsConditionMet delegate.&lt;/summary&gt; public delegate T RequestState(); public RequestState RequestStateDelegate { get; set; } /// &lt;summary&gt;A delegate provided by the user of this class which determines whether given the /// current state, the polling program should execute the ConditionMet delegate.&lt;/summary&gt; public delegate bool IsConditionMet&lt;T&gt;(T state); public IsConditionMet&lt;T&gt; IsConditionMetDelegate { get; set; } /// &lt;summary&gt;A delegate used to handle ConditionMonitor events.&lt;/summary&gt; public delegate void ConditionMonitorHandler&lt;T&gt;(ConditionMonitor&lt;T&gt; source, T state); /// &lt;summary&gt;An event which fires each time the state is polled (use sparingly).&lt;/summary&gt; public event ConditionMonitorHandler&lt;T&gt; RequestReceived; /// &lt;summary&gt;An event which fires when the condition is met.&lt;/summary&gt; public event ConditionMonitorHandler&lt;T&gt; ConditionMet; /// &lt;summary&gt;A delegate used to handle ConditionMonitor events.&lt;/summary&gt; public delegate void ConditionMonitorExceptionHandler&lt;T&gt;(ConditionMonitor&lt;T&gt; source, T state, Exception ex); /// &lt;summary&gt;An event which fires if an exception is thrown while retrieving the state /// or testing whether the condition is met.&lt;/summary&gt; public event ConditionMonitorExceptionHandler&lt;T&gt; RequestError; #endregion #region Public Properties /// &lt;summary&gt;The time between requests made to the RequestStateDelegate. Default is 1 second (1000ms)&lt;/summary&gt; public int PollInterval_Milliseconds { get; set; } /// &lt;summary&gt;Set to true to automatically halt polling once the condition is met. Default is False.&lt;/summary&gt; public bool HaltWhenConditionMet { get; set; } #endregion #region Constructors /// &lt;summary&gt;Creates a new instance of a ConditionMonitor&lt;/summary&gt; public ConditionMonitor() { originThread = Dispatcher.CurrentDispatcher; PollInterval_Milliseconds = (int)TimeSpan.FromSeconds(1).TotalMilliseconds; HaltWhenConditionMet = false; } #endregion #region Public Methods /// &lt;summary&gt;Begins polling the RequestStateDelegate on a seperate thread.&lt;/summary&gt; public virtual void BeginMonitoring() { if( monitorThread != null ) throw new Exception("Previous monitoring has not yet been stopped!"); if( RequestStateDelegate == null ) throw new Exception("No delegate specified for polling - please set the RequestStateDelegate property."); Halted = false; monitorThread = new Thread(new ThreadStart(PollState)); monitorThread.Start(); } /// &lt;summary&gt;Halts polling and ensures that no more requests will be made or events fired.&lt;/summary&gt; public virtual void StopMonitoring() { Halted = true; } #endregion #region Private Methods /// &lt;summary&gt;Responsible for the polling loop and invoking events back on the origin thread.&lt;/summary&gt; protected virtual void PollState() { while( !Halted ) { T state = default(T); bool bConditionMet = false; try { state = RequestStateDelegate(); InvokeEvent(RequestReceived, state); if( IsConditionMetDelegate != null &amp;&amp; !Halted ) { bConditionMet = IsConditionMetDelegate(state); if( bConditionMet ) { InvokeEvent(ConditionMet, state); if( HaltWhenConditionMet ) Halted = true; } } } catch( Exception ex ) { InvokeExceptionHandler(state, ex); } if( !Halted ) Thread.Sleep(PollInterval_Milliseconds); } monitorThread = null; } /// &lt;summary&gt;Invokes a delegate of type ConditionMonitorHandler on the origin thread.&lt;/summary&gt; /// &lt;param name="toInvoke"&gt;The delegate to invoke (RequestRecieved or ConditionMet)&lt;/param&gt; /// &lt;param name="state"&gt;The response from the last call to the RequestStateDelegate&lt;/param&gt; protected void InvokeEvent(ConditionMonitorHandler&lt;T&gt; toInvoke, T state) { if(toInvoke != null &amp;&amp; !Halted) originThread.BeginInvoke(toInvoke, new object[] { this, state }); } /// &lt;summary&gt;Invokes the exception delegate on the origin thread.&lt;/summary&gt; /// &lt;param name="state"&gt;The response from the last call to the RequestStateDelegate, or null.&lt;/param&gt; /// &lt;param name="ex"&gt;The exception raised while calling the RequestStateDelegate or IsConditionMetDelegate.&lt;/param&gt; protected void InvokeExceptionHandler(T state, Exception ex) { if( RequestError != null &amp;&amp; !Halted ) originThread.BeginInvoke(RequestError, new object[] { this, state, ex }); } #endregion } } </code></pre> <p>My intended first use is going to be in a program that people in my company have running pretty much all the time. They will be working on some 'deal', and want to know if anything associated with that deal changes so they can grab the latest numbers. My <code>RequestStateDelegate</code> will be a small database call to check the last modified time of the entry they're working on. I want the thread to silently poll and ONLY bother the main thread when the modified time is not equal to the modified time of the entry the user has loaded up (the <code>IsConditionMetDelegate</code> will be a small method that does that check).</p> <p>I just want to be sure I haven't set this up in a way where I risk spinning off more than a single thread, or end up with a thread that keeps running even after <code>StopMonitoring</code> has been called. Is there anything else I need to do to clean up the thread, or is simply letting <code>PollState</code> return sufficient?</p> <p>I'm also worried about what happens if someone abandons the <code>ConditionMonitor</code> instance without remembering to call <code>StopMonitoring()</code>. The GC would dispose of the class, but what would happen to the thread is spun up - would it get silently aborted, or throw a huge fuss since it references <code>ConditionMonitor</code> properties? I thought I might have to do something like this:</p> <pre><code>public ~ConditionMonitor() { StopMonitoring(); } </code></pre> <p>(Or something similar using <code>IDisposable</code>) But will the garbage collector even consider this instance for clean up if its thread is perpetually spinning its <code>PollState</code> instance method?</p> <h2>Revised Code</h2> <pre><code>using System; using System.Threading; using System.Windows.Threading; namespace WPF.Utilities.Common { /// &lt;summary&gt;This class allows a user to easily set up a seperate thread to poll some state, /// and set up an event that will fire if the state meets some condition.&lt;/summary&gt; /// &lt;typeparam name="T"&gt;The type of the value returned by the polling delegate.&lt;/typeparam&gt; public class ConditionMonitor&lt;T&gt; : IDisposable { #region Private Properties private Object multiThreadLock = new Object(); private Dispatcher originThread = null; private Thread monitorThread = null; private volatile bool Halted = false; #endregion #region Delegates /// &lt;summary&gt;A delegate provided by the user of this class which returns the current state, /// to be tested against a certain condition in the IsConditionMet delegate.&lt;/summary&gt; public delegate T RequestState(); public RequestState RequestStateDelegate { get; set; } /// &lt;summary&gt;A delegate provided by the user of this class which determines whether given the /// current state, the polling program should execute the ConditionMet delegate.&lt;/summary&gt; public delegate bool IsConditionMet(T state); public IsConditionMet IsConditionMetDelegate { get; set; } /// &lt;summary&gt;A delegate used to handle ConditionMonitor events.&lt;/summary&gt; public delegate void ConditionMonitorHandler(ConditionMonitor&lt;T&gt; source, T state); /// &lt;summary&gt;An event which fires each time the state is polled (use sparingly).&lt;/summary&gt; public event ConditionMonitorHandler RequestReceived; /// &lt;summary&gt;An event which fires when the condition is met.&lt;/summary&gt; public event ConditionMonitorHandler ConditionMet; /// &lt;summary&gt;A delegate used to handle ConditionMonitor events.&lt;/summary&gt; public delegate void ConditionMonitorExceptionHandler(ConditionMonitor&lt;T&gt; source, T state, Exception ex); /// &lt;summary&gt;An event which fires if an exception is thrown while retrieving the state /// or testing whether the condition is met.&lt;/summary&gt; public event ConditionMonitorExceptionHandler RequestError; #endregion #region Public Properties /// &lt;summary&gt;The time between requests made to the RequestStateDelegate. Default is 1 second (1000ms)&lt;/summary&gt; public int PollInterval_Milliseconds { get; set; } /// &lt;summary&gt;Set to true to automatically halt polling once the condition is met. Default is False.&lt;/summary&gt; public bool HaltWhenConditionMet { get; set; } #endregion #region Constructors /// &lt;summary&gt;Creates a new instance of a ConditionMonitor&lt;/summary&gt; public ConditionMonitor() { originThread = Dispatcher.CurrentDispatcher; PollInterval_Milliseconds = (int)TimeSpan.FromSeconds(1).TotalMilliseconds; HaltWhenConditionMet = false; } #endregion #region Public Methods /// &lt;summary&gt;Begins polling the RequestStateDelegate on a seperate thread.&lt;/summary&gt; public void BeginMonitoring() { if( RequestStateDelegate == null ) throw new Exception("No delegate specified for polling - please set the RequestStateDelegate property."); lock( multiThreadLock ) { if( monitorThread != null ) throw new Exception("Previous monitoring has not yet been stopped!"); monitorThread = new Thread(new ThreadStart(PollState)); } Halted = false; monitorThread.Start(); } /// &lt;summary&gt;Halts polling and ensures that no more requests will be made or events fired.&lt;/summary&gt; public void StopMonitoring() { Halted = true; } /// &lt;summary&gt;Halts the thread if it is still running so that the instance can be garbage collected.&lt;/summary&gt; public void Dispose() { StopMonitoring(); } #endregion #region Private Methods /// &lt;summary&gt;Responsible for the polling loop and invoking events back on the origin thread.&lt;/summary&gt; private void PollState() { while( !Halted ) { T state = default(T); bool bConditionMet = false; try { state = RequestStateDelegate(); InvokeEvent(RequestReceived, state); if( IsConditionMetDelegate != null &amp;&amp; !Halted ) { bConditionMet = IsConditionMetDelegate(state); if( bConditionMet ) { InvokeEvent(ConditionMet, state); if( HaltWhenConditionMet ) Halted = true; } } } catch( Exception ex ) { InvokeExceptionHandler(state, ex); } if( !Halted ) Thread.Sleep(PollInterval_Milliseconds); } monitorThread = null; } /// &lt;summary&gt;Invokes a delegate of type ConditionMonitorHandler on the origin thread.&lt;/summary&gt; /// &lt;param name="toInvoke"&gt;The delegate to invoke (RequestRecieved or ConditionMet)&lt;/param&gt; /// &lt;param name="state"&gt;The response from the last call to the RequestStateDelegate&lt;/param&gt; private void InvokeEvent(ConditionMonitorHandler toInvoke, T state) { if( toInvoke != null &amp;&amp; !Halted ) originThread.BeginInvoke(toInvoke, new object[] { this, state }); } /// &lt;summary&gt;Invokes the exception delegate on the origin thread.&lt;/summary&gt; /// &lt;param name="state"&gt;The response from the last call to the RequestStateDelegate, or null.&lt;/param&gt; /// &lt;param name="ex"&gt;The exception raised while calling the RequestStateDelegate or IsConditionMetDelegate.&lt;/param&gt; private void InvokeExceptionHandler(T state, Exception ex) { if( RequestError != null &amp;&amp; !Halted ) originThread.BeginInvoke(RequestError, new object[] { this, state, ex }); } #endregion } } </code></pre> <hr> <p>I am no attempting to implement the polling process using a <code>Timer</code> and the <code>ThreadPool</code> as recommended in the answer. A followup question has been posted here: </p> <p><a href="https://codereview.stackexchange.com/questions/13393/the-correct-way-to-use-threadpool-and-timer-to-poll-a-delegate">Timer to poll a Delegate</a></p>
[]
[ { "body": "<blockquote>\n <p>I want to do this in a way that consumes minimal resources</p>\n</blockquote>\n\n<p>Then don't have a separate thread that's not doing anything most of the time. Each thread in .Net consumes 1 MB of memory (both virtual and physical) and some other resources. A better solution would be to run your code on the ThreadPool and don't use <code>Thread.Sleep()</code>. The best way to do this is to use a Timer.</p>\n\n<blockquote>\n <p>I just want to be sure I haven't set this up in a way where I risk spinning off more than a single thread […]</p>\n</blockquote>\n\n<p>Actually, there is a chance exactly that will happen if two threads called <code>BeginMonitoring()</code> at the same time. Could that happen in your situation?</p>\n\n<blockquote>\n <p>[…] or end up with a thread that keeps running even after StopMonitoring has been called.</p>\n</blockquote>\n\n<p>I think that is also a possibility. The check of <code>Halted</code> might be optimized away, you should mark it as <code>volatile</code>, to make sure that doesn't happen.</p>\n\n<blockquote>\n <p>Is there anything else I need to do to clean up the thread, or is simply letting <code>PollState</code> return sufficient?</p>\n</blockquote>\n\n<p>Yes, that is sufficient, just let the method return and the thread will be safely destroyed.</p>\n\n<blockquote>\n <p>I'm also worried about what happens if someone abandons the <code>ConditionMonitor</code> instance without remembering to call <code>StopMonitoring()</code>. The GC would dispose of the class, but what would happen to the thread is spun up - would it get silently aborted, or throw a huge fuss since it references <code>ConditionMonitor</code> properties?</p>\n</blockquote>\n\n<p>The GC would do no such thing. The thread you created does have a reference to the instance, so the GC won't “dispose” it. (I use quotes, because disposing in .Net usually means calling <code>IDisposable.Dispose()</code>, that's not what I'm talking about here.) But because of that, the thread would run indefinitely. And a finalizer wouldn't help you either, again because the GC won't touch the instance, because it's still referenced.</p>\n\n<p>A solution here might be to have another object that isn't referenced from <code>PollState()</code> and that would make sure the thread is stopped in its finalizer.</p>\n\n<hr>\n\n<p>Also, it seems to me you're using <code>virtual</code> too much. It's meant only for methods that you really want to have overridden. And, actually <code>private virtual</code> doesn't make sense and should cause a compile error. Similarly, the default visibility for fields (and non-<code>public</code> methods) should be <code>private</code>, not <code>protected</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T22:31:10.940", "Id": "21601", "Score": "0", "body": "Re: private virtual - you're right that was stupid of me, but I do intend to make this class overridable in case one wants to support multiple conditions or additional events. Almost everything's virtual because I can envision the need to change them all in a more complex implementation. Perhaps to that effect, I should just create an interface and have this class implement the interface." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T22:35:44.413", "Id": "21602", "Score": "0", "body": "Re: Threading - I never imagined this class being instantiated and used from anything other than the main UI thread, so it doesn't attempt to take concurrency into account (aside from any internal concurrency issues that might arise between the instance's own polling thread and functions called from the origin thread.) I'm happy enough if it's safe under the assumption that only the instantiating thread makes any method calls or property sets." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T22:39:01.630", "Id": "21604", "Score": "0", "body": "Re: Halted being optimized away. I also never thought this possible. Wouldn't the compiler recognize the simple fact that the `if( HaltWhenConditionMet ) Halted = true;` modifies the value of Halted, so it can't possibly be removed from consideration?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T22:43:42.983", "Id": "21605", "Score": "0", "body": "Re: Resoures - my bad for not clarifying, a relatively small memory footprint doesn't concern me. I thought CPU wise, it was less computationally expensive to leave one method running (and sleeping the thread) than it was to have a timer spawn up fresh method calls on the stack every few seconds. I use a timer for some UI events that get periodically refreshed, because I can't sleep the UI thread, but since this is a dedicated thread, would `Sleep()` not be the least (CPU) invasive solution?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T22:53:04.640", "Id": "21606", "Score": "0", "body": "Re: Destructor - damn, I knew it wouldn't be simple. I think I get what you mean, but if I create a dummy class instance with simple destructor instructions to halt its owner's thread, won't that objects destructor also not get called until its owner is successfully garbage collected? I don't see a way around it. I feel, however, that if I implement `IDisposable`, it's a way of informing the user that they **must** dispose of this class to ensure no memory/process leaks, and the onus falls to them to fulfill this contract. Is this acceptable behaviour?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T22:57:48.357", "Id": "21607", "Score": "0", "body": "Re `Halt`: Yeah, I didn't notice you also set it inside the loop. But I would still use `volatile`, to make sure `Halt` is not reach from CPU cache on one core when it's changed on another." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T22:58:45.703", "Id": "21608", "Score": "0", "body": "Re resources: Timer shouldn't be any more CPU intensive than your version, I think." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T23:01:48.150", "Id": "21609", "Score": "1", "body": "Re destructor: The point is that the actual object won't have any references to the dummy object. That way, the dummy object can be GCed. And yeah, if you (as a user of some class) don't dispose of it, you can expect bad things to happen. And while finalizers can be useful as a last resort, they're by their nature quite unreliable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T12:50:31.917", "Id": "21645", "Score": "0", "body": "Thank you for your feedback. I made Halted [volatile](http://msdn.microsoft.com/en-us/library/x13ttww7%28v=vs.100%29.aspx) (Which seemed very appropriate given the MSDN description), got rid of unnecessary virtual/protected members, added a lock to `BeginMonitoring()` to prevent concurrency issues, and an IDisposable contract. I imagine I'll have a problem if the user Stops and then Starts monitoring again, expecting it to work right away, but the thread isn't gone yet because it's waiting for Thread.Sleep to complete, so I should switch to a timer mechanism too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T14:03:28.707", "Id": "21649", "Score": "0", "body": "I've posted a followup question here with my attempt to implement this using a Timer and the ThreadPool: [The correct way to use ThreadPool and Timer to poll a Delegate](http://codereview.stackexchange.com/questions/13393/the-correct-way-to-use-threadpool-and-timer-to-poll-a-delegate)" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T17:33:24.523", "Id": "13366", "ParentId": "13357", "Score": "9" } } ]
{ "AcceptedAnswerId": "13366", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T14:57:56.183", "Id": "13357", "Score": "5", "Tags": [ "c#", "multithreading", "generics", "delegates" ], "Title": "Polling loop to run in a background thread" }
13357
<p>I live in a country where an electricity blackout happens after every hour, which corrupts the Minecraft save files, so I came up with this auto backup utility which backs up the <em>%appData%.minecraft\saves</em> folder constantly after a specified time.</p> <p>It works fine but I'm still not satisfied with it. Tell me what more I can do to improve/enhance it.</p> <pre><code>import time import os import sys #class for parsing settings.ini class parseIni(object): def __init__(self, fileStream): self.lines = fileStream.readlines() self.options = [] for line in self.lines: if "=" not in line: continue else: self.options.append(tuple(line.replace("\n", "").split("="))) def getValueOf(self, option): for op, value in self.options: if op==option: return value #Tries to open the settings file, if unsuccessful then exit program settingsFileStream = None try: settingsFileStream = open("settings.ini") except IOError: print("ERROR: SETTINGS FILE NOT FOUND.", file=sys.stderr) raw_input("Press &lt;ENTER&gt; to exit....") sys.exit(0) #Initialize parser settings = parseIni(settingsFileStream) #Precondition: settings file was opened successfully #Assigning values to required variables timeDelayInMins = eval(settings.getValueOf("timeDelay")) #For user information timeDelay = timeDelayInMins * 60 #Converting to seconds, for time.sleep() method sourcePath = settings.getValueOf("sourcePath") destinationPath = settings.getValueOf("destinationPath") #Runs the game os.system("Minecraft.exe") #Prints out Welcome message print() print("|--------------------------------------------------------|") print("|WELCOME TO MINECRAFT AUTO BACKUP UTILITY! |") print("|--------------------------------------------------------|") print("|REFER TO THE settings.ini FILE TO EDIT SETTINGS FOR THIS|") print("|PROGRAM. e.g. TIME DELAY FOR AUTO BACKUP, PATHS etc |") print("|--------------------------------------------------------|") print("|TIME DELAY FOR AUTO BACKUP IS {:0.2f} MIN(S) |".format(timeDelayInMins)) print("|--------------------------------------------------------|") print() #Variable to keep tract of backups done per session backupsDone = 0 #mainLoop runs forever, backups "saves" folder every after ever timeDelay mins while True: time.sleep(timeDelay) os.system('robocopy "{}" "{}" /e'.format(sourcePath, destinationPath)) backupsDone += 1 print print print("|---------------------------------|") print("|{} BACKUP(S) DONE THIS SESSION. |".format(backupsDone)) print("|---------------------------------|") </code></pre> <p>And the <code>settings.ini</code> file with the program is:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>[TIME] timeDelay=1 [PATHS] sourcePath=%appData%\.minecraft\saves destinationPath=%appData%\.minecraft\SavesBackup </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T19:57:14.053", "Id": "21595", "Score": "3", "body": "Have you considered using [ConfigParser](http://docs.python.org/library/configparser.html)? I think it would simplify your code. Also you could print a triple quote string instead of having a dozen print statements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T06:39:52.073", "Id": "21622", "Score": "0", "body": "@BillBarry I think that's worth an answer post! Personally I'd love to see the ConfigParser in action." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T17:14:53.397", "Id": "21660", "Score": "0", "body": "but config parser requires alot of unnecessary things just to get a value from a simple ini file, thats why i made my own simple parser for the settings.ini" } ]
[ { "body": "<pre><code>import time\nimport os\nimport sys\n\n#class for parsing settings.ini\nclass parseIni(object):\n</code></pre>\n\n<p>Python style guide recommends names like <code>ParseIni</code></p>\n\n<pre><code> def __init__(self, fileStream):\n</code></pre>\n\n<p>Python style guide recommends argument like <code>file_stream</code>.</p>\n\n<pre><code> self.lines = fileStream.readlines()\n</code></pre>\n\n<p>You don't use the lines again, so why are you storing them on the object. There is not a whole lot of point in calling deadlines, because you can actually just pass the file object in the for loop for the same effect</p>\n\n<pre><code> self.options = []\n for line in self.lines:\n if \"=\" not in line:\n continue\n</code></pre>\n\n<p>I suggest almost always avoiding continue. As it is continue does nothing, replacing with pass will have the same effect. The whole if can be simplified by inverting the condition</p>\n\n<pre><code> else:\n self.options.append(tuple(line.replace(\"\\n\", \"\").split(\"=\")))\n</code></pre>\n\n<p>For clearing out excess whitespace, I recommend using <code>line.strip()</code>. I'd also suggest having options be a dictionary. Then you could do</p>\n\n<pre><code> key, value = line.strip().split('=')\n self.options[key] = value\n</code></pre>\n\n<p>It'll make lookup more efficient and is a bit simpler</p>\n\n<pre><code> def getValueOf(self, option):\n</code></pre>\n\n<p>Awkward and longish name. I'd have this be <code>__getitem__</code>, and then you can access it with the <code>[]</code> operator</p>\n\n<pre><code> for op, value in self.options:\n if op==option:\n return value\n</code></pre>\n\n<p>This is the for-if anti-pattern. Whenever you find yourself writing an if which should only be true for one instance of the surrounding loop, you should look for a better solution.</p>\n\n<p>Also, what happens if the option is missing? You should probably raise an exception.</p>\n\n<pre><code>#Tries to open the settings file, if unsuccessful then exit program\nsettingsFileStream = None\n</code></pre>\n\n<p>No point in doing this. </p>\n\n<pre><code>try:\n settingsFileStream = open(\"settings.ini\")\nexcept IOError:\n print(\"ERROR: SETTINGS FILE NOT FOUND.\", file=sys.stderr)\n raw_input(\"Press &lt;ENTER&gt; to exit....\")\n sys.exit(0)\n</code></pre>\n\n<p>You should probably print the exception itself. As it is you are throwing away potentially useful error information.</p>\n\n<pre><code>#Initialize parser\nsettings = parseIni(settingsFileStream)\n\n#Precondition: settings file was opened successfully\n#Assigning values to required variables\ntimeDelayInMins = eval(settings.getValueOf(\"timeDelay\")) #For user information\n</code></pre>\n\n<p>Using eval is a bad idea. It'll try to evaluate any valid python you pass to it which could allow an external file to cause your application to do bad things. You also can't be sure what kind of data you got back. Instead pass the incoming string to <code>int</code> or <code>float</code> to safely convert. </p>\n\n<pre><code>timeDelay = timeDelayInMins * 60 #Converting to seconds, for time.sleep() method\nsourcePath = settings.getValueOf(\"sourcePath\")\ndestinationPath = settings.getValueOf(\"destinationPath\")\n\n#Runs the game\nos.system(\"Minecraft.exe\")\n\n#Prints out Welcome message\nprint()\nprint(\"|--------------------------------------------------------|\")\nprint(\"|WELCOME TO MINECRAFT AUTO BACKUP UTILITY! |\")\nprint(\"|--------------------------------------------------------|\")\nprint(\"|REFER TO THE settings.ini FILE TO EDIT SETTINGS FOR THIS|\")\nprint(\"|PROGRAM. e.g. TIME DELAY FOR AUTO BACKUP, PATHS etc |\")\nprint(\"|--------------------------------------------------------|\")\nprint(\"|TIME DELAY FOR AUTO BACKUP IS {:0.2f} MIN(S) |\".format(timeDelayInMins))\nprint(\"|--------------------------------------------------------|\")\nprint()\n\n#Variable to keep tract of backups done per session\nbackupsDone = 0\n\n#mainLoop runs forever, backups \"saves\" folder every after ever timeDelay mins\nwhile True:\n time.sleep(timeDelay)\n os.system('robocopy \"{}\" \"{}\" /e'.format(sourcePath, destinationPath))\n</code></pre>\n\n<p>Python has function for copying files. Consider using that instead of calling to another program.</p>\n\n<pre><code> backupsDone += 1\n print\n print\n print(\"|---------------------------------|\")\n print(\"|{} BACKUP(S) DONE THIS SESSION. |\".format(backupsDone))\n print(\"|---------------------------------|\")\n</code></pre>\n\n<p>It would also be a good idea to move all this logic into a main() function. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T17:04:51.460", "Id": "21658", "Score": "0", "body": "Holy crap! thanks alot, n about the \"awkward function name\" i've been studying java for quite a while and just got used to its \"variableAndMethodNamingConvention\" :P" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T17:06:28.447", "Id": "21659", "Score": "0", "body": "Also about the \"settingsFileStream\" variable, i omitted it but then a NameError exception showed up so i thought maybe variables in try except are local to its suite like other languages" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T01:40:50.370", "Id": "21671", "Score": "0", "body": "@BUCKSHOT, Python certainly doesn't make the variable local to try blocks. I can't really guess what caused your NameError." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T15:17:48.210", "Id": "13397", "ParentId": "13358", "Score": "4" } } ]
{ "AcceptedAnswerId": "13397", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T15:34:57.257", "Id": "13358", "Score": "3", "Tags": [ "python", "file-system", "minecraft" ], "Title": "Minecraft auto-backup utility" }
13358
<p>I need to create a class with two properties:</p> <ol> <li><code>LogOutput</code></li> <li><code>ExceptionOutput</code></li> </ol> <p>These properties (of type <code>Action</code>) send a message or a exception depending on the target function. This target function is set via properties. Currently, I have the following code:</p> <pre><code>public class Output { private Action&lt;string&gt; logOutput; private Action&lt;Exception, string&gt; exceptionOutput; public Action&lt;string&gt; LogOutput { set { this.logOutput = value; } get { return this.logOutput; } } public Action&lt;Exception, string&gt; ExceptionOutput { set { this.exceptionOutput = value; } get { return this.exceptionOutput; } } public Output() : this(null, null) { } public Output(Action&lt;string&gt; logAction, Action&lt;Exception, string&gt; exceptionAction) { this.logOutput = logAction; this.exceptionOutput = exceptionAction; } public void WriteLogMessage(string format, params object[] args) { if (this.logOutput != null) logOutput(string.Format(format, args)); } public void WriteExceptionMessage(Exception ex, string format, params object[] args) { if (this.exceptionOutput != null) exceptionOutput(ex, string.Format(format, args)); } } </code></pre> <p>And this is my form code:</p> <pre><code>private void MainForm_Load(object sender, EventArgs e) { Output myOutput = new Output(); myOutput.ExceptionOutput = this.WriteExceptionMessageToTextBox; myOutput.LogOutput = this.WriteLogMessageToTextBox; myOutput.WriteLogMessage("this is my log message to text box"); myOutput.WriteExceptionMessage(new Exception("this is my exception"), "this is my exception message to text box"); } private void WriteLogMessageToTextBox(string message) { if (this.txtBox.IsDisposed) return; if (this.InvokeRequired) { BeginInvoke(new MethodInvoker(delegate() { WriteLogMessageToTextBox(message); })); } else { this.txtBox.AppendText(message + Environment.NewLine); } } private void WriteExceptionMessageToTextBox(Exception ex, string message) { if (this.txtBox.IsDisposed) return; if (this.InvokeRequired) { BeginInvoke(new MethodInvoker( delegate() { WriteExceptionMessageToTextBox(ex, message); })); } else { string msg = ""; msg += string.Format("Program:{0}", message); msg += string.Format("Message{0}", ex.Message); msg += string.Format("StackTrace:{0}", ex.StackTrace); msg += string.Format("Source:{0}", ex.Source); this.txtBox.AppendText(msg + Environment.NewLine); } } </code></pre> <p>The thing is I don't know if this is correct (although it's working). If it's not correct, how can I change it? How can I implement it with events?</p>
[]
[ { "body": "<p>Yes, I think this is reasonable code. If you want to set more delegates at the same time or unsubscribe a delegate, events would be more appropriate. But if you don't want to do that, delegate properties are fine.</p>\n\n<p>There are some things to think about though:</p>\n\n<ol>\n<li><p>The code you use to invoke the delegates is not thread-safe. If one thread called <code>WriteLogMessage()</code> and another thread set <code>logOutput</code> to <code>null</code> at the same time, you might get a <code>NullReferenceException</code>. The thread-safe version would be:</p>\n\n<pre><code>var logOutputTmp = this.logOutput;\nif (logOutputTmp != null)\n logOutputTmp(string.Format(format, args));\n</code></pre></li>\n<li><p>Consider using automatic properties. They do the same thing as your code, only with less writing. Also, <code>get</code> accessor is usually written before the <code>set</code> accessor, but that's only a minor style issue.</p>\n\n<pre><code>public Action&lt;string&gt; LogOutput { get; set; }\n</code></pre></li>\n<li><p>Do you need the public setters and the parameterless constructor? If you expect that both delegates will be always set at construction, then it's better to make that clear and have only one constructor and no public setters.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T17:47:56.687", "Id": "13367", "ParentId": "13359", "Score": "6" } } ]
{ "AcceptedAnswerId": "13367", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T15:56:07.203", "Id": "13359", "Score": "2", "Tags": [ "c#", "delegates", "properties" ], "Title": "Is it correct to use delegates as properties?" }
13359
<p>I need a NumPy matrix with comparisons among all elements in a sequence:</p> <pre><code>from numpy import matrix seq = [0, 1, 2, 3] matrix([[cmp(a, b) for a in seq] for b in seq]) </code></pre> <p>I'd like to know if there is a better way to do this.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T15:02:56.917", "Id": "21653", "Score": "0", "body": "Useful reference for anyone wanting to take this on: http://www.scipy.org/NumPy_for_Matlab_Users" } ]
[ { "body": "<p>Why are you using <code>matrix</code> rather than <code>array</code>? I recommend sticking with <code>array</code></p>\n\n<p>As for a better way:</p>\n\n<pre><code>seq = numpy.array([0, 1, 2, 3])\nnumpy.clip(seq[:,None] - seq, -1, 1)\n</code></pre>\n\n<ol>\n<li><code>seq[:, None]</code>, moves the numbers into the second dimension of the array</li>\n<li><code>seq[:, None] - seq</code> broadcasts the numbers against each other, and subtracts them.</li>\n<li><code>numpy.clip</code> converts lower/higher values into 1 and -1</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T15:06:02.077", "Id": "13396", "ParentId": "13364", "Score": "5" } } ]
{ "AcceptedAnswerId": "13396", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T17:22:07.140", "Id": "13364", "Score": "1", "Tags": [ "python", "matrix", "numpy" ], "Title": "Element-comparison NumPy matrix" }
13364
<p>I've been using this syntax alot recently to keep my class in scope of nested functions. It seems to work well in small to moderately sized class but I'm starting to wonder how efficient it actually is and if there is a better way to handle this. Any suggestions would be really useful.</p> <pre><code>myClass.prototype.myMethod = function() { var that = this; // Without taking the size of the class into consideration // does this create an unecessarily high load? function callback_one(data) { that.myOtherMethod(); } function callback_two(data) { that.myErrorMethod(); } $.post(this.getRequest(), this.getUrl()) .success(function(data) { callback_one(data); // Can also use that.anotherMethod() here }) .error(function(data) { callback_two(data); // Can also use that.anotherMethod() here }); } </code></pre>
[]
[ { "body": "<p>Yes, you can avoid creating functions inside functions entirely and you are correct it would be unmaintainable in the long term.</p>\n\n<pre><code>function MyClass() {\n //Proxy methods in constructor, so that the instance will have fixed context in the callbacks\n this.ajaxSucceeded = $.proxy( this.ajaxSucceeded, this );\n this.ajaxFailed = $.proxy( this.ajaxFailed, this );\n}\n\nMyClass.prototype.myMethod = function() {\n $.post(this.getRequest(), this.getUrl())\n .success( this.ajaxSucceeded )\n .error( this.ajaxFailed );\n};\n\nMyClass.prototype.ajaxSucceeded = function( data ) {\n //this.myOtherMethod(); &lt;-- is possibly redundant now\n};\n\nMyClass.prototype.ajaxFailed = function( xhr, status ) {\n //this.myErrorMethod(); &lt;-- is possibly redundant now\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T19:00:21.477", "Id": "21584", "Score": "0", "body": "This is a cool solution, This is my first encounter with `.proxy` and it looks like it would clean my code up loads" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T19:02:07.657", "Id": "21585", "Score": "1", "body": "@DavidBarker the native version (but only modern browsers support it) is [`Function#bind`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T19:19:48.907", "Id": "21587", "Score": "0", "body": "I get why this works, but it looks wrong to me. Inside `myMethod` (without knowing that the lines are defined as such in the constructor) I would expect `this` to be changed when it actually calls the `ajaxSucceeded` function (it looks wrong because of how I expect `success` to work). Also, overwriting prototype attached functions with instance ones strikes me as a very strange practice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T19:21:27.113", "Id": "21588", "Score": "0", "body": "@BillBarry it doesn't overwrite the prototype. When you set a property of an object, it's always on that object. When you get a property of an object, it might be gotten from that object's prototype. But you never set to prototype (unless you set `this.__proto__` of course). Also this works, even if it looks strange. You can test it easily :P. Basically the prototype method is a generic blueprint and each instance gets their own proxied version of it that is fixed to the context of that instance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T19:30:43.367", "Id": "21590", "Score": "0", "body": "I know it works; I am saying if I am reading `myMethod` here only I would be expecting that it wouldn't. I am also saying that I find the act of replacing something on the prototype with something having the same name in the constructor (overwriting a prototype attached function with an instance attached function) to look strange." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T19:35:57.670", "Id": "21592", "Score": "0", "body": "@BillBarry Yeah I admit it's kind of a new pattern and many aren't used to it. In my mind it's obvious that a method is bound if it's passed as `this.something` otherwise the code wouldn't work (So I guess it's optimism over pessimism :D). But the alternative of scattering functions inside other functions inside other functions all over the place instead of having a clean same level indented list of methods doesn't read well either." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T18:45:30.837", "Id": "13371", "ParentId": "13370", "Score": "3" } }, { "body": "<p>Your code is fine (assuming your nested functions are merely proxies to the class methods), I would suggest if the only thing you are doing in the anonymous functions is calling the callbacks then you should just pass them in:</p>\n<pre><code>$.post(this.getRequest(), this.getUrl()).success(callback_one).error(callback_two);\n</code></pre>\n<p>There is nothing wrong with the use of <code>that</code> in this code.</p>\n<h2>Edit (after reading <a href=\"https://codereview.stackexchange.com/questions/13370/var-that-this-keeping-a-class-in-scope-of-nested-functions/13371#13371\">Esailija</a>'s answer)</h2>\n<p>You could also do the proxies mentioned in the Esailija's answer inline like so:</p>\n<pre><code>myClass.prototype.myMethod = function () {\n $.post(this.getRequest(), this.getUrl())\n .success($.proxy(this.myOtherMethod, this))\n .error($.proxy(this.myErrorMethod, this));\n}\n</code></pre>\n<p>Essentially that is what you were doing with the nested functions; this just tightens the code by moving the proxy creation into a utility method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T18:58:42.667", "Id": "21582", "Score": "0", "body": "Thanks Bill that's put my mind at ease, after writing out two large classes I feared I'd dumped myself in it by using this, I mean that..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T19:13:05.823", "Id": "21586", "Score": "0", "body": "You don't want to do the proxying in the method, it can be done in the constructor once per instance creation instead of once per method call. It also ensures that all proxying is done in one place and the object is fully initialized after construction (can start passing handlers without losing context)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T19:26:07.857", "Id": "21589", "Score": "0", "body": "@Esailija: A class is not an atomic unit in JS, but a function is. If I am going to pass a function off to an event, I expect the context to change. I shouldn't have to go look at a third function to realize that some magic happened so that the context didn't change." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T19:34:31.060", "Id": "21591", "Score": "0", "body": "I can see arguments for both of the answers you guys gave, I don't see any problem with putting the code in the constructor to maintain the scope of a method if you know you've done it. On the other hand I can see that as a third party looking at it, if embedded it could cause more than a few headaches. Thanks for both your answers, you both gave me some piece of mind." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T21:00:28.140", "Id": "21598", "Score": "0", "body": "@Bill Barry What did you mean exactly by 'assuming your nested functions are merely proxies to the class methods', what if they weren't just the above and also call other methods etc.?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T22:38:07.270", "Id": "21603", "Score": "0", "body": "IMO it is fine to nest simple functions, but once they start getting to contain nontrivial amounts of logic they should be considered for refactoring." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T18:52:56.693", "Id": "13372", "ParentId": "13370", "Score": "4" } } ]
{ "AcceptedAnswerId": "13372", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T18:32:37.253", "Id": "13370", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "var that = this; Keeping a class in scope of nested functions" }
13370
<p>I am putting together an animated drawer from scratch for use but also as a learning experience as I am not very strong with jQuery and would really like to get better.</p> <p>I am hoping that someone here might take a moment to look over my JSFiddle and give me some direction/tips to help me continue to progress?</p> <p>For example: Is what I put together clean and correct way of doing things? Is creating a function to init the elements for users who have JavaScript as I have done correct? Will what I wrote function well across browsers or are there better ways of achieving this?</p> <p><a href="http://jsfiddle.net/XN8C8/" rel="nofollow noreferrer">jsFiddle</a></p> <pre><code>$(document).ready(function() { //Hide message if user has javascript function initPage() { $('#message').css('marginTop', '-60px'); $('#message').find('.droid').css('bottom', '-60px'); } function slideMessage() { var message = $('#message'); var tab = $('#tab'); var margin = $('#message').css('marginTop'); var speed = 300; if (margin != "0px") { tab.animate({top: "-90px"}, speed); message.delay(speed).animate({marginTop: "0px"}, speed); message.find('.droid').delay(1000).animate({bottom: "0px"}, 100); } else { message.find('.droid').delay(1000).css({bottom: "-60px"}, 100); message.animate({marginTop: "-60px"}, speed); tab.delay(speed).animate({top: "0px"}, speed); } } initPage(); setTimeout(function() { slideMessage(); }, 1000); $('#message .close, #tab').click(function() { slideMessage(); }); }); </code></pre>
[]
[ { "body": "<p>There are a few issues with your code I've modified it below. Some of the changes I made:</p>\n\n<ol>\n<li><p>cache your jQuery objects</p></li>\n<li><p>reword your <code>slideMessage</code> condition so that it is more readable</p></li>\n<li><p>parameterize the animations and pull them out into methods of their own</p></li>\n<li><p>move your initialization code so that it is all together</p></li>\n</ol>\n\n<p><a href=\"http://jsfiddle.net/XN8C8/3/\" rel=\"nofollow\">Updated JsFiddle</a></p>\n\n<hr>\n\n<pre><code>$(function () {\n var $message = $('#message'),\n $tab = $('#tab');\n var speed = 300;\n\n function animateMessage(to) {\n // don't want to animate them right now\n // rather: animate them when this function I'll return is called\n return function () {\n return $message.animate({\n marginTop: to\n }, speed);\n };\n }\n\n function animateTab(to) {\n return function () {\n return $tab.animate({\n top: to\n }, speed);\n };\n }\n\n //little helper method to queue animations\n function queue(immediate) {\n var rest = [].splice.call(arguments, 1);\n if (immediate) {\n $.when(immediate()).then(function () {\n queue.apply(window, rest);\n });\n }\n }\n\n function slideMessage() {\n var tabVisible = $message.css('marginTop') !== '0px';\n\n if (tabVisible) {\n queue(animateTab('-160px'),\n animateMessage('0px'));\n } else {\n queue(animateMessage('-40px'),\n animateTab('0px'));\n }\n }\n\n\n //Hide message if user has javascript\n $message.css('marginTop', '-40px');\n slideMessage();\n\n $('#message .close, #tab').click(function() {\n slideMessage();\n });\n});\n</code></pre>\n\n<hr>\n\n<p>In response to the comments:</p>\n\n<p>This is very similar to the code you initially put up. I derived it again on a gist using the code you put in your question here (slightly different from the code in the fiddle): <a href=\"https://gist.github.com/3060013/6a4de29001f845c625e2f907752562c7abf9dd85\" rel=\"nofollow\">https://gist.github.com/3060013/6a4de29001f845c625e2f907752562c7abf9dd85</a></p>\n\n<p>Clone that repository to see the full history.</p>\n\n<ol>\n<li><p>while your code does work, it has a couple of inefficiencies and the <code>slideMessage</code> has too much going on.</p>\n\n<ol>\n<li><p>every time you call <code>$('...')</code>, jQuery needs to do some work in the background to figure out what you mean in the string. You can instead cache these items and not need to depend on retrieving them repeatedly being fast. In this case it doesn't make much of a difference, but eventually it will cause your page to be slower.</p></li>\n<li><p>There is too much extra junk in the way to make it apparent what <code>slideMessage</code> is doing. A good rule of thumb is to wait a week, then if you cannot glance at a statement and know that it is both in the right place in the function and what it is doing then something is too complex. While your code is probably sensible to you right now I am willing to stake the claim that in a few weeks/months when you go to add some other functionality you would waste some time trying to figure out what this is doing.</p></li>\n</ol></li>\n<li><p>Caching a jQuery object is an expression for introducing a variable that holds the result of the <code>$('...')</code> function and its related forms.</p></li>\n<li><p>Perhaps you shouldn't? I'm not 100% on this yet. I think this part of the code can be further cleaned up. I'm still leaning against combining them. I think something that represents this pseudocode would be best, but I'm not sure how to do that best:</p>\n\n<pre><code>if tabVisible\n slide tab out then slide message in\nelse\n do the opposite of what I did to switch them back\n</code></pre></li>\n</ol>\n\n<p>That is to say, I don't think the else block should specify the logic of how to do the opposite.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T06:23:03.707", "Id": "21619", "Score": "0", "body": "Hey there Bill, thank you for taking the time to write that out for me. In looking at your code I feel completely lost as I thought my code would be much closer to the \"right way\" of doing it than it turns out to be. I have a few questions and I hope that you or someone else could help me with them?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T06:38:17.213", "Id": "21620", "Score": "0", "body": "1) All together, since what I wrote did work, could you tell me why I should have written it as you did? I am assuming its a performance thing, but I am not sure why or how." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T06:38:40.240", "Id": "21621", "Score": "0", "body": "2) Could you tell me where in the code I am caching the jquery object, I am not sure what that is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T06:39:53.893", "Id": "21623", "Score": "0", "body": "3) Since the animations of the sliding drawer and sliding tab are linked to one another and always will be, why should I separate them out into two functions as seen here?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T00:45:19.290", "Id": "13380", "ParentId": "13377", "Score": "3" } }, { "body": "<p>Two small improvements (Not already mentioned):</p>\n\n<ol>\n<li><p>creating an anonymous function that calls another function with no parameters? Not really nessasary.</p>\n\n<pre><code>setTimeout(function() {\n slideMessage();\n}, 1000);\n</code></pre>\n\n<p><code>slideMessage();</code> has no parameters. Dosen't change and seems a little odd unless sommething else is there in the anonymous function.</p>\n\n<pre><code>setTimeout(slideMessage, 1000);\n</code></pre>\n\n<p>should give the same result. <em>(There are occasions when it won't, but in this example there doesn't seem to be any reason.)</em></p></li>\n<li><p>Such a small thing but i would wrap my code in a closure just for future protection against any changes in my code. On a bigger project this will come in handy. (Or, like me , you might find yourself debugging why something unrelated broke your code.)</p>\n\n<p>Mostly I see others doing something like:</p>\n\n<pre><code>;(function($, window) {\n // ... Your code here\n})(jQuery, window);\n</code></pre>\n\n<p>The initial <code>;</code> stops unterminated code from interfering.<br>\nThe <code>(function(){</code> Wraps everything so it doesn't pollute the Global namespace.<br>\nThe <code>($, ...)</code> protects against other frameworks overriding the <code>$</code> value.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T06:58:01.697", "Id": "21625", "Score": "0", "body": "Ok great this is a great answer thanks. I have heard about closures and read a bit on them but understand next to nothing about them.\n\n1) I thought that when calling a function(is method the right term here?) we always needed to have the () at the end, as in slideMessage(). I did not even realize that i could simply write the name of the function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T07:10:10.583", "Id": "21628", "Score": "0", "body": "@Stefan think of the function names as variables containing a function. (thats not 100% correct... but who cares for a moment) Now think that the `()` mean run function inside variable. Now consider: `function awesome(){ do awesome stuff}; var pretendAwesome = awesome; pretendAwesome();` Tada!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T07:24:27.747", "Id": "21630", "Score": "0", "body": "ok and since the function setTimeout is receiving another function as a parameter, I can simply write the function name as a variable meaning that technically I dont need the (). Is that about right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T12:24:17.740", "Id": "21644", "Score": "0", "body": "@Stefan Basically yes." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T06:34:03.127", "Id": "13384", "ParentId": "13377", "Score": "3" } } ]
{ "AcceptedAnswerId": "13380", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T21:28:17.190", "Id": "13377", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "jQuery Drawer with Tab" }
13377
<p>I want to call an <code>Action</code> every X cycles (in my case, to a transaction commit every 100 records), so I do:</p> <pre><code>public class CyclicActionCaller { private int _counter; private int _cycleValue; private Action _methodToCall; public CyclicActionCaller() { _counter = 0; } public CyclicActionCaller Every(int cycleValue) { _cycleValue = cycleValue; return this; } public CyclicActionCaller Call(Action methodToCall) { _methodToCall = methodToCall; return this; } public void PerformCall() { Interlocked.Increment(ref _counter); // IS THIS THREAD SAFE - SHOULD BE CALLED EVERY _counter % _cycleValue - EVEN IN MULTITHREADING ENVIRONMENT if (_counter % _cycleValue == 0) { _methodToCall(); } } } CyclicActionCaller cyclicActionCaller = new CyclicActionCaller(); using (ModelContainer container = new ModelContainer()) { cyclicActionCaller.Every(100).Call(() =&gt; { container.SaveChanges(); }); while(...) { // Import Loop - assume multiple workers inside cyclicActionCaller.PerformCall(); // every worker calls this after inserting a row } } </code></pre> <p>Is this function thread safe? I want that - even if multiple threads call <code>PerformCall</code> - that it is just called once every 100 calls.</p>
[]
[ { "body": "<p>No, it's not thread-safe. Between the call to <code>Interlocked.Increment()</code> and the <code>if</code> check, another thread could call <code>Interlocked.Increment()</code>. That means both of them could see that <code>_counter</code> is 101, which means a call to <code>_methodToCall</code> would be skipped.</p>\n\n<p>But this is exactly why <code>Interlocked.Increment()</code> returns the incremented value. So the thread-safe version would be:</p>\n\n<pre><code>public void PerformCall()\n{\n if (Interlocked.Increment(ref _counter) % _cycleValue == 0)\n _methodToCall(); \n}\n</code></pre>\n\n<p>This is exactly why writing code like this is hard (although this is a simple situation, so it's not that hard here). It's much easier to write correct multi-threaded code, if you lock all shared values.</p>\n\n<p>Also, if you do something like this, you need to be sure that inserting a row in your code is also thread-safe. And the same applies to <code>SaveChanges()</code>. For example, if you used something like <code>ConcurrentQueue</code> in a straightforward way, it would be possible for <code>SaveChanges()</code> to save more than 100 items at a time, because new items could have been inserted between the call to <code>Interlocked.Increment()</code> and the final dequeue from the queue. This may not be a problem for you, but you should think about that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T07:23:25.597", "Id": "13387", "ParentId": "13382", "Score": "3" } } ]
{ "AcceptedAnswerId": "13387", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-07-06T06:01:22.587", "Id": "13382", "Score": "2", "Tags": [ "c#", "multithreading" ], "Title": "Call Action every X cycles" }
13382
<p>I was working on the challenge <em><a href="https://www.interviewstreet.com/challenges/dashboard/#problem/4f304a3d84b5e" rel="noreferrer">Save Humanity</a></em> from <a href="http://www.interviewstreet.com" rel="noreferrer">Interviewstreet</a> for a while then gave up, solved a few other challenges, and have come back to it again. </p> <p>The code below generates the correct answers but the time complexity <code>O(text * pattern)</code> is not sufficient for the auto-grader. Could anyone perhaps give me a hint or a pointer on how to improve my algorithm? </p> <pre><code>final BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); final StringBuilder builder = new StringBuilder(); final int number_trials = Integer.valueOf(input.readLine()); for(int trial = 0; trial &lt; number_trials; trial++) { final int allowed_mismatches = 1; final char[] text = input.readLine().toCharArray(); final char[] pattern = input.readLine().toCharArray(); input.readLine(); for(int text_index = 0; text_index &lt; text.length - pattern.length + 1; text_index++) { int pattern_index = 0; int missed = 0; while(pattern_index &lt; pattern.length &amp;&amp; missed &lt;= allowed_mismatches) { if(text[text_index + pattern_index] != pattern[pattern_index]) { missed++; } pattern_index++; } if(missed &lt;= allowed_mismatches) { builder.append(text_index); builder.append(" "); } } if(builder.length() &gt; 0 &amp;&amp; builder.charAt(builder.length() - 1) == ' ') { builder.deleteCharAt(builder.length() - 1); } if(trial + 1 &lt; number_trials) { builder.append("\n"); } } System.out.println(builder.toString()); </code></pre>
[]
[ { "body": "<p>1.I would use something like \"APPROXIMATE BOYER-MOORE STRING MATCHING\" described here: </p>\n\n<p><a href=\"http://www.cs.hut.fi/~tarhio/papers/abm.pdf\" rel=\"nofollow\">http://www.cs.hut.fi/~tarhio/papers/abm.pdf</a></p>\n\n<p>2.The second option is the Suffix Tree Solution:</p>\n\n<p><a href=\"http://homepage.usask.ca/~ctl271/810/approximate_matching.shtml\" rel=\"nofollow\">http://homepage.usask.ca/~ctl271/810/approximate_matching.shtml</a></p>\n\n<p>The Suffix Tree approach to the k-mismatch problem is essentially the same as the approach taken when matching with wild-cards; though in this case k is the number of allowable mismatches rather than the number of wildcards. The algorithm proceeds by executing up to k constant-time lce queries for each position i in the text. If the the lce queries span the end of P, then P occurs starting at position i of the text.</p>\n\n<pre><code>for i = 1; i &lt; m-n+1; i++\n 1. j = 1, i′ = i, count = 0\n 2. l = lce (P[j], T[i′])\n 3. if j+l = n+1, P occurs in T at i with only count mismatches; continue next i;\n 4. if count ≤ k, count++, j = j+l+1, i′=i′+l+1, go to 2\n 5. if count = k+1, then a k mismatch of P does not occur at i; continue next i;\n</code></pre>\n\n<p>An alternate approach, when both k and the alphabet size are relatively small is to generate all permutations of P with up to k changes and then search for each of these permutations in the tree. This would run in time O(P′ + m), where P′ is the combined length of the permissible permutations of P.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T04:13:37.003", "Id": "21716", "Score": "0", "body": "Interesting paper when we covered Boyer-Moore in class it was not taught as a using dimensional array for skip values. I used a code example from my book to make an approximate Boyer-Moore but it did as well as my original algorithm." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T09:25:43.773", "Id": "13388", "ParentId": "13383", "Score": "2" } }, { "body": "<p>Just litteral enhancements :</p>\n\n<pre><code>final int allowed_mismatches = 1; // outside the for\n\n// evaluate at the beginning\nfor(int text_index = 0, n = text.length - pattern.length + 1; text_index &lt; n ; text_index++)\n\nfinal int patternLength = pattern.length ; // as soon as possible, and replace it as needed \n\nif(builder.length() &gt; 0) ;// ' ' ends obviously builder.charAt(builder.length() - 1) == ' ') \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-19T12:21:50.097", "Id": "13835", "ParentId": "13383", "Score": "1" } }, { "body": "<p>This is a common problem in bioinformatics. There are in general three different approaches to the problem</p>\n\n<ol>\n<li>Inexact string search via dynamic programming</li>\n<li>Inexact string search via text search</li>\n<li>Filtering</li>\n</ol>\n\n<p>The filtering isn’t strictly speaking solving the problem – rather, it’s eliminating most of those regions in the string which are irrelevant. Still, it’s the most promising area: In modern-day sequencing projects, this is the go-to method, but it only makes sense if you search for <em>lots</em> of small strings, since you first need to create an index for the large string (the “reference”).</p>\n\n<p>Still, a brief overview.</p>\n\n<p>All the methods described in the following are implemented in the <a href=\"http://www.seqan.de/\" rel=\"nofollow\">SeqAn library</a> for C++. Unfortunately, the code uses some very special idioms to to implement highly efficient algorithms in a generic fashion but it’s still the best reference implementation that I know of.</p>\n\n<p><strong>The first method</strong> uses a dynamic programming local alignment algorithm (think <a href=\"http://en.wikipedia.org/wiki/Smith-Waterman_algorithm\" rel=\"nofollow\">Smith-Waterman</a>), with one modification: for each column that we calculate, we stop once we find the second error (in your case; in general, we allow <em>k</em> errors and stop after we find <em>k</em> + 1).</p>\n\n<p>Even though dynamic programming has a prohibitive O(n * m) complexity, this trick (called the “Ukkonen trick”) pushes runtime down to O(n * k) which, in your case, is linear. Combined with an efficient implementation of the dynamic programming table (Myers bit vector algorithm), this was fast enough to assemble reads at Celera during the Human Genome Project. There are some <a href=\"https://www.mi.fu-berlin.de/wiki/pub/ABI/RnaSeqP4/myers-bitvector-verification.pdf\" rel=\"nofollow\">lecture notes</a> which can serve as a basis for the implementation.</p>\n\n<p>Caveat: this is pretty tricky, especially if you want to understand the correctness proof of the bit vector algorithm.</p>\n\n<p>But actually, since you only allow mismatches instead of gaps this is overkill – it’s effectively the same as your method, albeit with a more efficient implementation.</p>\n\n<p><strong>The second approach</strong> uses modified exact string search, see cat_baxter’s answer for two excellent implementations. In particular, a modification of the suffix tree version (using a trie with backlinks due to Aho and Corasick) was used in some versions of the sequence search tool BLAST.</p>\n\n<p><strong>The third approach</strong> can be split again; I’m going to focus on two variants:</p>\n\n<ul>\n<li><p>pigeonhole-based search. In your case, that’s incredibly easy: since you only allow one error, you can just split each potential hit location into two; now you know that one of those <em>must</em> match exactly – otherwise there’d be at least two errors in the match.</p>\n\n<p>So you can just move a sliding window over the string and use an exact search algorithm to compare regions of the size m/2 against both halves of your pattern (of length m). This can be done <em>very</em> efficiently if you have an index for the reference string.</p></li>\n<li><p>Alternatively, you can harness the <em>q</em>-gram lemma which tells you that (in your case), the pattern has <em>t</em> common <em>q</em>-grams with each equal-length match in the reference, where <em>t</em> = <em>m</em> - 2 <em>q</em> + 1. If you choose your <em>q</em> appropriately, you can build a collision-free hash table for all <em>q</em>-grams in the reference, and look up all matching positions in O(1).</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-19T13:10:45.193", "Id": "13837", "ParentId": "13383", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T06:08:54.077", "Id": "13383", "Score": "8", "Tags": [ "java", "strings", "interview-questions" ], "Title": "Approximate String Matching Interview Question" }
13383
<p>The question was, which is the biggest product you can make from the digits of 1 to 9 (which is 9642*87531, BTW). It is pretty clear that one number starts with 9 and the other with 8, and that you need to append the remaining digits in descending order to one or the other number.</p> <pre><code>buildList x y [] acc = (x,y):acc buildList x y (z:zs) acc = buildList (10*x+z) y zs (buildList x (10*y + z) zs acc) list = buildList 9 8 [7,6,5,4,3,2,1] [] </code></pre> <p>Sorting it by descending products, and taking the beginning of the list:</p> <pre><code>import Data.List import Data.Function result = take 10 $ sortBy (compare `on` (negate.uncurry (*))) list </code></pre> <p>I'm not satisfied with my solution for <code>buildList</code>, which uses explicit recursion. I'd like to have something like a fold, just not linear but with different "branches". </p>
[]
[ { "body": "<p>Here is a quick try to implement your algorithm using 'foldr'. I did not check in depth whether my solution is correct.</p>\n\n<p>I have divided the problem into parts. First we define a function that takes a list and splits the list into pairs of partitions where the order of elements is preserved.</p>\n\n<pre><code>split :: [a] -&gt; [([a],[a])]\nsplit [] = [([],[])]\nsplit (x:xs) = concatMap (\\(fst,snd) -&gt; [(x:fst,snd), (fst,x:snd)]) (split xs)\n</code></pre>\n\n<p>Employing this definition we can define the list of tuples of decimals.</p>\n\n<pre><code>combinations :: [([Int],[Int])]\ncombinations = map (\\(fst,snd) -&gt; (9:fst,8:snd)) (split [7,6..1])\n</code></pre>\n\n<p>To transform these lists of decimals into numbers we use the following transformation.</p>\n\n<pre><code>toDeci :: [Int] -&gt; Int\ntoDeci = foldl (\\acc x -&gt; x + 10 * acc) 0\n</code></pre>\n\n<p>Combining these functions we can redefine <code>list</code> as follows.</p>\n\n<pre><code>list :: [(Int,Int)]\nlist = map (\\(fst,snd) -&gt; (toDeci fst,toDeci snd)) combinations\n</code></pre>\n\n<p>Now we can define <code>split</code> by using <code>foldr</code>. </p>\n\n<p>We can probably improve the code by using predefined functions like the arrow function <code>(***)</code>.</p>\n\n<p><strong>Edit:</strong> You can generalize <code>split</code> by using the list monad. First we defined <code>split</code> using <code>foldr</code> as follows.</p>\n\n<pre><code>foldr (\\x -&gt; concatMap (\\(fst,snd) -&gt; [(x:fst,snd), (fst,x:snd)])) [([],[])]\n</code></pre>\n\n<p>Now we can observe that the neutral element is <code>return ([],[])</code> in the list monad and <code>concatMap</code> is the implementation of <code>(&gt;&gt;=)</code>. That is, we can define <code>split</code> as follows.</p>\n\n<pre><code>foldr (\\x xs -&gt; xs &gt;&gt;= (\\(fst,snd) -&gt; [(x:fst,snd), (fst,x:snd)])) (return ([],[]))\n</code></pre>\n\n<p>This implementation can be shortened by using the predefined function <code>foldM</code> from <code>Control.Monad</code>.</p>\n\n<pre><code>foldM (\\(fst,snd) x -&gt; [(x:fst,snd), (fst,x:snd)]) ([],[])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T08:46:39.890", "Id": "21758", "Score": "0", "body": "I have to look closer at this. The \"multi-fold\" I'm looking for seems to be generalization of your `split`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T12:57:06.370", "Id": "13392", "ParentId": "13385", "Score": "4" } } ]
{ "AcceptedAnswerId": "13392", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-07-06T06:57:59.617", "Id": "13385", "Score": "3", "Tags": [ "haskell" ], "Title": "Finding the biggest product of two integers formed by the digits 1-9" }
13385
<p>I need some help improving my code and wondering if I there is a better way to do the following:</p> <pre><code>StringBuilder buf = new StringBuilder(node.length() + 8); for (int i=0, n=node.length(); i&lt;n; i++) { char c = node.charAt(i); String hexadecimal = ""; switch (c) { case '"': hexadecimal = "\\22"; break; case '&amp;': hexadecimal = "\\26"; break; case '\'': hexadecimal = "\\27"; break; case '/': hexadecimal = "\\2f"; break; case ':': hexadecimal = "\\3a"; break; case '&lt;': hexadecimal = "\\3c"; break; case '&gt;': hexadecimal = "\\3e"; break; case '@': hexadecimal ="\\40"; break; case '\\':hexadecimal = "\\5c"; break; default: { if (Character.isWhitespace(c)) { hexadecimal = "\\20"; }else if(c &gt; 127){ hexadecimal = "\\" + Integer.toHexString(c) + "\\"; } else { hexadecimal = String.valueOf(c); } } } buf.append(hexadecimal); } return buf.toString(); </code></pre> <p>I don't like how there is a <code>switch</code> statement which just sets a variable (<code>hexadecimal</code>) based on what the case is. I feel there is a better way to do this, such as by using a hash-map. I need the code to be flexible so that adding new characters and setting the hexadecimal is easy.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T10:30:12.593", "Id": "21640", "Score": "2", "body": "I'm not that versed in Java but isn't toHexString('#') == 22? So do you need the switch at all?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T11:36:17.330", "Id": "21641", "Score": "0", "body": "@dreza I'm assuming the formatting of \"\\22\" is important. In which case `Integer.toHexString('#')` would get messy. But definitely a good idea." } ]
[ { "body": "<p>A hash map is often a good idea for avoiding switch statements. It can be used in combination with the Strategy and Abstract Factory patterns, <a href=\"https://codereview.stackexchange.com/a/13347/14561\">such</a> <a href=\"http://www.tomasmalmsten.com/2011/01/create-factory-strategies-ifs/\" rel=\"nofollow noreferrer\">as</a> <a href=\"http://elegantcode.com/2009/01/10/refactoring-a-switch-statement/\" rel=\"nofollow noreferrer\">in</a> <a href=\"http://www.herrodius.com/blog/136\" rel=\"nofollow noreferrer\">these</a> <a href=\"http://www.codeproject.com/Articles/9942/Refactoring-to-Patterns-Factory-and-Strategy-Patte\" rel=\"nofollow noreferrer\">examples</a>.</p>\n\n<p>However, the Strategy Pattern is overkill for your problem. A simple hashmap would look like this</p>\n\n<pre><code>Map&lt;Character, String&gt; hexMap = new HashMap&lt;Character, String&gt;();\nhexMap.put('\\\"', \"\\\\22\");\nhexMap.put('\\n', \"\\\\20\");\n// puts more stuff in map...\n\n for (int i=0, n=node.length(); i&lt;n; i++) {\n char c = node.charAt(i);\n buf.append(hexMap.get(c));\n }\n</code></pre>\n\n<p>But a quick googling of \"java character to hexadecimal\" produces <a href=\"https://stackoverflow.com/a/4863353/830988\">these</a> <a href=\"http://jovialjava.blogspot.com/2010/05/hex-to-ascii-conversion-in-java.html\" rel=\"nofollow noreferrer\">results</a>. My favorite is</p>\n\n<pre><code>StringBuilder buf = new StringBuilder(node.length() + 8);\n\n for (int i = 0; i &lt; node.length(); ++i) {\n char ch = node.charAt(i);\n buf.append(String.format(\"\\\\%1$x\", (ch &amp; 0xFFFF)));\n }\n\nreturn buf.toString();\n</code></pre>\n\n<p><strong>EDIT:</strong> Forgot to say, don't use magic numbers. I have no clue what the frack that 8 is doing in your program nor do I have to patience to try to deduce.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T11:32:07.773", "Id": "13391", "ParentId": "13389", "Score": "29" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T09:45:01.027", "Id": "13389", "Score": "13", "Tags": [ "java" ], "Title": "Hexadecimal converter using a switch statement" }
13389
<p>This is a followup to <a href="https://codereview.stackexchange.com/questions/13357/polling-loop-to-run-in-a-background-thread">this</a> where I was initially using a single thread and <code>Thread.Sleep()</code> to poll a delegate. I was recommended to use a timer and the <code>ThreadPool</code> to minimize resources and improve the responsiveness of <code>StopMonitoring()</code>.</p> <p>This is the first time I've used the <code>ThreadPool</code> and timers in this way. I am worried about things like:</p> <ol> <li><p>Infinitely running threads</p></li> <li><p>Race Conditions</p></li> <li><p>Firing events after <code>StopMonitoring()</code> has been called</p></li> </ol> <p>Especially since I expect the user to call <code>StopMonitoring()</code> followed by <code>BeginMonitoring()</code> shortly after performing some actions. The only time I want the exceptions in place to be thrown are if the user has forgotten to call <code>StopMonitoring()</code> or if they have passed in a delegate which is stuck in a long-running process or infinite loop.</p> <ol> <li>Have I correctly implemented <code>Timer</code> and <code>ThreadPool.QueueUserWorkItem</code> to achieve what I want to achieve?</li> <li>Is there any way I can have a call to <code>StopMonitoring()</code> guarantee that a subsequent call to <code>BeginMonitoring()</code> will always succeed, even if the last thread was a runaway?</li> <li>What if a thread never becomes available on the thread pool, or is queued for an available thread while the user calls Stop and Begin again?</li> </ol> <p></p> <pre><code>using System; using System.Timers; using System.Windows.Threading; using Timer = System.Timers.Timer; namespace FlagstoneRe.WPF.Utilities.Common { /// &lt;summary&gt;This class allows a user to easily set up a seperate thread to poll some state, /// and set up an event that will fire if the state meets some condition.&lt;/summary&gt; /// &lt;typeparam name="T"&gt;The type of the value returned by the polling delegate.&lt;/typeparam&gt; public class ConditionMonitor&lt;T&gt; : IDisposable { #region Private Properties private Object multiThreadLock = new Object(); //Prevent BeginMonitoring() race condition. private Dispatcher originThread = null; //For event callbacks on the origin thread. private Timer nextRequest; //To delay between subsequent thread queuing. private volatile bool requestInProgress = false; //Prevent starting more than one thread. private volatile bool Halted = false; //Prevent any further event callbacks. #endregion #region Delegates /// &lt;summary&gt;A delegate provided by the user of this class which returns the current state, /// to be tested against a certain condition in the IsConditionMet delegate.&lt;/summary&gt; public delegate T RequestState(); public RequestState RequestStateDelegate { get; set; } /// &lt;summary&gt;A delegate provided by the user of this class which determines whether given the /// current state, the polling program should execute the ConditionMet delegate.&lt;/summary&gt; public delegate bool IsConditionMet(T state); public IsConditionMet IsConditionMetDelegate { get; set; } /// &lt;summary&gt;A delegate used to handle ConditionMonitor events.&lt;/summary&gt; public delegate void ConditionMonitorHandler(ConditionMonitor&lt;T&gt; source, T state); /// &lt;summary&gt;An event which fires each time the state is polled (use sparingly).&lt;/summary&gt; public event ConditionMonitorHandler RequestReceived; /// &lt;summary&gt;An event which fires when the condition is met.&lt;/summary&gt; public event ConditionMonitorHandler ConditionMet; /// &lt;summary&gt;A delegate used to handle ConditionMonitor events.&lt;/summary&gt; public delegate void ConditionMonitorExceptionHandler(ConditionMonitor&lt;T&gt; source, T state, Exception ex); /// &lt;summary&gt;An event which fires if an exception is thrown while retrieving the state /// or testing whether the condition is met.&lt;/summary&gt; public event ConditionMonitorExceptionHandler RequestError; #endregion #region Public Properties /// &lt;summary&gt;The time between requests made to the RequestStateDelegate. Default is 1 second (1000ms)&lt;/summary&gt; public double PollInterval_Milliseconds { get; set; } /// &lt;summary&gt;Set to true to automatically halt polling once the condition is met. Default is False.&lt;/summary&gt; public bool HaltWhenConditionMet { get; set; } #endregion #region Constructors /// &lt;summary&gt;Creates a new instance of a ConditionMonitor&lt;/summary&gt; public ConditionMonitor() { originThread = Dispatcher.CurrentDispatcher; PollInterval_Milliseconds = TimeSpan.FromSeconds(1).TotalMilliseconds; HaltWhenConditionMet = false; } #endregion #region Public Methods /// &lt;summary&gt;Begins polling the RequestStateDelegate on a seperate thread.&lt;/summary&gt; public void BeginMonitoring() { if( RequestStateDelegate == null ) throw new Exception("No delegate specified for polling - please set the RequestStateDelegate property."); lock( multiThreadLock ) { if( !Halted ) throw new Exception("Previous monitoring has not yet been stopped!"); if( requestInProgress ) throw new Exception("The previous request never completed, which means the thread is still queued, or a delegate is taking a long time to complete."); Halted = false; } if( nextRequest != null ) nextRequest.Dispose(); nextRequest = new Timer(PollInterval_Milliseconds) { AutoReset = false }; nextRequest.Elapsed += new ElapsedEventHandler(nextRequest_Elapsed); nextRequest.Start(); } /// &lt;summary&gt;Halts polling and ensures that no more requests will be made or events fired.&lt;/summary&gt; public void StopMonitoring() { Halted = true; nextRequest.Stop(); nextRequest.Dispose(); } /// &lt;summary&gt;Halts the thread if it is still running so that the instance can be garbage collected.&lt;/summary&gt; public void Dispose() { StopMonitoring(); } #endregion #region Private Methods /// &lt;summary&gt;Timer elapsed handler.&lt;/summary&gt; private void nextRequest_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { PollState(); } /// &lt;summary&gt;Responsible for the polling loop and invoking events back on the origin thread.&lt;/summary&gt; private void PollState() { T state = default(T); requestInProgress = true; try { if( Halted ) return; state = RequestStateDelegate(); InvokeEvent(RequestReceived, state); if( IsConditionMetDelegate != null &amp;&amp; !Halted ) { bool bConditionMet = false; bConditionMet = IsConditionMetDelegate(state); if( bConditionMet ) { InvokeEvent(ConditionMet, state); if( HaltWhenConditionMet ) Halted = true; } } } catch( Exception ex ) { InvokeExceptionHandler(state, ex); } finally { if( !Halted ) nextRequest.Start(); requestInProgress = false; } } /// &lt;summary&gt;Invokes a delegate of type ConditionMonitorHandler on the origin thread.&lt;/summary&gt; /// &lt;param name="toInvoke"&gt;The delegate to invoke (RequestRecieved or ConditionMet)&lt;/param&gt; /// &lt;param name="state"&gt;The response from the last call to the RequestStateDelegate&lt;/param&gt; private void InvokeEvent(ConditionMonitorHandler toInvoke, T state) { if( toInvoke != null &amp;&amp; !Halted ) originThread.BeginInvoke(toInvoke, new object[] { this, state }); } /// &lt;summary&gt;Invokes the exception delegate on the origin thread.&lt;/summary&gt; /// &lt;param name="state"&gt;The response from the last call to the RequestStateDelegate, or null.&lt;/param&gt; /// &lt;param name="ex"&gt;The exception raised while calling the RequestStateDelegate or IsConditionMetDelegate.&lt;/param&gt; private void InvokeExceptionHandler(T state, Exception ex) { if( RequestError != null &amp;&amp; !Halted ) originThread.BeginInvoke(RequestError, new object[] { this, state, ex }); } #endregion } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T14:24:33.237", "Id": "21650", "Score": "1", "body": "You don't need to manually queue to the thread pool from the `Elapsed` handler. It already executes on the thread pool." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T14:35:07.093", "Id": "21651", "Score": "0", "body": "Really? Wow thanks for pointing that out. It's not clear all all in the [documentation](http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx) until way down in the middle of the \"Remarks\" section: \"If the SynchronizingObject property is null, the Elapsed event is raised on a ThreadPool thread.\" I'll edit that part right now. I'll get rid of `QueueWorkItem` entirely, I don't mind if the first poll doesn't happen until `PollInterval` after `BeginMonitoring()` is called." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-13T08:16:31.953", "Id": "22051", "Score": "1", "body": "You should lock the entire initialization of the timer, and all changes to the `Halted` property. If `StopMonitoring` and `BeginMonitoring` are called simultaneously by two different threads, results will be unpredictable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-13T12:46:12.033", "Id": "22063", "Score": "1", "body": "That's very true, although my goal is to defend against normal use, not make it idiot proof. If anyone finds themselves in a situation where two different threads are trying to manage one polling class, they're doing something horribly horribly wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-26T13:57:20.403", "Id": "365450", "Score": "0", "body": "last version of code working?" } ]
[ { "body": "<p><strong>Technical</strong></p>\n\n<ol>\n<li>I'd use <code>Stop</code> rather than <code>Halt</code> - somehow sounds more natural.</li>\n<li><p>You should make more use of <code>Action</code> rather defining a bunch of delegate types. For instance this:</p>\n\n<pre><code>public delegate T RequestState();\npublic RequestState RequestStateDelegate { get; set; }\n</code></pre>\n\n<p>Can be written as</p>\n\n<pre><code>public Action&lt;T&gt; RequestState { get; set; }\n</code></pre>\n\n<p>Similar for <code>IsConditionMet</code> and your various event handlers. (I'd also remove the <code>Delegate</code> suffix.)</p></li>\n<li><p><code>PollInterval_Milliseconds</code> should be a <code>TimeSpan</code>. Then you can remove the unit as part of the name and gives the caller more flexibility.</p></li>\n<li>If you call <code>BeginMonitoring</code> in just the right moment again after it has been called before, you can have multiple <code>PollState()</code> calls going on. The right moment is that the timer just elapsed from the previous call and started to execute but hasn't set the flag yet. I don't know if you want to protect against it.</li>\n<li>You will call <code>Dispose</code> twice on the timer. This should be harmless but you might add <code>nextRequest = null</code> to <code>StopMonitoring</code>.</li>\n<li><p>This:</p>\n\n<pre><code>nextRequest.Elapsed += new ElapsedEventHandler(nextRequest_Elapsed);\n</code></pre>\n\n<p>Can be written as</p>\n\n<pre><code>nextRequest.Elapsed += (s, e) =&gt; PollState();\n</code></pre>\n\n<p>Then you can get rid of the <code>nextRequest_Elapsed</code> method.</p></li>\n<li><p>I would rewrite this:</p>\n\n<pre><code>bool bConditionMet = false;\nbConditionMet = IsConditionMetDelegate(state);\nif( bConditionMet )\n</code></pre>\n\n<p>As:</p>\n\n<pre><code>if (IsConditionMetDelegate(state))\n</code></pre>\n\n<p>I don't really see any benefit into introducing the local variable.</p></li>\n<li>Don't throw generic <code>Exception</code>. In your case I'd use <code>InvalidOperationException</code>. Using specific exceptions gives more meaning to the error and also potentially allows the caller to catch some exceptions but not others.</li>\n</ol>\n\n<p><strong>Design</strong></p>\n\n<p>As it stands your code is hard to unit test due to the async nature of the timer. Consider creating an <code>ITimer</code> interface which you can pass in with a thin wrapper implementation around the .NET <code>Timer</code>. This way you can pass in a mock implementation in unit tests which you can control as to when it executes. This is somewhat annoying but so far the only way to reliably test things like this I have found.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T09:10:31.477", "Id": "36115", "ParentId": "13393", "Score": "8" } } ]
{ "AcceptedAnswerId": "36115", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T14:02:59.037", "Id": "13393", "Score": "11", "Tags": [ "c#", "multithreading", "thread-safety", "timer" ], "Title": "Timer to poll a Delegate" }
13393
<p>I'm updating and old project from <a href="http://api.jquery.com/category/version/1.4/" rel="nofollow">jQuery 1.4</a> to <a href="http://api.jquery.com/category/version/1.7/" rel="nofollow">jQuery 1.7</a>.</p> <p>Can this be simplified, thus reducing the amount of code, and perhaps in such reduction, have it improved?</p> <p>Having the following code:</p> <pre><code>var cartItemDel = '&lt;td class="del"&gt;&lt;img src="components/themes/default/img/icons/cross-small.png" width="16" height="16" alt="X"&gt;&lt;input type="hidden" class="lid" name="lineID'+ id +'" value="'+ id +'"&gt;&lt;span class="hidden token"&gt;'+token+'&lt;/span&gt;&lt;/td&gt;', cartItemName = '&lt;td&gt;&lt;input class="CartItemId" type="hidden" name="id_'+ id +'" value="'+ id +'"&gt;&lt;span class="CartItemName"&gt;'+ name +'&lt;/span&gt;&lt;/td&gt;', cartItemPrice = '&lt;td&gt;&lt;input class="CartItemRef" type="hidden" name="ref_'+ ref +'" value="'+ ref +'"&gt;&lt;span class="class="CartItemPrice"&gt;&lt;span class="lineSum"&gt;'+ price +'&lt;/span&gt;&amp;euro;&lt;/span&gt;&lt;/td&gt;'; $(".cart-table tbody") .append('&lt;tr&gt;'+cartItemDel+cartItemName+cartItemPrice+'&lt;/tr&gt;'); </code></pre> <p>I've updated it to:</p> <pre><code>/* * ADD NEW LINE - First TD */ var $newLineIcon = $("&lt;img/&gt;", { src : "components/themes/default/img/icons/cross-small.png", width : "16", height : "16", alt : "X" }); var $newLineLID = $("&lt;input/&gt;", { type : "hidden", class : "lid", name : "lineID"+ lid, value : lid }); var $newLineToken = $("&lt;span/&gt;", { class : "hidden token", text : token }); var $newLine_firstTD = $("&lt;td/&gt;", { class : "del"}) .append($newLineIcon) .append($newLineLID) .append($newLineToken); /* * ADD NEW LINE - Second TD */ var $newLinePID = $("&lt;input/&gt;", { type : "hidden", class : "CartItemId", name : "id_"+ id, value : id }); var $newLinePNAME = $("&lt;span/&gt;", { class : "CartItemName", text : name }); var $newLine_secondTD = $("&lt;td/&gt;") .append($newLinePID) .append($newLinePNAME); /* * ADD NEW LINE - Third TD */ var $newLinePREF = $("&lt;input/&gt;", { type : "hidden", class : "CartItemRef", name : "ref_"+ ref, value : ref }); var $newLinePPRICE = $("&lt;span/&gt;", { class : "CartItemPrice", html : "&amp;euro;" }) .prepend($("&lt;span/&gt;", {class : "lineSum", text : price})); var $newLine_thirdTD = $("&lt;td/&gt;") .append($newLinePREF) .append($newLinePPRICE); $("&lt;tr/&gt;") .append($newLine_firstTD) .append($newLine_secondTD) .append($newLine_thirdTD) .appendTo($(".cart-table tbody")); </code></pre>
[]
[ { "body": "<p>Your code looks OK to me, very clear and organised.</p>\n\n<p>It's more important to <a href=\"http://en.wikipedia.org/wiki/Minification_%28programming%29\" rel=\"nofollow\">minify</a> your code to decrease load time. There's a whole bunch of minification tools on the Internet.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T10:46:05.903", "Id": "21836", "Score": "2", "body": "Although your response was the first one, and indicated in a simple manner the ideal procedure regarding the code as a whole (*minify*), You didn't provide a more extensive analysis in relation to this piece of code, being that what I was looking for. I've +1 your answer nonetheless because you deserve it. Thank you for you time. **ps:** thank you for the complement on my code presentation :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-21T02:20:23.137", "Id": "43049", "Score": "0", "body": "@Zuul: I think it should've been a comment instead, but he's already received the upvotes. :-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T14:24:18.773", "Id": "13395", "ParentId": "13394", "Score": "4" } }, { "body": "<p>+1 to this code looking fine as is (with caveats and one issue).</p>\n\n<p><strong>Issue:</strong> You should always quote class as it is a reserved word for future use in javascript.</p>\n\n<p>Don't take this as me advocating you use it or saying it is ready for production<sup>1</sup>, but I'm using <a href=\"http://borismoore.github.com/jsrender/demos/index.html\" rel=\"nofollow\">JsRender</a> in production to ease much of the pain you are seeing/imagining here.</p>\n\n<p>I think the central issue here is that this type of Javascript invokes a hard dependency on the structure of the page and so we look at it with a bit of queasiness that it rightly deserves. If your visual designer comes along and decides that the shopping cart needs to be in a dropdown list where you can drag (or swipe) items out of or into now you have to go and make a whole bunch of changes all over the place. </p>\n\n<p>Unfortunately I don't think it is reasonable in a modern website to expect both that the html has no dependencies on the Javascript (\"page works without javascript\") and that the Javascript has no dependencies on the design of the html(\"javascript works equally well on a totally different design that happens to have a couple of the same named elements\").</p>\n\n<p>I personally am comfortable ignoring the former to get much closer to an ideal on the latter. That said, my working environment is such that I have very little control over the redesigns that happen all too often in the products I work on. </p>\n\n<p>At a minimum I would strive to make sure this code stayed together inside its own function at or near the top of your javascript (or in its own global/namespaced function in the html file itself). This code has very little to do with your logic and a lot to do with your site design. Therefore it doesn't belong sitting alongside your page logic.</p>\n\n<p>On minification (for this code in particular) I am less concerned. A solid minifier is going to combine your <code>var</code> statements, rename the variables and possibly inline them and then remove whitespace. If you were concerned about this, you could inline everything yourself (and you would lose a little on the readibility), but the gzip of this even uncompressed is only about 480 bytes (closure compiler adds some stuff before it estimates) so at most you are going to gain maybe 100 bytes (closure advanced gets 140 but the result will not work; I can manually do it and get 145 off; none of these numbers will mean anything in terms of page performance for your site). </p>\n\n<p>FWIW, your original code was only 332 bytes zipped (smaller than my manual attempt) and compressed (manually) down to 297.</p>\n\n<hr>\n\n<p>\n1. The tests are poorly covering the functionality (willing to bet there are significant issues in various places) and it is sorely missing even half decent documentation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T10:46:44.097", "Id": "21837", "Score": "0", "body": "I did find weird the code highlight for the \"class\" word, now I know why! Tks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T10:47:02.690", "Id": "21838", "Score": "0", "body": "You are right as to the code being very dependent on the HTML Markup, but that's normal to me, since the solution being implemented is very specific to this client." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T10:47:27.967", "Id": "21839", "Score": "0", "body": "This piece of code is inside a function and it is called more than once with a different CSS, depending on the website area. Also, it's already at the very beginning of the JS file that contains code related to the cart presentation without page refresh." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T10:48:02.037", "Id": "21840", "Score": "0", "body": "Related to the code minify, although this piece of code as is doesn't require it, I'm doing it to the entire file since there much more to it that this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T10:49:13.147", "Id": "21841", "Score": "0", "body": "Thank you for taking the time to analyze several potential issues from this code and its surroundings. I've going it with your advice on the reserved word!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T23:47:50.147", "Id": "13408", "ParentId": "13394", "Score": "3" } } ]
{ "AcceptedAnswerId": "13408", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T14:13:28.337", "Id": "13394", "Score": "3", "Tags": [ "javascript", "jquery", "dom", "e-commerce" ], "Title": "Showing an item in a shopping cart" }
13394
<p><a href="http://www.w3.org/TR/DOM-Level-2-Core/introduction.html" rel="nofollow">What is the Document Object Model?</a></p> <blockquote> <p>The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated. In the DOM specification, the term "document" is used in the broad sense - increasingly, XML is being used as a way of representing many different kinds of information that may be stored in diverse systems, and much of this would traditionally be seen as data rather than as documents. Nevertheless, XML presents this data as documents, and the DOM may be used to manage this data.</p> </blockquote> <p><strong>Useful Links:</strong></p> <ul> <li><p><a href="https://developer.mozilla.org/en/DOM/" rel="nofollow">MDN - Document Object Model (DOM)</a></p></li> <li><p><a href="https://developer.mozilla.org/en/Gecko_DOM_Reference" rel="nofollow">MDN - Gecko DOM Reference</a></p></li> <li><p><a href="http://www.quirksmode.org/dom/intro.html" rel="nofollow">Quirksmode W3C DOM -Introduction</a></p></li> <li><p><a href="http://www.quirksmode.org/compatibility.html" rel="nofollow">Quirksmode compatibility tables</a></p></li> <li><p><a href="http://msdn.microsoft.com/en-us/library/ms533043%28v=VS.85%29.aspx" rel="nofollow">MSDN - About the W3C Document Object Model</a></p></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T18:00:40.147", "Id": "13398", "Score": "0", "Tags": null, "Title": null }
13398
The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T18:00:40.147", "Id": "13399", "Score": "0", "Tags": null, "Title": null }
13399
<p>I want to display a table similar to this:</p> <blockquote> <p><img src="https://i.stack.imgur.com/bvdeh.jpg" alt="Desired Table"></p> </blockquote> <p>This table is generated from three tables depending on the student ID:</p> <blockquote> <p><img src="https://i.stack.imgur.com/MIXvr.jpg" alt="Information"></p> </blockquote> <p>I don't want the table to depend on fixed values. For example, I should be able to add a subject or exam in the database and see the changes reflected in the table without touching the code. Any suggestions?</p> <pre><code>&lt;? $con = mysql_connect("localhost","root","123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("test", $con); //////////////////////// ///////////////// Select the exams and put it in array $ex = mysql_query("SELECT * FROM exams"); $dc=1; while ($rowex= mysql_fetch_array($ex)){ $exn[$dc]=$rowex['Exam_Title']; $exid[$dc]=$rowex['Exam_ID']; $dc++; } /////////////////////////// Select the subjects and put it in array $sj = mysql_query("SELECT * FROM subjects"); $dsj=1; while ($rowsj= mysql_fetch_array($sj)){ $sjn[$dsj]=$rowsj['Subj_Title']; $sjid[$dsj]=$rowsj['Subj_ID']; $dsj++; } ////////////////Select the student marks and put it in array with subject id and exam id $result = mysql_query("SELECT * FROM stu_marks"); while ($row= mysql_fetch_array($result)){ $arr[$row['Subj_ID']][$row['Exam_ID']]=$row['Grade']; } /////////////////////// count the exams and the subjects to draw the table $exc=count($exn); $sjc=count($sjn); ?&gt; &lt;table width="400" border="1"&gt; &lt;tr&gt; &lt;? ///////// display subjects in table rows for ($d=0;$d&lt;=$sjc;$d++){ if ($d==0){ echo '&lt;td&gt;-&lt;/td&gt;'; }else{ echo ' &lt;tr&gt;&lt;td&gt;'.$sjn[$d].'&lt;/td&gt;'; } ///////// display exams in table head tds for ($p=1;$p&lt;=$exc;$p++){ if ($d==0){ echo '&lt;td&gt; '.$exn[$p].'&lt;/td&gt;'; }else{ ?&gt; &lt;td&gt; &lt;?=$arr[$sjid[$d]][$exid[$p]]?&gt; &lt;/td&gt; &lt;?} } }?&gt; &lt;/table&gt; </code></pre>
[]
[ { "body": "<p>Probably the biggest thing that I would suggest you improve upon, is your spacing. For example, compare the following two code blocks.</p>\n\n<p><strong>Code Block 1</strong></p>\n\n<pre><code>$sj = mysql_query(\"SELECT * FROM subjects\"); \n$dsj=1; \nwhile ($rowsj= mysql_fetch_array($sj)){ \n$sjn[$dsj]=$rowsj['Subj_Title']; \n$sjid[$dsj]=$rowsj['Subj_ID']; \n$dsj++; \n}\n</code></pre>\n\n<p><strong>Code Block 2</strong></p>\n\n<pre><code>$sj = mysql_query(\"SELECT * FROM subjects\"); \n$dsj = 1; \nwhile ($rowsj = mysql_fetch_array($sj)) { \n $sjn[$dsj] = $rowsj['Subj_Title']; \n $sjid[$dsj] = $rowsj['Subj_ID']; \n $dsj++; \n}\n</code></pre>\n\n<p>I believe it's obvious which is easier to read and more pleasant to look at. You should always make sure to indent blocks (code between <code>{}</code>) and to leave space between operators (<code>+</code>, <code>-</code>, <code>=</code>, etc.)</p>\n\n<p>One way to rectify this would be to pick a style guide and stick with it. According to <a href=\"http://en.wikipedia.org/wiki/Programming_style\" rel=\"nofollow\">Wikipedia</a>, a style guide is.</p>\n\n<blockquote>\n <p>A style guide is a set of rules or guidelines used when writing the source\n code for a computer program.</p>\n</blockquote>\n\n<p>You should preferably choose a style guide from a reputable PHP project. Such as the following projects.</p>\n\n<ol>\n<li><a href=\"http://codeigniter.com/user_guide/general/styleguide.html\" rel=\"nofollow\">CodeIgniter User Guide Version 2.1.2</a></li>\n<li><a href=\"http://pear.php.net/manual/en/standards.php\" rel=\"nofollow\">PEAR Manual Coding Standards</a></li>\n<li><a href=\"http://framework.zend.com/manual/en/coding-standard.coding-style.html\" rel=\"nofollow\">Programmer's Reference Guide</a></li>\n</ol>\n\n<p>Of the three, the <em>Programmer's Reference Guide</em> is from the <em>Zend Framework Manual</em>. Zend is the company behind PHP and so most PHP programmers would be more apt to recognize their style guide as the official one. Ergo, I would probably choose the <em>Programmer's Reference Guide</em> as <strong>my</strong> personal reference guide. Hope this helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T08:11:20.110", "Id": "21678", "Score": "0", "body": "Thank you .. just i wrote it to display the idea and i will use codeigniter for my application .. so just i want to ask is this way -arrays- a good way or not ?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T20:57:29.947", "Id": "13405", "ParentId": "13401", "Score": "4" } }, { "body": "<pre><code>////////////////Select the student marks and put it in array with subject id and exam id \n\n$result = mysql_query(\"SELECT * FROM stu_marks\"); \nwhile ($row= mysql_fetch_array($result)){ \n$arr[$row['Subj_ID']][$row['Exam_ID']]=$row['Grade']; \n} \n</code></pre>\n\n<p>I don't fully understand why you are pulling data out of an array to put it back into an array. You should consider writing better, more specific sql queries so that the result of the individual SQl query is as close to what you want your table to look like as possible. From there, you can then loop through the already made (via mysql_fetch_array) result and reduce the amount of redundancy. </p>\n\n<p>Also, use PDO, don't use or die (probably not ready for these two yet) and for the love of god, <strong>NAME YOUR VARIABLES DESCRIPTIVELY</strong>. I can barely tell whats going on and it's not in any way complicated.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T08:06:07.027", "Id": "21677", "Score": "0", "body": "Coz i need Column1 as key Column 2 as value.. how can i do this ??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T08:14:01.323", "Id": "21679", "Score": "0", "body": "http://stackoverflow.com/questions/11336095/create-array-from-mysql-query-column1-as-key-column-2-as-value" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T21:06:26.663", "Id": "13407", "ParentId": "13401", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-07-06T18:53:16.600", "Id": "13401", "Score": "3", "Tags": [ "php", "mysql" ], "Title": "Student marks report" }
13401
<p>A <a href="https://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="nofollow noreferrer">Uniform Resource Locator (URL)</a> is a <a href="https://en.wikipedia.org/wiki/Uniform_resource_identifier" rel="nofollow noreferrer">Uniform Resource Identifier (URI)</a> that specifies where an identified resource is available and the mechanism for retrieving it.</p> <p>In popular usage and in many technical documents and verbal discussions, URL is often incorrectly used as a synonym for URI. The best-known example of the use of URLs is for the addresses of web pages on the World Wide Web, such as <a href="https://codereview.stackexchange.com/">https://codereview.stackexchange.com/</a>.</p> <p>The uniform resource locator was created in 1994 by Tim Berners-Lee and the URI working group of the <a href="https://en.wikipedia.org/wiki/Internet_Engineering_Task_Force" rel="nofollow noreferrer">Internet Engineering Task Force (IETF)</a>. The format is based on Unix file path syntax, where forward slashes are used to separate directory or folder and file or resource names. Conventions already existed where server names could be prepended to complete file paths, preceded by a double-slash (<code>//</code>).</p> <p>File formats may also be specified using a final dot suffix, so that requests for <code>file.html</code> or <code>file.txt</code> may be served directly whereas <code>file.php</code> needs to be sent to a PHP pre-processor before the processed result is served to the end user. The exposure of such implementation-specific details in public URLs is becoming less common; the necessary information can be better specified and exchanged using Internet media type identifiers, previously known as <a href="https://en.wikipedia.org/wiki/MIME" rel="nofollow noreferrer">MIME</a> types.</p> <p>Berners-Lee later regretted the use of dots to separate the parts of the domain name within URIs, wishing he had used slashes throughout. For example, <code>http://www.example.com/path/to/name</code> would have been written <code>http:com/example/www/path/to/name</code>. Berners-Lee has also said that, given the colon following the URI scheme, the two forward slashes before the domain name were also unnecessary.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T18:55:08.847", "Id": "13402", "Score": "0", "Tags": null, "Title": null }
13402
A Uniform Resource Locator (URL) is a Uniform Resource Identifier (URI) that specifies where an identified resource is available and the mechanism for retrieving it.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T18:55:08.847", "Id": "13403", "Score": "0", "Tags": null, "Title": null }
13403
<p>I have the following tables set up:</p> <p><code>t_users</code> table:</p> <pre class="lang-none prettyprint-override"><code>|----------------------------------| |uid | name | email | |----------------------------------| |1 | Maria | maria@example.com | |2 | George | george@example.com | |----------------------------------| </code></pre> <p><code>t_settings</code> table:</p> <pre class="lang-none prettyprint-override"><code>|---------------------------------| |t_sid | name | default_value | |---------------------------------| |1 | uicolour | #f00 | |2 | language | en | |---------------------------------| </code></pre> <p><code>t_users_settings</code> table:</p> <pre class="lang-none prettyprint-override"><code>|--------------------| |uid | t_sid | value | |--------------------| |2 | 1 | #000 | |1 | 2 | es | |--------------------| </code></pre> <p>What I want, is for each user, to be able to pull all of their custom settings, and also pull the default settings for anything that they haven't changed. I have the following query that works:</p> <pre class="lang-sql prettyprint-override"><code>SELECT t_users.*, t_users_settings.*, t_settings.* FROM t_users LEFT JOIN t_users_settings ON t_users.uid = t_users_settings.t_uid LEFT JOIN t_settings ON t_settings.t_sid != t_users_settings.t_sid WHERE t_users_settings.t_sid IS NOT NULL AND t_users_settings.t_uid IS NOT NULL AND t_users.uid = '&lt;input user id here&gt;'; </code></pre> <p>However, it appears that if I add more settings (Such as country), I then have to add another <code>JOIN</code> and <code>AND</code> statement. I think there is something missing something in the setup, or I'm just not familiar enough with MySQL to format the query correctly.</p> <p>Little help?</p>
[]
[ { "body": "<p>At first glance, there are some alarm bells ringing.</p>\n\n<ul>\n<li>You have <code>t_users_settings.t_sid IS NOT NULL AND t_users_settings.t_uid IS NOT NULL</code>. The first seems to imply you might have NULL values in your <code>t_users_settings.t_sid</code> column. The second seems to defeat the purpose of doing a left join to t_users_settings in the first place.</li>\n<li>A second concern is that you're over-generalising.<br>\nNotice that you're unable to choose a specific type for your <code>t_users_settings.value</code> column. This means you have to roll your own custom type checking or do without.<br>\nYes your design allows you to add new settings \"without code changes\". But in reality, those settings would be meaningless without code changes to make use of them in the first place.</li>\n</ul>\n\n<p>You could probably solve your current problems quite easily by defining your settings table with a separate column for each possible setting, and doing the minimal work of adding columns as you add new settings.</p>\n\n<p>However, that said here's a suggestion based on your current design.</p>\n\n<p>First you want to get all permutations of settings and users. For that you need a cross join.</p>\n\n<pre><code>SELECT u.*, s.*\nFROM t_users u\n CROSS JOIN t_settings s\n</code></pre>\n\n<p>That gives all combinations with their defaults. Now you want a left outer join to find out which defaults have been overridden for each user.</p>\n\n<pre><code>SELECT u.*, s.*\nFROM t_users u\n CROSS JOIN t_settings s\n LEFT JOIN t_users_settings us ON\n us.uid = u.uid\n AND us.t_sid = s.t_sid\n</code></pre>\n\n<p>Finally, cleanup it up with explicit column selection, and you can even derive the actual users_value with a COALESCE, ISNULL or CASE statement.</p>\n\n<pre><code>SELECT u.uid,\n u.name,\n u.email,\n s.t_sid,\n s.name,\n s.default_value,\n COALESCE(us.value, s.default_value) AS users_value\nFROM t_users u\n CROSS JOIN t_settings s\n LEFT JOIN t_users_settings us ON\n us.uid = u.uid\n AND us.t_sid = s.t_sid\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T15:07:24.490", "Id": "13419", "ParentId": "13404", "Score": "5" } }, { "body": "<p>Your query is much too complicated. Get rid of the <code>WHERE</code> clauses and add</p>\n\n<pre><code>IFNULL(value, default_value) user_value\n</code></pre>\n\n<p>That's all.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T05:19:45.920", "Id": "13529", "ParentId": "13404", "Score": "2" } } ]
{ "AcceptedAnswerId": "13419", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T20:11:34.083", "Id": "13404", "Score": "7", "Tags": [ "mysql", "sql" ], "Title": "Expanding a working query without adding multiple join statements?" }
13404
<p>I'm trying to optimize this bit of code and I thought I'd throw it out here to see if anyone has any ideas. I've been testing the performance using <code>Benchmark.measure {...}</code> and wrapping the entire function.</p> <p>Yes, the item has a date that is a Ruby <code>Date</code></p> <pre><code> puts Benchmark.measure { grouped_items } def grouped_items unless @grouped @grouped = {} @items.each do |item| key = item.date if @grouped.has_key?(key) @grouped[key] &lt;&lt; item else @grouped[key] = [item] end end end @grouped end </code></pre> <p>Thanks for any insight you care to share.</p> <p>Edit #1: My first optimization. I was aiming for a slightly more succinct function and gained a .2 seconds reduction in time to process 100_000 items.</p> <pre><code> def grouped_items unless @grouped @grouped = Hash.new { |h, k| h[k] = [] } @items.map {|item| @grouped[item.date] &lt;&lt; item } end @grouped end </code></pre> <p>Edit #2: My second iteration with more or less the same performance profile but with much less code.</p> <pre><code>def grouped_items @grouped ||= @items.group_by { |item| item.date } end </code></pre> <p>Edit #3: An alternative way to do the same thing above.</p> <pre><code>def grouped_items @grouped ||= @items.group_by &amp;:date end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T01:21:09.817", "Id": "21697", "Score": "0", "body": "Nope. I'll check that out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T00:58:49.843", "Id": "21698", "Score": "0", "body": "In future can you flag for a mod to migrate, please don't cross-post. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-12T02:41:06.030", "Id": "21961", "Score": "0", "body": "Did you try profiling the code?" } ]
[ { "body": "<p>Are you aware of <code>Enumerable#group_by</code>?</p>\n\n<pre><code>def grouped_items\n @items.group_by{|item| item.date}\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T01:41:57.013", "Id": "21672", "Score": "0", "body": "No, but I am now. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T01:44:16.030", "Id": "21673", "Score": "0", "body": "It more or less performs the same as the first edit (see above) but with much less code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-29T17:44:05.850", "Id": "22818", "Score": "1", "body": "I just came back across this and wanted to comment again how awesome this solution is. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-16T09:39:14.770", "Id": "134118", "Score": "0", "body": "Just to add, you could even use symbol-to-proc here since you are grouping by an immediate method call: `@items.group_by &:date`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-16T14:24:32.310", "Id": "134165", "Score": "0", "body": "Indeed, as the OP discovered and showed in his Edit #3." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T01:37:45.287", "Id": "13411", "ParentId": "13410", "Score": "8" } }, { "body": "<p>What about this?</p>\n\n<pre><code>@items.group_by { |item| item.effective_date }\n</code></pre>\n\n<p>Benchmarks for the curious:</p>\n\n<pre><code>Ryan v1 : 1.080000 0.000000 1.080000 ( 1.077599)\nRyan v2 : 0.620000 0.000000 0.620000 ( 0.622756)\ngroup_by: 0.580000 0.000000 0.580000 ( 0.576531)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T01:41:57.543", "Id": "13435", "ParentId": "13410", "Score": "4" } } ]
{ "AcceptedAnswerId": "13411", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T01:25:10.530", "Id": "13410", "Score": "5", "Tags": [ "ruby", "performance", "array" ], "Title": "How can I optimize this array.each in ruby?" }
13410
<p><a href="http://williams.best.vwh.net/sunrise_sunset_algorithm.htm" rel="nofollow">This</a> is the algorithm for calculating sun rise/set time at various places on Earth. I took it as an example of multiple functions inside of one top function.</p> <p>This is Ver 0.3:</p> <pre><code>fromDegree deg = deg * pi / 180 toDegree rad = rad * 180 / pi deg2rad = pi/180; -- deg2rad rad2deg = 180 / pi -- rad2deg --nn :: RealFrac a =&gt; a -&gt; a -&gt; a -&gt; a nn value start end = let width = end - start offsetValue = value - start -- value relative to 0 in (offsetValue - (fromIntegral (floor(offsetValue / width)) * width)) + start -- + start to reset back to start of original range {- zenith: Sun's zenith for sunrise/sunset offical = 90 degrees 50' civil = 96 degrees nautical = 102 degrees astronomical = 108 degrees longitude is positive for East and negative for West -} -- sun :: Double -&gt; Double -&gt; Double -&gt; Double -&gt; Double -&gt; Double -&gt; Double sun year month day lat lon zenit local = let -- OK -- 1. day of year doy = n1 - (n2 * n3) + day - 30 where n1 = fromIntegral (floor(275 * month / 9)) :: Double n2 = fromIntegral (floor((month + 9) / 12)) :: Double n3 = fromIntegral (1 + floor ( (year - fromIntegral(4 * floor(year / 4)) + 2) / 3)) :: Double -- OK -- 2. convert the longitude to hour value and calculate an approximate time lngHour = lon / 15 t_rise = doy + ((6 - lngHour) / 24) t_set = doy + ((18 - lngHour) / 24) -- OK -- 3. calculate the Sun's mean anomaly m t = (0.9856 * t) - 3.289 -- OK --4. calculate the Sun's true longitude, UGLY! l t = out res where out x -- adjust (0,360) by adding/subtracting 360 | x &lt; 0 = x + 360 | x &gt; 360 = x - 360 | otherwise = x res = m t + (1.916 * sin(m t * deg2rad)) + (0.020 * sin(2 * m t * deg2rad)) + 282.634 l' t = nn stl 0 360 -- little bit better where stl = m t + (1.916 * sin(m t * deg2rad)) + (0.020 * sin(2 * m t * deg2rad)) + 282.634 -- test OK m_rise = m t_rise m_set = m t_set stl1 = m_rise + (1.916 * sin(m_rise * deg2rad)) + (0.020 * sin(2 * m_rise * deg2rad)) + 282.634 stl = stl1 - 360 stl' = nn stl1 0 360 -- end test -- OK --5a. calculate the Sun's right ascension --ra [0,360) by adding/subtracting 360 ra' t = out res -- ugly, not used any more where out x | x &lt; 0 = x + 360 | x &gt; 360 = x - 360 | otherwise = x res = toDegree $ atan(0.91764 * tan(l t * deg2rad)) -- ??? --5b. right ascension value needs to be in the same quadrant as l ra t = (ra' t + (lQuadrant t - raQuadrant t)) /15 -- 5c... /15 where lQuadrant t = fromIntegral ((floor(l t / 90)) * 90) :: Double raQuadrant t = fromIntegral((floor(ra' t / 90)) * 90) :: Double ra' t = nn raas 0 360 -- better where raas = toDegree $ atan(0.91764 * tan(l t * deg2rad)) -- OK, done in 5b --5c. right ascension value needs to be converted into hours -- ra'' t = ra2 t / 15 -- ??? deg/rad conversion not needed? --6. calculate the Sun's declination sinDec t = 0.39782 * sin(l t * deg2rad) cosDec t = cos(asin(sinDec t)) -- ??? what values are apropriate for this? --7a. calculate the Sun's local hour angle cosH t = (cos(zenit*deg2rad) - (sinDec t * sin(lat*deg2rad))) / (cosDec t * cos(lat * deg2rad)) -- if (cosH &gt; 1) sun never rises -- if (cosH &lt; -1) sun never sets -- OK and 7b --8. calculate local mean time of rising/setting lmtr t = hr t + ra t - (0.06571 * t) - 6.622 where hr t = (360 - toDegree (acos(cosH t))) / 15 lmts t = hs t + ra t - (0.06571 * t) - 6.622 where hs t = (toDegree (acos(cosH t))) /15 --OK --9. adjust back to UTC --NOTE: UT potentially needs to be adjusted into the range [0,24) by adding/subtracting 24 utr t = out res where out x | x &lt; 0 = x + 24 | x &gt; 24 = x - 24 | otherwise = x res = lmtr t - lngHour uts t = out res where out x | x &lt; 0 = x + 24 | x &gt; 24 = x - 24 | otherwise = x res = lmts t - lngHour utr' t = (nn (lmtr t - lngHour) 0 24) + local uts' t = (nn (lmts t - lngHour) 0 24) + local -- OK done in 9. --10. convert UT value to local time zone of latitude/longitude -- localT = UT + localOffset in mapM_ putStrLn [ -- or print " day: " ++ show doy, " lngHour: " ++ show lngHour, " t rise: " ++ show t_rise, " tset: " ++ show t_set, " m rise: " ++ show m_rise, " m set: " ++ show m_set, " stl rise: " ++ show stl, " stl' rise: " ++ show stl', " l rise: " ++ show (l t_rise), " l' rise: " ++ show (l' t_rise), " l set: " ++ show (l t_set), " l' set: " ++ show (l' t_set), " ra rise: " ++ show (ra t_rise), " ra set: " ++ show (ra t_set), " sinDec set: " ++ show (sinDec t_set), " cosDec set: " ++ show (cosDec t_set), " cosH set: " ++ show (cosH t_set), " cosH rise: " ++ show (cosH t_rise), " lmtr r : " ++ show (lmtr t_rise), " lmts s: " ++ show (lmts t_set), " ut rise : " ++ show (utr t_rise), " ut set: " ++ show (uts t_set), " utr' rise : " ++ show (utr' t_rise), " uts' set: " ++ show (uts' t_set) ] </code></pre> <p>Here are my questions:</p> <ol> <li><p>What should I do with <code>sun</code> arguments? To force all of them to be <code>Double</code>?<br> First three arguments "natural" type would be Integral. But is it ok to have function with mixed type arguments? What are Haskell's convention on that?</p></li> <li><p><code>lat</code> and <code>lon</code> could be <code>Float</code> or <code>Double</code> or Fractional. What should I choose and why?</p></li> <li><p><code>zenit</code> could be Fractional, but could it also could be string taking "civil", or 1-4 and inside 1 = official 90.5?</p></li> <li><p>What is the best or easiest way to put together a lot of complex functions like in this example? From where do you start? I didn't want to pollute global name space, so I put them all in <code>sun</code>. After a while I figured out that I do not need multiple nested <code>where</code> or <code>let</code>. Each function defined in <code>sun</code> could be accessed through whole <code>sun</code>. Is this considered good practice?</p></li> <li><p>End result would be <code>(rise, set)</code> times. My thoughts were to create as much as possible common functions, and just feed them <code>t_rise</code> and <code>t_set</code>. Is it ok? Does anything better come to mind?</p></li> <li><p>Yes, I know it gives erroneous result. But that's not my main concern. My biggest issue is to find out "proper way" of doing complex things like this. "OK" are just my markers for what I think is correct.</p></li> <li><p><code>nn</code> normalizes any number to an arbitrary range by assuming the range wraps around when going below min or above max. start, end: -180,180; 0,360; 0,24; -<code>Math.PI</code>, <code>Math.PI</code>. It was a good function in JavaScript. How can I make it be <code>Num a =&gt; a -&gt; a -&gt; a -&gt; a</code>?</p> <pre><code>--nn :: RealFrac a =&gt; a -&gt; a -&gt; a -&gt; a nn value start end = let width = end - start offsetValue = value - start -- value relative to 0 in (offsetValue - (fromIntegral (floor(offsetValue / width)) * width)) + start </code></pre> <p><code>floor</code> and <code>/</code> require <code>Fractional</code> typeclass. But <code>Integral</code> have <code>quot</code> and <code>rem</code>. How do you combine those two and create <code>nn</code> than can take <code>Num</code>? My first thoughts were to create 2 functions: <code>nni</code> for Integral and <code>nnf</code> for Fractional. But is there a better way?</p></li> </ol>
[]
[ { "body": "<p>first thing good question and good observation - the code is ugly ;-), but here it starts getting better; You have a lot duplicate functionality and plain code duplication.</p>\n\n<blockquote>\n <p>Here are my questions:</p>\n \n <p>What should I do with sun arguments? To force all of them to be\n Double? First three arguments \"natural\" type would be Integral. But\n is it ok to have function with mixed type arguments? What are\n Haskell's convention</p>\n</blockquote>\n\n<p>Best way I can think about it is to give the natural types and adapt the functions, as good as possible.</p>\n\n<pre><code>type Radians = Double\ntype Degree = Double\n\ntype Year = Int\ntype Month = Int\ntype Day = Int\ntype Time = Double\n\ntype Longitude = Double\ntype Latitude = Double\n</code></pre>\n\n<blockquote>\n <p>lat and lon could be Float or Double or Fractional or... What to choose and why?</p>\n</blockquote>\n\n<p>I chose <code>Double</code> just for simplicity.</p>\n\n<blockquote>\n <p>zenit could be Fractional, but it also could be string taking \"civil\", or 1-4 and inside 1 = official 90.5...</p>\n</blockquote>\n\n<p>At first try to do it statically and provide functionality later on.</p>\n\n<blockquote>\n <p>What is the best or easiest way to put together a lot of complex\n functions like in this example? From where do you start? I didn't\n want to pollute global name space, so I put them all in sun. After a\n while I figured out that I do not need multiple nested where or let. \n Each function defined in sun could be accessed through whole sun. Is\n this considered good practice?</p>\n</blockquote>\n\n<p>At first you do not litter namespace with global functions !!! Not at all, you just make a module and snap - no namespace problem - export only your function of choice and noone will care if you have a thousand helper functions. You do this with:</p>\n\n<pre><code>module SunPos (sun) where\n</code></pre>\n\n<p>And secondly, please use type annotations for top level functions - it is so much more easy to read and reason about your code, and the type checker kicks in. With any decent editor you have a syntax checking plugin to help you prevent errors, in vim it is Syntastic I know, others like emacs should have one too.</p>\n\n<p>Now for the matter of complexity, just start simple - all simple functions.\n<code>toDegree</code> is a great example, <code>doy</code> too. almost everything you put into your big function <code>sun</code> can be extracted. This makes it also easier to write tests for your function and not be bugged with <code>print \"foo\"</code>, but have automated tests with <code>HUnit</code> or <code>Quickcheck</code>, so if you change any funcitonality it can be tested and you know where to look for bugs.</p>\n\n<p>It is really hard to find a bug in a 200 line of code function, but in 2 lines of code… . And try to restrict yourself to 80 characters of textwidth, as for example here on stackexchange you have to scroll, code with more than 80 characters per line, which is annoying, and easily solved.</p>\n\n<p>Next thing in Haskell it is common practise to use CamelCase instead of underscores. And please use names in your functions that are a bit more self explaining. Today editors help you with autocompletion and your harddrive has no problem with a few extra characters to memorize. <code>m -&gt; meanAnomaly</code> for example, <code>l -&gt; trueLong</code> or <code>nn -&gt; ????</code>, I changed a few but not nearly enough.</p>\n\n<p>so here is what i have corrected by now - it is not a complete but a compiling code i think.</p>\n\n<pre><code>module SunPos (sun) where\n\ntype Radians = Double\ntype Degree = Double\n\ntype Year = Int\ntype Month = Int\ntype Day = Int\ntype Time = Double\n\ntype Longitude = Double\ntype Latitude = Double\n\n{-fromDegree :: Degree -&gt; Radians\n fromDegree deg = deg * pi / 180-}\n\ntoDegree :: Radians -&gt; Degree\ntoDegree rad = rad * 180 / pi\n\ndeg2rad :: Double\ndeg2rad = pi/180; -- deg2rad\n-- rad2deg = 180 / pi -- rad2deg\n\nnn :: Double -&gt; Double -&gt; Double -&gt; Double\nnn value start end = offsetValue - (windingNum * width) + start\n where width = end - start\n offsetValue = value - start -- value relative to 0\n windingNum = fromIntegral (floor (offsetValue / width)::Int)\n-- + start to reset back to start of original range\n\n{-\n zenith: Sun's zenith for sunrise/sunset\n offical = 90 degrees 50'\n civil = 96 degrees\n nautical = 102 degrees\n astronomical = 108 degrees\n\nlongitude is positive for East and negative for West\n-}\n\n-- | 1. day of year\ndoy :: Year -&gt; Month -&gt; Day -&gt; Double\ndoy year month day = fromIntegral (n1 - (n2 * n3) + day - 30)\n where n1 = 275 * month `div` 9\n n2 = (month + 9) `div` 12\n n3 = 1 + ((year - (4 * (year `div` 4)) + 2) `div` 3)\n\nmeanAnomaly :: Time -&gt; Time\nmeanAnomaly t = (0.9856 * t) - 3.289\n\ntrueLong :: Time -&gt; Double\ntrueLong t = out res\n where res = stl t\n-- | adjust (0,360) by adding/subtracting 360\n\nout :: Double -&gt; Double\nout x = nn x 0.0 360.0\n\nstl :: Time -&gt; Double\nstl t = mA + (1.916 * sin(2*deg2rad*mA)) + (0.020 * sin(deg2rad*mA)) + 282.634\n where mA = meanAnomaly t\n\nl' :: Time -&gt; Double\nl' t = nn (stl t) 0 360 -- little bit better\n--\n-- | calculate the Sun's right ascension ra [0,360) by adding/subtracting 360\nra :: Time -&gt; Double\nra t = (ra' + (lQuadrant - raQuadrant)) /15 -- 5c... /15\n where lQuadrant = fromIntegral (floor(trueLong t / 90) * 90 ::Int)\n raQuadrant = fromIntegral(floor(ra' / 90) * 90 ::Int)\n ra' = out raas\n raas = toDegree $ atan(0.91764 * tan(trueLong t * deg2rad))\n\n-- | local mean time of rising/setting\nlmtr :: Time -&gt; Double -&gt; Latitude -&gt; Double\nlmtr t zenit lat = hr + ra t - (0.06571 * t) - 6.622\n where hr = (360 - toDegree (acos cosHour')) / 15\n cosHour' = cosHour t zenit lat\n\nlmts :: Time -&gt; Double -&gt; Latitude -&gt; Double\nlmts t zenit lat = hs + ra t - (0.06571 * t) - 6.622\n where hs = toDegree (acos cosHour') /15\n cosHour' = cosHour t zenit lat\n\n-- calculate the cosine of Sun's local hour angle\n\ncosHour :: Time -&gt; Double -&gt; Latitude -&gt; Double\ncosHour t zenit lat = (cZen - sLat ) / (cosDec t * cos(lat * deg2rad))\n where cZen = cos(zenit*deg2rad)\n sLat = sinDec t * sin(lat*deg2rad)\nsinDec :: Time -&gt; Double\nsinDec t = 0.39782 * sin(trueLong t * deg2rad)\ncosDec :: Time -&gt; Double\ncosDec t = cos(asin(sinDec t))\n\nlongHour :: Longitude -&gt; Double\nlongHour lon = lon / 15\n\nsun :: Year -&gt; Month -&gt; Day -&gt; Latitude -&gt; Longitude -&gt; Double -&gt; Double -&gt; String\nsun year month day lat lon zenit local =\n unlines [ \" day: \" ++ show doy',\n \" longHour: \" ++ show (longHour lon),\n \" t rise: \" ++ show timeOfRise,\n \" tset: \" ++ show timeOfSet,\n \" m rise: \" ++ show meanAnomalyOfRise,\n \" m set: \" ++ show meanAnomalyOfSet,\n \" stl' rise: \" ++ show stl',\n \" l rise: \" ++ show (trueLong timeOfRise),\n \" l' rise: \" ++ show (l' timeOfRise),\n \" l set: \" ++ show (trueLong timeOfSet),\n \" l' set: \" ++ show (l' timeOfSet),\n \" ra rise: \" ++ show (ra timeOfRise),\n \" ra set: \" ++ show (ra timeOfSet),\n \" sinDec set: \" ++ show (sinDec timeOfSet),\n \" cosDec set: \" ++ show (cosDec timeOfSet),\n \" lmtr: \" ++ show lR,\n \" lmts: \" ++ show lS,\n \" ut rise : \" ++ show utr,\n \" ut set: \" ++ show uts]\n where doy' = doy year month day\n timeOfRise = doy' + (( 6 - longHour lon) / 24)\n timeOfSet = doy' + ((18 - longHour lon) / 24)\n meanAnomalyOfRise = meanAnomaly timeOfRise\n meanAnomalyOfSet = meanAnomaly timeOfSet\n stl1 = meanAnomalyOfRise + stl meanAnomalyOfRise\n stl' = nn stl1 0 360\n utr = nn lR 0 24 + local\n lR = lmtr timeOfRise zenit lat - longHour lon\n uts = nn lS 0 24 + local\n lS = lmts timeOfSet zenit lat - longHour lon\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T11:54:44.820", "Id": "13416", "ParentId": "13413", "Score": "7" } }, { "body": "<p>Haskell is really beautiful and really ugly language at the same time. It's pretty useless in current state (everything is a function) simply because not everything is a function... What I did here was just finding common patterns and making functions for that patterns. Like a tree. Leafs are almost universal functions like normalize number or degree transformations. Branches become functions used just in sun. And at the end there is sun function which combines branches and leafs.</p>\n\n<p>It took me some real time to refactor and debug <code>sun</code> function. </p>\n\n<p>Fully functional. Full module. Use it for what ever you want :)</p>\n\n<pre><code>module Sky\n (sun, toHourMin)\nwhere\n\n--import MyLib.Functions -- nn nni, toDegree, deg2rad, rad2deg, doy\nimport Data.Fixed -- mod'\n\n\n\n\ntype Radians = Double\ntype Degree = Double\n\n{-type Year = Integral\ntype Month = Integral\ntype Day = Integral\n-}\n\ntype Longitude = Degree\ntype Latitude = Degree\ntype Zenith = Degree\ntype Time = Double\ntype LocalTime = Double\ntype GMTtime = Double\n\n\n\n\n\n------------------ common helper functions-------------------------------------\n\n\n-- normalise number x\nnn start end x = let\n width = end - start\n offsetValue = x - start -- x relative to 0\n in (offsetValue - (fromIntegral (floor(offsetValue / width)) * width)) + start\n\n\nnorm360 :: Degree -&gt; Degree\nnorm360 x = nn 0 360 x\n\nnorm24 :: Time -&gt; Time\nnorm24 x = nn 0 24 x\n\n\n\ntoRadian deg = deg * pi / 180 \ntoDegree rad = rad * 180 / pi\n\ndeg2rad = pi/180\nrad2deg = 180 / pi\n\n-- upgrade it to Real a\narcAngleRight max start end\n | (diff &lt;= 0) = -diff\n | otherwise = max - diff\n where\n m2 = max/2\n diff = (start + m2 - end) `mod'` max - m2;\n\n\ndoy year month day = n1 - (n2 * n3) + day - 30\n where\n n1 = quot (275 * month) 9 -- infixl 7: n1 = 275 * month `quot` 9\n n2 = quot (month + 9) 12\n n3 = 1 + quot (year - 4 * quot year 4 + 2) 3\n\n\ntoHourMin time = hour ++ \":\" ++ min\n where\n (h, m) = properFraction time -- (Integral, Realfrac) 1.99 =&gt; (1, 0.99)\n hour = show h\n m' = floor (m * 60)\n min\n | m' &gt;= 10 = show m'\n | otherwise = \"0\" ++ show m'\n\n\n\n\n\n\n------------------ common sun functions ---------------------------------------\n\nlongitudeHour :: Longitude -&gt; Time\nlongitudeHour l = l / 15\n\nsunMeanAnomaly :: Time -&gt; Degree -- 3.\nsunMeanAnomaly time = (0.9856 * time) - 3.289\n\n\nsunTrueLongitude :: Time -&gt; Degree -- 4.\nsunTrueLongitude time = norm360 stl\n where\n m = sunMeanAnomaly time\n stl = m + (1.916 * sin (m*deg2rad)) + (0.02 * sin((2*m)*deg2rad)) + 282.634\n-- stl = m + (1.916 * sin m) + (0.02 * sin(2*m)) + 282.634\n\n\nsunRightAscention :: Time -&gt; Degree\nsunRightAscention time = ra / 15 -- 5c\n where\n stl = sunTrueLongitude time\n nra = norm360 $ toDegree $ atan(0.91764 * tan(stl*deg2rad)) -- 5a\n lQ = fromIntegral (floor(stl/90) * 90) -- 5b\n raQ = fromIntegral (floor(nra/90) * 90) -- 5b\n ra = nra + (lQ - raQ) -- 5b\n\n\n\n\n-------------------- require common sun f -------------------------------------\n\n\n\n-- if (cosH &gt; 1) sun never rises\n-- if (cosH &lt; -1) sun never sets\n--7a. calculate the Sun's local hour angle; aka: cosH\nsunLocalHourAngle :: Time -&gt; Latitude -&gt; Zenith -&gt; Degree\nsunLocalHourAngle time lat zenith =\n (cos(zenith*deg2rad) - (sinDec * sin(lat*deg2rad))) /\n (cosDec * cos(lat*deg2rad))\n where\n stl = sunTrueLongitude time\n -- sun declination\n sinDec = 0.39782 * sin(stl*deg2rad) -- 6\n cosDec = cos(asin sinDec) -- 6\n\n\n{-\nLocal mean rising / setting time are real local times of dusk / sunset\nbut many cities and countries incorporate manu time zones in just one.\nothervise there would be 4 min time difference for every longitude degree.\n\n360/24H = 15\n15 degrees of longitude separation between each of the 24 primary time zones. \n15 / 60 = 0.25 or 1 = 4min\n\n realLocalRiseTime = toHourMin . norm24 $ lmtRise aproxTimeRise\n\nBecause we live in politicly corrected timezones, this is not usefull.\n-}\n--8. local mean Rising time\nlmtRise time lat zen = hRise + ra - (0.06571 * time) - 6.622\n where\n ra = sunRightAscention time\n cosH = sunLocalHourAngle time lat zen\n hRise = (360 - toDegree (acos cosH)) / 15 -- 7b.\n\n-- local mean Setting time\nlmtSet time lat zen = hSet + ra - (0.06571 * time) - 6.622\n where\n ra = sunRightAscention time\n cosH = sunLocalHourAngle time lat zen\n hSet = (toDegree (acos cosH )) /15 -- 7b.\n\n\n\n\n\n{-\n zenithh: Sun's zenithh for sunrise/sunset\n offical = 90 degrees 50'\n civil = 96 degrees\n nautical = 102 degrees\n astronomical = 108 degrees\n\nlongitude is positive for East and negative for West\n\nreturn double or (hh,mm)\n-} \n\n--sun :: Integral a =&gt; a -&gt; a -&gt; a -&gt; Latitude -&gt; Longitude -&gt; Zenith -&gt; Time -&gt; Time -&gt; ()\nsun year month dayy lat lon zenith timeZone dST = let\n\n day :: Time\n day = fromIntegral $ doy year month dayy\n\n lonHour :: Time\n lonHour = longitudeHour lon\n\n aproxTimeRise :: Time\n aproxTimeRise = day + ((6.0 - lonHour) / 24.0)\n\n aproxTimeSet :: Time\n aproxTimeSet = day + ((18.0 - lonHour) / 24.0)\n\n\n-- if (sunLocalHourAngle aproxTimeRise &gt; 1) sun never rises\n-- if (sunLocalHourAngle aproxTimeSet &lt; -1) sun never sets\n\n lRise :: Time\n lRise\n | noRise &gt; 1 = 0 -- sun never rises\n | noRise &lt; -1 = 24 -- sun never sets\n | otherwise = lmtRise aproxTimeRise lat zenith\n where\n noRise = sunLocalHourAngle aproxTimeRise lat zenith\n\n lSet :: Time\n lSet\n | noRise &gt; 1 = 0 -- sun never rises\n | noRise &lt; -1 = 24 -- sun never sets\n | otherwise = lmtSet aproxTimeSet lat zenith\n where\n noRise = sunLocalHourAngle aproxTimeSet lat zenith\n\n\n\n\n--9. adjust back to UTC/GMT 0-24\n gmtRise :: GMTtime\n gmtRise = norm24 (lRise - lonHour)\n gmtSet :: GMTtime\n gmtSet = norm24 $ lSet - lonHour\n\n localRise :: LocalTime\n localRise = norm24 $ gmtRise + timeZone + dST\n\n localSet :: LocalTime\n localSet = norm24 $ gmtSet + timeZone + dST\n\n\n\n outT :: Time -&gt; Time -&gt; Time\n outT _ 0 = 0 -- sun never rises\n outT _ 24 = 24 -- sun never sets\n outT time _ = time\n\n\n dayLength :: Time\n dayLength\n | lRise ==0 &amp;&amp; lSet == 0 = 0 -- sun never rises\n | lRise == 24 &amp;&amp; lSet == 24 = 24 -- sun never sets\n | lRise /= 0 &amp;&amp; lRise /= 24 &amp;&amp; lSet /= 0 &amp;&amp; lSet /= 24 = arcAngleRight 24 gmtRise gmtSet\n | otherwise = 0\n\n\n\n\n in ((outT localRise lRise, outT localSet lSet, dayLength),\n (outT gmtRise lRise, outT gmtSet lSet, dayLength))\n</code></pre>\n\n<p>How to call it:</p>\n\n<pre><code>ny = ((r,s,l),(ur, us, p))\n-- or: toHourMin r ++ \" set: \" ++ toHourMin s ++ \" l: \" ++ toHourMin l\n where \n ((r,s,l),(ur, us, p)) = sun 2012 7 8 40.7 (-74) 90.5 (-5) 1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-09T08:39:34.337", "Id": "169177", "Score": "0", "body": "@200_success: If you've asked me that 3 years ago, my answer would be more eloquent. But now... Haskel is really beautiful and really ugly language at the same time. It's pretty useless in current state (everything is a function) simply because not everything is a function... What I did here was just finding common patterns and making functions for that patterns. Like a tree. Leafs are almost universal functions like `normalize number` or degree transformations. Branches become functions used just in `sun`. And at the end there is `sun` function which combines branches and leafs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-09T08:45:09.097", "Id": "169179", "Score": "0", "body": "If there were no modules, this approach would be very wrong. Haskel didn't have modules from beginning. Modules were added later. `epsilonhalbe` answer helped a lot. He pointed me to avoid global pollution, to re-factor the code. Doing that I created something like tree structure. After a while almost all leafs ended in my functions.hs file because they are universal. But helper functions stayed in sun module because they will probably be used only here and nowhere else." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T01:17:36.430", "Id": "13526", "ParentId": "13413", "Score": "1" } } ]
{ "AcceptedAnswerId": "13416", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T03:05:22.637", "Id": "13413", "Score": "4", "Tags": [ "haskell", "datetime", "geospatial" ], "Title": "Calculating sun rise/set time at various places on Earth" }
13413
<p>I'm studying Common Lisp on my own. Coming from C++, Common Lisp feels kind of strange sometimes. I'd like to get some feedback on what I understood so far.</p> <p>For learning purposes, I wrote this simple vector class package. The only requirements apart from correctness are non-destructiveness and performance. I want it to be as fast as possible. Is this the way to do it? Are there any serious flaws?</p> <pre><code>(in-package :cl-user) (defpackage math (:use :cl) (:export :vector3 :create-vector3 :vector3-x :vector3-y :vector3-z :neg :mul :div :add :sub :dot :len :norm)) (in-package :math) (defclass vector3 () ((x :accessor vector3-x :initarg :x :initform 0 :type double-float) (y :accessor vector3-y :initarg :y :initform 0 :type double-float) (z :accessor vector3-z :initarg :z :initform 0 :type double-float))) (defun create-vector3 (x y z) (make-instance 'vector3 :x x :y y :z z)) (defmethod neg ((v vector3)) (create-vector3 (- (vector3-x v)) (- (vector3-y v)) (- (vector3-z v)))) (defmethod mul ((s double-float) (v vector3)) (create-vector3 (* s (vector3-x v)) (* s (vector3-y v)) (* s (vector3-z v)))) (defmethod div ((v vector3) (s double-float)) (create-vector3 (/ (vector3-x v) s) (/ (vector3-y v) s) (/ (vector3-z v) s))) (defmethod add ((a vector3) (b vector3)) (create-vector3 (+ (vector3-x a) (vector3-x b)) (+ (vector3-y a) (vector3-y b)) (+ (vector3-z a) (vector3-z b)))) (defmethod sub ((a vector3) (b vector3)) (create-vector3 (- (vector3-x a) (vector3-x b)) (- (vector3-y a) (vector3-y b)) (- (vector3-z a) (vector3-z b)))) (defmethod dot ((a vector3) (b vector3)) (+ (* (vector3-x a) (vector3-x b)) (* (vector3-y a) (vector3-y b)) (* (vector3-z a) (vector3-z b)))) (defmethod len ((v vector3)) (sqrt (+ (* (vector3-x v) (vector3-x v)) (* (vector3-y v) (vector3-y v)) (* (vector3-z v) (vector3-z v))))) (defmethod norm ((v vector3)) (let ((l (len v))) (if (&gt; l 0) (let ((inv (/ 1.0 l))) (create-vector3 (* (vector3-x v) inv) (* (vector3-y v) inv) (* (vector3-z v) inv))) (create-vector3 (vector3-x v) (vector3-y v) (vector3-z v))))) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T02:50:22.847", "Id": "21712", "Score": "1", "body": "Start with using the time macro, check out how to disassemble functions, and try to find a good profiler for your lisp implementation" } ]
[ { "body": "<p>Here are a few minor suggestions:</p>\n\n<ol>\n<li>Use uninterned symbols instead of keywords in <code>defpackage</code> (e.g., <code>#:neg</code> instead of <code>:neg</code>) to avoid polluting the keyword package.</li>\n<li>Fix your indentation.</li>\n<li>Add a <code>defgeneric</code> with docs for each defmethod (you can fold <code>defmethod</code> inside <code>defgeneric</code>)</li>\n<li>Decide if your objects are read-only; if they are, replace <code>:accessor</code> with <code>:reader</code>, if they are not, add mutator functions (e.g., scale in-place)</li>\n<li>Rename <code>norm</code> to <code>normalize</code> (<code>norm</code> in math refers to the length of the vector)</li>\n<li>Use <code>(plusp x)</code> instead of <code>(&gt; x 0)</code></li>\n<li>Use <code>(/ x)</code> instead of <code>(/ 1 x)</code></li>\n<li>In the <code>else</code> clause in <code>norm</code> can just return the argument or <code>(create-vector3 0 0 0)</code> for clarity</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T17:55:11.850", "Id": "20339", "ParentId": "13414", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T08:54:18.533", "Id": "13414", "Score": "4", "Tags": [ "performance", "functional-programming", "common-lisp", "computational-geometry" ], "Title": "First Common Lisp vector math code" }
13414
<p>I have an abstract class <code>Entity</code> in my code, which requires a reference to an instance of <code>EntityData</code> to operate. (<code>EntityData</code> provides basic information about the type of the entity).<br/> In the design of my program, every type of entity would have its own class that extends <code>Entity</code>, and thus would have to provide <code>EntityData</code> that would describe and be shared between all of the instances of that that entity class.<br/> <code>EntityData</code> itself is an immutable class that is built like a multiton (similar to Java's enum). It has a private constructor, and its instances are revealed as readonly static fields.</p> <p>An example of how <code>EntityData</code> would look:</p> <pre><code>sealed class EntityData { public static readonly EntityData Table = new EntityData(250, 60); public static readonly EntityData Chair = new EntityData(120, 25); public readonly int Cost; public readonly int Weight; private EntityData(int cost, int weight) { Weight = weight; Cost = cost; } } </code></pre> <p>I can think of two simple ways to deal with this, but I am uncertain which one I should go with.</p> <p><strong>First one</strong> is to add a reaodnly field to <code>Entity</code> and request is via the constructor, so <code>Entity</code> would look like this:</p> <pre><code>abstract class Entity { private readonly EntityData data; protected Entity(EntityData data) { this.data = data; } } </code></pre> <p>While an extending class, <code>Table</code> for example, would look like this:</p> <pre><code>sealed class Table: Entity { public Table() : base(EntityData.Table) {} } </code></pre> <hr> <p>The <strong>second option</strong> would be to add an abstract, protected property (getter only) to <code>Entity</code>. In this case <code>Entity</code> would look like this:</p> <pre><code>abstract class Entity { protected abstract EntityData Data { get; } } </code></pre> <p>While the extending class <code>Table</code> would look like this:</p> <pre><code>sealed class Table : Entity { protected override EntityData Data { get { return EntityData.Table; } } } </code></pre> <p>Thus internally, <code>Entity</code> would simply use the property instead of a field.</p> <hr> <p>The performance differences are probably in the realm of micro-optimization, but I would still like to take them into consideration.</p> <p>The first way obviously increases the size of any <code>Entity</code> object.<br/> The first way also forces all the extending types to define their constructors and call the base constructor <em>or</em> will simply increase the number of parameters in the already existent constructor.</p> <p>The second way doesn't increase the size of objects, and (to me) look shorter and slightly more concise.<br/> Performance-wise however, benchmarking showed that a virtual method call is much slower than accessing a field.<br/> It is also less obvious that such a property is a dependency of <code>Entity</code>, something the first way makes perfectly clear.</p> <p>As there's no clear-cut answer here, I would simply love to have a few opinions on the matter, and which of the two ways you find 'better'. <br/> Thanks in advance.</p> <p><em>(Please no responses about how this is in the realm of micro optimization and thus I shouldn't waste my time with it. I simply find this interesting.)</em></p>
[]
[ { "body": "<p>I think I personally like the set by constructor method in general. I think it provides a means by which you can better allow for TDD and also implicitly implies the contract all inheriting classes must obey in providing a Entity object if they wish to inherit from the base class. </p>\n\n<p>I think if I were going make Entity a requirement of the second method I would make the protected method <em>abstract</em> which would also enforce this constraint. However that doesn't allow for the easy of use in using dependency injection which I think would suit this approach nicely.</p>\n\n<p>I'm not sure why there would be a huge increase in the size of the Entity object itself. I would assume the size increase would only be as large as the size of the memory register holding the location of the Entity object itself. As for performance, I can't comment explicitly but I would assume you would still need to make visible the EntityData object to it's children so you would probably do that via a property accessor or method anyway so performance impacts to me would be low on the priority list unless profiling the code suggested otherwise.</p>\n\n<p>So assuming the Entity is required in inherited classes I would consider something like:</p>\n\n<pre><code>abstract class Entity\n{\n protected EntityData Data { get; private set; }\n\n protected Entity(EntityData data)\n {\n this.Data = data;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T22:35:38.700", "Id": "13423", "ParentId": "13420", "Score": "2" } }, { "body": "<p>Maybe I'm a bit of a stick in the mud on this, but I simply can't let member variables be <code>public</code> -- no matter how <code>readonly</code> or <code>static</code> they are. So here's a slightly altered version that makes the variables <code>private</code> and exposes them via read-only properties. I'm also a fan of interfaced classes, particularly for unit testing, but also for dependency-injection, etc.</p>\n\n<pre><code>interface IEntityData\n{\n int Cost\n {\n get;\n }\n\n int Weight\n {\n get;\n }\n}\n\nsealed class EntityData : IEntityData\n{\n private static readonly IEntityData table = new EntityData(250, 60);\n private static readonly IEntityData chair = new EntityData(120, 25);\n\n private readonly int cost;\n private readonly int weight;\n\n private EntityData(int cost, int weight)\n {\n this.weight = weight;\n this.cost = cost;\n }\n\n public static IEntityData Table\n {\n get\n {\n return table;\n }\n }\n\n public static IEntityData Chair\n {\n get\n {\n return chair;\n }\n }\n\n public int Cost\n {\n get\n {\n return this.cost;\n }\n }\n\n public int Weight\n {\n get\n {\n return this.weight;\n }\n }\n}\n</code></pre>\n\n<p>I would do similar with <a href=\"https://codereview.stackexchange.com/users/5140/dreza\">dreza</a>'s <a href=\"https://codereview.stackexchange.com/a/13423/6172\">snippet</a>:</p>\n\n<pre><code>abstract class Entity : IEntity\n{\n private readonly EntityData data;\n\n protected EntityData Data\n {\n get\n {\n return this.data;\n }\n }\n\n protected Entity(EntityData data)\n {\n this.data = data;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T03:42:18.757", "Id": "21750", "Score": "1", "body": "Yikes, do you get paid by the line of code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T03:46:08.780", "Id": "21751", "Score": "2", "body": "No, but I *do* get paid for not creating technical debt." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-07T19:27:41.217", "Id": "23356", "Score": "2", "body": "I feel solid Java experience here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-08T16:47:58.250", "Id": "23413", "Score": "1", "body": "@loki2302: Me too. There's a *much* better way to approach this in C#. Give me five minutes and I'll cut his LOC in half." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T00:21:38.303", "Id": "13431", "ParentId": "13420", "Score": "0" } }, { "body": "<p>While Jesse's position that fields should never be public has merit, dreza's use of auto-properties is a <em>much</em> easier way to accomplish almost exactly the same ends:</p>\n\n<pre><code>sealed class EntityData\n{\n static EntityData()\n {\n table = new EntityData(250, 60);\n chair = new EntityData(120, 25);\n } \n\n private EntityData(int cost, int weight)\n {\n this.weight = weight;\n this.cost = cost;\n }\n\n public static EntityData Table{get; private set;}\n public static EntityData Chair{get; private set;}\n\n public int Cost{get; private set;}\n public int Weight{get; private set;}\n}\n</code></pre>\n\n<p>The one thing this doesn't save you from is Joe Programmer implementing some method within this class that mutates Cost or Weight, requiring slightly more discipline in code reviews (and Joe Programmer can do similar damage to pretty much any other implementation; the readonly keyword on a field will just show him he's wrong, and then he's double-wrong if he removes it). If you ever needed to convert this to a property with a backing field, that can be done trivially by any refactoring tool you can plug in (and if you aren't using something like ReSharper or CodeRush, you're not doing it right).</p>\n\n<p>BTW, regarding public static readonly fields, I don't have much bad to say about them, and I don't think they should be avoided out of hand. C# In Depth states that using a public static readonly field for the instance member of a singleton (or here, a multiton) is not only fully thread-safe, it's reasonably lazy when used as a true singleton. In a multiton situation, the constructor's invoked, creating all static instances, on the first reference to any one of them; using the <code>Lazy&lt;T&gt;</code> structure will get you lazier and still thread-safe operation.</p>\n\n<p>I would avoid exposing instance-level fields (readonly or otherwise) if you also use properties. This combination of member types makes reflectively accessing members more difficult because you not only have to scan the type for member fields, but also for member properties. Public fields have additional drawbacks vs property accessors, but if there weren't some merit to being able to expose them, then the C# team simply would have disallowed use of <code>public</code> on a field, <em>n'est-ce pas</em>?.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-08T16:59:47.347", "Id": "14456", "ParentId": "13420", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T16:56:12.560", "Id": "13420", "Score": "5", "Tags": [ "c#", "static" ], "Title": "`Static inheritance` pattern" }
13420
<p>As sort of a follow up to my <a href="https://codereview.stackexchange.com/questions/3212/improving-a-custom-integer-class">previous question</a> from a year ago, what are some suggestions you can think of that will improve this code, whether is directly programming related or algorithm related? I know there are better algorithms for multiplication and division, but I don't understand many of them (yet).</p> <p>I have improved my code a lot since last year, but its still very slow.</p> <p>Sorry for the long code, but there is a lot of stuff, even after removing over 100000 characters. Also, all this modifying might have messed up some of the formatting. </p> <p><strong>Please visit <a href="http://calccrypto.wikidot.com/programming:integer" rel="nofollow noreferrer">http://calccrypto.wikidot.com/programming:integer</a> for the most up to date code. The code below is only for reference and may not have the bug fixes suggested put in</strong></p> <pre><code>// Note: All of the operators have been templated or explicitly overloaded for standard // integer types in the full code // go to http://calccrypto.wikidot.com/programming:integer // for an older version of this class because most functions haven't // been touched for a long time // i removed them because they took up so much space, and apparantly there // is a limit of 300000 characters to post #include &lt;cstdlib&gt; #include &lt;deque&gt; #include &lt;iostream&gt; #ifndef __INTEGER__ #define __INTEGER__ class integer{ private: bool SIGN; // false = positive, true = negative std::deque &lt;uint8_t&gt; value; // holds the actual value in base256 void clean(){ // remove 0 bytes from top of deque to save memory while (value.size() &amp;&amp; !value[0]) value.pop_front(); } public: // Constructors integer(){SIGN = false;} // similar for uint8_t, uint16_t, and uint64_t integer(uint32_t rhs){ SIGN = false; while (rhs){ value.push_front(rhs &amp; 255); rhs &gt;&gt;= 8; } } // similar for int8_t, int16_t, and int64_t integer(int32_t rhs){ SIGN = (rhs &lt; 0); if (rhs &lt; 0) rhs = -rhs; while (rhs){ value.push_front(rhs &amp; 255); rhs &gt;&gt;= 8; } } integer(const integer &amp; rhs){ value = rhs.value; SIGN = rhs.SIGN; clean(); } integer(std::deque &lt;uint8_t&gt; &amp; val){ value = val; SIGN = false; clean(); } integer(bool s, std::deque &lt;uint8_t&gt; &amp; val){ value = val; SIGN = value.size()?s:false; clean(); } integer(std::string str, int base){ integer temp = 0; SIGN = false; if (str[0] == '-'){ SIGN = true; str = str.substr(1, str.size() - 1); } switch (base){ case 2: for(unsigned int x = 0; x &lt; str.size(); x++) temp = (temp &lt;&lt; 1) + (str[x] - 48); break; case 8: for(unsigned int x = 0; x &lt; str.size(); x++) temp = (temp &lt;&lt; 3) + (str[x] - 48); break; case 10: for(unsigned int x = 0; x &lt; str.size(); x++) temp = (temp &lt;&lt; 3) + (temp &lt;&lt; 1) + (str[x] - 48); break; case 16: for(unsigned int x = 0; x &lt; str.size(); x++){ temp &lt;&lt;= 4; if ((0x2f &lt; str[x]) &amp;&amp; (str[x] &lt; 0x3a)) // 0 - 9 temp += str[x] - 0x30; else if ((0x60 &lt; str[x]) &amp;&amp; (str[x] &lt; 0x67)) // a - f temp += str[x] - 0x57; else if ((0x40 &lt; str[x]) &amp;&amp; (str[x] &lt; 0x47)) // A - F temp += str[x] - 0x37; else{ std::cerr &lt;&lt; "Error: Character not between 'a' and 'f' found." &lt;&lt; std::endl; exit(1); } } break; case 256: for(unsigned int x = 0; x &lt; str.size(); x++) temp.value.push_back(str[x]); break; default: break; } value = temp.value; } // RHS input args only // Assignment Operator // similar for uint8_t, uint16_t, and uint64_t integer &amp; operator=(uint32_t rhs){ value.clear(); SIGN = false; while (rhs){ value.push_front(rhs &amp; 255); rhs &gt;&gt;= 8; } return *this; } // similar for int8_t, int16_t, and int64_t integer &amp; operator=(int32_t rhs){ value.clear(); SIGN = (rhs &lt; 0); if (rhs &lt; 0) rhs = -rhs; while (rhs){ value.push_front(rhs &amp; 255); rhs &gt;&gt;= 8; } return *this; } integer &amp; operator=(integer rhs){ value = rhs.value; SIGN = rhs.SIGN; return *this; } // Typecast Operators operator bool(){ return (bool) value.size(); } operator char(){ if (!value.size()) return 0; return (char) value.back(); } operator uint8_t(){ if (!value.size()) return 0; return value.back(); } // similar for uint16_t, and uint64_t operator uint32_t(){ uint32_t out = 0; for(uint8_t x = 0; x &lt; ((4 &lt; value.size())?4:value.size()); x++) out = (out &lt;&lt; 8) + (uint8_t) value[value.size() - x - 1]; return out; } operator int8_t(){ if (!value.size()) return 0; int8_t out = value.back(); if (SIGN) out = -out; return out; } // similar for int16_t, and int64_t operator int32_t(){ int64_t out = 0; for(uint8_t x = 0; x &lt; ((4 &lt; value.size())?4:value.size()); x++) out = (out &lt;&lt; 8) + (uint8_t) value[value.size() - x - 1]; if (SIGN) out = -out; return out; } // Bitwise Operators integer operator&amp;(integer rhs){ std::deque &lt;uint8_t&gt; out; for(std::deque &lt;uint8_t&gt;::reverse_iterator i = value.rbegin(), j = rhs.value.rbegin(); (i != value.rend()) &amp;&amp; (j != rhs.value.rend()); i++, j++) out.push_front(*i &amp; *j); return integer(SIGN &amp; rhs.SIGN, out); } integer operator|(integer rhs){ std::deque &lt;uint8_t&gt; out; std::deque &lt;uint8_t&gt;::reverse_iterator i = value.rbegin(), j = rhs.value.rbegin(); for(; (i != value.rend()) &amp;&amp; (j != rhs.value.rend()); i++, j++) out.push_front(*i | *j); while (i != value.rend()) out.push_front(*i++); while (j != rhs.value.rend()) out.push_front(*j++); return integer(SIGN | rhs.SIGN, out); } integer operator^(integer rhs){ std::deque &lt;uint8_t&gt; out; std::deque &lt;uint8_t&gt;::reverse_iterator i = value.rbegin(), j = rhs.value.rbegin(); for(; (i != value.rend()) &amp;&amp; (j != rhs.value.rend()); i++, j++) out.push_front(*i ^ *j); while (i != value.rend()) out.push_front(*i++); while (j != rhs.value.rend()) out.push_front(*j++); return integer(SIGN ^ rhs.SIGN, out); } integer operator&amp;=(integer rhs){ *this = *this &amp; rhs; return *this; } integer operator|=(integer rhs){ *this = *this | rhs; return *this; } integer operator^=(const integer rhs){ *this = *this ^ rhs; return *this; } integer operator~(){ std::deque &lt;uint8_t&gt; out = value; for(unsigned int i = 1; i &lt; out.size(); i++) out[i] ^= 0xff; uint8_t mask = 128; while (!(out[0] &amp; mask)) mask &gt;&gt;= 1; while (mask){ out[0] ^= mask; mask &gt;&gt;= 1; } return integer(SIGN, out); } // Bit Shift Operators // left bit shift. sign is maintained integer operator&lt;&lt;(uint64_t shift){ if (!*this || !shift) return *this; std::deque &lt;uint8_t&gt; out = value; for(uint64_t i = 0; i &lt; (shift &gt;&gt; 3); i++) out.push_back(0); shift &amp;= 7; if (shift){ out.push_back(0); return integer(SIGN, out) &gt;&gt; (8 - shift); } return integer(SIGN, out); } integer operator&lt;&lt;(integer shift){ integer out = *this; for(integer i = 0; i &lt; (shift &gt;&gt; 3); i++) out.value.push_back(0); return out &lt;&lt; (uint64_t) (shift &amp; 7); } // right bit shift. sign is maintained integer operator&gt;&gt;(uint64_t shift){ if (shift &gt;= bits()) return integer(0); std::deque &lt;uint8_t&gt; out = value; for(uint64_t i = 0; i &lt; (shift &gt;&gt; 3); i++) out.pop_back(); shift &amp;= 7; if (shift){ std::deque &lt;uint8_t&gt; v; for(unsigned int i = out.size() - 1; i != 0; i--) v.push_front(((out[i] &gt;&gt; shift) | (out[i - 1] &lt;&lt; (8 - shift))) &amp; 0xff); v.push_front(out[0] &gt;&gt; shift); out = v; } return integer(SIGN, out); } integer operator&gt;&gt;(integer shift){ integer out = *this; for(integer i = 0; i &lt; (shift &gt;&gt; 3); i++) out.value.pop_back(); return out &gt;&gt; (uint64_t) (shift &amp; 7); } // Logical Operators bool operator!(){ return !(bool) *this; } bool operator&amp;&amp;(integer rhs){ return (bool) *this &amp;&amp; (bool) rhs; } bool operator||(integer rhs){ return ((bool) *this) || (bool) rhs; } // Comparison Operators bool operator==(integer rhs){ return ((SIGN == rhs.SIGN) &amp;&amp; (value == rhs.value)); } bool operator!=(integer rhs){ return !(*this == rhs); } private: // operator&gt; not considering signs bool gt(integer &amp; lhs, integer &amp; rhs){ if (lhs.value.size() &gt; rhs.value.size()) return true; if (lhs.value.size() &lt; rhs.value.size()) return false; if (lhs.value == rhs.value) return false; for(unsigned int i = 0; i &lt; lhs.value.size(); i++) if (lhs.value[i] != rhs.value[i]) return lhs.value[i] &gt; rhs.value[i]; return false; } public: bool operator&gt;(integer rhs){ if (SIGN &amp; !rhs.SIGN) // - &gt; + return false; else if (!SIGN &amp; rhs.SIGN) // + &gt; - return true; else if (SIGN &amp; rhs.SIGN) // - &gt; - return !gt(*this, rhs); // else (!SIGN &amp; !rhs.SIGN) // + &gt; + return gt(*this, rhs); } bool operator&gt;=(integer rhs){ return ((*this &gt; rhs) | (*this == rhs)); } private: // operator&lt; not considering signs bool lt(integer &amp; lhs, integer &amp; rhs){ if (lhs.value.size() &lt; rhs.value.size()) return true; if (lhs.value.size() &gt; rhs.value.size()) return false; if (lhs.value == rhs.value) return false; for(unsigned int i = 0; i &lt; lhs.value.size(); i++) if (lhs.value[i] != rhs.value[i]) return lhs.value[i] &lt; rhs.value[i]; return false; } public: bool operator&lt;(integer rhs){ if (SIGN &amp; !rhs.SIGN) // - &lt; + return true; else if (!SIGN &amp; rhs.SIGN) // + &lt; - return false; else if (SIGN &amp; rhs.SIGN) // - &lt; - return !lt(*this, rhs); // else (!SIGN &amp; !rhs.SIGN) // + &lt; + return lt(*this, rhs); } bool operator&lt;=(integer rhs){ return ((*this &lt; rhs) | (*this == rhs)); } private: // Arithmetic Operators integer add(integer &amp; lhs, integer &amp; rhs){ std::deque &lt;uint8_t&gt; out; std::deque &lt;uint8_t&gt;::reverse_iterator i = lhs.value.rbegin(), j = rhs.value.rbegin(); bool carry = false; uint16_t sum; for(; ((i != lhs.value.rend()) &amp;&amp; (j != rhs.value.rend())); i++, j++){ sum = *i + *j + carry; out.push_front(sum); carry = (sum &gt; 255); } for(; i != lhs.value.rend(); i++){ sum = *i + carry; out.push_front(sum); carry = (sum &gt; 255); } for(; j != rhs.value.rend(); j++){ sum = *j + carry; out.push_front(sum); carry = (sum &gt; 255); } if (carry) out.push_front(1); return integer(false, out); } public: integer operator+(integer rhs){ if (!rhs) return *this; if (!*this) return rhs; integer out = *this; if (SIGN == rhs.SIGN){ out = add(out, rhs); out.SIGN = SIGN; } else if (gt(out, rhs)){ if ((!SIGN &amp; rhs.SIGN) | (SIGN &amp; !rhs.SIGN)) // + + - - + + out = sub(out, rhs); if ((!SIGN &amp; !rhs.SIGN) | (SIGN &amp; rhs.SIGN)) // + + + - + - out = add(out, rhs); out.SIGN = SIGN; } else if (lt(out, rhs)){ if ((!SIGN &amp; rhs.SIGN) | (SIGN &amp; !rhs.SIGN)){ // + + - - + + out = sub(rhs, out); out.SIGN = !SIGN; } if ((SIGN &amp; rhs.SIGN) | (!SIGN &amp; !rhs.SIGN)){ // + + + - + - out = add(rhs, out); out = SIGN; } } else{ //if (eq(out, rhs)){ if ((SIGN &amp; rhs.SIGN) | (!SIGN &amp; !rhs.SIGN)) return integer(0); //if ((SIGN &amp; !rhs.SIGN) | (!SIGN &amp; rhs.SIGN)) out = out &lt;&lt; 1; out.SIGN = SIGN; } if (!out.value.size()) // if the value became 0 out.SIGN = false; return out; } integer operator+=(integer rhs){ *this = *this + rhs; return *this; } private: // Subtraction as done by hand integer long_sub(integer &amp; lhs, integer &amp; rhs){ // rhs always smaller than lhs unsigned int lsize = lhs.value.size() - 1; unsigned int rsize = rhs.value.size() - 1; for(unsigned int x = 0; x &lt; rsize + 1; x++){ // if rhs digit is smaller than lhs digit, subtract if (rhs.value[rsize - x] &lt;= lhs.value[lsize - x]) lhs.value[lsize - x] -= rhs.value[rsize - x]; else{// carry unsigned int y = lsize - x - 1; while (!lhs.value[y]) y--; lhs.value[y]--; y++; for(; y &lt; lsize - x; y++) lhs.value[y] = 0xff; lhs.value[y] = ((uint16_t) lhs.value[y]) + 256 - rhs.value[rsize - x]; } } return lhs; } // implemented but erased here and commented out in code // // Two's Complement Subtraction integer sub(integer &amp; lhs, integer &amp; rhs){ if (!rhs) return lhs; if (!lhs) return -rhs; if (lhs == rhs) return 0; return long_sub(lhs, rhs); // return two_comp_sub(lhs, rhs); } public: integer operator-(integer rhs){ integer out = *this; if (gt(out, rhs)){ if ((!SIGN &amp; rhs.SIGN) | (SIGN &amp; !rhs.SIGN)) // + - - - - + out = add(out, rhs); if ((!SIGN &amp; !rhs.SIGN) | (SIGN &amp; rhs.SIGN)) // + - + - - - out = sub(out, rhs); out.SIGN = SIGN; } else if (lt(out, rhs)){ if ((!SIGN &amp; rhs.SIGN) | (SIGN &amp; !rhs.SIGN)){ // + - - - - + out = add(out, rhs); out.SIGN = SIGN; } if ((SIGN &amp; rhs.SIGN) | (!SIGN &amp; !rhs.SIGN)){ // + - + - - - out = sub(rhs, out); out.SIGN = !SIGN; } } else{ //if (eq(out, rhs)){ if ((SIGN &amp; rhs.SIGN) | (!SIGN &amp; !rhs.SIGN)) return integer(0); //if ((SIGN &amp; !rhs.SIGN) | (!SIGN &amp; rhs.SIGN)) out &lt;&lt;= 1; out.SIGN = SIGN; } if (!out.value.size()) // if the value became 0 out.SIGN = false; clean(); return out; } integer operator-=(integer rhs){ *this = *this - rhs; return *this; } private: // implemented but erased here and commented out in code: // // Peasant Multiplication // // Recurseive Peasant Algorithm // // Recursive Multiplication // // Karatsuba Algorithm O(n^log2(3) = n ^ 1.585) // Long multiplication integer long_mult(integer lhs, integer rhs){ unsigned int zeros = 0; integer row, out = 0; for(std::deque &lt;uint8_t&gt;::reverse_iterator i = lhs.value.rbegin(); i != lhs.value.rend(); i++){ row.value = std::deque &lt;uint8_t&gt;(zeros++, 0); // zeros on the right hand side uint8_t carry = 0; for(std::deque &lt;uint8_t&gt;::reverse_iterator j = rhs.value.rbegin(); j != rhs.value.rend(); j++){ uint16_t prod = (uint16_t(*i) * uint16_t(*j)) + carry;// multiply through row.value.push_front(prod &amp; 0xff); carry = prod &gt;&gt; 8; } if (carry) row.value.push_front(carry); out = add(out, row); } return out; } public: integer operator*(integer rhs){ if ((!*this) || (!rhs)) // if multiplying by 0 return 0; if (*this == 1) // if multiplying by 1 return rhs; if (rhs == 1) // if multiplying by 1 return *this; bool s = SIGN ^ rhs.SIGN; integer out = *this; out.SIGN = false; rhs.SIGN = false; if (rhs.abs() == 10){ // if rhs == 10 out = (out &lt;&lt; 3) + (out &lt;&lt; 1); out.SIGN = s; return out; } if (out.abs() == 10){ // if lhs == 10 out = (rhs &lt;&lt; 3) + (rhs &lt;&lt; 1); out.SIGN = s; return out; } // while lhs is multiple of 2 while (!(rhs &amp; 1)){ rhs &gt;&gt;= 1; out &lt;&lt;= 1; } // out = peasant(out, rhs); // out = recursive_peasant(out, rhs); // out = recursive_mult(out, rhs); // out = karatsuba(out, rhs); out = long_mult(out, rhs); out.SIGN = s; if (!out.value.size()) // if the value became 0 out.SIGN = false; return out; } integer operator*=(integer rhs){ *this = *this * rhs; return *this; } private: // implemented but erased here and commented out in code: // // Long Division returning both quotient and remainder // // Recursive Division that returns both the quotient and remainder // Non-Recursive version of above algorithm std::deque &lt;integer&gt; divmod(integer &amp; lhs, integer &amp; rhs){ std::deque &lt;integer&gt; qr; qr.push_back(0); qr.push_back(0); for(unsigned int x = lhs.bits(); x &gt; 0; x--){ qr[0] &lt;&lt;= 1; qr[1] &lt;&lt;= 1; if (lhs[x - 1]) qr[1]++; if (qr[1] &gt;= rhs){ qr[1] -=rhs; qr[0]++; } } return qr; } // division ignoring signs std::deque &lt;integer&gt; dm(integer &amp; lhs, integer &amp; rhs){ if (!rhs){ // divide by 0 error std::cerr &lt;&lt; "Error: division or modulus by zero" &lt;&lt; std::endl; exit(1); } std::deque &lt;integer&gt; out; if (rhs == 1){ // divide by 1 check out.push_back(lhs); out.push_back(0); return out; } if (lhs == rhs){ // divide by same value check out.push_back(1); out.push_back(0); return out; } if (!lhs){ // 0 / rhs check out.push_back(0); out.push_back(0); return out; } if (lt(lhs, rhs)){ // lhs &lt; rhs check out.push_back(0); out.push_back(lhs); return out; } // Check for powers of two ///////////////////// // Cannot do it the easy way for some reason if (!(rhs &amp; 1)){ uint64_t s = 0; integer copyd(rhs); while (!(copyd &amp; 1)){ copyd &gt;&gt;= 1; s++; } if (copyd == 1){ out.push_back(lhs &gt;&gt; s); out.push_back(lhs - (out[0] &lt;&lt; s)); return out; } } //////////////////////////////////////////////// // return long_div(lhs, rhs); // return recursive_divmod(lhs, rhs); return divmod(lhs, rhs); } public: integer operator/(integer rhs){ bool s = SIGN ^ rhs.SIGN; integer lhs = *this; lhs.SIGN = false; rhs.SIGN = false; integer out = dm(lhs, rhs)[0]; out.SIGN = s; if (!out.value.size()) // if the value became 0 out.SIGN = false; return out; } integer operator/=(integer rhs){ *this = *this / rhs; return *this; } integer operator%(integer rhs){ bool s1 = SIGN; bool s2 = rhs.SIGN; integer lhs = *this; lhs.SIGN = false; rhs.SIGN = false; integer out = dm(lhs, rhs)[1]; if (out.value.size()) if (s1 == s2) out.SIGN = s1; else{ out = rhs - out; out.SIGN = s2; } else //if (!out.value.size()) // if the value became 0 out.SIGN = false; return out; } integer operator%=(integer rhs){ *this = *this % rhs; return *this; } // Increment Operator integer &amp; operator++(){ *this += 1; return *this; } integer operator++(int){ integer temp(*this); ++*this; return temp; } // Decrement Operator integer &amp; operator--(){ *this -= 1; return *this; } integer operator--(int){ integer temp(*this); --*this; return temp; } // Nothing done since promotion doesnt work here integer operator+(){ return *this; } // Flip Sign integer operator-(){ integer out = *this; if (out.value.size()) out.SIGN ^= true; return out; } // get private values bool sign(){ return SIGN; // false = pos, true = neg } unsigned int bits(){ if (!value.size()) return 0; unsigned int out = value.size() &lt;&lt; 3; uint8_t mask = 128; while (!(value[0] &amp; mask)){ out--; mask &gt;&gt;= 1; } return out; } unsigned int bytes(){ return value.size(); } std::deque &lt;uint8_t&gt; data(){ return value; } // Miscellaneous Functions integer twos_complement(unsigned int b = 0){ std::deque &lt;uint8_t&gt; out = value; for(unsigned int i = 1; i &lt; out.size(); i++) out[i] ^= 0xff; uint8_t mask = 128; while (!(out[0] &amp; mask)) mask &gt;&gt;= 1; integer top = integer(1) &lt;&lt; ((uint64_t) (out.size() - 1) &lt;&lt; 3); while (mask){ out[0] ^= mask; mask &gt;&gt;= 1; top &lt;&lt;= 1; } integer OUT(SIGN, out); while (b){ OUT ^= top; top &lt;&lt;= 1; b--; } return OUT + 1; } integer abs(){ integer out = *this; out.SIGN = false; return out; } void fill(uint64_t b){ // fills an integer with 1s value = std::deque &lt;uint8_t&gt;(b &gt;&gt; 3, 255); if (b &amp; 7) value.push_front((1 &lt;&lt; (b &amp; 7)) - 1); } bool operator[](unsigned int b){ // get bit, where 0 is the lsb and bits() - 1 is the msb if (b &gt;= bits()) // if given index is larger than bits in this value, return 0 return 0; return (value[value.size() - (b &gt;&gt; 3) - 1] &gt;&gt; (b &amp; 7)) &amp; 1; } // Output value as a string in bases 2 to 16, and 256 std::string str(integer base = 10, unsigned int length = 0){ std::string out = ""; if (base == 256){ if (!value.size()) out = std::string(1, 0); for(unsigned int x = 0; x &lt; value.size(); x++) out += std::string(1, value[x]); while (out.size() &lt; length) out = std::string(1, 0) + out; if (SIGN){ if (!out[0]) out = out.substr(1, out.size() - 1); out = "-" + out; } } else{ if ((base &lt; 2) || (base &gt; 16)) // if base outside of 2 &lt;= base &lt;= 16 base = 10; // set to default value of 10 integer rhs = *this; static const std::string B16 = "0123456789abcdef"; std::deque &lt;integer&gt; qr; do{ qr = dm(rhs, base); out = B16[qr[1]] + out; rhs = qr[0]; } while (rhs); while (out.size() &lt; length) out = "0" + out; if (SIGN){ if (out[0] == '0') out = out.substr(1, out.size() - 1); out = "-" + out; } } return out; } }; // lhs type T as first arguemnt // erased because they were taking up too much space // IO Operators std::ostream &amp; operator&lt;&lt;(std::ostream &amp; stream, integer rhs){ if (stream.flags() &amp; stream.oct) stream &lt;&lt; rhs.str(8); else if (stream.flags() &amp; stream.hex) stream &lt;&lt; rhs.str(16); else stream &lt;&lt; rhs.str(10); return stream; } std::istream &amp; operator&gt;&gt;(std::istream &amp; stream, integer &amp; rhs){ uint8_t base; if (stream.flags() &amp; stream.oct) base = 8; else if (stream.flags() &amp; stream.hex) base = 16; else base = 10; std::string in; stream &gt;&gt; in; rhs = integer(in, base); return stream; } </code></pre> <p>EDIT: Forgot to mention: This should be compiled with C++11 enabled</p> <p>Link to working code: <a href="http://ideone.com/mYDLp" rel="nofollow noreferrer">http://ideone.com/mYDLp</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T03:24:45.580", "Id": "21713", "Score": "2", "body": "At a quick glance, operator bool() makes me uneasy. But since this is pretty large, I tried compiling and running it. I did find that evaluating (integer && anything) causes a stack overflow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T03:55:16.707", "Id": "21714", "Score": "0", "body": "ok. fixed that i think. i havent updated this post or the site yet, though" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T05:06:21.493", "Id": "21717", "Score": "0", "body": "found a bug with the typecase operators that i mistakenly updated incorrectly" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T10:11:41.877", "Id": "21719", "Score": "1", "body": "@calccrypto sorry, but you need to post the up-to-date version inline ([faq])." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T14:32:03.343", "Id": "21721", "Score": "0", "body": "Cannot build new version. Chokes up on std::string with these operators: + << >>." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T16:35:36.910", "Id": "21722", "Score": "0", "body": "@codesparkle this code is ridiculously long and i cannot simply copy and paste. i have to erase so much (100K+ characters) just to post." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T16:35:43.197", "Id": "21723", "Score": "0", "body": "@ROBOKITTY: why are you adding strings to values? which operators<< and >> are you talking about? bit shift or iostream?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T22:00:09.320", "Id": "21725", "Score": "0", "body": "@calccrypto I'm not sure I understand your difficulty with pasting the code? Does StackExchange have a max length on questions or something?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T22:00:44.477", "Id": "21726", "Score": "0", "body": "@Corbin yes. you cant post more than 300k characters at a time" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T22:02:58.487", "Id": "21727", "Score": "0", "body": "@calccrypto Ah, never mind then :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T01:25:44.383", "Id": "21735", "Score": "1", "body": "@calccrypto: Never mind, my compiler didn't like the lack of an #include <string>. And I think you ought to call it VeryLongInteger rather than just integer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T02:48:26.480", "Id": "21748", "Score": "0", "body": "@calccrypto: You said it's very slow. What compiler are you using, and how slow do you mean? I built it with Visual C++ and MinGW in debug mode. VSCPP binary flailed for a second on 5.32533e25 * 5.32533e25, while MinGW's binary started choking on 8.12951e55 * 8.12951e55. That doesn't seem too bad." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T02:53:39.487", "Id": "21749", "Score": "0", "body": "@ROBOKITTY im working with cryptographic values of the range [2^512, 2^2048] which is about [10^154, 10^605]. Python's built-in int type can handle numbers of that magnitude with no problem" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T06:15:30.777", "Id": "21754", "Score": "0", "body": "Out of curiosity, just created an integer from a 500 character string of psuedo-random digits (in the spirit of [2^512, 2^2048]). It took an extremely long time...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T06:44:39.273", "Id": "21755", "Score": "0", "body": "@Corbin now make the number odd and imagine running that number in a primality test" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T08:37:14.487", "Id": "21757", "Score": "0", "body": "@calccrypto Sounds extremely unpleasant :p" } ]
[ { "body": "<p>I'm not familiar with the algorithms used (or any in the same category for that matter), but I do have a few notes on style/practices.</p>\n\n<hr>\n\n<p><strong>std::cerr/exit inside of a class</strong></p>\n\n<p>If a value is unexpected or invalid for a parameter, exceptions should be used, not outputting an error and then killing the program. What if the programmer wants to be able to recover from such an error? For example, what if you had a program that was taking hex input from users and the user provided an invalid character that ended up getting passed into <code>integer(std::string str, int base)</code>. You probably would not want the program to die in the situation.</p>\n\n<p>I would do something like:</p>\n\n<pre><code>else {\n throw std::runtime_error(\"Error: Character not between 'a' and 'f' found\");\n}\n</code></pre>\n\n<p>Same concept applies in the <code>dm</code> method.</p>\n\n<hr>\n\n<p><strong>SIGN</strong></p>\n\n<p>I'm guessing this is named in all uppercase because of the conflict with the sign method. I would consider using _sign or something similar instead. Everywhere I look in the code, the all caps property jumps out at me unnecessarily.</p>\n\n<p>Also, I might consider renaming <code>sign</code> to <code>isPositive</code>. <code>true</code> and <code>false</code> conveys a different meaning to me than I except for a sign. I guess the use of a high and low bit for sign is by far standard enough for people to understand this behavior though.</p>\n\n<hr>\n\n<p><strong>integer</strong></p>\n\n<p>Extremely minor thing, and 100% opinion, but I would consider renaming the class.</p>\n\n<p><code>integer</code> makes me think of a standard <code>int</code> more so than an arbitrary length integer. </p>\n\n<hr>\n\n<p><strong>typedefs</strong></p>\n\n<p>I would use typedefs for a few things both to increase readability and lesser so maintainability.</p>\n\n<p>For example, I might alias <code>std::deque&lt;uint8_t&gt;</code> as <code>value_type</code> or something similar, and would use <code>sign_type</code> instead of bool.</p>\n\n<hr>\n\n<p><strong>clean</strong></p>\n\n<p>Very minor, but I would consider renaming this <code>compact</code> or <code>trim</code>.</p>\n\n<p>Also, I would consider using <code>empty</code> instead of <code>size</code> since <code>empty</code> is constant complexity for all containers and <code>size</code> is only constant for some (though it is of course constant for deque).</p>\n\n<hr>\n\n<p><strong>initializer lists</strong></p>\n\n<p>It's more idiomatic to use initializer lists when possible (there's other benefits too, but in the case of your code, they're fairly insignificant).</p>\n\n<p>For example:</p>\n\n<pre><code>integer() : SIGN(false) { }\n\ninteger(const integer &amp; rhs) : SIGN(rhs.sign), value(rhs.value) {\n clean();\n}\n\ninteger(std::deque &lt;uint8_t&gt; &amp; val) : SIGN(false), value(val) {\n clean();\n}\n</code></pre>\n\n<hr>\n\n<p><strong>const correctness</strong></p>\n\n<p>There's a few places where const correctness is in place, but there's also some places where things could be const but are not.</p>\n\n<p>For example:</p>\n\n<pre><code>integer(bool s, const std::deque &lt;uint8_t&gt; &amp; val) {\n value = val;\n SIGN = value.size() ? s : false;\n clean();\n}\n</code></pre>\n\n<hr>\n\n<p><strong>type casting</strong></p>\n\n<p>I wouldn't provide the type casts (bool, uint8_t, etc). These only make sense if there is a meaningful cast to them, and in my opinion there is not. An arbitrary length integer is not meant to be cut into a smaller piece. I might expose a way to extract this data, but I would not do it via casts. (For example, a method to get the bottom N bytes or something.)</p>\n\n<p>The ability to do this casting implicity especially concerns me. Imagine a method with signature <code>void f(uint16_t)</code>. An <code>integer</code> being passed to by mistake could have some very odd implications.</p>\n\n<hr>\n\n<p><strong>cstdint</strong></p>\n\n<p>Not familiar enough with the C++ standard to comment on this for sure, but I suspect that you should be including <code>cstdint</code> explicity in <code>integer.h</code> rather than counting on a different header to pull it in.</p>\n\n<hr>\n\n<p><strong><code>integer(std::string str, int base)</code></strong></p>\n\n<p>This method has a few things going on.</p>\n\n<p>I would try to avoid copying the string. That will of course require changing the body of the constructor.</p>\n\n<p><code>base</code> should have an unsigned type. A negative base has no meaning.</p>\n\n<p><code>str</code> shadows the method called <code>str</code>. In this situation, it doesn't matter, but shadowing should typically be avoided. (For what it's worth, I always compile with <code>-Wshadow</code>.)</p>\n\n<hr>\n\n<p><strong>match types where possible</strong></p>\n\n<p>In situations like:</p>\n\n<pre><code>for (unsigned int x = 0; x &lt; str.size(); x++)\n</code></pre>\n\n<p>You should consider using:</p>\n\n<pre><code>for (std::string::size_type x = 0; x &lt; str.size(); x++)\n</code></pre>\n\n<p>Also, since str.size() isn't changing, you should consider using:</p>\n\n<pre><code>for (std::string::size_type x = 0, s = str.size(); x &lt; s; ++x)\n</code></pre>\n\n<hr>\n\n<p><strong><code>integer(std::string str, int base)</code> suggestion</strong></p>\n\n<p>I would get rid of the <code>temp</code> and rewrite it to be iterator based. This would end up being a lot more flexible while maintaining the existing functionality (and performance should be either the same, or very, very similar).</p>\n\n<pre><code>template &lt;typename Iterator&gt;\ninteger(Iterator start, const Iterator&amp; end, uint16_t base)\n{\n if (start == end) {\n return;\n }\n if (*start == '-') {\n SIGN = true;\n ++start;\n }\n\n switch (base) {\n case 2:\n while (start != end) {\n *this = (*this &lt;&lt; 1) + (*start - '0');\n ++start;\n }\n break;\n case 8:\n while (start != end) {\n *this = (*this &lt;&lt; 3) + (*start - '0');\n ++start;\n }\n break;\n case 10:\n while (start != end) {\n *this = (*this &lt;&lt; 3) + (*this &lt;&lt; 1) + (*start - '0');\n ++start;\n }\n break;\n case 16:\n while (start != end) {\n *this &lt;&lt;= 4;\n if (std::isxdigit(*start)) {\n if (std::isupper(*start)) {\n //A-F\n *this += (*start - 'A') + 10;\n } else if (std::isdigit(*start)) {\n //0-9\n *this += *start - '0';\n } else {\n //a-f\n *this += (*start - 'a') + 10;\n }\n } else {\n throw std::runtime_error(\"Character not between 'a' and 'f' found\");\n }\n ++start;\n }\n break;\n case 256:\n while (start != end) {\n this-&gt;value.push_back(*start);\n ++start;\n }\n break;\n default:\n throw std::runtime_error(\"Unknown base provided (must be 2,8, 10, 16 or 256)\");\n break;\n }\n}\n\n/**\n *\n * @param val The value the integer should take\n * @param base The base that val is in\n */\ninteger(const std::string&amp; val, uint16_t base) : integer(val.begin(), val.end(), base)\n{ }\n</code></pre>\n\n<p>An example of how this could be more flexible:</p>\n\n<pre><code>const char* str = \"ffff\";\ninteger i(str, str+4, 16);\n</code></pre>\n\n<p>Or even:</p>\n\n<pre><code>const char* str = \"0xffff\";\ninteger i(str+2, str+6, 16);\n</code></pre>\n\n<p>The performance of this is still potentially bad for large containers. For example, <code>*this = (*this &lt;&lt; 3) + (*this &lt;&lt; 1) + (*start - '0');</code> is going to end up doing a lot of extra work.</p>\n\n<p>You could rewrite this to use methods that do not copy instead of operators to have better performance.</p>\n\n<hr>\n\n<p><strong><code>add</code>/<code>sub</code>/etc</strong></p>\n\n<p>I would make methods that operate on their own objects instead of other objects. For example, instead of <code>integer add(integer &amp; lhs, integer &amp; rhs)</code> (which should probably be <code>integer add(const integer &amp; lhs, const integer &amp; rhs)</code>), I would have something like:</p>\n\n<pre><code>void add(integer &amp; rhs) {\n //add rhs to this\n}\n</code></pre>\n\n<p>That way you're given a choice of whether or not you want to make a copy. Let's revisit the constructor I talked about for a minute:</p>\n\n<pre><code>*this = (*this &lt;&lt; 1) + (*start - '0');\n</code></pre>\n\n<p>This can be de-prettified into:</p>\n\n<pre><code>this-&gt;operator=(this-&gt;operator+(this-&gt;operator&lt;&lt;(1), *start - '0'));\n</code></pre>\n\n<p>And this is being run for <em>every</em> character in the string. Binary strings get huge very quickly, so this going to be doing a lot of copying.</p>\n\n<p>Consider instead if there were methods that acted on the actual object:</p>\n\n<pre><code>this-&gt;shiftLeft(1);\nthis-&gt;add(*start - '0');\n</code></pre>\n\n<p>If a copy needed to be made, it of course still could be:</p>\n\n<pre><code>integer copy(*this);\ncopy.shiftLeft(1);\ncopy.add(*start - '0');\n</code></pre>\n\n<hr>\n\n<p><strong>Note</strong></p>\n\n<p>This is incomplete at the moment. I've ran out of time, and am not sure when I'll be available to revisit this. I do plan on looking through the code more in the future though as I've only had a chance to glance through the entirety and then closely examine a few methods.</p>\n\n<hr>\n\n<p><strong>UPDATE #1</strong></p>\n\n<p><strong>operator= self assignment</strong></p>\n\n<p>You should always check for self assignment in operator=. It would actually be harmless in your situation assuming that deque didn't choke on it, but it's still good practice:</p>\n\n<pre><code>integer &amp; operator=(integer rhs) {\n if (&amp;rhs != this) {\n value = rhs.value;\n SIGN = rhs.SIGN;\n }\n return *this;\n}\n</code></pre>\n\n<p><strong>UPDATE #2</strong></p>\n\n<p><strong>Potential infinite loop (and undefined behavior) in signed primitive constructors</strong></p>\n\n<p>There's a potential infinite loop in your constructors of signed primitive types.</p>\n\n<p>The fatal mistake is that <code>-x</code> is not well defined when <code>-x</code> is the largest negative number for the type of x.</p>\n\n<p>Concrete example:</p>\n\n<pre><code>integer(int32_t rhs) {\n //assume rhs = -2147483648; //-2^31\n _sign = (rhs &lt; 0);\n if (rhs &lt; 0)\n rhs = -rhs;\n //int32_t is not guaranteed to be able to hold +2147483648\n while (rhs) {\n _value.push_front(rhs &amp; 255);\n rhs &gt;&gt;= 8;\n }\n}\n</code></pre>\n\n<p>To fix it, just use a proper unsigned type when you flip the sign:</p>\n\n<pre><code>integer(int32_t rhs) {\n _sign = (rhs &lt; 0);\n uint32_t mag = _sign ? -rhs : rhs;\n while (mag) {\n _value.push_front(mag &amp; 255);\n mag &gt;&gt;= 8;\n }\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Be very careful with for loops</strong></p>\n\n<p>When working with primitives or non expressions, it doesn't matter, but when working with performance critical code, you should always remember to use pre-increment and avoid putting non-constant expressions as a for loop's condition.</p>\n\n<p>For example:</p>\n\n<pre><code>for (integer i = 0; i &lt; (shift &gt;&gt; 3); i++)\n</code></pre>\n\n<p>I would write as:\n for (integer i = 0, s = shift >> 3; i &lt; s; ++i)</p>\n\n<p>operator++(int) creates a copy whereas operator++() does not.</p>\n\n<p>This can be optimized out, but it is not guaranteed to be.</p>\n\n<p>(The same with the <code>shift &gt;&gt; 3</code>. I could be wrong on this, but since <code>shift</code> is not <code>const</code>, I do not believe that the compiler is required to optimize that.)</p>\n\n<hr>\n\n<p><strong>flipping a bool</strong></p>\n\n<pre><code>out.SIGN ^= true;\n</code></pre>\n\n<p>I would use:</p>\n\n<pre><code>out.SIGN = !out.SIGN;\n</code></pre>\n\n<p>It's sometimes useful to remember that true and false are really just 1 and 0, but using bitwise operators to flip a bool just looks odd.</p>\n\n<hr>\n\n<p><strong>Comments</strong></p>\n\n<p>I would probably comment a few things. In particular, I would use docblocks for all public methods.</p>\n\n<p>I'm not quite sure what twos_complement does, for example.</p>\n\n<hr>\n\n<p><strong>const correctness (revisited)</strong></p>\n\n<p>I've already mentioned this, but after looking through the code more indepth, I feel that it needs much more attention.</p>\n\n<p>The basic gist of cost correctness is to default to const and then have something be non-const only when it is going to be mutated. For example, any method that is a getter or in general just doesn't change the state of an object should be const:</p>\n\n<pre><code>type method() const;\n</code></pre>\n\n<p>Any parameter that is not modified should be a constant reference:</p>\n\n<pre><code>type method(const T&amp;);\n</code></pre>\n\n<p>(Also, a good reason to default to const is that it's a <strong>huge</strong> pain to fix const correctness in large code bases. In fact, I tried to fix it in a few places in your code for examples, and even one little change requires fixing basically all of it.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T01:36:38.943", "Id": "21736", "Score": "0", "body": "About the copying, like in `integer(std::string str, int base)` and `operator+()`: what about if i want to do inline conversions from strings to integers? should i add an overload for `integer(std::string & str, int base)`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T01:39:41.247", "Id": "21737", "Score": "0", "body": "@calccrypto Am not sure if I understand your question correctly? I think I understand what you mean by inlining conversions from strings to integers (allowing `\"100\"` to be implicitly converted to `integer(100)`), and I understand what you mean about the copying (the `operator<<` and `operator+` creating copies), but I'm not sure how the two are linked?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T01:49:50.300", "Id": "21738", "Score": "0", "body": "wont those operators have pass by reference arguments? won't that make inline conversions not work? `integer operator+(integer & rhs)` -> `some integer + integer(f())`, where f returns a string" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T02:01:14.817", "Id": "21739", "Score": "0", "body": "@calccrypto Oh, so you mean if a `void add(integer& rhs)` method existed, you're afraid that `x.add(\"10\")` wouldn't be valid? It's actually not valid now as there's no constructor that takes only a string. For that to happen, you'd need a default value for `base` in the `integer (str, base)` constructor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T02:09:34.770", "Id": "21740", "Score": "0", "body": "no. im not trying to add a string directly to an integer. However, i do want to convert it to an integer first. wont this: `some_preexisting_integer + integer(5)` (int constructor) not work because `operator+` be pass by reference?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T02:11:38.973", "Id": "21741", "Score": "0", "body": "@calccrypto So you mean like: `integer x(5); string y(\"10\"); integer z = x + y;`? Sorry for the frustration, but I think I'm still not getting it... :(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T02:14:06.840", "Id": "21742", "Score": "0", "body": "sorry. i pressed enter for newline by accident. i modified the previous comment. im trying to modify it again, but it wont let me, so: no. wont this: `some_preexisting_integer + integer(5)` (any temporary integer) not work because `operator+` be pass by reference?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T02:20:23.117", "Id": "21744", "Score": "0", "body": "@calccrypto operator+ is typically pass by reference but returns a value. `integer operator+(integer rhs)` This creates an unnecessary copy of `rhs` since rhs should not be modified inside of this. Instead, `rhs` should be passed by a const reference. Like: `integer operator+(const integer& rhs)`. I think the confusion here might be an assumption that you cannot pass something by reference that doesn't actually exist in a variable? For example, do you think the following is possible: `void f(const int& i) { } f(5);`? It *is* possible (and normal), and I think this is the confusion?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T02:22:57.420", "Id": "21745", "Score": "0", "body": "(Ran out of characters on my previous comment.) It is worth noting though that `void f(int& i) { } f(5);` is *not* valid since an rvalue cannot be used as a non-const reference." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T02:26:51.673", "Id": "21746", "Score": "0", "body": "Yeah. This time I think you got it. Sorry for not being able to explain myself properly. I did not know that. Thanks! and i call myself a programmer **:(**" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T02:30:13.183", "Id": "21747", "Score": "0", "body": "@calccrypto No problem haha. I'm bad at communicating about programming via text, especially C++, since everything is so damn similar in terminology :). Anyway, just one of the many reasons to strive for const correctness :)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T19:05:04.220", "Id": "21797", "Score": "0", "body": "Updated integer.h with most of your suggestions. Hopefully I didnt do anything wrong. Unfortunately, some functions could not be const correct. oh well. ill figure it out later on. Thanks so much!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T00:40:54.293", "Id": "21813", "Score": "0", "body": "@calccrypto Have looked back through the code and nothing jumped out at me this time. I did, however, notice that there's 8 overloads for a lot of different methods. I wrote a second answer on how to reduce that a bit." } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T01:00:47.177", "Id": "13452", "ParentId": "13424", "Score": "7" } }, { "body": "<p>The duplicated constructors and operators have been bugging me, so I have a few suggestions to reduce code repetition.</p>\n\n<p>(Note that about half of them are untested.)</p>\n\n<hr>\n\n<p><strong>Constructor #1</strong></p>\n\n<p>In C++, it's valid for an integeral type to be implicitly expanded to a larger integeral type.</p>\n\n<p>For example:</p>\n\n<pre><code>void f(int64_t x) { }\nvoid g(uint64_t x) { }\nint16_t a = -12;\nint64_t b = a; //Completely valid -- no warnings\nf(a); //Completely valid -- no warnings\ng(a); //Completely valid -- no warnings\n</code></pre>\n\n<p>If you read that carefully, the <code>g</code> line probably made you go \"what?!\"</p>\n\n<p>Even weirder:</p>\n\n<pre><code>void f1(int64_t x) { }\nvoid f1(uint64_t x) { }\n\nf1(5); //Error -- int -&gt; uint64_t and int -&gt; int64_t are equally valid conversions\n</code></pre>\n\n<p>This has two implications (one useful, one that makes me scratch my head as to why C++ did this):\n* You don't need a different overload for every integeral type -- just the largest one\n* If signed and unsigned matter, then you actually do need an overload for every integral type</p>\n\n<p>There is, however, the option for templates:</p>\n\n<pre><code>template &lt;typename Numeric&gt;\ninteger(const Numeric&amp; val)\n{\n\n //Can only be negative if the type is signed and the val is less than 0\n _sign = (std::numeric_limits&lt;Numeric&gt;::is_signed &amp;&amp; val &lt; 0);\n\n //mag will be of type unsigned Numeric\n typename std::make_unsigned&lt;Numeric&gt;::type mag;\n mag = _sign ? -val : val;\n\n //Could just use 255, but might as well go for generic while we'ere at it\n base256::value_type mask = std::numeric_limits&lt;base256::value_type&gt;::max();\n\n while (mag) {\n digits.push_front(mag &amp; mask);\n //digits will be the number of digits in whatever the underlying\n //radix is. (In other words, this will be the number of bits for\n //unsigned integral types.)\n mag &gt;&gt;= std::numeric_limits&lt;base256::value_type&gt;::digits;\n }\n\n}\n</code></pre>\n\n<p>This looks a little odd at first, but it just uses some template features of C++ to determine the type.</p>\n\n<p>Also, since only numeric types (or types that have specialized the templates themselves) will have make_unsigned and family defined, this constructor can't be accidentally used for a string or double.</p>\n\n<hr>\n\n<p><strong>Constructor #2</strong></p>\n\n<pre><code>integer(bool s, const base256 &amp; val)\n</code></pre>\n\n<p>If you flip this around, you can combine it with the constructor above it:</p>\n\n<pre><code>integer(const base256 &amp; val, bool s = false): _sign(s), digits(val){\n trim();\n if (digits.empty()) {\n _sign = false;\n }\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Constructor #3</strong></p>\n\n<pre><code> //need at least gcc 4.7 to compile this line, otherwise use uncommented version\n //integer(const std::string &amp; val, uint16_t base): integer(val.begin(), val.end(), base) {}\n integer(const std::string &amp; val, uint16_t base){\n *this = integer(val.begin(), val.end(), base);\n }\n</code></pre>\n\n<p>Aside from unnecessarily requiring 4.7 (nothing here warrants breaking non-C++11 compatibility), this is wrong.</p>\n\n<pre><code>integer(const std::string &amp; val, uint16_t base) : integer(val.begin(), val.end(), base) {}\n</code></pre>\n\n<p>And:</p>\n\n<pre><code>integer(const std::string &amp; val, uint16_t base){\n *this = integer(val.begin(), val.end(), base);\n}\n</code></pre>\n\n<p>Do completely different things.</p>\n\n<p>Imagine this code:</p>\n\n<pre><code>integer i(\"1000\", 10);\n</code></pre>\n\n<p>The first one silently converts this to:</p>\n\n<pre><code>const std::string s = \"1000\";\ninteger i(s.begin(), s.end(), 10);\n</code></pre>\n\n<p>There is no extra work here. There is no un-needed copying or anything of that nature.</p>\n\n<p>Now the second one silently converts to (oversimplifying this a bit by the way):</p>\n\n<pre><code>const std::string s = \"1000\";\ninteger temp(s.begin(), s.end(), 10);\ninteger i(temp);\n</code></pre>\n\n<p>In other words, temp is copied for no reason.</p>\n\n<hr>\n\n<p><strong>operator=</strong></p>\n\n<p>The same type of template-use can reduce the number of operator= overloads from 9 to 2. I would refactor the main part of the constructor into a private method and then use that private method in the constructor and operator=:</p>\n\n<pre><code>template &lt;typename Numeric&gt;\nvoid setFromNumeric(const Numeric&amp; val)\n{\n\n digits.clear();\n\n //Can only be negative if the type is signed and the val is less than 0\n _sign = (std::numeric_limits&lt;Numeric&gt;::is_signed &amp;&amp; val &lt; 0);\n\n //mag will be of type unsigned Numeric\n typename std::make_unsigned&lt;Numeric&gt;::type mag;\n mag = _sign ? -val : val;\n\n //Could just use 255, but might as well go for generic while we'ere at it\n base256::value_type mask = std::numeric_limits&lt;base256::value_type&gt;::max();\n\n while (mag) {\n digits.push_front(mag &amp; mask);\n //digits will be the number of digits in whatever the underlying\n //radix is. (In other words, this will be the number of bits for\n //unsigned integral types.)\n mag &gt;&gt;= std::numeric_limits&lt;base256::value_type&gt;::digits;\n }\n\n}\n\ntemplate &lt;typename Numeric&gt;\ninteger(const Numeric&amp; val)\n{\n setFromNumeric(val);\n}\n\ntemplate &lt;typename Numeric&gt;\ninteger&amp; operator=(const Numeric&amp; val)\n{\n setFromNumeric(val);\n return *this;\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Potential bug</strong></p>\n\n<p>I'm guessing that in operator+:</p>\n\n<pre><code>out = _sign;\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>out._sign = _sign;\n</code></pre>\n\n<hr>\n\n<p><strong>operator&lt;&lt;</strong></p>\n\n<p>This one you can heavily reduce without having to use templates. You only need:</p>\n\n<pre><code>integer operator&lt;&lt;(uint64_t shift)\n</code></pre>\n\n<p>That's the only operator&lt;&lt; that you need since anything smaller than a uint64_t will be upcasted to a uint64_t (even signed types).</p>\n\n<p>This same concept applies to <code>operator&lt;&lt;=</code> and so on.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T01:14:16.327", "Id": "21814", "Score": "0", "body": "wow so much stuff. Im modifying some of the stuff now. About that constructor needing gcc 4.7. its not that the method isnt in C++11. its that it wasnt implemented in gcc until 4.7: http://stackoverflow.com/questions/11391108/c-class-is-not-base-of-itself" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T01:47:40.530", "Id": "21817", "Score": "0", "body": "I have a slight problem with your operator=: i cant add booleans anymore, since booleans dont have signs. i have to change all of them to ints, but theres so many of them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T01:56:47.617", "Id": "21818", "Score": "0", "body": "Now i remember why I have so many overloads: when i compile integer, hundreds of warnings appear about ambiguity. i guess i didnt want to see them every time. Also, they take more time to display than compiling the program does" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T02:12:53.010", "Id": "21819", "Score": "1", "body": "@calccrypto Ah I understood that comment backwards then. Sorry about that. Didn't realize that calling a different constructor was new in C++11. And booleans don't have the numeric_limits defined, though you could use a more specific operator to handle them. As for the ambiguity, there must be something else going on, because nothing about it should be ambiguous. Will look into it in a few hours when I get a chance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T02:14:28.890", "Id": "21820", "Score": "0", "body": "Most of the ambiguity is from operator<< and >> (the bit shifts, not iostreams) when the other overloads are removed. i have a few `>> 3`s laying around" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T02:35:16.167", "Id": "21823", "Score": "0", "body": "I might also have been worried that some wise*** (aka me) might put in non-integral types into templates, and see it integer's reaction, and i specifically wanted to not allow that to happen. now that they **are** templated, the warnings are all gone" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T23:39:13.863", "Id": "21896", "Score": "1", "body": "@calccrypto Hmm so with the ambiguous `>> 3` type stuff, I wonder why that's ambiguous. I guess it can't decide between converting up to a uint64_t or converting to an `integer(3)`? Anyway, the templated operator= and ctor I provided will give an error at compile time for any non numeric type. Basically a specialization of numeric_limits needs to exist for the type or there will be a compile error." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T00:40:00.613", "Id": "13485", "ParentId": "13424", "Score": "5" } } ]
{ "AcceptedAnswerId": "13452", "CommentCount": "16", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T23:17:09.547", "Id": "13424", "Score": "5", "Tags": [ "c++", "integer" ], "Title": "Improving a custom integer class 2.0" }
13424
<p>After the purpose and specifications of software are determined, software developers will design or employ designers to develop a plan for a solution. It includes low-level component and algorithm implementation issues as well as the architectural view.</p> <p><strong>Software design topics</strong></p> <ul> <li><p>Design concepts</p> <blockquote> <p>The design concepts provide the software designer with a foundation from which more sophisticated methods can be applied. A set of fundamental design concepts has evolved.</p> </blockquote></li> <li><p>Design considerations</p> <blockquote> <p>There are many aspects to consider in the design of a piece of software. The importance of each should reflect the goals the software is trying to achieve.</p> </blockquote></li> <li><p>Modeling language</p> <blockquote> <p>A modeling language is any artificial language that can be used to express information or knowledge or systems in a structure that is defined by a consistent set of rules. The rules are used for interpretation of the meaning of components in the structure. A modeling language can be graphical or textual.</p> </blockquote></li> </ul> <p>An more comprehensive description can be found at <a href="http://en.wikipedia.org/wiki/Software_design#Software_design_topics" rel="nofollow">Wikipedia :: Software design topics</a>.</p> <hr> <p><strong>Software Design Principles</strong></p> <p>Software design principles represent a set of guidelines that helps us to avoid having a bad design. The design principles are associated to <a href="http://www.objectmentor.com/omTeam/martin_r.html" rel="nofollow">Robert Martin</a> who gathered them in "<a href="http://books.google.pt/books/about/Agile_Software_Development.html?id=0HYhAQAAIAAJ&amp;redir_esc=y" rel="nofollow">Agile Software Development: Principles, Patterns, and Practices</a>". According to Robert Martin there are 3 important characteristics of a bad design that should be avoided:</p> <ul> <li><p>Rigidity</p> <p>It is hard to change because every change affects too many other parts of the system.</p></li> <li><p>Fragility</p> <p>When you make a change, unexpected parts of the system break.</p></li> <li><p>Immobility</p> <p>It is hard to reuse in another application because it cannot be disentangled from the current application.</p></li> </ul> <hr> <p><strong>Interesting reading:</strong></p> <ul> <li><p><a href="http://www.bleading-edge.com/Publications/C++Journal/Cpjour2.htm" rel="nofollow">What is Software Design?</a> <em>by</em> <a href="http://c2.com/cgi/wiki?JackReeves" rel="nofollow">Jack W. Reeves</a> ©C++ Journal - 1992 </p></li> <li><p><a href="http://c2.com/cgi/wiki?TheSourceCodeIsTheDesign" rel="nofollow">The Source Code Is The Design</a></p></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T23:33:14.987", "Id": "13425", "Score": "0", "Tags": null, "Title": null }
13425
Software design is a process of problem solving and planning for a software solution.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T23:33:14.987", "Id": "13426", "Score": "0", "Tags": null, "Title": null }
13426
<p>An HTML form is a section of a document containing normal content, markup, special elements called controls (checkboxes, radio buttons, menus, etc.), and labels on those controls.</p> <p>Users generally "complete" a form by modifying its controls (entering text, selecting menu items, etc.), before submitting the form to an agent for processing (e.g., to a Web server, to a mail server, etc.)</p> <p><strong>Example:</strong></p> <pre><code>&lt;FORM action="http://somesite.com/prog/adduser" method="post"&gt; &lt;P&gt; &lt;LABEL for="firstname"&gt;First name: &lt;/LABEL&gt; &lt;INPUT type="text" id="firstname"&gt;&lt;BR&gt; &lt;LABEL for="lastname"&gt;Last name: &lt;/LABEL&gt; &lt;INPUT type="text" id="lastname"&gt;&lt;BR&gt; &lt;LABEL for="email"&gt;email: &lt;/LABEL&gt; &lt;INPUT type="text" id="email"&gt;&lt;BR&gt; &lt;INPUT type="radio" name="sex" value="Male"&gt; Male&lt;BR&gt; &lt;INPUT type="radio" name="sex" value="Female"&gt; Female&lt;BR&gt; &lt;INPUT type="submit" value="Send"&gt; &lt;INPUT type="reset"&gt; &lt;/P&gt; &lt;/FORM&gt; </code></pre> <p><a href="http://www.w3.org/TR/html401/interact/forms.html" rel="nofollow">Official documentation</a> is maintained by the World Wide Web Consortium (<a href="http://www.w3.org/" rel="nofollow">W3C</a>).</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T23:56:11.570", "Id": "13427", "Score": "0", "Tags": null, "Title": null }
13427
An HTML form is a section of a document containing normal content, markup, special elements called controls and labels on those controls.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T23:56:11.570", "Id": "13428", "Score": "0", "Tags": null, "Title": null }
13428
<p>Programming style aka <em>code style</em> or <em>coding style</em>, is a set of rules or guidelines used when writing the source code for a computer program.</p> <p>It is often claimed that following a particular programming style will help programmers to read and understand source code conforming to the style, and help to avoid introducing errors.</p> <p><strong>References to coding styles:</strong></p> <ul> <li><p><a href="http://source.android.com/source/code-style.html" rel="nofollow">Android Code Style Guidelines for Contributors</a></p></li> <li><p><a href="http://geosoft.no/development/cppstyle.html/" rel="nofollow">C++ Programming Style Guidelines</a></p></li> <li><p><a href="http://pear.php.net/manual/en/standards.php" rel="nofollow">PHP Pear Coding Standards</a></p></li> <li><p><a href="http://www.extremeperl.org/bk/coding-style" rel="nofollow">Extreme Perl: Chapter 10: Coding Style</a></p></li> <li><p><a href="https://github.com/ginatrapani/ThinkUp/wiki/Code-Style-Guide%3a-HTML" rel="nofollow">HTML Code Style Guide</a></p></li> <li><p><a href="http://google-styleguide.googlecode.com/svn/trunk/htmlcssguide.xml#CSS_Style_Rules" rel="nofollow">CSS Style Guide</a></p></li> <li><p><a href="http://geosoft.no/development/javastyle.html" rel="nofollow">Java Programming Style Guidelines</a></p></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T00:18:02.497", "Id": "13429", "Score": "0", "Tags": null, "Title": null }
13429
Programming style is a set of rules or guidelines used when writing the source code for a computer program.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T00:18:02.497", "Id": "13430", "Score": "0", "Tags": null, "Title": null }
13430
<p><a href="http://en.wikipedia.org/wiki/Comma-separated_values" rel="nofollow">Comma-separated values</a> is a common, relatively simple file format that is widely supported by consumer, business, and scientific applications. Among its most common uses is moving tabular data between programs that natively operate on incompatible (often proprietary and/or undocumented) formats. This works because so many programs support some variation of CSV at least as an alternative import/export format.</p> <p>CSV formats are best used to represent sets or sequences of records in which each record has an identical list of fields. This corresponds to a single relation in a relational database, or to data (though not calculations) in a typical spreadsheet.</p> <hr> <p><strong>Basic rules</strong></p> <p><a href="http://www.ietf.org/rfc/rfc4180.txt" rel="nofollow">RFC 4180</a> attempts to standardize CSV, but many programs do not follow the standard strictly.</p> <ul> <li><p>CSV is a delimited data format that has fields/columns separated by the comma character and records/rows terminated by newlines.</p></li> <li><p>A CSV file does not require a specific character encoding, byte order, or line terminator format (some software does not support all line-end variations).</p></li> <li><p>A record ends at a line terminator. However, line-terminators can be embedded as data within fields, so software must recognize quoted line-separators (see below) in order to correctly assemble an entire record from perhaps multiple lines.</p></li> <li><p>All records should have the same number of fields, in the same order.</p></li> <li><p>Fields may be quoted, usually with double quotes, to allow literal commas to be represented.</p></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T00:38:39.863", "Id": "13432", "Score": "0", "Tags": null, "Title": null }
13432
A comma-separated values (CSV) file stores tabular data (numbers and text) as plain text, with rows and columns delimited by line terminators and commas, respectively. You may also use this tag for variants where fields are separated by tabs or semicolons.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T00:38:39.863", "Id": "13433", "Score": "0", "Tags": null, "Title": null }
13433
<p>I am using an Xbox controller to send data to my computer, and am using the <code>SendInput</code> method to handle keys. I was wondering if there was any other, better way to do this. </p> <pre><code>INPUT Input = { 26 }; Input.type = INPUT_KEYBOARD; Input.ki.dwFlags = VK_UP; SendInput(1, &amp;Input, sizeof(INPUT)); std::cout &lt;&lt; "Up"; </code></pre>
[]
[ { "body": "<p>Are you wanting to direct this to a specific application? It's usually better to send <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms646280%28v=vs.85%29.aspx\" rel=\"nofollow\"><code>WM_KEYDOWN</code></a> and/or <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms646281%28v=vs.85%29.aspx\" rel=\"nofollow\"><code>WM_KEYUP</code></a> using the <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms644950%28v=vs.85%29.aspx\" rel=\"nofollow\"><code>SendMessage</code></a> function.</p>\n\n<p>If not, then I would suggest using the <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms646304%28v=vs.85%29.aspx\" rel=\"nofollow\"><code>keybd_event</code></a> function. You can find some good examples on <a href=\"http://www.codeproject.com/Articles/7305/Keyboard-Events-Simulation-using-keybd_event-funct\" rel=\"nofollow\">Code Project</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T06:00:09.010", "Id": "13440", "ParentId": "13439", "Score": "2" } } ]
{ "AcceptedAnswerId": "13440", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T02:38:44.577", "Id": "13439", "Score": "1", "Tags": [ "c++" ], "Title": "Is there a better way to use SendInput?" }
13439
<p><em><a href="https://github.com/Onheiron/foRml" rel="nofollow">GitHub project repo</a></em></p> <p>I've been working on this little function to convert an HTML form into a JSON Object having the same structure of the form. Basically it is intended to be useful in those situations where you let your user dynamically alter the structure of your form, for examle:</p> <pre><code> &lt;form name="myForm" data-detect="true"&gt; &lt;label for="myForm"&gt;Form&lt;/label&gt; &lt;input name="myFirstName" placeholder="myFirstName"/&gt; &lt;input name="mySecondName" placeholder="mySecondName"/&gt; &lt;input name="myLastName" placeholder="myLastName"/&gt; &lt;fieldset name="myLibrary"&gt; &lt;legend&gt;Library&lt;/legend&gt; &lt;input name="myLibraryName" placeholder="myLibraryName"/&gt; &lt;select name="myLibraryGenre"&gt; &lt;option value="SciFi"&gt;Sci-Fi&lt;/option&gt; &lt;option value="Horror"&gt;Horror&lt;/option&gt; &lt;option value="Manuals"&gt;Manuals&lt;/option&gt; &lt;option value="Comics"&gt;Comics&lt;/option&gt; &lt;/select&gt; &lt;fieldset name="myBook"&gt; &lt;legend&gt;Book&lt;/legend&gt; &lt;input name="myBookTitle" placeholder="myBookTitle"/&gt; &lt;input name="myBookDate" type="date" placeholder="myBookDate"/&gt; &lt;input name="myBookEditor" placeholder="myBookEditor"/&gt; &lt;br/&gt; &lt;input name="myFavouriteQuote" placeholder="myFavouriteQuote"/&gt; &lt;input name="myFavouriteQuote" placeholder="myFavouriteQuote"/&gt; &lt;input name="myFavouriteQuote" placeholder="myFavouriteQuote"/&gt; &lt;input name="myFavouriteQuote" placeholder="myFavouriteQuote"/&gt; &lt;/fieldset&gt; &lt;fieldset name="myBook"&gt; &lt;legend&gt;Book&lt;/legend&gt; &lt;input name="myBookTitle" placeholder="myBookTitle"/&gt; &lt;input name="myBookDate" type="date" placeholder="myBookDate"/&gt; &lt;input name="myBookEditor" placeholder="myBookEditor"/&gt; &lt;br/&gt; &lt;input name="myFavouriteQuote" placeholder="myFavouriteQuote"/&gt; &lt;input name="myFavouriteQuote" placeholder="myFavouriteQuote"/&gt; &lt;input name="myFavouriteQuote" placeholder="myFavouriteQuote"/&gt; &lt;input name="myFavouriteQuote" placeholder="myFavouriteQuote"/&gt; &lt;/fieldset&gt; &lt;/fieldset&gt; &lt;input type="submit" value="Submit me!"&gt; &lt;/form&gt; </code></pre> <p>where user can add more favourite quotes, or add more books or even more libraries dynamically using jQuery to add form parts and assigning the new inputs names to be those shown in the above three example, i.e. a new fav. quote input text will have name="myFavouriteQuote" and so on.</p> <p>Done this you want to grab your datas so you can send them over to a server scipt in a way that keeps the original data structure created within the form using fieldsets as in the example.</p> <p>So a JSON rapresentation of the Object would be for example:</p> <pre><code>{ "myFirstName":"Carlo", ..., "myBook":[ { "myBookTitle":"some title" ..., "myFavouriteQuote":[ {0:"quote1"}, {1:"quote2"}, ... ] }, ... ] } </code></pre> <p>This because the final goal is to send this object to a server side php script which will convert the correctly nested data array to an XML file representing the exact structure of the form (where the tag names will be the elements' 'name' attributes).</p> <p>To do so I basically select the form with $("[data-detect]") and pass it as the node parameter to my toJSON function:</p> <pre><code>function toJSON(node){ if($(node).children().length == 0) return $(node).val(); var json = new Object(); $(node).children("[name]").each(function(){ name = $(this).attr('name'); if($(node).children("[name="+name+"]").length &gt; 1){ if(!json[name]) json[name] = []; json[name].push(toJSON(this)); }else if(($(this).children(':not(option)').length &gt; 0)){ json[name] = toJSON(this); }else{ json[name] = $(this).val(); } }); return json; } </code></pre> <p>so like : </p> <pre><code>myJSONDatas = toJSON($("[data-detect]")); </code></pre> <p>Is there any way I can improve my function? How could I modify this to handle combo and radio boxes?</p> <p><strong>EDIT</strong></p> <p>I rewrote the function as a jQuery plugin and improved it a bit:</p> <pre><code>$.fn.toJSON = function() { if(!this.children().length) return this.val(); var json = new Object(); this.children('[name]').each(function(){ if($(this).siblings("[name="+$(this).attr('name')+"]").length){ if(!json[$(this).attr('name')]) json[$(this).attr('name')] = []; json[$(this).attr('name')].push($(this).toJSON()); }else if($(this).children('[name]').length){ json[$(this).attr('name')] = $(this).toJSON(); }else{ json[$(this).attr('name')] = $(this).val(); } }); return json; }; </code></pre> <p>now the call will be simply </p> <pre><code>myJSONForm = $("[data-detect]").toJSON(); </code></pre> <p><strong>EDIT 2</strong></p> <p>I added support for checkbox and radio input. Plus I replaced all those $(this).attr('name'); in code.</p> <pre><code>$.fn.toJSON = function() { if(!this.children().length) return this.val(); var json = new Object(); this.children('[name]').each(function(){ var name = $(this).attr('name'); var type = $(this).attr('type'); if($(this).siblings("[name="+name+"]").length){ if( type == 'checkbox' &amp;&amp; !$(this).prop('checked')) return true; if( type == 'radio' &amp;&amp; !$(this).prop('checked')) return true; if(!json[name]) json[name] = []; json[name].push($(this).toJSON()); }else if($(this).children('[name]').length){ json[name] = $(this).toJSON(); }else{ json[name] = $(this).val(); } }); return json; }; </code></pre> <p>Is this really returning a JSON object? What is the difference with a regular JS Objects?</p> <p><strong>LAST EDIT</strong></p> <p>Here is my last edit since I think this is as concise as my brain can go. Basically I deleted that double this.children.length check:</p> <pre><code>$.fn.toJSO = function() { if(!this.children('[name]').length) return this.val(); var jso = new Object(); this.children('[name]').each(function(){ var name = $(this).attr('name'); var type = $(this).attr('type'); if($(this).siblings("[name="+name+"]").length){ if( type == 'checkbox' &amp;&amp; !$(this).prop('checked')) return true; if( type == 'radio' &amp;&amp; !$(this).prop('checked')) return true; if(!jso[name]) jso[name] = []; jso[name].push($(this).toJSO()); }else{ jso[name] = $(this).toJSO(); } }); return jso; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T17:56:17.537", "Id": "21785", "Score": "3", "body": "Have you considered [Knockout.js](http://knockoutjs.com/)? I am working on an answer specifically to this question but modification to handle combos/radios/dates/tabular data/whatever else is at least non-trivial." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-12T09:06:55.620", "Id": "21962", "Score": "2", "body": "Is it really JSON or just a JS object? By the way, your code formatting style is quite confusing and you're repeating \"$(this).attr('name')\" a lot." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-12T09:44:32.937", "Id": "21963", "Score": "0", "body": "You mean I should like assign that \"$(this).attr('name')\" to some alias to use instead? I thought about that, but is it really optimization or just \"write less\"? As for the JSON/JS Object part, I admit I have no indeep knowledge of that, but it returns a structure like the one here : http://www.json.org/js.html. How can I format my code better? is it for the extralines? thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-12T13:30:37.713", "Id": "21966", "Score": "2", "body": "Don't forget to declare your variables with `var` or they will be global." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-12T18:03:35.893", "Id": "22021", "Score": "1", "body": "Is there any difference between JavaScript literal objects and what we call JSON objects? I honestly didn't see any difference between those, this article agrees: http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/. I'm guess the big difference are functions in javascript?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-12T20:29:22.433", "Id": "22029", "Score": "0", "body": "what I figured out is JSON being JavaScript Object Notation which is the classical {\"key\":\"value\"} notation to represent an object. I guess even a string with that content can be called a JSON string. Actually in this script there's no reference to such a notation so those are simply javascript object JSO. But this is just my guess." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-16T18:39:29.780", "Id": "22176", "Score": "0", "body": "Is there any particular reason you don't use .serialize()? It appears you're re-implementing it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-16T19:58:10.207", "Id": "22183", "Score": "1", "body": "`toJSON` is correct. It's a flawed naming convention in ECMAScript. It returns the object to use when calling `JSON.stringify`: `JSON.stringify({toJSON: function () {return someVar;}}) == JSON.stringify(someVar)`" } ]
[ { "body": "<p>This is a re-implementation of jQuery's build-in <a href=\"http://api.jquery.com/serialize/\" rel=\"nofollow\">serialize()</a> function. In general I would recommend using the built-in function since the jQuery developers will keep it updated for browser compatibility and use with other jQuery functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-17T08:22:04.290", "Id": "22202", "Score": "0", "body": "I actually looked at .serialize a little more and it doesn't do exactly what I need. It seems to convert forms in \"key=value&key2=value...\" strings witho no structure at all (i know you can set a name like array[i] to make .serialize generate structured datas, but this isn't good if you want your user to just compose forms AS IF they were an XML), also it doesn't detect fieldsets and this doesn't help building the XML structures (like the <myBook> tag which is a mere container). Can you suggest me some workarounds for these problems? thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-18T14:16:59.897", "Id": "22258", "Score": "1", "body": ".serialize() will only include the forms' user input elements. So you're right that it'll ignore extra info like fieldsets. Since all of your processing must be done client side I think your custom solution (last edit) is the way to go. I haven't come across a jQuery plugin that will do anything much closer to what you need. Sorry!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-16T19:54:55.740", "Id": "13727", "ParentId": "13443", "Score": "0" } }, { "body": "<p>Here are a few enhancements that I made to your code.</p>\n\n<h1>1)</h1>\n\n<p>Cached references to <code>this</code> and <code>$(this).children('[name]')</code>.</p>\n\n<h1>2)</h1>\n\n<p>Used a regular expression to check if the element type is a radio or checkbox.</p>\n\n<h1>3)</h1>\n\n<p>In this case,</p>\n\n<pre><code>if (!jso[name])\n jso[name] = [];\n</code></pre>\n\n<p>is the same as </p>\n\n<pre><code>jso[name] = jso[name] || [];\n</code></pre>\n\n<h1>4)</h1>\n\n<p><code>var jso = new Object();</code> is the same as <code>var jso = {};</code></p>\n\n<h1>5)</h1>\n\n<p>Negated the if condition to get rid of the <code>return true</code>.</p>\n\n<pre><code>if (type == 'radio' &amp;&amp; !$(this).prop('checked')){\n return true;\n}\n//other stuff\n</code></pre>\n\n<p>becomes </p>\n\n<pre><code>if (type != 'radio' || $(this).prop('checked')){\n //other stuff\n}\n</code></pre>\n\n<h1>Final Result</h1>\n\n<pre><code>$.fn.toJSO = function () {\n var obj = {},\n $kids = $(this).children('[name]');\n if (!$kids.length) {\n return $(this).val();\n }\n $kids.each(function () {\n var $el = $(this),\n name = $el.attr('name');\n if ($el.siblings(\"[name=\" + name + \"]\").length) {\n if (!/radio|checkbox/i.test($el.attr('type')) || $el.prop('checked')) {\n obj[name] = obj[name] || [];\n obj[name].push($el.toJSO());\n }\n } else {\n obj[name] = $el.toJSO();\n }\n });\n return obj;\n};\n</code></pre>\n\n<p>Demo: <a href=\"http://jsfiddle.net/x4DjZ/\" rel=\"nofollow\">http://jsfiddle.net/x4DjZ/</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-06T05:14:14.450", "Id": "15373", "ParentId": "13443", "Score": "2" } } ]
{ "AcceptedAnswerId": "15373", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T10:51:29.593", "Id": "13443", "Score": "5", "Tags": [ "javascript", "jquery", "html", "json", "form" ], "Title": "jQuery plugin $(node).toJSON() - convert html form to JS Object" }
13443
<p>File Transfer Protocol (FTP) is a standard network protocol used to transfer files from one host to another host over a <a href="http://en.wikipedia.org/wiki/Transmission_Control_Protocol" rel="nofollow">TCP</a>-based network, such as the Internet.</p> <p>It is often used to upload web pages and other documents from a private development machine to a public web-hosting server.</p> <p>FTP is built on a client-server architecture and uses separate control and data connections between the client and the server.</p> <p>A more extensive reading can be found at <a href="http://en.wikipedia.org/wiki/FTP" rel="nofollow">Wikipedia</a>.</p> <hr> <h2><strong>Usage:</strong></h2> <ul> <li><p><strong>command-line</strong></p> <blockquote> <p>The first FTP client applications were interactive command-line tools, implementing standard commands and syntax.</p> </blockquote></li> <li><p><strong>GUI</strong></p> <blockquote> <p>Graphical user interfaces have since been developed for many of the popular desktop operating systems in use today.</p> </blockquote> <p>Some of the most popular are:</p> <ul> <li><p><a href="http://filezilla-project.org/" rel="nofollow">FileZilla</a></p></li> <li><p><a href="http://www.gftp.org/" rel="nofollow">gFTP</a></p></li> </ul> <p>A comprehensive comparative list can be found at <a href="http://en.wikipedia.org/wiki/Comparison_of_FTP_client_software" rel="nofollow">Wikipedia - Comparison of FTP client software</a>!</p></li> <li><p><strong>FTP URL</strong></p> <blockquote> <p>FTP can be used through a web browser, commonly know as FTP URL, the syntax is described in <a href="http://www.ietf.org/rfc/rfc1738.txt" rel="nofollow">RFC1738</a>, taking the following form:</p> </blockquote> <pre><code>ftp://[&lt;user&gt;[:&lt;password&gt;]@]&lt;host&gt;[:&lt;port&gt;]/&lt;url-path&gt;[13] </code></pre> <p><em>The bracketed parts are optional.</em></p> <p><strong>e.g.,</strong></p> <pre><code>ftp://public.ftp-servers.example.com/mydirectory/myfile.txt </code></pre> <p>or</p> <pre><code>ftp://user001:secretpassword@private.ftp-servers.example.com/mydirectory/myfile.txt </code></pre></li> </ul> <hr> <h2><strong>Related reading:</strong></h2> <ul> <li><a href="http://www.ietf.org/" rel="nofollow">IETF</a> RFC 959 :: <a href="http://tools.ietf.org/html/rfc959" rel="nofollow">FILE TRANSFER PROTOCOL (FTP)</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T22:46:25.787", "Id": "13445", "Score": "0", "Tags": null, "Title": null }
13445
File Transfer Protocol (FTP) is a standard network protocol used to transfer files from one host to another host over a TCP-based network, such as the Internet.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T22:46:25.787", "Id": "13446", "Score": "0", "Tags": null, "Title": null }
13446
<p>I feel like this structure could be better, but I can't realize how.</p> <pre><code> internal AuthenticationResult ProcessOpenIdResponse(IAuthenticationResponse response) { switch (response.Status) { case AuthenticationStatus.Authenticated: { string openId = response.ClaimedIdentifier; User user = userRepository.GetByOpenId(openId); bool userIsNew = false; bool connectionIsNew = false; if (user == null) { connectionIsNew = true; string email = null; string displayName = null; var fetch = response.GetExtension&lt;FetchResponse&gt;(); if (fetch != null) { email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email); displayName = fetch.GetAttributeValue(WellKnownAttributes.Name.FullName); } if (!email.NullOrEmpty()) // maybe they already have an account. { user = userRepository.GetByEmail(email); } if (user == null) // create a brand new account. { user = userRepository.CreateFromOpenId(openId, email, displayName); userIsNew = true; } else // just connect the existing account to their OpenId account. { userRepository.AddOpenIdConnection(user, openId); } } return new AuthenticationResult { Status = ConnectionStatus.Authenticated, UserIsNew = userIsNew, ConnectionIsNew = connectionIsNew, DisplayName = user.DisplayName, UserId = user.UserId }; } case AuthenticationStatus.Canceled: { return new AuthenticationResult { Status = ConnectionStatus.Canceled, Message = Common.Resources.Authentication.CanceledAtProvider }; } case AuthenticationStatus.Failed: { return new AuthenticationResult { Status = ConnectionStatus.Faulted, Message = response.Exception.Message, Exception = response.Exception }; } default: { return new AuthenticationResult { Status = ConnectionStatus.Faulted }; } } } </code></pre> <p>and another:</p> <pre><code> public AuthenticationResult AuthenticateWithFacebook(string facebookId, string accessToken) { if (facebookId == null) { throw new ArgumentNullException("facebookId"); } if (accessToken == null) { throw new ArgumentNullException("accessToken"); } dynamic response; try { FacebookClient client = new FacebookClient(accessToken); response = client.Get("me"); } catch (FacebookApiException exception) { _log.Info(Common.Resources.Error.FacebookApiException, exception); return new AuthenticationResult { Status = ConnectionStatus.Faulted, Message = exception.Message, Exception = exception }; } if (response == null) // sanity { return new AuthenticationResult { Status = ConnectionStatus.Faulted, Message = Common.Resources.Error.FacebookApiException }; } else if (response.error != null) { return new AuthenticationResult { Status = ConnectionStatus.Faulted, Message = response.error.message ?? Common.Resources.Error.FacebookApiException }; } else if (response.id != facebookId) // validate access token against facebookId for enhanced security. { return new AuthenticationResult { Status = ConnectionStatus.InvalidCredentials, Message = Common.Resources.Authentication.InvalidCredentials }; } else { User user = userRepository.GetByFacebookGraphId(facebookId); bool userIsNew = false; bool connectionIsNew = false; if (user == null) { connectionIsNew = true; string email = response.email; if (!email.NullOrEmpty()) // maybe they already have an account. { user = userRepository.GetByEmail(email); } if (user == null) // create a brand new account. { string displayName = response.name; user = userRepository.CreateFromFacebook(facebookId, accessToken, email, displayName); userIsNew = true; } else // just connect the existing account to their Facebook account. { userRepository.AddFacebookConnection(user, facebookId, accessToken); } } return new AuthenticationResult { Status = ConnectionStatus.Authenticated, UserIsNew = userIsNew, ConnectionIsNew = connectionIsNew, DisplayName = user.DisplayName, UserId = user.UserId }; } } </code></pre> <p>Just in case anyone wonders about dependencies from outside the method, here is the class:</p> <pre><code>public class AuthenticationService { private static readonly ILog _log = LogManager.GetLogger(typeof(AuthenticationService)); private readonly OpenIdRelyingParty relyingParty; private readonly IUserRepository userRepository; private readonly IMembershipProvider membershipProvider; public AuthenticationService(OpenIdRelyingParty relyingParty, IUserRepository userRepository, IMembershipProvider membershipProvider) { if (relyingParty == null) { throw new ArgumentNullException("relyingParty"); } if (userRepository == null) { throw new ArgumentNullException("userRepository"); } if (membershipProvider == null) { throw new ArgumentNullException("membershipProvider"); } this.relyingParty = relyingParty; this.userRepository = userRepository; this.membershipProvider = membershipProvider; } [...] } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T23:29:47.317", "Id": "21729", "Score": "0", "body": "Can you include the whole method that this code is in? There's much more to improve in this and we need to see the whole picture." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T23:31:59.920", "Id": "21730", "Score": "0", "body": "sure, included both complete methods, thank you. I've also added the ctor so you have a basic idea of the injected dependencies too" } ]
[ { "body": "<p>I would first start by creating a method for the Authentication failed parts of the code. Something like</p>\n\n<pre><code>private AuthenticationResult AuthenticationFailed(AuthenticationStatus status, string message = \"\", Exception exception = null)\n{\n return new AuthenticationResult\n {\n Status = status,\n Message = message,\n Exception = exception\n }\n}\n</code></pre>\n\n<p>Then your first switch for the FB authentication ends up being something like:</p>\n\n<pre><code> internal AuthenticationResult ProcessOpenIdResponse(IAuthenticationResponse response)\n {\n switch (response.Status)\n {\n case AuthenticationStatus.Authenticated:\n {\n // successfull authentication\n }\n case AuthenticationStatus.Canceled:\n {\n return AuthenticationFailed(ConnectionStatus.Canceled, Common.Resources.Authentication.CanceledAtProvider); \n }\n case AuthenticationStatus.Failed:\n {\n return AuthenticationFailed(ConnectionStatus.Faulted, response.Exception.Message, response.Exception); \n }\n default:\n {\n return AuthenticationFailed(ConnectionStatus.Faulted, response.Exception.Message, response.Exception); \n }\n }\n }\n</code></pre>\n\n<p>I would further refactored the getting of user email into it's own method as that seems to be common across both forms.</p>\n\n<pre><code>private User GetUserByEmail(string email)\n{\n return email.NullOrEmpty() ?? null : userRepository.GetByEmail(email);\n}\n</code></pre>\n\n<p>Although this might be overkill I would also consider separating the methods for doing the authentication into their own classes. I believe this may help with being able to do unit testing against each class in isolation as well as not separating the responsibilities out of whichever class is handling identifying which process to use etc. Something like this perhaps.</p>\n\n<pre><code>abstract class AuthenticationPortal\n{ \n abstract AuthenticationResult Authenticate();\n\n protected virtual User GetUserByEmail(string emailAddress)\n { \n return emailAddress.NullOrEmpty() ?? null : userRepository.GetByEmail(emailAddress); \n }\n\n private AuthenticationResult AuthenticationFailed(AuthenticationStatus status, string message = \"\", Exception exception = null)\n {\n return new AuthenticationResult\n {\n Status = status,\n Message = message,\n Exception = exception\n }\n }\n}\n\ninternal class OpenIdAuthenticationPortal : AuthenticationPortal\n{\n private readonly IAuthenticationResponse authenticationResponse;\n private readonly UserRepository userRepository;\n\n public OpenIdAuthenticationPortal(IAuthenticationResponse response, UserRepository userRepository)\n {\n this.authenticationResponse = response;\n this.userRepository = userRepository;\n }\n\n public AuthenticationResult Authenticate()\n {\n switch (authenticationResponse.Status)\n {\n case AuthenticationStatus.Authenticated:\n {\n return Authenticated();\n }\n case AuthenticationStatus.Canceled:\n {\n return AuthenticationFailed(ConnectionStatus.Canceled, Common.Resources.Authentication.CanceledAtProvider); \n }\n case AuthenticationStatus.Failed:\n {\n return AuthenticationFailed(ConnectionStatus.Faulted, authenticationResponse.Exception.Message, authenticationResponse.Exception); \n }\n default:\n {\n return AuthenticationFailed(ConnectionStatus.Faulted, authenticationResponse.Exception.Message, authenticationResponse.Exception); \n }\n }\n }\n\n private AuthenticationResult Authenticated()\n {\n string openId = authenticationResponse.ClaimedIdentifier;\n User user = userRepository.GetByOpenId(openId);\n bool userIsNew = false;\n bool connectionIsNew = false;\n\n if (user == null)\n {\n connectionIsNew = true;\n\n string email = null;\n string displayName = null;\n var fetch = authenticationResponse.GetExtension&lt;FetchResponse&gt;();\n\n if (fetch != null)\n {\n email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);\n displayName = fetch.GetAttributeValue(WellKnownAttributes.Name.FullName);\n\n // try to fetch by email first\n user = GetUserByEmail(userRepository, email);\n\n if (user == null) // create a brand new account.\n {\n user = userRepository.CreateFromOpenId(openId, email, displayName);\n userIsNew = true;\n }\n else // just connect the existing account to their OpenId account.\n {\n userRepository.AddOpenIdConnection(user, openId); \n }\n }\n }\n\n return new AuthenticationResult\n {\n Status = ConnectionStatus.Authenticated,\n UserIsNew = userIsNew,\n ConnectionIsNew = connectionIsNew,\n DisplayName = user.DisplayName,\n UserId = user.UserId\n };\n }\n}\n</code></pre>\n\n<p>The Facebook client would follow similiar pattern.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T00:11:36.673", "Id": "21731", "Score": "0", "body": "I'm not looking at adding any other forms of authentication in the future, that's not a concern, but I'm a sucker for readability and coding cleanly. Currently the authentication options are twitter/fb (oauth), yahoo/gmail (openid), or straight up email/password" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T00:34:41.567", "Id": "21732", "Score": "0", "body": "these was a pretty good idea, making helpers for the returned results significantly reduced code repetition .." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T23:59:55.430", "Id": "13449", "ParentId": "13447", "Score": "5" } }, { "body": "<ol>\n<li>Move common code into helper methods</li>\n<li><p>Fail early. Prefer this pattern</p>\n\n<pre><code>if(something_is_wrong) { throw error }\n</code></pre>\n\n<p>over</p>\n\n<pre><code>if(every_is_ok) { ... }\nelse { throw error }\n</code></pre></li>\n<li><p>There is little point to use <code>else</code> when the <code>if()</code> before that always throws an error.</p></li>\n<li><p>When a method gets too long, split it into several helper methods with meaningful names. Prefer</p>\n\n<pre><code>if(!parameter_x_is_valid(x)) { throw \"x is invalid\" }\nbeginTransaction();\nwriteToDatabase(x);\nendTransaction();\n</code></pre>\n\n<p>over one 150 line method where you'll need comments to understand what is happening.</p>\n\n<p>That will also make it easier to test the code because short helper methods almost always need less setup.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T13:51:36.130", "Id": "13463", "ParentId": "13447", "Score": "2" } } ]
{ "AcceptedAnswerId": "13449", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T22:48:02.783", "Id": "13447", "Score": "3", "Tags": [ "c#" ], "Title": "nested if structure, how could it be improved?" }
13447
<p>I want to get opinions on the code I have put together for a centralized DataContext via a DataHelper class that I have created to be re-used on projects. </p> <p><strong>NOTE</strong> - there is a ton of code here, sorry about that, but I really wanted to layout out the complete approach and uses for my ideas. I'm an not saying this is the right approach, but it works for me so far (still playing with the approach, nothing in production yet, but very similar to stuff I have built over the years) and I really want to get constructive feedback from the community on what I have built to see if it is insane, great, can be improved, etc...</p> <p>A few thoughts I put into this: </p> <ol> <li>Data Context needs to be stored in a common memory space, easily accessible</li> <li>Transactions should take the same approach</li> <li>It must be disposed of properly</li> <li>Allows for better separation of business logic for Saving and Deleting in transactions.</li> </ol> <p>Here is the code for each item:</p> <p>1 - First the data context stored in either the current HttpContext.Current.Items collection (so it only lives for the life of the page and only is fired up once at the first requested) or if the HttpContext doesn't exist uses a ThreadSlot (in which case that code most clean it up itself, like a console app using it...):</p> <pre class="lang-cs prettyprint-override"><code>public static class DataHelper { /// &lt;summary&gt; /// Current Data Context object in the HTTPContext or Current Thread /// &lt;/summary&gt; public static TemplateProjectContext Context { get { TemplateProjectContext context = null; if (HttpContext.Current == null) { LocalDataStoreSlot threadSlot = Thread.GetNamedDataSlot("DataHelper.CurrentContext"); if (Thread.GetData(threadSlot) == null) { context = new TemplateProjectContext(); Thread.SetData(threadSlot, context); } else { context = (TemplateProjectContext)Thread.GetData(threadSlot); } } else { if (HttpContext.Current.Items["DataHelper.CurrentContext"] == null) { context = new TemplateProjectContext(); HttpContext.Current.Items["DataHelper.CurrentContext"] = context; } else { context = (TemplateProjectContext)HttpContext.Current.Items["DataHelper.CurrentContext"]; } } return context; } set { if (HttpContext.Current == null) { if (value == null) { Thread.FreeNamedDataSlot("DataHelper.CurrentContext"); } else { LocalDataStoreSlot threadSlot = Thread.GetNamedDataSlot("DataHelper.CurrentContext"); Thread.SetData(threadSlot, value); } } else { if (value == null) HttpContext.Current.Items.Remove("DataHelper.CurrentContext"); else HttpContext.Current.Items["DataHelper.CurrentContext"] = value; } } } ... </code></pre> <p>2 - To support transactions, I use a similar approach, and also include helper methods to Begin, Commit and Rollback:</p> <pre class="lang-cs prettyprint-override"><code> /// &lt;summary&gt; /// Current Transaction object in the HTTPContext or Current Thread /// &lt;/summary&gt; public static DbTransaction Transaction { get { if (HttpContext.Current == null) { LocalDataStoreSlot threadSlot = Thread.GetNamedDataSlot("currentTransaction"); if (Thread.GetData(threadSlot) == null) { return null; } else { return (DbTransaction)Thread.GetData(threadSlot); } } else { if (HttpContext.Current.Items["currentTransaction"] == null) { return null; } else { return (DbTransaction)HttpContext.Current.Items["currentTransaction"]; } } } set { if (HttpContext.Current == null) { LocalDataStoreSlot threadSlot = Thread.GetNamedDataSlot("currentTransaction"); Thread.SetData(threadSlot, value); } else { HttpContext.Current.Items["currentTransaction"] = value; } } } /// &lt;summary&gt; /// Begins a transaction based on the common connection and transaction /// &lt;/summary&gt; public static void BeginTransaction() { DataHelper.Transaction = DataHelper.CreateSqlTransaction(); } /// &lt;summary&gt; /// Creates a SqlTransaction object based on the current common connection /// &lt;/summary&gt; /// &lt;returns&gt;A new SqlTransaction object for the current common connection&lt;/returns&gt; public static DbTransaction CreateSqlTransaction() { return CreateSqlTransaction(DataHelper.Context.Connection); } /// &lt;summary&gt; /// Creates a SqlTransaction object for the requested connection object /// &lt;/summary&gt; /// &lt;param name="connection"&gt;Reference to the connection object the transaction should be created for&lt;/param&gt; /// &lt;returns&gt;New transaction object for the requested connection&lt;/returns&gt; public static DbTransaction CreateSqlTransaction(DbConnection connection) { if (connection.State != ConnectionState.Open) connection.Open(); return connection.BeginTransaction(); } /// &lt;summary&gt; /// Rolls back and cleans up the current common transaction /// &lt;/summary&gt; public static void RollbackTransaction() { if (DataHelper.Transaction != null) { DataHelper.RollbackTransaction(DataHelper.Transaction); if (HttpContext.Current == null) { Thread.FreeNamedDataSlot("currentTransaction"); } else { HttpContext.Current.Items.Remove("currentTransaction"); } } } /// &lt;summary&gt; /// Rolls back and disposes of the requested transaction /// &lt;/summary&gt; /// &lt;param name="transaction"&gt;The transaction to rollback&lt;/param&gt; public static void RollbackTransaction(DbTransaction transaction) { transaction.Rollback(); transaction.Dispose(); } /// &lt;summary&gt; /// Commits and cleans up the current common transaction /// &lt;/summary&gt; public static void CommitTransaction() { if (DataHelper.Transaction != null) { DataHelper.CommitTransaction(DataHelper.Transaction); if (HttpContext.Current == null) { Thread.FreeNamedDataSlot("currentTransaction"); } else { HttpContext.Current.Items.Remove("currentTransaction"); } } } /// &lt;summary&gt; /// Commits and disposes of the requested transaction /// &lt;/summary&gt; /// &lt;param name="transaction"&gt;The transaction to commit&lt;/param&gt; public static void CommitTransaction(DbTransaction transaction) { transaction.Commit(); transaction.Dispose(); } </code></pre> <p>3 - Clean and easy Disposal</p> <pre class="lang-cs prettyprint-override"><code> /// &lt;summary&gt; /// Cleans up the currently active connection /// &lt;/summary&gt; public static void Dispose() { if (HttpContext.Current == null) { LocalDataStoreSlot threadSlot = Thread.GetNamedDataSlot("DataHelper.CurrentContext"); if (Thread.GetData(threadSlot) != null) { DbTransaction transaction = DataHelper.Transaction; if (transaction != null) { DataHelper.CommitTransaction(transaction); Thread.FreeNamedDataSlot("currentTransaction"); } ((TemplateProjectContext)Thread.GetData(threadSlot)).Dispose(); Thread.FreeNamedDataSlot("DataHelper.CurrentContext"); } } else { if (HttpContext.Current.Items["DataHelper.CurrentContext"] != null) { DbTransaction transaction = DataHelper.Transaction; if (transaction != null) { DataHelper.CommitTransaction(transaction); HttpContext.Current.Items.Remove("currentTransaction"); } ((TemplateProjectContext)HttpContext.Current.Items["DataHelper.CurrentContext"]).Dispose(); HttpContext.Current.Items.Remove("DataHelper.CurrentContext"); } } } </code></pre> <p>3b - I'm building this in MVC, so I have a "base" Controller class that all my controllers inherit from - this way the Context only lives from when first accessed on a request, and until the page is disposed, that way its not too "long running"</p> <pre class="lang-cs prettyprint-override"><code>using System.Web.Mvc; using Core.ClassLibrary; using TemplateProject.Business; using TemplateProject.ClassLibrary; namespace TemplateProject.Web.Mvc { public class SiteController : Controller { protected override void Dispose(bool disposing) { DataHelper.Dispose(); base.Dispose(disposing); } } } </code></pre> <p>4 - So I am big on business classes, separation of concerns, reusable code, all that wonderful stuff. I have an approach that I call "Entity Generic" that can be applied to any entity in my system - for example, Addresses and Phones</p> <p>A Customer can have 1 or more of each, along with a Store, Person, or anything really - so why add street, city, state, etc to every thing that needs it when you can just build an Address entity, that takes a Foreign Type and Key (what I call EntityType and EntityId) - then you have a re-usable business object, supporting UI control, etc - so you build it once and re-use it everywhere.</p> <p>This is where the centralized approach I am pushing for here really comes in handy and I think makes the code much cleaner than having to pass the current data context/transaction into every method.</p> <p>Take for example that you have a Page for a customer, the Model includes the Customer data, Contact, Address and a few Phone Numbers (main, fax, or cell, whatever)</p> <p>When getting a Customer Edit Model for the page, here is a bit of the code I have put together (see how I use the DataHelper.Context in the LINQ):</p> <pre class="lang-cs prettyprint-override"><code> public static CustomerEditModel FetchEditModel(int customerId) { if (customerId == 0) { CustomerEditModel model = new CustomerEditModel(); model.MainContact = new CustomerContactEditModel(); model.MainAddress = new AddressEditModel(); model.ShippingAddress = new AddressEditModel(); model.Phone = new PhoneEditModel(); model.Cell = new PhoneEditModel(); model.Fax = new PhoneEditModel(); return model; } else { var output = (from c in DataHelper.Context.Customers where c.CustomerId == customerId select new CustomerEditModel { CustomerId = c.CustomerId, CompanyName = c.CompanyName }).SingleOrDefault(); if (output != null) { output.MainContact = CustomerContact.FetchEditModelByPrimary(customerId) ?? new CustomerContactEditModel(); output.MainAddress = Address.FetchEditModelByType(BusinessEntityTypes.Customer, customerId, AddressTypes.Main) ?? new AddressEditModel(); output.ShippingAddress = Address.FetchEditModelByType(BusinessEntityTypes.Customer, customerId, AddressTypes.Shipping) ?? new AddressEditModel(); output.Phone = Phone.FetchEditModelByType(BusinessEntityTypes.Customer, customerId, PhoneTypes.Main) ?? new PhoneEditModel(); output.Cell = Phone.FetchEditModelByType(BusinessEntityTypes.Customer, customerId, PhoneTypes.Cell) ?? new PhoneEditModel(); output.Fax = Phone.FetchEditModelByType(BusinessEntityTypes.Customer, customerId, PhoneTypes.Fax) ?? new PhoneEditModel(); } return output; } } </code></pre> <p>And here is a sample of the the phone returning the Edit model to be used:</p> <pre class="lang-cs prettyprint-override"><code> public static PhoneEditModel FetchEditModelByType(byte entityType, int entityId, byte phoneType) { return (from p in DataHelper.Context.Phones where p.EntityType == entityType &amp;&amp; p.EntityId == entityId &amp;&amp; p.PhoneType == phoneType select new PhoneEditModel { PhoneId = p.PhoneId, PhoneNumber = p.PhoneNumber, Extension = p.Extension }).FirstOrDefault(); } </code></pre> <p>Now the page has posted back and this all needs to be save, so the Save method in my control just lets the business object handle this all:</p> <pre class="lang-cs prettyprint-override"><code> [Authorize(Roles = SiteRoles.SiteAdministrator + ", " + SiteRoles.Customers_Edit)] [HttpPost] public ActionResult Create(CustomerEditModel customer) { return CreateOrEdit(customer); } [Authorize(Roles = SiteRoles.SiteAdministrator + ", " + SiteRoles.Customers_Edit)] [HttpPost] public ActionResult Edit(CustomerEditModel customer) { return CreateOrEdit(customer); } private ActionResult CreateOrEdit(CustomerEditModel customer) { if (ModelState.IsValid) { SaveResult result = Customer.SaveEditModel(customer); if (result.Success) { return RedirectToAction("Index"); } else { foreach (KeyValuePair&lt;string, string&gt; error in result.ErrorMessages) ModelState.AddModelError(error.Key, error.Value); } } return View(customer); } </code></pre> <p>And inside the Customer business object - it handles the transaction centrally and lets the Contact, Address and Phone business classes do their thing and really not worry about the transaction:</p> <pre class="lang-cs prettyprint-override"><code> public static SaveResult SaveEditModel(CustomerEditModel model) { SaveResult output = new SaveResult(); DataHelper.BeginTransaction(); try { Customer customer = null; if (model.CustomerId == 0) customer = new Customer(); else customer = DataHelper.Context.Customers.Single(c =&gt; c.CustomerId == model.CustomerId); if (customer == null) { output.Success = false; output.ErrorMessages.Add("CustomerNotFound", "Unable to find the requested Customer record to update"); } else { customer.CompanyName = model.CompanyName; if (model.CustomerId == 0) { customer.SiteGroup = CoreSession.CoreSettings.CurrentSiteGroup; customer.CreatedDate = DateTime.Now; customer.CreatedBy = SiteLogin.Session.ActiveUser; DataHelper.Context.Customers.AddObject(customer); } else { customer.ModifiedDate = DateTime.Now; customer.ModifiedBy = SiteLogin.Session.ActiveUser; } DataHelper.Context.SaveChanges(); SaveResult result = Address.SaveEditModel(model.MainAddress, BusinessEntityTypes.Customer, customer.CustomerId, AddressTypes.Main, false); if (!result.Success) { output.Success = false; output.ErrorMessages.Concat(result.ErrorMessages); } result = Address.SaveEditModel(model.ShippingAddress, BusinessEntityTypes.Customer, customer.CustomerId, AddressTypes.Shipping, false); if (!result.Success) { output.Success = false; output.ErrorMessages.Concat(result.ErrorMessages); } result = Phone.SaveEditModel(model.Phone, BusinessEntityTypes.Customer, customer.CustomerId, PhoneTypes.Main, false); if (!result.Success) { output.Success = false; output.ErrorMessages.Concat(result.ErrorMessages); } result = Phone.SaveEditModel(model.Fax, BusinessEntityTypes.Customer, customer.CustomerId, PhoneTypes.Fax, false); if (!result.Success) { output.Success = false; output.ErrorMessages.Concat(result.ErrorMessages); } result = Phone.SaveEditModel(model.Cell, BusinessEntityTypes.Customer, customer.CustomerId, PhoneTypes.Cell, false); if (!result.Success) { output.Success = false; output.ErrorMessages.Concat(result.ErrorMessages); } result = CustomerContact.SaveEditModel(model.MainContact, customer.CustomerId, false); if (!result.Success) { output.Success = false; output.ErrorMessages.Concat(result.ErrorMessages); } if (output.Success) { DataHelper.Context.SaveChanges(); DataHelper.CommitTransaction(); } else { DataHelper.RollbackTransaction(); } } } catch (Exception exp) { DataHelper.RollbackTransaction(); ErrorHandler.Handle(exp, true); output.Success = false; output.ErrorMessages.Add(exp.GetType().ToString(), exp.Message); output.Exceptions.Add(exp); } return output; } </code></pre> <p>Notice how each Address, Phone, Etc is handled by its own business class, here is the Phone's save method - notice how it doesn't actually do the save here unless you tell it to (save is handled in the Customer's method so save is called just once for the context)</p> <pre class="lang-cs prettyprint-override"><code> public static SaveResult SaveEditModel(PhoneEditModel model, byte entityType, int entityId, byte phoneType, bool saveChanges) { SaveResult output = new SaveResult(); try { if (model != null) { Phone phone = null; if (model.PhoneId != 0) { phone = DataHelper.Context.Phones.Single(x =&gt; x.PhoneId == model.PhoneId); if (phone == null) { output.Success = false; output.ErrorMessages.Add("PhoneNotFound", "Unable to find the requested Phone record to update"); } } if (string.IsNullOrEmpty(model.PhoneNumber)) { if (model.PhoneId != 0 &amp;&amp; phone != null) { DataHelper.Context.Phones.DeleteObject(phone); if (saveChanges) DataHelper.Context.SaveChanges(); } } else { if (model.PhoneId == 0) phone = new Phone(); if (phone != null) { phone.EntityType = entityType; phone.EntityId = entityId; phone.PhoneType = phoneType; phone.PhoneNumber = model.PhoneNumber; phone.Extension = model.Extension; if (model.PhoneId == 0) { phone.CreatedDate = DateTime.Now; phone.CreatedBy = SiteLogin.Session.ActiveUser; DataHelper.Context.Phones.AddObject(phone); } else { phone.ModifiedDate = DateTime.Now; phone.ModifiedBy = SiteLogin.Session.ActiveUser; } if (saveChanges) DataHelper.Context.SaveChanges(); } } } } catch (Exception exp) { ErrorHandler.Handle(exp, true); output.Success = false; output.ErrorMessages.Add(exp.GetType().ToString(), exp.Message); output.Exceptions.Add(exp); } return output; } </code></pre> <p>FYI - SaveResult is just a little container class that I used to get detailed information back if a save fails:</p> <pre class="lang-cs prettyprint-override"><code>public class SaveResult { private bool _success = true; public bool Success { get { return _success; } set { _success = value; } } private Dictionary&lt;string, string&gt; _errorMessages = new Dictionary&lt;string, string&gt;(); public Dictionary&lt;string, string&gt; ErrorMessages { get { return _errorMessages; } set { _errorMessages = value; } } private List&lt;Exception&gt; _exceptions = new List&lt;Exception&gt;(); public List&lt;Exception&gt; Exceptions { get { return _exceptions; } set { _exceptions = value; } } } </code></pre> <p>The other piece to this is the re-usable UI code for the Phone, Address, etc - which handles all the validation, etc in just one location too.</p> <p>So, let your thoughts flow and thanks for taking the time to read/review this huge post!</p>
[]
[ { "body": "<p>I don't mean to hurt your feelings, because you've obviously put a lot of work into this, but I personally don't like it. It seems like you've forsaken Inversion of Control and Dependency Injection for a collection of static \"God\" classes and methods. </p>\n\n<p>For example, the <code>Context</code> property of your <code>DataHelper</code> method. Pretty much any decent IoC container can do this for you in a non-static way. And you have a static <code>Dispose</code> method? Usually that method name is reserved for non-static classes so that instances are automatically cleaned up inside of a using statement (classes that implement the <code>IDisposable</code> interface).</p>\n\n<p>You also have persistence logic in your viewmodels / editmodels. Persistence is an infrastructure concern, whereas these MVC models are HTTP/web concerns. If you should be doing persistence anywhere in MVC, it should be in the controller or an <code>ActionFilter</code> (but ideally you should outsource persistence to an interface).</p>\n\n<p>Have a read of these <a href=\"http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91\" rel=\"nofollow\">two</a> <a href=\"http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92\" rel=\"nofollow\">articles</a>. Try out their tactics. I think you will find a better separation of concerns between infrastructure, application, and presentation layers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T15:43:02.290", "Id": "21771", "Score": "1", "body": "No problem on the feelings - I posted this to get feedback like this, I appreciate good feedback and direction, that's really what I want here is to open the discussion. I will read through the articles you posted. One of the reasons I did this approach was because the \"save\" method in each class handles itself, and with the \"entity generic\" classes needed to have the FK defined up front, had to save off the parent class first - then call the child save methods with the new Id... my thinking has change to make the database use many-to-many tables for the child entities....." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T15:51:28.053", "Id": "21774", "Score": "0", "body": "That removes the need for a \"manual\" transaction and eliminates the Data Helper. I am not sure I've forsaken DI or IoC - I don't use them since all my tests actually just hit the database (they actually build up the data for themselves as they test - just requires a clean DB for each test). As for the persistence logic note - I'm afraid I don't understand and probably need more discussion on that - The models I have are purely a structure for passing data between view/business classes (handled by the controller) - i'm a neophyte with MVC so could be I am understanding the use wrong?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T04:00:32.930", "Id": "13457", "ParentId": "13448", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T23:09:53.187", "Id": "13448", "Score": "2", "Tags": [ "c#", "entity-framework" ], "Title": "Your Thoughts: Entity Framework Data Context via a DataHelper class (centralized context and transactions)" }
13448
<p>I am fairly new to Entity Framework and I am not sure I am really using it to it's max potential. I have this query, that IMHO seems to take a little longer than I feel it should. I have tried various combinations to retrieve all the data I need making as few connections as possible and so far this query yeilds the best results with an average of about 320 ms. Is there anything I can do to make this query faster?</p> <p>Something to note is that the include for Awe_PageContainerBlurb is a many-to-many relationship based on 3 tables.</p> <pre><code>var roles = from role in db.aspnet_Roles join userRole in db.aspnet_UsersInRoles on role.RoleId equals userRole.RoleId where userRole.UserId == userID select role; var awePageData = ((ObjectQuery&lt;Awe_Page&gt;)(from page in db.AweBjects.OfType&lt;Awe_Page&gt;() join app in db.aspnet_Applications on page.ApplicationId equals app.ApplicationId where app.ApplicationName == user.ApplicationName &amp;&amp; page.Active &amp;&amp; page.Name == pageName from pageRole in page.aspnet_Roles where roles.Contains(pageRole) select page)) .Include("Awe_PageContainerBlurb.Awe_Container") .Include("Awe_PageContainerBlurb.Awe_Blurb"); var menuItems = from menu in db.AweBjects.OfType&lt;Awe_Menu&gt;() join app in db.aspnet_Applications on menu.ApplicationId equals app.ApplicationId where app.ApplicationName == user.ApplicationName &amp;&amp; menu.Active from menuRole in menu.aspnet_Roles where roles.Contains(menuRole) select menu; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T04:12:21.553", "Id": "21752", "Score": "2", "body": "320ms? Is this called in a loop a million times? That's hardly poor performance. I've seen some EF code take multiple seconds at times on some pretty heavy metal servers. I'd fire up SQL Profiler and see what queries are coming across and analyze their performance against your schema." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T03:28:59.093", "Id": "21761", "Score": "1", "body": "You can also trace the sql statement that produced here and use the tuning adviser or an sql expert to improve it. This might be a lot more helpful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T12:45:32.227", "Id": "25548", "Score": "0", "body": "I notice you are not using the awePageData variable anywhere? How does it factor in here? Are we missing something?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T14:29:04.193", "Id": "25560", "Score": "0", "body": "Yes I use it later on in my code. I only included the queries since they are all I really care about. Also, it's important to note that the whole thing can be done in one query using joins and such, but what I found was when I split it into these three quries, I achieved the best results.\n\nHow it works is Users, Pages and menu items each have roles. A user's roles must match a page's and a menu item's (independant of each other) to be able to access them. A page has placeholders and content.\n\nAs such, two users may have access to the same page, but one has limited access to menu items." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-05T05:11:22.827", "Id": "32242", "Score": "0", "body": "Are you pulling this from database Views or Tables? If views, EF will run those Include values as OUTER JOIN rather than INNER JOIN. That has been the source of some slowness for me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-07T21:07:56.450", "Id": "32385", "Score": "0", "body": "nah always being run on tables" } ]
[ { "body": "<p>First things first. Since we are talking about an SQL backend (unless I'm mistaken) - you need to profile SQL and take each (sub)query seperately, then determine which query takes the longest. It would simply be pure guess work, taking answers out of thin air otherwise, since we have no reference for what the bottleneck actually is.</p>\n\n<p>Next, what are you SQL indexes? You have many joins and where clauses. If you don't have your indexes set up correctly, then - there's your problem!</p>\n\n<p>Finally compare your c# query to the actual SQL query. Sometimes your LINQ can look beautiful, but the actual code generated for the query is utter BS. I deal with LINQ2SQL myself and have many times been forced to make a list (<code>ToList()</code>) from the sub-queries, forcing the data into the client, into the realm of c# and doing the final query on top of those lists instead. I may use more memory for a brief period of time, but I gain orders of magnitude more speed...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T16:48:43.617", "Id": "30143", "ParentId": "13450", "Score": "2" } } ]
{ "AcceptedAnswerId": "30143", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T00:17:14.130", "Id": "13450", "Score": "2", "Tags": [ "c#", "linq", "entity-framework" ], "Title": "Linq-to-entities query too slow" }
13450
<p>I'm completing exercises in <em>Compilers: Principles, Techniques, and Tools (2nd Edition)</em> in Python. The following code converts:</p> <pre><code>{ int x; char y; { bool y; x; y; } x; y; } </code></pre> <p>to:</p> <pre><code>{ { x:int; y:bool; } x:int; y:char; } </code></pre> <p>I had the following concerns about my code:</p> <ol> <li><p>Is it acceptable to do <code>list(tokenize(...))</code> instead of using it like a proper iterator? I think it would be more efficient, but I wanted the flexibility of an array so that I could traverse backward and forward through the tokens.</p></li> <li><p>Does it make sense to handle the control flow of the application by using Exceptions? I decided to use exceptions and rewinding instead of sentinels and peeking forward. I'm not sure if this is the best way though.</p></li> </ol> <p>I'm not really concerned about the <code>tokenize</code> function as much, since I'm already aware of the problems there.</p> <p>I would be open to any other suggestions or ways I could make this more Pythonistic. </p> <pre><code>class exercise(object): """ program -&gt; block block -&gt; { decls stmts } decls -&gt; decls decl | ∅ decl -&gt; type id ; stmts -&gt; stmts stmt | ∅ stmt -&gt; block | factor ; factor -&gt; id """ def __init__(self, target): self.at = 0 self.tokens = list(tokenize(target)) self.writer = [] self.symbols = symboltable() def match(self, value=None, type='symbol'): token = self.tokens[self.at] t_type, t_value = token if t_type != type or (value and t_value != value): raise InvalidSyntax('Expected {0} "{1}" but received {2} "{3}"'. \ format(type, value, t_type, t_value)) self.at += 1 return token def parse(self): self.writer = [] self.Program() return ' '.join(self.writer) def snapshot(self): return (self.at, len(self.writer)) def rewind(self, snapshot): old_at, old_writer_len = snapshot self.at = old_at self.writer = self.writer[:old_writer_len] def Program(self): self.Block() def Block(self): self.match('{') self.writer.append('{') self.symbols = symboltable(self.symbols) try: self.Decls() except ParsingComplete: pass try: self.Stmts() except ParsingComplete: pass self.match('}') self.writer.append('}') self.symbols = self.symbols.parent def Decls(self): self.Decls_b() #self.Decl() def Decls_b(self): self.Decl() self.Decls() def Decl(self): snapshot = self.snapshot() try: _, type = self.match(type='word') _, id = self.match(type='word') self.symbols.put(id, type) self.match(';') return except: self.rewind(snapshot) raise ParsingComplete() def Stmts(self): self.Stmts_b() #self.Stmt() def Stmts_b(self): self.Stmt() self.Stmts() def Stmt(self): snapshot = self.snapshot() try: self.Block() return except: self.rewind(snapshot) try: self.Factor() self.match(';') return except: self.rewind(snapshot) raise ParsingComplete() def Factor(self): _, id = self.match(type='word') type = self.symbols.get(id) if not type: type = 'undeclared' self.writer.append('{0}:{1};'.format(id, type)) class InvalidSyntax(Exception): pass class ParsingComplete(Exception): pass class symboltable(object): """ Store lexeme name and value information for a given scope """ def __init__(self, parent=None): self.parent = parent self.table = dict() def get(self, key): if key in self.table: return self.table[key] if not self.parent: return None return self.parent.get(key) def put(self, key, value): self.table.update({key: value}) def tokenize(target): i = 0 while i &lt; len(target): c = target[i] if c == ' ': pass elif c.isdigit(): n = 0 while True: n = n * 10 + int(c) c = target[i + 1] if not c.isdigit(): break i += 1 yield ('number', n) elif c.isalpha(): letters = [] while True: letters.append(c) c = target[i + 1] if not c.isalpha() and not c.isdigit(): break i += 1 word = ''.join(letters) yield ('word', word) else: yield('symbol', c) i += 1 input = '{ int x; char y; { bool y; x; y; } x; y; }' expected = '{ { x:int; y:bool; } x:int; y:char; }' actual = exercise(input).parse() assert actual == expected </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T03:48:31.447", "Id": "21760", "Score": "0", "body": "It may be worth looking into pylint and pychecker, there are a number of quick fixes and small errors that come up" } ]
[ { "body": "<pre><code>class exercise(object):\n</code></pre>\n\n<p>The python style guide recommends CamelCase for class names</p>\n\n<pre><code> \"\"\"\n program -&gt; block\n block -&gt; { decls stmts }\n decls -&gt; decls decl\n | ∅\n decl -&gt; type id ;\n stmts -&gt; stmts stmt \n | ∅\n stmt -&gt; block \n | factor ;\n factor -&gt; id\n \"\"\"\n\n def __init__(self, target):\n self.at = 0\n self.tokens = list(tokenize(target))\n</code></pre>\n\n<p>This is perfectly fine. It's probably faster this way, but will take more memory.</p>\n\n<pre><code> self.writer = []\n self.symbols = symboltable()\n\n def match(self, value=None, type='symbol'):\n token = self.tokens[self.at]\n t_type, t_value = token\n if t_type != type or (value and t_value != value):\n</code></pre>\n\n<p>For checking if value is None, I recommend <code>value is None</code> rather then just checking for false. Another false value could be passed</p>\n\n<pre><code> raise InvalidSyntax('Expected {0} \"{1}\" but received {2} \"{3}\"'. \\\n format(type, value, t_type, t_value))\n self.at += 1\n return token\n</code></pre>\n\n<p>I would actually separate <code>match</code>, <code>snapshot</code> and, <code>rewind</code> off onto their own class. Those form a unit of logic of operating over the token stream, and are best kept separate from the actual parsing logic.</p>\n\n<pre><code> def parse(self):\n self.writer = []\n</code></pre>\n\n<p>This attribute bothers me. I wonder if the code would be cleaner to use return values for this. The name is also a little bit off because its hold data, it doesn't really write anything itself.</p>\n\n<pre><code> self.Program()\n return ' '.join(self.writer)\n\n def snapshot(self):\n return (self.at, len(self.writer))\n\n def rewind(self, snapshot):\n old_at, old_writer_len = snapshot\n self.at = old_at\n self.writer = self.writer[:old_writer_len]\n</code></pre>\n\n<p>It may be better to <code>del</code> the extra stuff in writer, rather then slice it</p>\n\n<pre><code> def Program(self):\n</code></pre>\n\n<p>Python convention is to have lowercase_with_underscores for method names. This method is also internal to the parser and should perhaps begin with an underscore.</p>\n\n<pre><code> self.Block()\n\n def Block(self):\n self.match('{')\n self.writer.append('{')\n self.symbols = symboltable(self.symbols)\n try:\n self.Decls()\n except ParsingComplete:\n pass\n</code></pre>\n\n<p>Using an exception to say something is finished will be severely looked down upon</p>\n\n<pre><code> try:\n self.Stmts()\n except ParsingComplete:\n pass\n self.match('}')\n self.writer.append('}')\n self.symbols = self.symbols.parent\n\n def Decls(self):\n self.Decls_b()\n #self.Decl()\n</code></pre>\n\n<p>There isn't a whole lot of point to a function that just calls another function</p>\n\n<pre><code> def Decls_b(self):\n self.Decl()\n self.Decls()\n</code></pre>\n\n<p>I would suggest that you use a loop rather then recursion here, and that you handle the exception here. This is the point where a Decl is either Decl Decls or nothing. So here is the best place to have the logic diverge. Something lile</p>\n\n<pre><code>def Decls(self):\n while True:\n try:\n snapshot = self.snapshot()\n self.Decl() # try parsing another Decl\n except InvalidSyntaxError:\n self.rewind(snapshot)\n break # if we failed to parse the Decl, stop\n</code></pre>\n\n<p>I think using the looping constructs of the language make this much clearer. However, this points to a problem with your approach. Pretty much every single syntax error will be diagnosed as a missing <code>}</code>, not a very helpful error message. This is because most failure exceptions gets interpreted having attempted to parse the wrong thing. </p>\n\n<pre><code> def Decl(self):\n snapshot = self.snapshot()\n try:\n _, type = self.match(type='word')\n _, id = self.match(type='word')\n self.symbols.put(id, type)\n self.match(';')\n return\n except:\n</code></pre>\n\n<p>Don't do this. You should catch only the specific type of exception you are interested in. Otherwise you'll catch other exceptions and make bugs hard to find.</p>\n\n<pre><code> self.rewind(snapshot)\n raise ParsingComplete()\n</code></pre>\n\n<p>This is only executed in the case of an exception, so why isn't it in the exception block?</p>\n\n<p>[Snip Stmt section, similar issues apply]</p>\n\n<pre><code>class InvalidSyntax(Exception):\n pass\n\nclass ParsingComplete(Exception):\n pass\n\nclass symboltable(object):\n \"\"\" Store lexeme name and value information for a given scope \"\"\"\n\n def __init__(self, parent=None):\n self.parent = parent\n self.table = dict()\n\n def get(self, key):\n if key in self.table:\n return self.table[key]\n</code></pre>\n\n<p>This is considered a bad idea in python because you have to lookup the key twice</p>\n\n<pre><code> if not self.parent:\n return None\n</code></pre>\n\n<p>Do you really want to return None? Shouldn't you throw an exception?</p>\n\n<pre><code> return self.parent.get(key)\n</code></pre>\n\n<p>I'd write this as</p>\n\n<pre><code>try:\n return self.table[key]\nexcept KeyError:\n if self.parent is None:\n raise UnknownVariableError(key)\n else:\n return self.parent.get(key)\n</code></pre>\n\n<p>I think it is clearer</p>\n\n<pre><code> def put(self, key, value):\n self.table.update({key: value})\n</code></pre>\n\n<p>Why not <code>self.table[key] = value</code>?</p>\n\n<p>[skipped tokenize] </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T18:51:55.000", "Id": "21794", "Score": "0", "body": "Thanks for the feedback, I'll be improving my code with some of these suggestions. Decls_b only exists because I wanted to express \"decls -> decls decl\" which is defined in the grammar, but using a loop instead will actually simplify the code and make it easier to understand. The \"writer\" is actually a convention from .NET I'm using even though it isn't intuitive here. It's supposed to represent the semantic action for each production rule." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T18:56:26.197", "Id": "21795", "Score": "0", "body": "I agree using exceptions to handle control flow does obscure syntax errors... I'll try to fix that. Though I'm less than 1/7th of the way through this book and it hasn't really covered error handling in-depth. Thanks for the input." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T18:58:41.903", "Id": "21796", "Score": "0", "body": "I'll post the updated code later if I can fix the syntax errors. Another improvement I made, beyond these suggestions, was to use a namedtuple for tokens so I don't have to unpack every time to retrieve the token value." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T15:45:10.277", "Id": "13467", "ParentId": "13451", "Score": "1" } } ]
{ "AcceptedAnswerId": "13467", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T00:41:02.803", "Id": "13451", "Score": "3", "Tags": [ "python" ], "Title": "Does this code use good Python practices for a context-free grammar implementation?" }
13451
<p>I've been doing MVC for a few months now using the CodeIgniter framework in PHP but I still don't know if I'm really doing things right.</p> <p>What I currently do is:</p> <p><strong>Model</strong> - this is where I put database queries (select, insert, update, delete). Here's a sample from one of the models that I have:</p> <pre><code>function register_user($user_login, $user_profile, $department, $role) { $department_id = $this-&gt;get_department_id($department); $role_id = $this-&gt;get_role_id($role); array_push($user_login, $department_id, $role_id); $this-&gt;db-&gt;query("INSERT INTO tbl_users SET username=?, hashed_password=?, salt=?, department_id=?, role_id=?", $user_login); $user_id = $this-&gt;db-&gt;insert_id(); array_push($user_profile, $user_id); $this-&gt;db-&gt;query(" INSERT INTO tbl_userprofile SET firstname=?, midname=?, lastname=?, user_id=? ", $user_profile); } </code></pre> <p><strong>Controller</strong> - talks to the model, calls up the methods in the model which queries the database, supplies the data which the views will display(success alerts, error alerts, data from database), inherits a parent controller which checks if user is logged in.</p> <pre><code>function create_user(){ $this-&gt;load-&gt;helper('encryption/Bcrypt'); $bcrypt = new Bcrypt(15); $user_data = array( 'username' =&gt; 'Username', 'firstname' =&gt; 'Firstname', 'middlename' =&gt; 'Middlename', 'lastname' =&gt; 'Lastname', 'password' =&gt; 'Password', 'department' =&gt; 'Department', 'role' =&gt; 'Role' ); foreach ($user_data as $key =&gt; $value) { $this-&gt;form_validation-&gt;set_rules($key, $value, 'required|trim'); } if ($this-&gt;form_validation-&gt;run() == FALSE) { $departments = $this-&gt;user_model-&gt;list_departments(); $it_roles = $this-&gt;user_model-&gt;list_roles(1); $tc_roles = $this-&gt;user_model-&gt;list_roles(2); $assessor_roles = $this-&gt;user_model-&gt;list_roles(3); $data['data'] = array('departments' =&gt; $departments, 'it_roles' =&gt; $it_roles, 'tc_roles' =&gt; $tc_roles, 'assessor_roles' =&gt; $assessor_roles); $data['content'] = 'admin/create_user'; parent::error_alert(); $this-&gt;load-&gt;view($this-&gt;_at, $data); } else { $username = $this-&gt;input-&gt;post('username'); $salt = $bcrypt-&gt;getSalt(); $hashed_password = $bcrypt-&gt;hash($this-&gt;input-&gt;post('password'), $salt); $fname = $this-&gt;input-&gt;post('firstname'); $mname = $this-&gt;input-&gt;post('middlename'); $lname = $this-&gt;input-&gt;post('lastname'); $department = $this-&gt;input-&gt;post('department'); $role = $this-&gt;input-&gt;post('role'); $user_login = array($username, $hashed_password, $salt); $user_profile = array($fname, $mname, $lname); $this-&gt;user_model-&gt;register_user($user_login, $user_profile, $department, $role); $data['content'] = 'admin/view_user'; parent::success_alert(4, 'User Sucessfully Registered!', 'You may now login using your account'); $data['data'] = array('username' =&gt; $username, 'fname' =&gt; $fname, 'mname' =&gt; $mname, 'lname' =&gt; $lname, 'department' =&gt; $department, 'role' =&gt; $role); $this-&gt;load-&gt;view($this-&gt;_at, $data); } } </code></pre> <p><strong>Views</strong> - this is where I put HTML, CSS, and JavaScript code (form validation code for the current form, looping through the data supplied by controller, a few if statements to hide and show things depending on the data supplied by the controller).</p> <pre><code>&lt;!--User registration form--&gt; &lt;form class="well min-form" method="post"&gt; &lt;div class="form-heading"&gt; &lt;h3&gt;User Registration&lt;/h3&gt; &lt;/div&gt; &lt;label for="username"&gt;Username&lt;/label&gt; &lt;input type="text" id="username" name="username" class="span3" autofocus&gt; &lt;label for="password"&gt;Password&lt;/label&gt; &lt;input type="password" id="password" name="password" class="span3"&gt; &lt;label for="firstname"&gt;First name&lt;/label&gt; &lt;input type="text" id="firstname" name="firstname" class="span3"&gt; &lt;label for="middlename"&gt;Middle name&lt;/label&gt; &lt;input type="text" id="middlename" name="middlename" class="span3"&gt; &lt;label for="lastname"&gt;Last name&lt;/label&gt; &lt;input type="text" id="lastname" name="lastname" class="span3"&gt; &lt;label for="department"&gt;Department&lt;/label&gt; &lt;input type="text" id="department" name="department" class="span3" list="list_departments"&gt; &lt;datalist id="list_departments"&gt; &lt;?php foreach ($data['departments'] as $row) { ?&gt; &lt;option data-id="&lt;?php echo $row['department_id']; ?&gt;" value="&lt;?php echo $row['department']; ?&gt;"&gt;&lt;?php echo $row['department']; ?&gt;&lt;/option&gt; &lt;?php } ?&gt; &lt;/datalist&gt; &lt;label for="role"&gt;Role&lt;/label&gt; &lt;input type="text" id="role" name="role" class="span3" list=""&gt; &lt;datalist id="list_it"&gt; &lt;?php foreach ($data['it_roles'] as $row) { ?&gt; &lt;option data-id="&lt;?php echo $row['role_id']; ?&gt;" value="&lt;?php echo $row['role']; ?&gt;"&gt;&lt;?php echo $row['role']; ?&gt;&lt;/option&gt; &lt;?php } ?&gt; &lt;/datalist&gt; &lt;datalist id="list_collection"&gt; &lt;?php foreach ($data['tc_roles'] as $row) { ?&gt; &lt;option data-id="&lt;?php echo $row['role_id']; ?&gt;" value="&lt;?php echo $row['role']; ?&gt;"&gt;&lt;?php echo $row['role']; ?&gt;&lt;/option&gt; &lt;?php } ?&gt; &lt;/datalist&gt; &lt;datalist id="list_assessor"&gt; &lt;?php foreach ($data['assessor_roles'] as $row) { ?&gt; &lt;option data-id="&lt;?php echo $row['role_id']; ?&gt;" value="&lt;?php echo $row['role']; ?&gt;"&gt;&lt;?php echo $row['role']; ?&gt;&lt;/option&gt; &lt;?php } ?&gt; &lt;/datalist&gt; &lt;p&gt; &lt;button type="submit" class="btn btn-success"&gt;Create User&lt;/button&gt; &lt;/p&gt; &lt;/form&gt; &lt;script&gt; var departments = []; var roles = []; $('#list_departments option').each(function(i){ departments[i] = $(this).val(); }); $('#list_it option').each(function(i){ roles[roles.length + 1] = $(this).val(); }); $('#list_collection option').each(function(i){ roles[roles.length + 1] = $(this).val(); }); $('#list_assessor option').each(function(i){ roles[roles.length + 1] = $(this).val(); }); $('#department').blur(function(){ var department = $.trim($(this).val()); $('#role').attr('list', 'list_' + department); }); var password = new LiveValidation('password'); password.add(Validate.Presence); password.add(Validate.Length, {minimum: 10}); $('input[type=text]').each(function(i){ var field_id = $(this).attr('id'); var field = new LiveValidation(field_id); field.add(Validate.Presence); if(field_id == 'department'){ field.add(Validate.Inclusion, {within : departments}); } else if(field_id == 'role'){ field.add(Validate.Inclusion, {within : roles}) } }); &lt;/script&gt; </code></pre> <p>The code above is actually code from the application that I'm currently working on.</p> <p>I'm also looking for some guidelines in writing MVC code, such as the things that should and shouldn't be included in views, models and controllers. How else can I improve the current code that I have right now?</p> <p>I've written some really terrible code before (duplication of logic, etc.), which is why I want to improve my code so that I can easily maintain it in the future.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T05:51:45.693", "Id": "21753", "Score": "3", "body": "just a quick note on 'encryption/Bcrypt': BCrypt is a hashing algorithm, so it is not encryption. Encryption is reversible, hashing is intended to be one way. Think of a hashing algorithm as a meat grinder. You can put in the cow to get meat pulp. You cannot reverse the process and get your cow back from the minced meat result." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T04:51:36.320", "Id": "21825", "Score": "0", "body": "Have you tried DataMapper? Check its [getting started guide](http://datamapper.wanwizard.eu/pages/gettingstarted.html) to give yourself an idea how models, controllers and views could be coded with a few lines. I recommend to read the entire guide before any implementation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T13:16:28.123", "Id": "21845", "Score": "1", "body": "Your perception of what a model is [is wrong](http://stackoverflow.com/questions/5863870/how-should-a-model-be-structured-in-mvc/5864000#5864000)." } ]
[ { "body": "<p>Your understanding of MVC seems to be skewed. There are slightly different implementations of MVC, so one person's definition of a certain aspect of it might be slightly different than another's. I'll explain how basic MVC works, and why I think your implementation is not a true implementation of MVC. Also, I'm going to make some comments on your separation of code, or rather, lack of separation. Methods should be separated by functionality. In other words, they should do one thing to the exclusion of all others. Understanding this will make understanding MVC a little easier.</p>\n\n<p><strong>Models</strong></p>\n\n<p>As PeeHaa said, your explanation seems to be off. I've seen other people mistakenly think of their actual databases as their model without even knowing it. This appears to be what you are doing here. What you have is not what I would call a model, but rather a mini controller with too much information. As I mentioned before there are slightly different implementations of MVC, but as I just pointed out, this more closely resembles a controller. Usually, should probably read always, a model can be thought of as an interface to the database. The database can be anything from a text document, to a JSON database, to an XML file, to a MySQL database. The model has to allow the controller to <code>add()</code>, <code>remove()</code>, <code>fetch()</code>, etc..., depending on the circumstances and without knowledge of what type of database it is accessing.</p>\n\n<p>Also, as I pointed out above with that list of methods, the method names in a model will more closely resemble an actual task you would perform on a database. <code>register_user()</code> is something I would expect to see on a controller. It implies that you are not just adding a user to the database, but validating, sending emails, etc....</p>\n\n<p>Now, my first comments on your actual code. <code>register_user()</code> is doing too much. <code>$department_id</code> and <code>$role_id</code> should be defined and pushed into the array beforehand. These variables are static, not to be confused with the keyword static. In other words, they don't depend on values inside that method to change them. Their values are going to stay the same no matter what you do inside that method.</p>\n\n<p><strong>Controllers</strong></p>\n\n<p>As the model is an interface between the database and controller, so is the controller an interface between the model and view. And just as the view does not need to know how the controller is doing what it is, so does the controller not need to know how the model is doing what it is. In other words, controllers don't need MySQL queries. I only mention this because I mentioned that your model resembled a controller and did not want you to become confused. The model should handle the creation/deletion of entries, the controller should only be concerned about making the model do it and then telling the view what it has done.</p>\n\n<p>According to your method name <code>create_user()</code>, your controller appears to be doing what your model needs. I would switch these names around to avoid confusion. Asides from the actual method name being odd, the functionality is spot on. I won't go into detail to avoid confusion, but another implementation, and one that I favor, adds another level of abstraction by adding a router/dispatcher between the controller and view to handle POST, GET, SESSION, COOKIE, and authentication. CodeIgniter does something very similar here, sans the authentication, with methods such as <code>$this-&gt;input-&gt;post()</code>.</p>\n\n<p>Again, your methods are doing too much. <code>create_user()</code> should only \"create a user\". Even if you change that to <code>register_user()</code>. It doesn't need to be concerned with encryption or form validation. These things need to be done, but in their own methods.</p>\n\n<p><strong>Views</strong></p>\n\n<p>Your views are fine as far as PHP goes. However, if you ever need to code a view for someone completely oblivious to PHP, you could make it a little easier for them to understand by abstracting initial arrays and using standard view loop/if/else format. Example:</p>\n\n<pre><code>$departments = $data[ 'departments' ];//performed in controller before view is included.\n\n&lt;?php foreach($departments as $row) : ?&gt;\n&lt;?php endforeach; ?&gt;\n</code></pre>\n\n<p>I think I would also use <code>extract()</code> within these loops to abstract from the array again, but that is definitely a matter of preference.</p>\n\n<p>Unless you are importing PHP variables into your JS, your JS should really be external.</p>\n\n<p>Just like in PHP, with CSS you can make referencing a certain field easier if you find you are doing it consistently. For instance. All those \"span3\" classed inputs can be better written as so.</p>\n\n<pre><code>//CSS: .span3 input { }\n&lt;span class=\"span3\"&gt;\n &lt;label&gt;&lt;/label&gt;\n &lt;input /&gt;\n&lt;/span&gt;\n</code></pre>\n\n<p>Or since it appears that all those inputs use the same class, you can just ignore the class altogether and set the default CSS for the input tag.</p>\n\n<p>Good Luck!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T14:26:15.130", "Id": "36680", "Score": "0", "body": "+ 1 for that @mseancole,\nbut I want to know how to avoid controller to get bigger with bigger projects, should i have hierarchical models structure, like 2 layers 1 for business and 1 for CRUD" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-30T07:58:26.940", "Id": "117483", "Score": "0", "body": "You have some good points. But 'a model is the interface between the controller and the database' is just plain wrong. A model is a representation of data. It could resemble a row in a sql-table. But It could also be a representation of multiple rows over multiple tables, maybe even different db's. The model could care less. You would then have a repository that does all the saving, updating, ... of the models. The model shouldnt know about mysql, or nosql or csv or..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T15:31:47.750", "Id": "13538", "ParentId": "13453", "Score": "3" } } ]
{ "AcceptedAnswerId": "13538", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T03:06:02.983", "Id": "13453", "Score": "4", "Tags": [ "php", "mvc", "validation" ], "Title": "Applying MVC to a validation application" }
13453
<p>I've written a short piece of code to get myself familiar with backbone.js. I'm filtering 100 results from the Twitter API. Once those are in, I use a time picker and a hash tag selector to filter my results.</p> <p>I want the filter to work in the following manner:</p> <p>Pick a time range, get a filtered collection and a filtered set of hash tags in the selector tag. Pick a hash tag, filter the SAME RESULTS within that time range.</p> <p>Pick a hashtag, get a filtered collection. Select a date and filter the same results gotten with the originally chosen hashtag.</p> <p>Don't lose the original collection:</p> <pre><code>"use strict"; </code></pre> <p>Define the model:</p> <pre><code>var Tweet = Backbone.Model.extend({}); </code></pre> <p>Define the collection:</p> <pre><code>var Tweets = Backbone.Collection.extend({ initialize : function(options) { if (options !== undefined) { if (options.location !== undefined) { this.location = options.location; // console.log(location); } } }, model : Tweet, parse : function(response) { var data = response.results; $(data).each( function() { var timezoneOffset = new Date().getTimezoneOffset() / -60; // var offset = Date.getTimezoneOffset(today.getTimezone(), // today.hasDaylightSavingTime()); // console.log(timezoneOffset); var dateTime = Date.parse(this.created_at).addHours( timezoneOffset).toString( "dddd, MMMM dd, yyyy, h:mm:ss tt"); this.created_at = dateTime; this.text = twttr.txt.autoLink(this.text); this.from_user = twttr.txt.autoLink("@" + this.from_user); // console.log("user: ", this.from_user); }); // console.log('\nformatted data: ', data); return data; }, </code></pre> <p>Overwrite the sync method to pass over the Same Origin Policy:</p> <pre><code> sync : function(method, model, options) { // console.log(options); var self = this; var params = { url : 'http://search.twitter.com/search.json?q=' + self.location + '&amp;rpp=100&amp;lang=all&amp;include_entities=true', type : 'GET', dataType : 'jsonp', processData : false }; options = _.extend(options, params); return $.ajax(options); }, showhide : function(toDate, fromDate) { // console.log(toDate,"\n", fromDate,"\n", this.models); var results; //if(toDate !== undefined &amp;&amp; fromDate !== undefined){ results = this.filter(function(tweet) { var tweetDate = Date.parse(tweet.attributes.created_at); if (tweetDate.between(fromDate, toDate)) { //console.log("valid ", tweet); return true; } }); //} return results; console.log("Date Filtered Results: ", results); }, selectShowHide : function(selectedHashTag){ var results; if(selectedHashTag !== 'all'){ results = this.filter(function(tweet){ var hashtag = tweet.attributes.entities.hashtags; //console.log("hashtag array: ", hashtag); var matchingHashTag = ""; $(hashtag).each(function(){ if(this.text == selectedHashTag){ return matchingHashTag = true; } }); return matchingHashTag; }); } else{ results = this.filter(function(tweet){ return true; }); } return results; console.log("Date Filtered Results: ", results); } }); </code></pre> <p>Define the Master View:</p> <pre><code>var MasterView = Backbone.View.extend({ initialize : function() { // console.log("Master View Initialized"); }, events : { "click #buttonSubmit" : "doSearch", }, doSearch : function() { // console.log(this); var $self = this.$el; // THIS IS VERY IMPORTANT!!! DEFINE A TOP VIEW LEVEL COLLECTION FOR YOUR // VIEWS TO WORK ON // IF YOU WISH TO DO FRONT END FILTERING ON YOUR RESULTS!!! var TweetResults = new Tweets({ location : $self.find('#textLocation').val() }); TweetResults.fetch({ success : function(collection, resp) { var dateView = new DateView({ el : $('#date'), collection : collection }); var selectView = new SelectView({ el: $('#hashTag'), collection: collection }); var resultsView = new ResultsView({ el : $('#display'), collection : collection }); var resetView = new ResetView({ el: $("#reset"), collection : collection }); } }); } }); </code></pre> <p>Define the reset View</p> <pre><code>var ResetView = Backbone.View.extend({ initialize: function(options){ this.collection = options.collection; this.render(); }, render: function(){ this.$el.html(""); var self = this; $.ajax({ url : '../templates/ResetTemplate.html', cache : false, success : function(data) { templateLoader(data, self); } }); }, events:{ "click #buttonReset": "collectionReset" }, collectionReset: function(){ var dateView = new DateView({ el : $('#date'), collection : this.collection }); var resultsView = new ResultsView({ el : $('#display'), collection : this.collection }); var selectView = new SelectView({ el: $('#hashTag'), collection: this.collection }); } }); </code></pre> <p>Define the date View</p> <pre><code>var DateView = Backbone.View .extend({ initialize : function(options) { // console.log('Date View Initialized'); this.collection = options.collection; this.render(); }, render : function() { this.$el.html(""); var self = this; $.ajax({ url : '../templates/DateTemplate.html', cache : false, success : function(data) { templateLoader(data, self); datePicker(self, "#textFrom"); datePicker(self, "#textTo"); } }); }, events : { "click #buttonFilter" : "showHide" }, // filter the results showHide : function() { var fromDate = ""; var toDate = ""; if ($('#textFrom').val() === "") { alert("Please Enter a 'From' Date"); } else { fromDate = Date.parse($('#textFrom').val()); } if ($('#textTo').val() === "") { alert("Please Enter a 'To' Date"); } else { toDate = Date.parse($('#textTo').val()); } if (toDate &amp;&amp; fromDate &amp;&amp; fromDate.isBefore(toDate)) { var filteredCollection = new Tweets(this.collection .showhide(toDate, fromDate)); //console.log("filtered results: ", filteredCollection); var filteredResultsView = new ResultsView({ el : $('#display'), collection : filteredCollection }); /*var filteredSelectView = new SelectView({ el : $('#hashTag'), collection : filteredCollection });*/ } else { alert("Please check if your 'From' date comes before your 'To' date!"); } } }); </code></pre> <p>Define the select View:</p> <pre><code>var SelectView = Backbone.View.extend({ initialize : function(options) { // create a collection this.collection = options.collection; //console.log('select collection: ', this.collection); this.render(); }, render : function() { this.$el.html(""); var self = this; $.ajax({ url : '../templates/HashTagSelectionTemplate.html', cache : true, success : function(data) { templateLoader(data, self); } }); }, events:{ "change #selectHashTag" : "selectShowHide" }, selectShowHide: function() { var selected = $("#selectHashTag").find("option:selected").val(); console.log("selected option: ", selected); var filteredCollection = new Tweets(this.collection .selectShowHide(selected)); var filteredResultsView = new ResultsView({ el : $('#display'), collection : filteredCollection }); /*var filteredDateView = new DateView({ el : $('#date'), collection : filteredCollection });*/ } }); </code></pre> <p>Define the results View:</p> <pre><code>var ResultsView = Backbone.View.extend({ initialize : function(options) { // console.log(options); // create a collection this.collection = options.collection; this.render(); }, render : function() { this.$el.html(""); var self = this; $.ajax({ url : '../templates/TweetsTemplate.html', cache : false, success : function(data) { templateLoader(data, self); } }); } }); </code></pre> <p>Function to handle template loading:</p> <pre><code>function templateLoader(data, self) { var source = data; var template = Handlebars.compile(source); var html = template(self.collection); self.$el.html(html); } </code></pre> <p>Function to attach the datepicker to the supplied element:</p> <pre><code>function datePicker(self, elementId) { self.$el.find(elementId).datetimepicker({ dateFormat : "DD, dd MM yy", ampm : true }); } </code></pre> <p>Initialize the master view:</p> <pre><code>var app = new MasterView({ el : $('#fieldsetForm') }); </code></pre> <p>Am I on the right track? Should I be using another way? Am I in danger of memory leaks?</p>
[]
[ { "body": "<p>From a once over:</p>\n\n<p><strong>Collection</strong></p>\n\n<ul>\n<li>You could merge those 2 if statements into 1</li>\n<li>You should remove commented out code</li>\n<li>You should remove console.log code</li>\n<li>You should try to have 1 chained <code>var</code> block</li>\n<li>You should use lowerCamelCasing consistently</li>\n</ul>\n\n<p>This makes the code look a little tighter:</p>\n\n<pre><code>var Tweets = Backbone.Collection.extend({\n initialize : function(options) {\n if (options &amp;&amp; options.location) {\n this.location = options.location;\n }\n },\n model : Tweet,\n parse : function(response) {\n var data = response.results;\n $(data).each( function() {\n var timezoneOffset = new Date().getTimezoneOffset() / -60,\n dateTime = Date.parse(this.created_at).addHours(timezoneOffset)\n .toString(\"dddd, MMMM dd, yyyy, h:mm:ss tt\");\n this.createdAt = dateTime;\n this.text = twttr.txt.autoLink(this.text);\n this.fromUser = twttr.txt.autoLink(\"@\" + this.from_user);\n\n });\n return data;\n },\n</code></pre>\n\n<p><strong>sync related</strong></p>\n\n<ul>\n<li><em>sync</em>\n<ul>\n<li>No need to declare <code>self = this</code>, you only use <code>self</code> once, and it is not in a closure.</li>\n</ul></li>\n<li><p><em>showHide</em></p>\n\n<ul>\n<li>You can return <code>tweetDate.between(fromDate, toDate)</code> in your filter function, it is shorter and more explicit that it return false when <code>tweetDate</code> is outside the provided dates</li>\n<li><p>If you drop the console code, and not use a temp variable, your code becomes so much tighter/readable<br></p>\n\n<pre><code>showhide : function(toDate, fromDate) {\n return this.filter(function(tweet) {\n var tweetDate = Date.parse(tweet.attributes.created_at);\n return tweetDate.between(fromDate, toDate);\n });\n},\n</code></pre></li>\n</ul></li>\n<li><em>selectShowHide</em> \n<ul>\n<li>You are using <code>each</code> to find a match, since you should stop searching and exit after finding a match, you should not use <code>each</code> which forces you to go through all entries, a <code>for</code> loop with a <code>return</code> would do a better job</li>\n<li>When you need all entries to be returned, you could just use <code>this.makeArray()</code> instead of filtering and always returning <code>true</code>.</li>\n<li>If find code easier to read if you test on equality ( and then switch your 2 blocks )</li>\n</ul></li>\n<li><em>templateLoader</em>\n<ul>\n<li>You copy <code>data</code> to <code>source</code>, and use <code>source</code> only once, you could name the parameter itself <code>source</code> in that case</li>\n<li>You might want to consider memoizing the result of the compilations to speed up your code</li>\n</ul></li>\n</ul>\n\n<p>As for your questions:</p>\n\n<p><em>Am I on the right track? Should I be using another way?</em></p>\n\n<p>Looks okay to me, but I am no backbone expert.</p>\n\n<p><em>Am I in danger of memory leaks?</em> </p>\n\n<p>If you worry about this, then you should use the Google Developer tools, they are the only surefire way to tell.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T04:00:30.660", "Id": "40653", "ParentId": "13454", "Score": "5" } }, { "body": "<p>I would always much rather use the Backbone event listeners where possible rather than use callback hoooks. For example in <code>MasterView</code>, where you are fetching the tweets, a tidier approach might be to bind to the collection <code>sync</code> event, rather than use a callback:</p>\n\n<pre><code>var MasterView = Backbone.View.extend({\n initialize : function() {},\n events : {\n \"click #buttonSubmit\" : \"doSearch\",\n },\n\n doSearch : function() {\n\n var TweetResults = new Tweets({\n location : $('#textLocation', this.$el).val()\n }).on('sync', this.createViews)\n .fetch();\n },\n\n createViews: function() {\n // all that view init code\n }\n})\n</code></pre>\n\n<p>Notice I also prefer providing a context to jQuery selectors, rather than using find: <code>$('#textLocation', this.$el) === this.$el.find('#textLocation')</code>.</p>\n\n<p>The only other big critisism I have is that you'll have to recreate your <code>View</code> objects on every search. It might be better to initialise them in advance, rendering their root elements, and then add the results to them once they are returned. I see it something like this;</p>\n\n<pre><code>var MasterView = Backbone.View.extend({\n initialize : function() {\n this.dateView = new DateView()\n // you could even add the element to the page here\n // to be rendered later\n // (if it doesn't exist already)\n .$el.appendTo(this.$el);\n ...\n },\n ... \n // separate initialisation from rendering\n renderViews: function() {\n this.dateView.render();\n ...\n }\n</code></pre>\n\n<p>And calling the <code>render</code> method within the view constructors is probably not what you want to do, as it means you're not separating your concerns. Initialisers should be initialising values, probably not rendering. The view should be initialised as soon as possible, and when the data is ready it should be rendered.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T17:01:46.357", "Id": "40757", "ParentId": "13454", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T03:26:19.193", "Id": "13454", "Score": "5", "Tags": [ "javascript", "backbone.js", "twitter" ], "Title": "Filtering a Backbone collection with multiple parameters" }
13454
<p>There is a handful of LinkedIn clients written in C# on the NuGet package library, but as far as I can tell, most only do authentication via LinkedIn. I found a couple which offer a LinkedIn REST API interface. Of those two, <a href="http://djsolid.net/blog/linked-in-oauth-library">one looks like it has gone inactive</a> (the nuget pack even warns that it is elementary). The <a href="http://www.springframework.net/social-linkedin/">other one, by Spring</a>, has a very wide <code>IProfileOperations</code> interface. I wondered what a more fluent interface would look like, so I tried my hand at rolling one over the weekend.</p> <p>I've already written <a href="https://github.com/danludwig/NGeo">a couple of API clients (all together in one library)</a>, but this is my first one with OAuth. There are many more plugin points for this, and so my client's API is a little more complex. I am using <code>DotNetOpenAuth</code> in the background, but trying to hide that as an implementation detail (as much as possible anyway).</p> <p>Here are my goals:</p> <ul> <li>A default implementation that "just works" out of the box.</li> <li>Ability to customize the default implementation either through an IoC container or by overriding classes and implementing interfaces. <ul> <li>The above should be accomplished using a reasonable level of granularity for swapping out different aspects of the implementation. Meaning, allow customization with the least number of interfaces.</li> </ul></li> <li>A "fluent" API to consume LinkedIn data.</li> <li>Only 1 or 2 classes / interfaces to work with in client code. By that I mean the starting interface, where you new something up and use IntelliSense to discover your options.</li> </ul> <p>Let's start with the oauth consumer key and secret. It seems the most logical place for this is in the <code>*.config</code> file, but someone might want to get it from a database to make it easier to set. If you have different app names under a single config, you could also implement this as a factory that retrieves the appropriate consumer key &amp; secret for the app name you want LinkedIn to display to the user. I based the property names on the actual fields from the LinkedIn developer form:</p> <pre><code>namespace LinkedN { // wraps the oauth consumer key and secret public interface IAuthenticateLinkedInApp { string ApiKey { get; } string SecretKey { get; } } } </code></pre> <p><code>DotNetOpenAuth</code> does this in its <code>IConsumerTokenManager</code> interface, which is great, but is mixed with another concern: It contains methods for creating, expiring, and getting access token secrets. I'm not really sure whether these two need to be together. <strong>Should you store your access secrets and tokens along with the consumer key?</strong> Currently I am not, guess I'm hoping that the oauth people thought of this and make all tokens unique across all consumer keys. Either way, just in case, and to make this easier to wrap in a class that implements DNOA's <code>IConsumerTokenManager</code>, I have added the previous interface as a property of this one:</p> <pre><code>namespace LinkedN { public interface IStoreLinkedInSecrets { IAuthenticateLinkedInApp AppCredentials { get; } void Create(string token, string secret); void Expire(string token); string Get(string token); } } </code></pre> <p>But These methods require you to already know the token. Tokens are obtained per user, so care should be taken to make sure we send the correct token when sending an authorized request. For this I have implemented a separate interface just for storing tokens. The default implementation I have now stores it in an HTTP Cookie, so the <code>IPrincipal</code> arguments are ignored. But an application-level implementation of this could be configured to get this from session, database, cache, or whatever, as long as the accessed collection can be keyed on <code>IPrincipal.Identity.Name</code>:</p> <pre><code>namespace LinkedN { public interface IStoreLinkedInTokens { void Create(IPrincipal principal, string token); void Expire(IPrincipal principal); string Get(IPrincipal principal); } } </code></pre> <p>The previous 3 interfaces all provide infrastructure concerns for connecting to LinkedIn via oauth. In the process, you basically use the consumer key &amp; secret (<code>IAuthenticateLinkedInApp</code> concerns) to push the user over to LinkedIn and get them asked if they want to allow access to your app. After user says yes, LinkedIn pushes the user back to your app with an authorization token that is unique to them (<code>IStoreLinkedInTokens</code> concerns, separate from consumer key and secret). I know I've skipped over a lot of stuff that happens behind the scenes, but that's the point. I only really need to do 2 things in order to get started:</p> <pre><code>namespace LinkedN { public interface IConsumeLinkedInApi { void RequestUserAuthorization(LinkedInAuthorizationRequest request); LinkedInAuthorizationResponse ReceiveUserAuthorization(IPrincipal principal); // ... there is actually another method here, more on that later } } </code></pre> <p>The first method is what pushes the user to linkedin. There's nothing special about the request arg, it's basically just a wrapper for the URL you want the user pushed back to after they authorize @linkedin. What I did struggle with a bit is the second method, which is used at the endpoint where linked in pushes the user back to the app. That is the point where you can obtain the access token (WITHOUT the secret). The <code>LinkedInAuthorizationResponse</code> class is basically just a wrapper for the token and the "extra data" key/value pairs, but again, <em>it does not expose the user's secret</em>. Secrets are stored separately by the <code>IStoreLinkedInSecrets</code> implementation, and its use is encapsulated out of the client's scope.</p> <p>What I struggled with was the fact that there are 2 ways you can design the client, and 2 ways to consume it. The second method in the <code>IConsumeLinkedInApi</code> doesn't say anything about how the token gets into the <code>IStoreLinkedInTokens</code> implementation. <strong>Is one of these more correct than the other and, of so, why?</strong></p> <ol> <li>The <code>IConsumeLinkedInApi.ReceiveUserAuthorization(User)</code> could store the token itself, by constructor injecting it into the implementation class.</li> <li>The developer invoking <code>IConsumeLinkedInApi.ReceiveUserAuthorization(User)</code> could maintain his own implementation of <code>IStoreLinkedInTokens</code>. This would mean he may have to have constructor inject / new up / ultimately work with TWO interface instances.</li> </ol> <p>For now I am dealing with it in both ways over the remaineder of the interface:</p> <pre><code>namespace LinkedN { public interface IConsumeLinkedInApi { // you already saw the other 2 methods above IProvideLinkedInEndpoint&lt;TResource&gt; Resource&lt;TResource&gt;(); } public interface IProvideLinkedInEndpoint&lt;out TResource&gt; { IDictionary&lt;Enum, string&gt; RequestBag { get; } TResource RequestUsing(IPrincipal principal); TResource RequestUsing(string token); } } </code></pre> <p>Here you can see the 3rd method on the primary API interface along with the 5th and final interface I have created for the project. I have 2 overloads of <code>RequestUsing</code> because of the struggle I mentioned above. If a developer wants control over the <code>IStoreLinkedInTokens</code> implementation, they can use it to pass a string token directly to send the endpoint request. Otherwise, they can pass an <code>IPrincipal</code> like the <code>Controller.User</code> property in MVC, <code>Thread.CurrentPrincipal</code>, or whatever. They can then expect the <code>RequestUsing</code> method to internally use the <code>IPrincipal</code> as an argument to an encapsulated <code>IStoreLinkedInTokens</code> instance.</p> <p>The fluent code methods for accessing the API are all done with extension methods. Basically there are extension methods that use the <code>RequestBag</code> to configure the api call details. Here are some example extension methods for the <code>PersonProfile</code> endpoint provider implementation:</p> <pre><code>namespace LinkedN { public static class PersonProfileEndpointExtensions { public static IProvideLinkedInEndpoint&lt;PersonProfile&gt; Myself( this IProvideLinkedInEndpoint&lt;PersonProfile&gt; endpoint) { endpoint.ThrowExceptionWhenSettingIdentificationTwice(); endpoint.SetOption(PersonProfileRequestOption.Identification, "~"); return endpoint; } public static IProvideLinkedInEndpoint&lt;PersonProfile&gt; MemberId( this IProvideLinkedInEndpoint&lt;PersonProfile&gt; endpoint, string memberId) { endpoint.ThrowExceptionWhenSettingIdentificationTwice(); endpoint.SetOption(PersonProfileRequestOption.Identification, string.Format("id={0}", memberId)); return endpoint; } public static IProvideLinkedInEndpoint&lt;PersonProfile&gt; MemberUrl( this IProvideLinkedInEndpoint&lt;PersonProfile&gt; endpoint, string memberUrl) { endpoint.ThrowExceptionWhenSettingIdentificationTwice(); endpoint.SetOption(PersonProfileRequestOption.Identification, string.Format("url={0}", memberUrl)); return endpoint; } internal static string GetOption( this IProvideLinkedInEndpoint&lt;PersonProfile&gt; endpoint, PersonProfileRequestOption option) { return endpoint.RequestBag.ContainsKey(option) ? endpoint.RequestBag[option] : null; } private static void SetOption( this IProvideLinkedInEndpoint&lt;PersonProfile&gt; endpoint, PersonProfileRequestOption option, string value) { endpoint.RequestBag[option] = value; } private static void ThrowExceptionWhenSettingIdentificationTwice( this IProvideLinkedInEndpoint&lt;PersonProfile&gt; endpoint) { var option = endpoint.GetOption(PersonProfileRequestOption.Identification); if (!string.IsNullOrWhiteSpace(option)) throw new InvalidOperationException(string.Format( "The person profile endpoint has already been configured to " + "identify resources for '{0}'.", option)); } } } </code></pre> <p>There are other extension methods that do the same thing, setting values in the <code>RequestBag</code>. The <code>IProvideLinkedInEndpoint</code> implementation then uses those settings to configure the REST URL and HTTP headers, which is why it's not meant to be swapped like the other 4 interfaces are. Ultimately you can end up with a client that looks like this:</p> <pre><code>var linkedN = new DefaultLinkedInClient(); var personProfile = linkedN.Resource&lt;PersonProfile&gt; .Myself() .SelectFields( PersonProfileFieldSelector.FirstName, PersonProfileFieldSelector.LastName, PersonProfileFieldSelector.Educations ) .InLanguages("en-US", "es-ES", "zh-CN") .RequestUsing(User) ; </code></pre> <p>The granularity of the <code>SelectFields</code> extension may be a little too much. This can be overloaded to map certain collections of fields though. The default client does the following to "work out of the box":</p> <ol> <li>Has an implementation of <code>IAuthenticateLinkedInApp</code> that stores the consumer key &amp; secret as <code>appSettings</code> in the config file, using the keys <code>"LinkedInRestV1OAuth1aApiKey"</code> and <code>"LinkedInRestV1OAuth1aSecretKey"</code>.</li> <li>Has an implementation of <code>IStoreLinkedInSecrets</code> that uses an XML file stored in the <code>App_Data</code> directory.</li> <li>Has an implementation of <code>IStoreLinkedInTokens</code> that uses cookies to set &amp; get the token on the browser.</li> <li>Has an implementation of <code>IServiceProvider</code> used to scan the assembly for implementations of the generic <code>IProvideLinkedInEndpoint&lt;TResource&gt;</code>. This is needed when an IoC container is absent.</li> </ol> <p>When using an IoC, developers can opt for the non-default <code>LinkedInClient</code> class. It uses constructor injection to resolve the above dependencies. In fact, <code>DefaultLinkedInClient</code> mentioned above just extends <code>LinkedInClient</code> and passes in custom args to its base constructor.</p> <pre><code>public class MyController : Controller { // register IConsumeLinkedInApi to resolve to LinkedInClient instance, // NOT DefaultLinkedInClient instance, in IoC container private readonly IConsumeLinkedInApi _linkedN; public MyController(IConsumeLinkedInApi linkedN) { _linkedN = linkedN; } public ActionResult Consume() { var personProfile = _linkedN.MemberId("youknowthis").RequestUsing(User); } } </code></pre> <p>Everything else is just plumbing. The <code>IProvideLinkedInEndpoint</code> classes internally use their <code>RequestBag</code>s to build URL's and DNOA to send requests / receive responses. Internally they use <code>?format=json</code> and convert the response string to a POCO using <code>DataContactJsonSerializer</code>.</p> <p>Going back to the concern of how to consume the API, hopefully this should illustrate my major concern with this client interface:</p> <pre><code>// how best to design this interface? public class LinkedInController : Controller { private readonly IConsumeLinkedInApi _linkedN; //private readonly IStoreLinkedInTokens _tokens; public LinkedInController(IConsumeLinkedInApi linkedN // , IStoreLinkedInTokens tokens ) { _linkedN = linkedN; //_tokens = tokens; } public ActionResult RequestUserAuthorization() { var callback = Url.Action("ReceiveUserAuthorization"); _linkedN.RequestUserAuthorization( new LinkedInAuthorizatonRequest(Request.Url, callback)); return View(); } public ActionResult ReceiveUserAuthorization() { var response = _linkedN.ReceiveUserAuthorization(); // _tokens.Create(response.Token); return View(); } public ActionResult Resource() { // this implementation assumes the client is smart &amp; can find the token // by the IPrincipal.Identity.Name. var resource = _linkedN.Resource&lt;PersonProfile&gt;.Myself().RequestUsing(User); //// this implementation assumes the client is dumb or not trustworthy, and //// that token storage should be controlled separately from API calls. // var token = _tokens.Get(User); // var token = "test token i got from cookie, session, cache, wherever"; // var resource = _linkedN.Resource&lt;PersonProfile&gt;.Myself() // .RequestUsing(token); return View(); } } </code></pre> <p>Please review my code. If you have any questions, please ask. If you have any comments, please give them.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-16T21:53:08.633", "Id": "87939", "Score": "5", "body": "I really can't find anything to comment on in a review. This is well written code, and obviously well thought out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-08T13:48:34.570", "Id": "99390", "Score": "0", "body": "Sorry it took so long for you to get an answer to your question, there is a large group of us starting a new beginning for Code Review, it looks like you have plenty to offer in terms of helping this site grow with questions and answers, please feel free to join us in [The Second Monitor](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) either to converse with us or bring attention your questions" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-08T15:19:32.833", "Id": "99415", "Score": "1", "body": "If anyone is interested, this code is still sitting in my github account: https://github.com/danludwig/LinkedN" } ]
[ { "body": "<p>As @Jeff pointed out, this code is ...beautiful. Well done!</p>\n\n<hr>\n\n<p>I like the fluent interface a lot, but the code itself is at first glance... wow.</p>\n\n<ul>\n<li><p><strong>Naming</strong> </p>\n\n<ul>\n<li>All identifiers follow conventional casing (<code>camelCase</code> for locals and parameters, <code>PascalCase</code> for types and their members). </li>\n<li>I like that you're using an <code>_underscore</code> prefix for field names, but that's just my opinion - you're perfectly consistent about it, and that is an objective fact.</li>\n<li>Every single name is meaningful.</li>\n<li>Method names start with a verb, the presented interfaces are <em>highly cohesive</em>, focused.</li>\n</ul></li>\n<li><p><strong>Comments</strong></p>\n\n<ul>\n<li><p>If there's an opportunity in your code, it has be about comments. Instead of this:</p>\n\n<pre><code>// wraps the oauth consumer key and secret\npublic interface IAuthenticateLinkedInApp\n</code></pre>\n\n<p>You could have a <code>&lt;summary&gt;</code> XML comment and IntelliSense would pick it up, and people writing the client code would certainly appreciate - it's the difference between this:</p>\n\n<p><img src=\"https://i.stack.imgur.com/TeN3t.png\" alt=\"interface CR.Sandbox.Program.IFoo\"></p>\n\n<p>And that:</p>\n\n<p><img src=\"https://i.stack.imgur.com/Z2pii.png\" alt=\"interface CR.Sandbox.Program.IFoo / Does something foo.\"></p>\n\n<p>If you write your XML comments the same way you crafted your code, having XML documentation on all public members would be the <em>icing on the cake</em>. And if you <em>really</em> flesh it up, you can have the build process generate an XML file for you, with all the documentation in your project - then you can use 3rd-party tools to generate a whole website around that documentation, MSDN-style if you like.</p></li>\n</ul></li>\n<li><p><strong>Exceptions</strong></p>\n\n<ul>\n<li><p>I like that the <code>ThrowExceptionWhenSettingIdentificationTwice</code> extension is throwing an <code>InvalidOperationException</code>, it's a perfectly appropriate exception to be thrown in these circumstances. Again, XML comments would be a nice addition:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Does something foo.\n/// &lt;/summary&gt;\n/// &lt;param name=\"foo\"&gt;Any foo.&lt;/param&gt;\n/// &lt;exception cref=\"InvalidOperationException\"&gt;\n/// Thrown when \"bar\" is specified for &lt;c&gt;foo&lt;/c&gt;.\n/// &lt;/exception&gt;\npublic void DoSomethingFoo(string foo)\n{\n if (foo == \"bar\")\n {\n throw new InvalidOperationException(\"Invalid foo.\");\n }\n}\n</code></pre></li>\n<li><p>Throwing your own custom <code>OptionAlreadySetException</code> would allow you to turn this:</p>\n\n<pre><code>var option = endpoint.GetOption(PersonProfileRequestOption.Identification);\nif (!string.IsNullOrWhiteSpace(option))\n throw new InvalidOperationException(string.Format(\n \"The person profile endpoint has already been configured to \" + \n \"identify resources for '{0}'.\", option));\n</code></pre>\n\n<p>Into that:</p>\n\n<pre><code>var option = endpoint.GetOption(PersonProfileRequestOption.Identification);\nif (!string.IsNullOrWhiteSpace(option))\n throw new OptionAlreadySetException(option);\n</code></pre></li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p>Your code looks as SOLID as can be. Being a fan of <em>Dependency Injection</em>, I like that you've implemented a class for use with an IoC container. You've done a ...<em>solid</em> job. Seriously. I want to be maintaining code written like that!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-08T03:37:08.700", "Id": "56398", "ParentId": "13458", "Score": "15" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T06:26:07.083", "Id": "13458", "Score": "28", "Tags": [ "c#", ".net", "asp.net-mvc-3", "rest", "linkedin" ], "Title": "Fluent LinkedIn REST API client interface design" }
13458
<p>I have a grid that lists products. The grid is three columns wide, but it could grow to be four or five columns wide. I've written my script to count the columns. The markup is something like this:</p> <pre><code>&lt;ul&gt; &lt;li class="item first"&gt;...&lt;/li&gt; &lt;li class="item"&gt;...&lt;/li&gt; &lt;li class="item"&gt;...&lt;/li&gt; &lt;li class="item first"&gt;...&lt;/li&gt; &lt;li class="item"&gt;...&lt;/li&gt; &lt;li class="item"&gt;...&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>In the project, I can't change the markup. I can however write JavaScript/jQuery any which way I please. What I have is working, but I'm using four loops. Since my JS chops aren't too hot, I'm not convinced that what I have is particularly fast or concise.</p> <pre><code>jQuery(document).ready(function ($) { "use strict"; var maxItemHeight, firstItem = $('.item.first'), gridRow = [], i; firstItem.each(function () { gridRow.length = 0; maxItemHeight = 0; gridRow.push($(this)); $(this).nextUntil(firstItem).each(function () { gridRow.push($(this)); }); for (i = 0; i &lt; gridRow.length; i++) { maxItemHeight = (gridRow[i].find('h2').outerHeight() &gt; maxItemHeight) ? gridRow[i].find('h2').outerHeight() : maxItemHeight; }; for (i = 0; i &lt; gridRow.length; i++) { gridRow[i].find('h2').css('height', maxItemHeight); }; }); }); </code></pre> <p>How could this be improved?</p>
[]
[ { "body": "<p>Can't say if this is much faster, but it's more concise</p>\n\n<pre><code>jQuery(document).ready(function($) {\n \"use strict\";\n\n var firstItems = $('.item.first');\n\n firstItems.each(function() {\n var $first, row, headings, heights, maxHeight;\n\n $first = $(this);\n\n // Get collection of \"columns\"\n row = $first.add($first.nextUntil(firstItems));\n\n // Find each column's heading\n headings = row.find(\"h2\"); \n\n // Get the heights of the headings\n heights = headings.map(function () {\n return $(this).outerHeight();\n }).toArray();\n\n // Get the maximum\n maxHeight = Math.max.apply(null, heights);\n\n // Set the heading heights to the maximum\n headings.css(\"height\", maxHeight);\n });\n});​​​\n</code></pre>\n\n<p>--Edit--</p>\n\n<p>In my particular instance, the above script had conflict issues with prototype, since it lives inside a Magento install. I <a href=\"https://stackoverflow.com/questions/11434468/jquery-conflicting-with-prototype-in-magento\">sought help and found this improvement</a>.</p>\n\n<p>/Jezen</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T13:12:04.970", "Id": "21762", "Score": "0", "body": "That is so damn cool. I feel there's plenty to learn from this. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T15:05:13.283", "Id": "21942", "Score": "0", "body": "I'm editing in a fix." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T12:16:49.290", "Id": "13460", "ParentId": "13459", "Score": "3" } } ]
{ "AcceptedAnswerId": "13460", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T09:18:51.673", "Id": "13459", "Score": "0", "Tags": [ "javascript", "jquery" ], "Title": "Iterating through each grid row and matching elements to largest height" }
13459
<p>I have written some code to establish a client and server. I have managed to get a one way communication from client to server. I have added the code below. Can someone please have a look and see it is the right way to do it? If this is good enough, how can I get two communication to work now?</p> <p>Client: </p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #include &lt;errno.h&gt; #include &lt;string.h&gt; #include &lt;netdb.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/socket.h&gt; #include &lt;netinet/in.h&gt; #include &lt;arpa/inet.h&gt; #define PORT 3490 #define MAXSIZE 1024 int main(int argc, char *argv[]) { struct sockaddr_in server_info; struct hostent *he; int socket_fd,num; char buffer[1024]; char buff[1024]; if (argc != 2) { fprintf(stderr, "Usage: client hostname\n"); exit(1); } if ((he = gethostbyname(argv[1]))==NULL) { fprintf(stderr, "Cannot get host name\n"); exit(1); } if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0))== -1) { fprintf(stderr, "Socket Failure!!\n"); exit(1); } memset(&amp;server_info, 0, sizeof(server_info)); server_info.sin_family = AF_INET; server_info.sin_port = htons(PORT); server_info.sin_addr = *((struct in_addr *)he-&gt;h_addr); if (connect(socket_fd, (struct sockaddr *)&amp;server_info, sizeof(struct sockaddr))&lt;0) { //fprintf(stderr, "Connection Failure\n"); perror("connect"); exit(1); } //buffer = "Hello World!! Lets have fun\n"; //memset(buffer, 0 , sizeof(buffer)); while(1) { fgets(buffer,MAXSIZE-1,stdin); if ((send(socket_fd,buffer, strlen(buffer),0))== -1) { fprintf(stderr, "Failure Sending Message\n"); close(socket_fd); exit(1); } else { printf("Message being sent: %s\n",buffer); } } /*if ((num = recv(socket_fd, buff, 1024,0))== -1) { //fprintf(stderr,"Error in receiving message!!\n"); perror("recv"); exit(1); } // num = recv(client_fd, buffer, sizeof(buffer),0); buff[num] = '\0'; printf("Message received: %s\nNumber of bytes received: %d\n", buff,num);*/ close(socket_fd); } </code></pre> <p>Server: </p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #include &lt;errno.h&gt; #include &lt;string.h&gt; #include &lt;netdb.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/socket.h&gt; #include &lt;netinet/in.h&gt; #include &lt;arpa/inet.h&gt; #define PORT 3490 #define BACKLOG 10 int main() { struct sockaddr_in server; struct sockaddr_in dest; int status,socket_fd, client_fd,num; socklen_t size; char buffer[10241]; char *buff; // memset(buffer,0,sizeof(buffer)); int yes =1; if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0))== -1) { fprintf(stderr, "Socket failure!!\n"); exit(1); } if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &amp;yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } memset(&amp;server, 0, sizeof(server)); memset(&amp;dest,0,sizeof(dest)); server.sin_family = AF_INET; server.sin_port = htons(PORT); server.sin_addr.s_addr = INADDR_ANY; if ((bind(socket_fd, (struct sockaddr *)&amp;server, sizeof(struct sockaddr )))== -1) { //sizeof(struct sockaddr) fprintf(stderr, "Binding Failure\n"); exit(1); } if ((listen(socket_fd, BACKLOG))== -1){ fprintf(stderr, "Listening Failure\n"); exit(1); } while(1) { size = sizeof(struct sockaddr_in); if ((client_fd = accept(socket_fd, (struct sockaddr *)&amp;dest, &amp;size))==-1) { //fprintf(stderr,"Accept Failure\n"); perror("accept"); exit(1); } printf("Server got connection from client %s\n", inet_ntoa(dest.sin_addr)); //buffer = "Hello World!! I am networking!!\n"; while(1) { if ((num = recv(client_fd, buffer, 10240,0))== -1) { //fprintf(stderr,"Error in receiving message!!\n"); perror("recv"); exit(1); } else if (num == 0) { printf("Connection closed\n"); return 0; } // num = recv(client_fd, buffer, sizeof(buffer),0); buffer[num] = '\0'; printf("Message received: %s\n", buffer); } /* buff = "I am communicating with the client!!\n"; if ((send(client_fd,buff, strlen(buff),0))== -1) { fprintf(stderr, "Failure Sending Message\n"); close(client_fd); exit(1); } else { printf("Message being sent: %s\nNumber of bytes sent: %d\n",buff, strlen(buff)); }*/ close(client_fd); close(socket_fd); //return 0; } //close(client_fd); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T08:00:36.123", "Id": "21763", "Score": "0", "body": "what i meant to ask if my code was the right way to establish one way communication??\nmy more specific ques is how can i establsih 2-way (duplex communication)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T08:04:52.253", "Id": "21764", "Score": "0", "body": "and thnx for the link!!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T20:50:55.163", "Id": "58738", "Score": "0", "body": "Checkout \"A Sample GNU/Linux Application\" chapter from \"[Advanced Linux Programming](http://www.advancedlinuxprogramming.com/alp-folder/)\" book. In this chapter you can find good practices for two-way communication since a simple HTTP web server is implemented." } ]
[ { "body": "<p>You can do a two way data transfer here. I have modified your code to show that. Now the \nserver is echoing back to the client the same string which it has received. Now the client \ndisplays the same string, which it receives from the server. Pl. experiment with this. </p>\n\n<p>client main loop </p>\n\n<pre><code> while(1) {\n printf(\"Client: Enter Data for Server:\\n\");\n fgets(buffer,MAXSIZE-1,stdin);\n if ((send(socket_fd,buffer, strlen(buffer),0))== -1) {\n fprintf(stderr, \"Failure Sending Message\\n\");\n close(socket_fd);\n exit(1);\n }\n else {\n printf(\"Client:Message being sent: %s\\n\",buffer);\n num = recv(socket_fd, buffer, sizeof(buffer),0);\n if ( num &lt;= 0 )\n {\n printf(\"Either Connection Closed or Error\\n\");\n //Break from the While\n break;\n }\n\n buff[num] = '\\0';\n printf(\"Client:Message Received From Server - %s\\n\",buffer);\n }\n }\n close(socket_fd);\n\n}//End of main\n</code></pre>\n\n<p>Server main loop</p>\n\n<pre><code> while(1) {\n\n size = sizeof(struct sockaddr_in);\n\n if ((client_fd = accept(socket_fd, (struct sockaddr *)&amp;dest, &amp;size))==-1 ) {\n perror(\"accept\");\n exit(1);\n }\n printf(\"Server got connection from client %s\\n\", inet_ntoa(dest.sin_addr));\n\n while(1) {\n\n if ((num = recv(client_fd, buffer, 1024,0))== -1) {\n perror(\"recv\");\n exit(1);\n }\n else if (num == 0) {\n printf(\"Connection closed\\n\");\n //So I can now wait for another client\n break;\n }\n buffer[num] = '\\0';\n printf(\"Server:Msg Received %s\\n\", buffer);\n if ((send(client_fd,buffer, strlen(buffer),0))== -1) \n {\n fprintf(stderr, \"Failure Sending Message\\n\");\n close(client_fd);\n break;\n }\n\n printf(\"Server:Msg being sent: %s\\nNumber of bytes sent: %d\\n\",b\n uffer, strlen(buffer));\n\n } //End of Inner While...\n //Close Connection Socket\n close(client_fd);\n } //Outer While\n\n close(socket_fd);\n return 0;\n} //End of main\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T17:04:41.750", "Id": "21776", "Score": "0", "body": "thank you. i will test it out!! \nso this 2way communication is sufficient to be considered as chat messaging btw two machines???" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T17:13:11.083", "Id": "21784", "Score": "0", "body": "Since you are using TCP, this is having some limitations. TCP is a byte oriented protocol. So ideally you cannot expect to get all the data in a single \"recv\". You need to run recv in loop even to grab all the data in a line, if the line is arbitrarily large. Anyway this code should work for normal user inputs, which may not be that large. I would suggest, you may also try implementing this using UDP.Also pl. read from the link , http://www.faqs.org/faqs/unix-faq/socket/ to learn more about sockets or from any good book like \"Network Programming\" byStevens.Pl. let me know if the code worked." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T04:56:52.897", "Id": "21826", "Score": "0", "body": "nope, it is not working!!client is able to send message which server receives, but after that nothing happens!!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T06:04:38.737", "Id": "21828", "Score": "0", "body": "I missed the send function in the server side , which I have updated.The character array buffer is populated by the recv function and the same array \"buffer\" is used to send data.I hope you are not using the \"buff\" as was there in your orginal code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T06:05:45.977", "Id": "21829", "Score": "0", "body": "hey, i made a mistake!! ur modifications worked!! but now i want to implement a continuous 2 way communication whereby a server can also send messages to the client, can u help me how? i cannot find much on google\nalso, how do i check in recv function if all the data has been actually received??\nthnx again for ur help!!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T06:27:17.643", "Id": "21830", "Score": "0", "body": "If you want server to send messages to the client.. simply add a fgets after the server's recv (as you did in client) and then use send.In your current code the problem will be, this becomes an iterative server, which can server only a single client at one point of time. That means finally you need to implement a concurrent server using threads/fork.For the second question, how to know that you have received all the data using recv->when recv returns 0, but this is possible only when the other side closes connection (this will not work for you) or send number of data, before sending data." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T06:45:23.167", "Id": "21831", "Score": "0", "body": "another problem is that this isnt full duplex. do i need to implement full duplex using threads??? \nand to handle multiple clients, i need to use fork()??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T07:02:32.447", "Id": "21833", "Score": "0", "body": "yes, you can do it in that way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T08:12:45.937", "Id": "21834", "Score": "0", "body": "hey Tanmoy, i managed to get full duplex to work using fork(). what else can i try now to expand on sockets programming?? wud really appreciate some guidance here" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T12:33:51.243", "Id": "13462", "ParentId": "13461", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T03:34:04.230", "Id": "13461", "Score": "8", "Tags": [ "c", "networking" ], "Title": "Two-way communication in TCP: server-client implementation" }
13461
<p>Does this piece of code make sense? The idea is to throw any exceptions that may occur but always run the finally block to close the streams. </p> <pre><code>private void streamToFile(HttpResponse transferResponse) throws Exception { OutputStream output = null; InputStream input = null; try { input = new BufferedInputStream(transferResponse.getEntity().getContent()); output = new FileOutputStream(transferFile); final int BUFFER_SIZE = 1024*10; byte data[] = new byte[BUFFER_SIZE]; int count; while ((count = input.read(data)) != -1) { output.write(data, 0, count); publishProgress(count); remainingBytes = remainingBytes - count; } } finally { input.close(); output.close(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T14:29:22.117", "Id": "21765", "Score": "4", "body": "This is what a `finally` block is for." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T15:03:15.677", "Id": "21767", "Score": "0", "body": "It runs the code in all circumstances. ie weather the exception is thrown or not" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T15:19:54.723", "Id": "21768", "Score": "0", "body": "My comment wasn’t a question, it was a statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T15:30:23.927", "Id": "21769", "Score": "0", "body": "Sorry Konrad, its not so clear. What is?" } ]
[ { "body": "<p>Yes this is the right way to do it but you should check output and input variables for null value before calling on them the close() method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-03T05:06:00.057", "Id": "91651", "Score": "0", "body": "... and also change it to something like `try {close1(); } finally {close2()}`, so that both get executed." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T14:24:03.697", "Id": "13465", "ParentId": "13464", "Score": "4" } }, { "body": "<p>You could use the <a href=\"http://commons.apache.org/io/apidocs/org/apache/commons/io/IOUtils.html#closeQuietly%28java.io.InputStream%29\" rel=\"nofollow\"><code>closeQuietly</code></a> methods of <code>IOUtils</code> (<a href=\"http://commons.apache.org/io/\" rel=\"nofollow\">Apache Commons IO</a>) (or similar ones) for input streams. It ignores exceptions and accepts <code>null</code> values.</p>\n\n<p>Its implementation is just a few lines of code, so you can copy it directly to your Android application without the jar file:</p>\n\n<pre><code>public static void closeQuietly(Closeable closeable) {\n try {\n if (closeable != null) {\n closeable.close();\n }\n } catch (IOException ioe) {\n // ignore\n }\n}\n</code></pre>\n\n<p>You could also create a close method for ouput streams:</p>\n\n<pre><code>public static void closeQuietly(OutputStream stream) throws IOException {\n if (stream != null) {\n stream.close();\n }\n}\n</code></pre>\n\n<p>Both methods accept <code>null</code> values which means that you can call them with <code>null</code>, <code>closeQuietly</code> and <code>close</code> will handle that and you don't have to check <code>null</code> values in the <code>finally</code> block:</p>\n\n<pre><code>} finally {\n if (input != null) {\n closeQuietly(input);\n }\n close(output);\n}\n</code></pre>\n\n<p>Instead of this the following is completely enough:</p>\n\n<pre><code>} finally {\n closeQuietly(input);\n close(output);\n}\n</code></pre>\n\n<p>It's much simpler.</p>\n\n<p><code>closeQuietly</code> ignores exceptions which means that it catches them but don't do anything with them. Notice the empty <code>catch</code> block:</p>\n\n<pre><code> } catch (IOException ioe) {\n // ignore\n }\n</code></pre>\n\n<p>It ensures that if <code>closeable.close()</code> throws an <code>IOException</code> the <code>close(output)</code> will run and it will close the <code>output</code> stream too.</p>\n\n<p>I'm a little bit paranoid about this so I always put a logging statement to the catch block:</p>\n\n<pre><code> } catch (IOException ioe) {\n logger.warn(\"Could not close the stream\", ioe);\n }\n</code></pre>\n\n<p>To be honest, I've never seen this exception, so I think it's safe to left this block empty.</p>\n\n<p>Ignoring <code>IOException</code>s of output streams could be dangerous: you might miss a bug and get a corrupted output file.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T15:01:46.583", "Id": "21766", "Score": "0", "body": "its actually Android so thats not really an option" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T15:36:00.177", "Id": "21770", "Score": "0", "body": "@jiduvah: check the update, please." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T15:44:19.060", "Id": "21772", "Score": "0", "body": "what is the point of this code? You mentioned that I should use closeQuietly methods as it ignores exceptions and accepts null. But here you are catching an exception and checking for null" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T15:48:25.717", "Id": "21773", "Score": "2", "body": "... so you include this function, and call it from your `finally` blocks - instead of checking for nulls and exceptions and calling `.close()`. Seems clear enough for me - not for you?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T22:30:43.927", "Id": "21810", "Score": "0", "body": "Ah because in my code if the .close() throws an exception it will be passed up. I didn't think about that" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-30T04:50:08.680", "Id": "90130", "Score": "1", "body": "You should NOT use `closeQuietly`, surely not for outputs streams, as it's [unsafe](http://goo.gl/eTEoQp). [`Closer`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Closer.html) is the replacement (or [`@Cleanup`](http://projectlombok.org/features/Cleanup.html) if you can use Lombok)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-01T10:41:29.337", "Id": "91375", "Score": "0", "body": "@maaartinus: Thanks for catching it! I remember that I've pointed out an ignored outputstream.close() exception on a code review with a colleague a few months ago so it's fun that I did the same mistake here. Anyway, I've updated the answer. Thanks for the `Closer` link too, that was new to me. You could write it as an answer too (I would upvote it)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-03T05:04:33.660", "Id": "91649", "Score": "0", "body": "No, a single complete answer is better. I'm just missing here my [favorite solution](http://projectlombok.org/features/Cleanup.html)." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T14:45:00.800", "Id": "13466", "ParentId": "13464", "Score": "10" } } ]
{ "AcceptedAnswerId": "13466", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T13:58:46.877", "Id": "13464", "Score": "2", "Tags": [ "java", "exception-handling" ], "Title": "Throwing the Exception But Using the Finally Block" }
13464
<p>The following works as intended, however is there a more concise way to write this script without changing it too much? It's a simple menu with sub-levels which have a plus/minus icon when each <code>li</code> opens/closes.</p> <p>jQuery:</p> <pre><code>$(document).ready(function() { $li = $('#main &gt; li.expand'); $li.click(function(){ $ul = $(this).find('ul.sub-level').delay(200).slideDown(400); $(this).removeClass('expand').addClass('minus'); $('#main &gt; li &gt; ul').not($ul).slideUp('slow'); $('#main &gt; li.minus').not($(this)).removeClass('minus').addClass('expand'); }) $li2 = $('.sub-level &gt; li.expand'); $li2.click(function(){ $(this).find('ul.sub-level2').delay(200).slideToggle(400); $li2.toggleClass('minus').toggleClass('expand'); }) }); </code></pre> <p>HTML:</p> <pre><code>&lt;ul id="main"&gt; &lt;li class="expand"&gt;test-1 &lt;ul class="sub-level"&gt; &lt;li class="expand"&gt;sub-test-1 &lt;ul class="sub-level2"&gt; &lt;li&gt;sfasfasf&lt;/li&gt; &lt;li&gt;sfafasf&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;test-2&lt;/li&gt; &lt;li class="expand"&gt;test-3 &lt;ul class="sub-level"&gt; &lt;li&gt;sub-test-2&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;test-4&lt;/li&gt; &lt;/ul&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T16:46:57.007", "Id": "21777", "Score": "1", "body": "One suggestion, add `var` before your variables." } ]
[ { "body": "<p>Some suggestions:</p>\n\n<ul>\n<li>Use <code>var</code> when declaring variables, unless you <em>really</em> want to make global variables (which you probably don't)</li>\n<li><p>Combine <code>var</code> statements using <code>,</code></p>\n\n<pre><code>var a = 1, b = 2, c = 3;\n</code></pre></li>\n<li><p>Combine classes in <code>toggleClass</code></p>\n\n<pre><code>$(this).toggleClass('minus expand')\n</code></pre></li>\n<li>Cache selectors that are used often (like <code>$('#main')</code>)</li>\n<li>You don't need to use <code>$li2</code> inside the click handler, you can just use <code>$(this)</code></li>\n<li>Turn repeated code into a function</li>\n</ul>\n\n\n\n<pre><code>$(function(){\n var $main = ('#main'),\n slide = function(ele, find){\n return $(ele).toggleClass('minus expand').find(find).delay(200).slideToggle(400);\n },\n $li = $('&gt; li.expand', $main).click(function(){\n var $ul = slide(this, 'ul.sub-level');\n $('&gt; li &gt; ul', $main).not($ul).slideUp('slow');\n $('&gt; li.minus', $main).not(this).toggleClass('minus expand')\n }),\n $li2 = $('.sub-level &gt; li.expand').click(function(){\n slide(this, 'ul.sub-level2');\n });\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T18:06:00.487", "Id": "21786", "Score": "0", "body": "You don't appear to need `$li` or `$li2` at all. It might be useful though to extract and name some of the constants in there in case you need to discover/change them in the future." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T18:09:14.603", "Id": "21787", "Score": "0", "body": "@BillBarry: I kept `$li` and `$li2`, because I figured this script was part of a bigger program, and that maybe they were used again elsewhere." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T18:41:30.423", "Id": "21792", "Score": "1", "body": "@Rocket - After reviewing your answer again I like the way you refactored the slide logic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T18:42:34.640", "Id": "21793", "Score": "0", "body": "@ChaosPandion: Thanks. I prefer using functions instead of writing the same thing multiple times." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T22:42:37.813", "Id": "21894", "Score": "0", "body": "`You don't need to use $li2 inside the click handler, you can just use $(this)` - Why create a new jQuery object every time the element is clicked?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T00:56:59.710", "Id": "21902", "Score": "0", "body": "@JosephSilber: Because `$li2` can contain *multiple* elements, and `this` will be just the one clicked on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T01:46:08.893", "Id": "21911", "Score": "0", "body": "@Rocket - Then he **should** use `$(this)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T14:14:00.030", "Id": "21940", "Score": "0", "body": "@JosephSilber: Yes, exactly. I guess I should change my wording. Unless he *does* actually want to change all the elements, and not just the clicked one. Whatever." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T16:58:45.983", "Id": "13469", "ParentId": "13468", "Score": "6" } }, { "body": "<p>You want to make sure you always declare your variables before you assign. The reason for this is JavaScript will declare and assign in one statement but always on the global scope. This might overwrite important variables and cause you hours of debugging. The following has been cleaned up with some explanations.</p>\n\n<pre><code>// I personally prefer passing my ready callbacks directly to the jQuery function.\n$(function() {\n // Declare a few constants for easier maintenance\n var delayTime = 200, slideDownTime = 400, slideUpSpeed = 'slow';\n\n // No need to declare or assign a variable here.\n $('#main &gt; li.expand').click(function() { \n // Lets declare this since we use it quite often\n var $this = $(this);\n // Modify the top element first \n $this.removeClass('expand').addClass('minus');\n // No need to assign this result\n $this.find('ul.sub-level').delay(delayTime).slideDown(slideDownTime); \n // Take advantage of the not selector\n $('#main &gt; li &gt; ul:not(.sub-level)').slideUp(slideUpSpeed);\n // Pass our declared variable instead and take advantage of toggleClass\n $('#main &gt; li.minus').not($this).toggleClass('minus expand');\n });\n\n // Declare and assign. Maybe come up with a better name?\n var $li = $('.sub-level &gt; li.expand');\n $li.click(function(){\n $(this).find('ul.sub-level2').delay(delayTime).slideToggle(slideDownTime);\n $li.toggleClass('minus expand');\n }); \n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T18:10:34.443", "Id": "21788", "Score": "1", "body": "`$li.toggleClass('minus').toggleClass('expand');` could more simply be: `$(this).toggleClass('minus expand')`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T18:37:50.393", "Id": "21790", "Score": "0", "body": "@Rocket - Nice catch, I didn't even notice it when I reviewed your answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T18:39:01.023", "Id": "21791", "Score": "0", "body": "In my answer, I abstracted that out to its own function." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T17:42:13.017", "Id": "13471", "ParentId": "13468", "Score": "3" } } ]
{ "AcceptedAnswerId": "13471", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T16:51:30.113", "Id": "13468", "Score": "7", "Tags": [ "javascript", "jquery", "html" ], "Title": "Simple menu with sub-levels" }
13468
<p>This is my very very very first attempt to write anything meaningful in node. The client side is a simple form that has login, workspace, and simply saves them onto the database. It would have been a 5-liner in PHP!</p> <p>My question really is: does this code look sane/good? I am trying to avoid using async.js for now, just because I want to get my hands dirty a little to start with.</p> <p>A few notes:</p> <ul> <li><p>I want to check if workspace and user names are taken first, but I want to check for BOTH in case they are taken</p></li> <li><p>There is still a slight race condition here: what two users submit different usernames and same workspace names at the same time? OK it's unlikely, but one of them will end up failing (one of them will be workspace-less). How would you address it? Simply deleting the user just created? Or...?</p></li> <li><p>There is a lot of indentation here. I know that it's a known issue with node... I cannot really use "return" as a trick to interrupt execution, because it's often used in an anonymous function context. So...</p></li> <li><p>I sometimes go next("Bad error here"). I plan on writing an error handler in Connect to handle these (I will probably log things onto the database).</p></li> </ul> <p>Here we go...</p> <pre><code>// Helper function. The javascript on the other side calls this with Ajax, and expects // a hash with "response" (can be OK or ERRORS) and a "errors" vector var serverResponse = function(res, errors){ if(errors.length){ res.json( { response: 'ERRORS', errors: errors } , 200) console.log("Sent ERROR"); } else { res.json( { response: 'OK' } , 200) console.log("Sent OK"); } } // The actual call exports.nonApiRegister = function(req, res, next){ // ***** UNINDENTED ON PURPOSE: artificial delay setTimeout(function(){ // ***** var errors = []; var Workspace = mongoose.model("Workspace"); var User = mongoose.model("User"); User.findOne( { login: req.body.login}, function(err, docs){ // Log database error if it's there if(err){ next("Database error fetching user"); // TODO: add error handler } else { // If the user exists, add it to the error vector BUT keep going if(docs){ errors.push({ field:'login', message: 'Login name taken, sorry!' } ); } Workspace.findOne({ name: req.body.workspace }, function(err, docs){ if(err){ next("Database error fetching workspace"); } else { if(docs){ errors.push( {field: "workspace", message: "Workspace taken, sorry!"} ); } if(errors.length != 0){ serverResponse(res, errors); } else { // // AT THIS POINT, UNLESS SOMETHING JUMPS ON US, both user and workspace are available // // User doesn't exist: create it var u = new User(); u.login = req.body.login; u.password = req.body.password[0]; u.workspaceIds = []; u.save( function(err) { if(err){ next("Database error saving user"); } else { var w = new Workspace(); w.name = req.body.workspace; w.activeFlag = true; w.ownerUserId = u._id; w.countryId = null; w.save( function(err){ if(err){ next("Database error saving workspace. WATCH OUT: user " + u.login + " doesn't have a workspace!"); } else{ serverResponse(res, errors); } }) } }) } } }) } }); // } , 500); // Artificial timeout // } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T09:29:00.990", "Id": "21789", "Score": "0", "body": "since you are using mongodb, and i assume a workspace has many users, why dont you embed users in the workspace collection?" } ]
[ { "body": "<blockquote>\n <p>There is a lot of indentation here. I know that it's a known issue with node...</p>\n</blockquote>\n\n<p>In JavaScript you can avoid deep nesting by defining the functions ahead of time. For example:</p>\n\n<pre><code>var userFindOneHandler = function(err, docs) {\n // code here \n}\n\nUser.findOne( { login: req.body.login}, findOneHandler );\n</code></pre>\n\n<p>and you can do this for all the nested calls (e.g. create a workspaceFindOneHandler.) I've got small example of something like this in here: <a href=\"http://hectorcorrea.com/Blog/JavaScript-Async-Programming-for-Sync-Heads\" rel=\"nofollow\">http://hectorcorrea.com/Blog/JavaScript-Async-Programming-for-Sync-Heads</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T13:08:19.587", "Id": "13474", "ParentId": "13473", "Score": "2" } }, { "body": "<p>Here are some simple tips.</p>\n\n<h1>1)</h1>\n\n<p>You can combine the two if conditions for <code>if(docs)</code> and <code>if(errors.length != 0)</code>, since if docs is true, then errors has positive length.</p>\n\n<p>Old Code:</p>\n\n<pre><code>if (docs) {\n errors.push({\n 'field' : field,\n 'message' : errorMessage\n });\n}\nif (errors.length) {\n errors.push({\n field : \"workspace\",\n message : \"Workspace taken, sorry!\"\n });\n serverResponse(res, errors);\n return;\n}\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>if (docs) {\n errors.push({\n field : \"workspace\",\n message : \"Workspace taken, sorry!\"\n });\n serverResponse(res, errors);\n return;\n}\n</code></pre>\n\n<h1>2)</h1>\n\n<p>For this sitation, it's best not to make multiple function calls to the same function.</p>\n\n<p>Old Code:</p>\n\n<pre><code>var serverResponse = function(res, errors){\n if(errors.length){\n res.json( { response: 'ERRORS', errors: errors } , 200)\n console.log(\"Sent ERROR\");\n } else {\n res.json( { response: 'OK' } , 200)\n console.log(\"Sent OK\");\n }\n}\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>var serverResponse = function (res, errors) {\n var status = {};\n if (errors.length) {\n status.response = 'ERRORS';\n status.errors = errors;\n } else {\n status.response = 'OK';\n }\n res.json( status, 200 );\n console.log( \"SENT \" + status.response );\n}\n</code></pre>\n\n<h1>3)</h1>\n\n<p>Pass warnings but not errors. Deal with errors immediately.</p>\n\n<h1>4)</h1>\n\n<p>Avoid having too many else conditions. Use a if guard to avoid this.</p>\n\n<p>Old Code:</p>\n\n<pre><code>function a( err ){\n if( err ){\n throw new Error( err );\n }else{\n //... code\n }\n} \n</code></pre>\n\n<p>New Code: </p>\n\n<pre><code>function a( err ){\n if( err ){\n throw new Error( err );\n return\n }\n //... code \n} \n</code></pre>\n\n<p>*/</p>\n\n<h1>5)</h1>\n\n<p>Don't repeat yourself. </p>\n\n<h1>6)</h1>\n\n<p>Split up functions longer than 8 - 12 lines into smaller functions.</p>\n\n<h1>7)</h1>\n\n<p><code>if(errors.length != 0){</code> is the same as <code>if(error.length){</code>.</p>\n\n<h1>8)</h1>\n\n<p>Try to only have 1 nexted functions created in a single function. The <code>setTimeout</code> section has this problem.</p>\n\n<h1>9)</h1>\n\n<p>If it doesn't hurt the performance or security of the program then I would make <code>User</code> and <code>Workspace</code> global variables. Otherwise you could pass them where needed.</p>\n\n<h1>Final Code Revision</h1>\n\n<pre><code>var User, Workspace;\nvar serverResponse = function (res, errors) {\n var status = {};\n if (errors.length) {\n status.response = 'ERRORS';\n status.errors = errors;\n } else {\n status.response = 'OK';\n }\n res.json( status, 200 );\n console.log( \"SENT \" + status.response );\n};\nvar getDatabaseRequestFunc = function (field, errorMessage, callback) {\n return function (err, docs) {\n if (err) {\n next(\"Database error fetching field: \" + field);\n return;\n }\n if (docs) {\n var error = [{\n 'field' : field,\n 'message' : errorMessage\n }];\n serverResponse(res, error);\n return;\n }\n callback();\n };\n};\nvar getUserSaveFunc = function (req, res, next, user) {\n return function (err) {\n if (err) {\n next(\"Database error saving user\");\n return;\n }\n var w = new Workspace();\n w.name = req.body.workspace;\n w.activeFlag = true;\n w.ownerUserId = user._id;\n w.countryId = null;\n w.save(function (err) {\n if (err) {\n next(\"Database error saving workspace. WATCH OUT: user \" + user.login + \" doesn't have a workspace!\");\n return;\n }\n serverResponse(res, []);\n });\n };\n};\nvar registerWorkspace = function (req, res, next) {\n Workspace.findOne({\n name : req.body.workspace\n }, getDatabaseRequestFunc( \"workspace\", \"Workspace taken, sorry!\" , function(){\n var u = new User();\n u.login = req.body.login;\n u.password = req.body.password[0];\n u.workspaceIds = [];\n u.save(getUserSaveFunc(req, res, next, u));\n })\n );\n};\nvar registerUserLogin = function (req, res, next) {\n User.findOne({\n login : req.body.login\n }, getDatabaseRequestFunc( \"login\", \"Login name taken, sorry!\" , function(){\n registerWorkspace(req, res, next);\n })\n );\n};\nexports.nonApiRegister = function (req, res, next) {\n setTimeout(function () {\n User = mongoose.model(\"User\");\n Workspace = mongoose.model(\"Workspace\"); \n registerUserLogin(req, res, next);\n }, 500);\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T01:50:45.787", "Id": "83321", "Score": "0", "body": "Thank you and sorry for the late acceptance. My goodness, it's been a while and about 60,000 lines of code on my side, and I've learned a little since then :D Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-07T21:02:28.763", "Id": "15423", "ParentId": "13473", "Score": "3" } } ]
{ "AcceptedAnswerId": "15423", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T03:28:10.490", "Id": "13473", "Score": "1", "Tags": [ "javascript", "node.js", "asynchronous" ], "Title": "A server response written in node/express/mongodb: does this look right?" }
13473
<p>I've got a class which describes and calculates centrifugal pump impeller properties (dimensions, flow speed etc. ). At the beginning i have created it in this way (since my class is quite large and calculations are complex i will simplify it using cylinder as example):</p> <pre><code>class Cylinder { double height; double radius; //Properties rising event when value is changed //Constructors //Property changed event handler implementation public double FlatSideArea() { return Math.PI * radius; } public double Volume() { return FlatSideArea()*height; } } </code></pre> <p>So i have ended up with a lot of methods which calls each other, additionally number of unnecessary method calls is growing when i'm displaying results to the screen.</p> <p>My last solution to this problem was creating a class in this way:</p> <pre><code>enum PropertyType { Height, Radius, FlatSideArea, Volume } class Cylinder { double height; double radius; double flatSideArea; double volume; public double Radius { get { return radius; } set { if (radius != value) { radius = value; RisePropertyChanged(PropertyType.Radius); } } } public double Height { get { return height; } set { if (height != value) { height = value; RisePropertyChanged(PropertyType.Height); } } } public double FlatSideArea { get { return flatSideArea; } private set { if (flatSideArea != value) { flatSideArea = value; RisePropertyChanged(PropertyType.FlatSideArea); } } } public double Volume { get { return volume; } private set { if (volume != value) { volume = value; RisePropertyChanged(PropertyType.Volume); } } } public Cylinder(double height, double radius) { this.height = height; this.radius = radius; this.flatSideArea = Equations.Area(radius); this.volume = Equations.Volume(flatSideArea, radius); PropertyChanged+=new EventHandler(Cylinder_PropertyChanged); } public delegate void EventHandler(Cylinder sender, PropertyType rodzajParametru); public event EventHandler PropertyChanged; private void RisePropertyChanged(PropertyType rodzajParametru) { if (PropertyChanged != null) { PropertyChanged(this, rodzajParametru); } } private void Cylinder_PropertyChanged(Cylinder sender, PropertyType propertyType) { switch (propertyType) { case PropertyType.Radius: FlatSideArea = Equations.Area(radius); break; case PropertyType.Height: case PropertyType.FlatSideArea: Volume = Equations.Volume(flatSideArea,height); break; } } } static class Equations { public static double Area(double radius) { return Math.PI * Math.Pow(radius,2); } public static double Volume(double area, double height) { return area * height; } } </code></pre> <p>Additional info:</p> <ul> <li>My application is designing only impeller.</li> <li>My class got almost 80 properties.</li> <li>I have used separate static class with equations because i want to use some of the equation in other places.</li> <li>User is allowed to change some of the properties and is provided "real time" with results</li> </ul> <p>If example is still unclear let me know i will extend it.</p> <p>Questions:</p> <ul> <li>Is this a good solution or is there something better?</li> <li>Since i know that i will be using only one type of event is it correct to use enum instead of EventArg?</li> </ul> <p><strong>Edit:</strong> After receiving very good answers i felt bad :) for not even following faq (pts .3 and 4 from on-topic questions) so i have extended my code. It is still not from my application but at least it is working now. </p>
[]
[ { "body": "<p>I'm feeling like this isn't a good place to have properties changing. In other words, if your objects are indeed similar to a <code>Cylinder</code>, perhaps they should be immutable. That way, calculations can be a) done once at construction, b) done once, but lazily or c) done every time the property is accessed. But your mileage obviously will vary: if these are more of an entity object rather than an identity object, you'll have to do something different. But <code>Cylinder</code> seems like an identity to me. Example:</p>\n\n<pre><code>class Cylinder\n{\n readonly double height;\n readonly double radius;\n\n readonly double flatSideArea;\n readonly double volume;\n\n public Cylinder(double height, double radius)\n {\n this.height = height;\n this.radius = radius;\n\n this.flatSideArea = Math.PI * radius;\n this.volume = this.flatSideArea * height;\n }\n\n public double FlatSideArea()\n {\n return this.flatSideArea;\n }\n public double Volume()\n {\n return this.volume;\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T19:32:35.953", "Id": "21798", "Score": "0", "body": "Sorry if i haven't specified that before but user is allowed to change some of the properties and is provided with results in \"real time\". Creating new object each time user changes one property wouldn't become too slow?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T19:38:28.227", "Id": "21799", "Score": "0", "body": "I hate to break out the old canard, but \"it depends\" :) Since you mention that there's 80 properties, it likely could be expensive to recalculate all of them when a user changes one of them. Unless, of course, they will be requesting all those changed parts right afterwards. Then it's likely not that big of a deal." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T20:02:41.490", "Id": "21800", "Score": "0", "body": "How many of those 80 properties are \"calculated\" properties? In your simplified example of a Cylinder, asking for the cylinder's volume is trivial whether you do it in one method call or two. Method calls are cheap, relatively speaking; it's dereferencing (going out to the heap) that's more expensive." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T20:24:50.037", "Id": "21801", "Score": "0", "body": "@KeithS 72 are calculated properties most of them with a lot of math and one with simple iteration (no more then 20 recalculations)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T20:36:06.427", "Id": "21802", "Score": "0", "body": "So of the 80 properties, only 8 are user-definable? Check out my answer; I virtually guarantee it will solve your problem." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T19:24:07.940", "Id": "13477", "ParentId": "13475", "Score": "2" } }, { "body": "<p><strong>TLDR</strong>:</p>\n<ul>\n<li>Implement an actual event if you want it to look like an event (don't make it look like a convention if you intend to not follow a convention).</li>\n<li>Properly implement <code>INotififyPropertyChanged</code> if that is the event model you are trying for here.</li>\n<li>Use properties without setters for those that don't make sense to edit.</li>\n</ul>\n<hr />\n<p>ignoring immutability and such (like having a getter and no setter for FlatSideArea that computes on the fly)...</p>\n<p>What you are basically implementing here is an internal usage of the <a href=\"http://msdn.microsoft.com/en-us/library/ms229614.aspx\" rel=\"nofollow noreferrer\">INotifyPropertyChanged interface</a>.</p>\n<p>If you are going to implement that interface, I suggest you actually do so instead of only sorta partially doing so:</p>\n<pre><code>public class Cylinder : INotifyPropertyChanged {\n public class Properties {\n public const string Height = &quot;Height&quot;;\n public const string Radius = &quot;Radius&quot;;\n public const string FlatSideArea = &quot;FlatSideArea&quot;;\n public const string Volume = &quot;Volume&quot;;\n }\n double height;\n double radius;\n\n double flatSideArea;\n double volume;\n\n public event PropertyChangedEventHandler PropertyChanged;\n\n protected void SetProperty&lt;T&gt;(ref T field, T value, string name) {\n if (!EqualityComparer&lt;T&gt;.Default.Equals(field, value)) {\n field = value;\n var handler = PropertyChanged;\n if (handler != null) {\n handler(this, new PropertyChangedEventArgs(name));\n }\n }\n }\n\n public Cylinder() {\n PropertyChanged += OnPropertyChanged;\n }\n\n void OnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs) {\n switch (propertyChangedEventArgs.PropertyName) {\n case Properties.Radius:\n FlatSideArea = Math.PI * Radius;\n goto propagateRadius; //note: break works here (due to confusing redirects)\n case Properties.Height:\n case Properties.FlatSideArea:\n propagateRadius:\n Volume = FlatSideArea * Height;\n break;\n }\n }\n\n public double Height {\n get { return height; }\n set { SetProperty(ref height, value, Properties.Height); }\n }\n\n public double Radius {\n get { return radius; }\n set { SetProperty(ref radius, value, Properties.Radius); }\n }\n\n public double FlatSideArea {\n get { return flatSideArea; }\n set { SetProperty(ref flatSideArea, value, Properties.FlatSideArea); }\n }\n\n public double Volume {\n get { return volume; }\n set { SetProperty(ref volume, value, Properties.Volume); }\n }\n}\n</code></pre>\n<p>This implementation (whether or not you pull out the functions is irrelevant to this single use) will let you manage inheritance properly, but it does have some inefficiencies (setting radius raises the event 3 times, similar to how your implementation does). If you weren't concerned about inheritance you could simplify this by not bothering with the change event and modifying the private members outside of their own setters:</p>\n<pre><code>public class Cylinder {\n enum Properties {\n Height,\n Radius,\n FlatSideArea,\n Volume \n }\n double height;\n double radius;\n\n double flatSideArea;\n double volume;\n\n\n void SetProperty&lt;T&gt;(ref T field, T value, Properties name) {\n if (!EqualityComparer&lt;T&gt;.Default.Equals(field, value)) {\n switch (name) {\n case Properties.Radius:\n flatSideArea = Math.PI * radius;\n goto propagateRadius; //note: break will not work here (using the fields means no recursion)\n case Properties.Height:\n case Properties.FlatSideArea:\n propagateRadius:\n volume = flatSideArea * height;\n break;\n }\n }\n }\n ... same as above for the public properties\n}\n</code></pre>\n<p>One thing I would <strong>not</strong> do is name this method as if it were an event and then not use <code>EventArgs</code> based arguments. Conventions are good when everyone follows them, but when you don't but remain close enough that the code looks at a glance like you are then you have only made the future editor of your code think more.</p>\n<h3>Edit:</h3>\n<p>Using .NET 4, (still ignoring immutability) I would probably implement it like this:</p>\n<pre><code>public class Cylinder {\n double height;\n double radius;\n\n Lazy&lt;double&gt; flatSideArea;\n Lazy&lt;double&gt; volume;\n \n void SetProperty&lt;T&gt;(ref T field, T value) {\n if (!EqualityComparer&lt;T&gt;.Default.Equals(field, value)) {\n field = value;\n ResetComputedFields();\n }\n }\n \n void ResetComputedFields() {\n flatSideArea = new Lazy&lt;double&gt;(() =&gt; Math.PI * Radius);\n volume = new Lazy&lt;double&gt;(() =&gt; FlatSideArea * Height);\n }\n \n public Cylinder() {\n ResetComputedFields();\n }\n \n public double Height {\n get { return height; }\n set { SetProperty(ref height, value); }\n }\n\n public double Radius {\n get { return radius; }\n set { SetProperty(ref radius, value); }\n }\n\n public double FlatSideArea {\n get { return flatSideArea.Value; }\n }\n\n public double Volume {\n get { return volume.Value; }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T20:59:25.963", "Id": "21805", "Score": "0", "body": "Done before seeing your answer and slightly better IMO (not resetting if you set new radius the same as old), and it doesn't have syntax errors :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T21:50:02.330", "Id": "21809", "Score": "0", "body": "+1 for extended Lazy<T> solution and criticizing my method named like event but not really being one :). My first question here and I've got really hard time choosing which answer to accept i love SE sites :)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T20:12:43.643", "Id": "13478", "ParentId": "13475", "Score": "2" } }, { "body": "<p>While commenting on your comment to Jesse's answer, I thought of a solution; <code>Lazy&lt;T&gt;</code>.</p>\n\n<p>.NET 4 contains this new class, which for the purposes of most external consumers would have the following definition:</p>\n\n<pre><code>public class Lazy&lt;T&gt;\n{\n private Func&lt;T&gt; func;\n private T val;\n private bool isCreated;\n\n public Lazy(Func&lt;T&gt; input)\n {\n func = input;\n }\n\n public bool IsValueCreated {get {return isCreated;}}\n\n public T Value \n {\n get { \n if(!isCreated)\n {\n val = func();\n isCreated = true;\n }\n return val;\n }\n } \n}\n</code></pre>\n\n<p>There's some additional code involved in the real implementation for thread-safety etc but this is the general idea (and it can be dropped into a .NET 3.5 solution if needed; .NET 2.0 doesn't have lambda statements or the <code>Func&lt;T&gt;</code> class but it's still possible to implement the concept). You can use it with an immutable class to provide for lazily-evaluated properties; the calculations for calculated fields are performed if and when they are needed, and are only performed on the first access of \"Value\", after which the result of the calculation is used without re-running it. The class doesn't HAVE to be immutable, but if consumers can change properties, the calculated properties that depend on the change must be recalculated when next accessed.</p>\n\n<p>Here's your Cylinder class with the Lazy properties FlatArea and Volume:</p>\n\n<pre><code>class Cylinder\n{\n readonly double height;\n readonly double radius;\n\n readonly Lazy&lt;double&gt; flatSideArea;\n readonly Lazy&lt;double&gt; volume;\n\n public Cylinder(double height, double radius)\n {\n this.height = height;\n this.radius = radius;\n\n this.flatSideArea = new Lazy&lt;double&gt;(()=&gt;Math.PI * Math.Pow(radius, 2));\n this.volume = new Lazy&lt;double&gt;(()=&gt;flatSideArea.Value * height);\n }\n\n public double FlatSideArea\n {\n get { return this.flatSideArea.Value; }\n }\n public double Volume\n {\n get { return this.volume.Value; }\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>//Only the user-defined properties are set here; no calculations.\nCylinder myCylinder = new Cylinder(20, 10);\n\n//the FlatSideArea calculation is now performed:\nvar area = myCylinder.FlatSideArea;\n\n//and now it's known, and doesn't have to be recalculated:\nvar vol = myCylinder.Volume;\n\n//You don't have to access them in order of dependency either:\nvar vol2 = new Cylinder(10,20).Volume; //results in the calculation of FSA as well\n</code></pre>\n\n<p>So, the net result in your full situation of 80 properties is that, while re-instantiation to incorporate a change is still needed, calculation of dependent fields is not. If those 80 properties include a large number of purely calculated fields (and the calculation is not simply for sanity within a mutable class) you save a lot of work compared to \"eager\" calculation when a user is only interested in one or two calculations, or compared to a mutable class when needs to make several changes before being interested in the calculated fields.</p>\n\n<p>If the class absolutely has to be mutable, then I would extract the instantiation of the \"lazy\" private fields into a method, \"ClearCalculatedValues\", and call it from the setters of the user-defined values if the new value differs from the old:</p>\n\n<pre><code>class Cylinder\n{\n readonly double height;\n readonly double radius;\n\n readonly Lazy&lt;double&gt; flatSideArea;\n readonly Lazy&lt;double&gt; volume;\n\n public Cylinder(double height, double radius)\n {\n this.height = height;\n this.radius = radius;\n\n ClearLazyValues();\n }\n\n private void ClearLazyValues()\n {\n this.flatSideArea = new Lazy&lt;double&gt;(()=&gt;Math.PI * Math.Pow(radius, 2));\n this.volume = new Lazy&lt;double&gt;(()=&gt;flatSideArea * height);\n }\n\n public double FlatSideArea\n {\n get{return this.flatSideArea.Value;}\n }\n public double Volume\n {\n get{return this.volume.Value;}\n }\n\n public double Radius\n {\n get{return this.radius;}\n set{if(this.radius != value) {this.radius = value; ClearLazyValues();}\n }\n\n public double Height\n {\n get{return this.height;}\n set{if(this.height != value) {this.height = value; ClearLazyValues();}\n }\n}\n</code></pre>\n\n<p>You can, if you want, limit the number of calculations that must be re-performed; for instance, a change to the Height property doesn't change the current value of FlatSideArea, so you can choose to only clear the Volume value. This will make that logic more complicated to code, but could save you some steps at runtime (which is a common tradeoff).</p>\n\n<p><strong>PS:</strong> BTW, if high precision is needed and you're dealing with cylinders (or other shapes) smaller in size than that of the known universe, I'd use <code>decimal</code> instead of <code>double</code> as it will reduce the amount of floating-point error inherent in storing base-10 numbers in base-2 scientific notation. A decimal can hold a number &lt;= abs(+-7.9<sub>E</sub>28), which is suitable for most practical calculations outside astronomy and theoretical physics.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T20:48:30.827", "Id": "21804", "Score": "0", "body": "Nice catch on the formula for `flatSideArea` being wrong for a cylinder; I didn't even notice. And +1 for the `decimal` recommendation." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T20:20:26.210", "Id": "13479", "ParentId": "13475", "Score": "7" } }, { "body": "<p>In addition to the other two answers, from Bill Barry and KeithS, which I <em>really</em> liked, I wanted to toss out some more code, because, well, CODE.</p>\n\n<p>I happen to use a base class which implements some boilerplate <code>INotifyPropertyChanged</code> which allows my property setters to look like this:</p>\n\n<pre><code>public class Cylinder : PropertyChangedBase\n{\n private double radius;\n\n //// Other stuff ...\n\n public double Radius\n {\n get\n {\n return this.radius;\n }\n\n set\n {\n this.SetProperty(ref this.radius, value, () =&gt; this.Radius);\n }\n }\n}\n</code></pre>\n\n<p>Here's the class (note the <code>SetProperty</code> which is quite similar to the one shown):</p>\n\n<pre><code>public abstract class PropertyChangedBase : INotifyPropertyChanged\n{\n public event PropertyChangedEventHandler PropertyChanged;\n\n protected void RaisePropertyChanged(string propertyName)\n {\n var propertyChanged = this.PropertyChanged;\n\n if (propertyChanged != null)\n {\n propertyChanged(this, new PropertyChangedEventArgs(propertyName));\n }\n }\n\n protected bool SetProperty&lt;T&gt;(ref T backingField, T Value, Expression&lt;Func&lt;T&gt;&gt; propertyExpression)\n {\n var changed = !EqualityComparer&lt;T&gt;.Default.Equals(backingField, Value);\n\n if (changed)\n {\n backingField = Value;\n this.RaisePropertyChanged(ExtractPropertyName(propertyExpression));\n }\n\n return changed;\n }\n\n private static string ExtractPropertyName&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; propertyExpression)\n {\n var memberExp = propertyExpression.Body as MemberExpression;\n\n if (memberExp == null)\n {\n throw new ArgumentException(\"Expression must be a MemberExpression.\", \"propertyExpression\");\n }\n\n return memberExp.Member.Name;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T01:52:21.633", "Id": "13486", "ParentId": "13475", "Score": "2" } } ]
{ "AcceptedAnswerId": "13479", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T18:49:26.893", "Id": "13475", "Score": "5", "Tags": [ "c#" ], "Title": "Multiple properties updated by event vs few properties and methods" }
13475
<p>I am learning scheme to get something new from a programming language and this code below is the solution to Project Euler question 21 but the code runs 10x slower than the listed Python code when I use Chibi-Scheme. Can any Scheme craftsman refactor the code into the Scheme idiom for efficiency.</p> <p>Scheme Code:</p> <pre><code>(define (sum-of-amicable-pairs n) (let ((sums (make-vector n))) (for-each (lambda (i) (vector-set! sums i (reduce + 0 (filter (lambda (j) (= (remainder i j) 0)) (iota (+ 1 (quotient i 2)) 1 1))))) (iota n 0 1)) (let loop ((res (make-vector n 0)) (i 0)) (cond ((= i n) (reduce + 0 (vector-&gt;list res))) ((and (&lt; (vector-ref sums i) n) (not (= (vector-ref sums i) i)) (= (vector-ref sums (vector-ref sums i)) i)) (begin (vector-set! res i i) (vector-set! res (vector-ref sums i) (vector-ref sums i)) (loop res (+ 1 i)))) (else (loop res (+ i 1))))))) (display (sum-of-amicable-pairs 10000)) (newline) </code></pre> <p>Python code:</p> <pre><code>def amicable_pairs(n): """returns sum of all amicable pairs under n. See project euler for definition of an amicable pair""" div_sum = [None]*n amicable_pairs_set = set() for i in range(n): div_sum[i] = sum([j for j in range(1, i/2 + 1) if i%j == 0]) for j in range(n): if div_sum[j] &lt; n and div_sum[div_sum[j]] == j and div_sum[j] != j: amicable_pairs_set.add(j) amicable_pairs_set.add(div_sum[j]) #print sum(amicable_pairs_set) return sum(list(amicable_pairs_set)) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-01T21:10:02.193", "Id": "130392", "Score": "1", "body": "Chibi is meant to be small and easily embedded, not a speed demon. Fast Schemes include Gambit and Chicken (both of which are compilers, and are available for Windows)." } ]
[ { "body": "<p>Well, for one thing, the python code is using a set for its amicable_pair_set, where-as you're using a large vector and setting the n'th element to n when you need to add to the set. It's a reasonable way to imitate a set, if your scheme doesn't have a set library; however, this situation doesn't need true set semantics. You can use a simple list instead, so your named let becomes:</p>\n\n<pre><code>(let loop ((res '())\n (i 0))\n (cond\n ((= i n) (reduce + 0 res))\n ((and (&lt; (vector-ref sums i) n) (not (= (vector-ref sums i) i)) \n (= (vector-ref sums (vector-ref sums i)) i))\n (loop (cons i res) (+ 1 i)))\n (else\n (loop res (+ i 1)))))\n</code></pre>\n\n<p>This keeps it close to the python code, but you could go a step further and have <code>res</code> be an integer accumulator, adding to it instead of consing to it, getting rid of the need to add the list at the end. Of course, the same optimization could be made to the python version as well.</p>\n\n<p>Unfortunately, I've optimized the part of the code that runs quick :-). The real work is being done above, when the <code>sums</code> vector is being populated. Since that is a pretty direct translation, I would chalk it up to chibi's implementation of scheme versus whatever implementation of python you're using (PyPy, for instance, is probably going to be faster). I use racket-scheme which is jit compiled. Calling your code returns an answer in ~680ms for me. Calling it with the default python 2.7.3 compiler gives me a result in ~1400ms.</p>\n\n<p>Here's a version which only calculates the sum of its proper divisors for the numbers that are needed, and then stores them for future use. Basically memoizing the results. The first run is slightly faster for me ~30ms, and then subsequent runs return in less than 1ms.</p>\n\n<pre><code>(define d\n (let ((cache (make-vector 10000 #f)))\n (lambda (n)\n (or (vector-ref cache n)\n (let ((val (reduce + 0 (filter (lambda (d) (= 0 (remainder n d)))\n (iota (quotient n 2) 1)))))\n (vector-set! cache n val)\n val)))))\n\n(define (sum-of-amicable-pairs n)\n (let loop ((a 0)\n (sum 0))\n (if (&lt; a n)\n (let ((b (d a)))\n (loop (+ a 1)\n (if (and (&lt; a b n) (= (d b) a))\n (+ sum a b)\n sum)))\n sum)))\n\n(time (sum-of-amicable-pairs 10000))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T05:12:31.587", "Id": "21827", "Score": "0", "body": "your code actually might contain a bug because when you use a list, you run into the problem of adding duplicate pairs to the list as you iterate from 0 to n-1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T15:29:19.020", "Id": "21874", "Score": "0", "body": "in each iteration, we either cons `i` to the list or we don't, and since `i` is strictly increasing, we don't ever add duplicates to the list." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T00:31:25.363", "Id": "13484", "ParentId": "13476", "Score": "3" } }, { "body": "<p>I would optimize the python code first and then translate it to the scheme (sorry, can't find Scheme compiler for Windows). Here is python solution that 100-200 times faster (the idea based on the Sieve of Eratosthenes algorithm):</p>\n\n<pre><code>python25\\python 21.py\namicable_pairs : 31626 Time (s): 2.313000\namicable_pairs_fast : 31626 Time (s): 0.015000\n\npython26\\python 21.py\namicable_pairs : 31626 Time (s): 1.969000\namicable_pairs_fast : 31626 Time (s): 0.016000\n\npython27\\python 21.py\namicable_pairs : 31626 Time (s): 1.782000\namicable_pairs_fast : 31626 Time (s): 0.000000\n\npython32\\python 21.py\namicable_pairs : 31626 Time (s): 3.157000\namicable_pairs_fast : 31626 Time (s): 0.015000\n\npypy\\pypy 21.py\namicable_pairs : 31626 Time (s): 0.157000\namicable_pairs_fast : 31626 Time (s): 0.015000\n</code></pre>\n\n<p>.</p>\n\n<pre><code> import time\n\n\"\"\"\n\n http://projecteuler.net/problem=21\n Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).\n If d(a) = b and d(b) = a, where a != b, then a and b are an amicable pair and each of a and b are called amicable numbers.\n\n For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284.\n The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.\n Evaluate the sum of all the amicable numbers under 10000.\n\n http://codereview.stackexchange.com/questions/13476/a-little-scheme-programming-challenge\n\n\"\"\"\n\ndef amicable_pairs(n):\n \"\"\"returns sum of all amicable pairs under n. See project euler for\n definition of an amicable pair\"\"\"\n div_sum = [None]*n\n amicable_pairs_set = set()\n for i in range(n):\n div_sum[i] = sum([j for j in range(1, int(i/2) + 1) if i%j == 0])\n for j in range(n):\n if div_sum[j] &lt; n and div_sum[div_sum[j]] == j and div_sum[j] != j:\n amicable_pairs_set.add(j)\n amicable_pairs_set.add(div_sum[j])\n #print sum(amicable_pairs_set)\n return sum(list(amicable_pairs_set))\n\ndef amicable_pairs_fast(n):\n\n div_sum = [1]*n\n for i in range(2, int(n/2) + 1):\n for j in range(i, n, i):\n if j != i:\n div_sum[j] += i\n total = 0\n for i in range(1, n):\n s = div_sum[i]\n if s &lt; n:\n s1 = div_sum[s]\n if s1 == i and s != i:\n total += s1\n return total\n\nt = time.time()\nprint(\"amicable_pairs : %d \" % amicable_pairs(10000) + \" Time (s): %f \" % (time.time()-t))\n\nt1 = time.time()\nprint(\"amicable_pairs_fast : %d \" % amicable_pairs_fast(10000) + \" Time (s): %f \" % (time.time()-t1))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-12T09:26:18.747", "Id": "13557", "ParentId": "13476", "Score": "2" } } ]
{ "AcceptedAnswerId": "13557", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T19:10:23.620", "Id": "13476", "Score": "4", "Tags": [ "python", "optimization", "project-euler", "scheme", "programming-challenge" ], "Title": "A little scheme programming challenge" }
13476
<p>I'm writing something that basically takes a bunch of files and renames them into a nice format, such as <code>pic_000.jpeg</code>, <code>pic_001.jpeg</code>, etc. One of the options is to write the incrementation as letters, e.g. <code>pic_aaa.jpeg</code>, <code>pic_aab.jpeg</code>, etc. Also, is they are converting a set of <code>pic_000</code>s into a set of <code>pic_aaa</code>s, then there's also an option to preserve the order of increments. In other words, if you deleted <code>pic_000</code> through <code>pic_117</code>, then the <code>pic_aaa</code> set would start at <code>pic_aen</code>, not <code>pic_aaa</code>. It's a little weird, but I'm just trying to give the user lot of options so they can do whatever they want.</p> <p>I suppose there are two different types of output for a base-10 to base-26 function such as this:</p> <ol> <li><p>without a fixed-length result, e.g.: A, B, ... , Z, AA, AB, ... ZZ, AAA (notice that A is representing a 1 when it is the leading letter and the result is more than one letter in length, else it is representing a 0)</p></li> <li><p>with a fixed-length result, e.g. AAA, AAB, ... , ZZY, ZZZ (A will always represent a zero, here)</p></li> </ol> <p>Again, I've chosen to write it both ways and let the user decide what they want. With (2), you just have to count how many input numbers there are (the numbers that we're converting in the first place) and then use an appropriately-sized result. Obviously two characters (AA, AB, etc.) isn't enough to represent a million different numbers, so you'd have see if three letters could do it, then four, and so on. (To make this easier, you can just do <code>resultLength = ceil(log(inputNumber)/log(26))</code> (not vb6 code, but you get the idea) I haven't written (2) yet, but I assume it will be pretty easy.</p> <p>Number 1, though, proved to be a bit of a doozy since A-Z can represent 0-25 in some places and 1-26 in others. If A is 0, then Z is 25, but unless you want to use BA for 26, skipping A_, then you have to let A be equal to 1 where it is a leading character (e.g. AA, AB, etc.) when the result is not 1 character long (i.e. for the result of <code>A</code>, A is 0 even though it is the leading character.)</p> <p>It gets trickier, however. One result of the fact that A-Z represents 0-25 in certain slots and 1-26 in others is that figuring out how many characters the result will be is tricky.</p> <p>Examples:</p> <pre><code>If input &lt; 26^1, Then resultLength = 1 Elseif input &lt; (27*(26^1) -1) Then 'ZZ represents (27*26) -1 resultLength = 2 Elseif input &lt; (27*(26^2) -1) Then 'ZZ represents (27*26^2) -1 resultLength = 3 End If </code></pre> <p>Anyways, I'm pretty sure it works, so I'll let you take a look at it.</p> <pre><code>Function NumericToAlpha(inString As String) As String Dim outString As String Dim asLong As Long Dim Index As Integer Dim i As Integer Dim j As Double Dim intDiv As Integer asLong = Val(inString) ' validate input; no negative numbers or decimals If asLong &lt; 0 Or InStr(inString, ".") Then MsgBox "Cannot process negative values or numbers that include a decimal point." NumericToAlpha = "" Exit Function End If Do While (27 * 26 ^ (Index) - 1) &lt; asLong Index = Index + 1 Loop If asLong = 26 Then Index = 1 For i = Index To 0 Step -1 j = 26 ^ i If (i = Index) And (Index &gt; 1) And Int(asLong / j) = 1 Then asLong = asLong - 26 ^ (i - 1) intDiv = Int(asLong / j) If Len(outString) Then ' non-leading character outString = outString &amp; Chr(Asc("A") + intDiv) Else 'outString leading character If i = 0 Then outString = Chr(Asc("A") + intDiv) Else outString = Chr(Asc("A") + intDiv - 1) End If End If asLong = asLong - (intDiv * j) Next i NumericToAlpha = outString End Function </code></pre> <p>I test this with the following numbers, which I've come up with by doing the math by hand:</p> <pre><code>Dim newL As String newL = Chr(13) MsgBox NumericToAlpha(0) &amp; newL &amp; NumericToAlpha(25) &amp; newL &amp; NumericToAlpha(26) &amp; newL &amp; NumericToAlpha(701) &amp; newL &amp; NumericToAlpha(702) &amp; newL &amp; NumericToAlpha(18251) &amp; newL &amp; NumericToAlpha(18252) &amp; newL &amp; NumericToAlpha(474551) &amp; newL &amp; NumericToAlpha(474552) &amp; newL &amp; NumericToAlpha(474551) &amp; newL &amp; NumericToAlpha(474552) </code></pre> <p>If there are any bugs or if you can think up a sexier way to do this, please let me know!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T19:26:02.747", "Id": "112451", "Score": "0", "body": "Instead of doing it yourself, use this: http://gladman.plushost.co.uk/oldsite/computing/gmp4win.php and http://www.mpir.org/ also see: http://www.exploringbinary.com/how-to-install-and-run-gmp-on-windows-using-mpir/ Then `gmp_strval(number, 36)` Or 62 (instead of 36) to use both upper and lowercase letters." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T00:26:42.870", "Id": "112452", "Score": "0", "body": "@Ariel My program is in VB6, not C++. I know you can include C++ code in a VB6 program somehow (don't know if people are referring to .dll calls or what when they say you can do this), but I've never done it before. On a side not, I am rather surprised to see that there exist numerous web sites dedicated to a library made up of this function and other similar ones." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T00:38:19.000", "Id": "112453", "Score": "0", "body": "gmp is a very useful library. It's not just for this base conversion - it's for arbitrary precision math and it's one of the best." } ]
[ { "body": "<h2>First Point:</h2>\n\n<p>For multiple <code>If</code>/<code>Else</code> blocks, I prefer to use <a href=\"http://msdn.microsoft.com/en-us/library/cy37t14y.aspx\" rel=\"nofollow\"><code>Select Case</code></a>. I would just do this out of habit, though your check is small enough that it may not matter too much. </p>\n\n<p>Also, this may be trickier, given that something falling into the first case looks like it would also fall into the other two. However, unlike other languages, there is no <code>break</code> required, and the <code>Select</code> block ends at the first case it comes to (like the <code>If</code>/<code>Else</code> would have).</p>\n\n<pre><code>Select Case input\n\nCase Is &lt; 26 ^ 1:\n resultLength = 1\nCase Is &lt; (27 * (26 ^ 1) - 1): 'ZZ represents (27*26) -1\n resultLength = 2\nCase Is &lt; (27 * (26 ^ 2) - 1): 'ZZ represents (27*26^2) -1\n resultLength = 3\nEnd Select\n</code></pre>\n\n<hr>\n\n<h2>Second Point:</h2>\n\n<p>I know I'm not doing much in the way of efficiency (more just style, I think), but here's another. Regarding:</p>\n\n<pre><code>If (i = Index) And (Index &gt; 1) And Int(asLong / 26 ^ (i)) = 1 Then\n j = 26 ^ i\n asLong = asLong - 26 ^ (i - 1)\nElse\n j = 26 ^ i\nEnd If\n</code></pre>\n\n<p>Since you assign <code>j = 26 ^ i</code> in both cases, why not just assign it before the <code>If</code>?</p>\n\n<pre><code>j = 26 ^ i\n\nIf (i = Index) And (Index &gt; 1) And Int(asLong / 26 ^ (i)) = 1 Then\n asLong = asLong - 26 ^ (i - 1)\nEnd If\n</code></pre>\n\n<hr>\n\n<p><sub>Sorry for not getting this all out at once. I'll continue to pick apart as I have time and add to this answer as needed...</sub></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T00:19:15.263", "Id": "21897", "Score": "0", "body": "The `If`/`ElseIf` portion was just code to explain the concept. In the actual code, I used a `Do While` loop. Although the upper limit of the `Long` data type probably wouldn't take too long to hit with a base of 26, if this were base 2, the `switch`/`case` statement would be very long. Seeing as how the `do while` loop can handle everything you could throw at it, and is the best solution for other bases, I guess I just see it as proper form." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T00:49:04.930", "Id": "21900", "Score": "1", "body": "RE your edit: Yes, sorry; it is indeed redundant. I was rather tired when I wrote code. Whoops!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T00:50:29.323", "Id": "21901", "Score": "0", "body": "@Michael No worries. I've written plenty of code that I knew better not to after the fact!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T21:37:06.087", "Id": "13522", "ParentId": "13480", "Score": "2" } }, { "body": "<p>You asked for a 'sexier' way to do this, and I think I've got it, but I'll let you be the judge:</p>\n\n<pre><code>Function NumToAlph(inString As String) As String\nDim outString As String\nDim i As Integer\nDim inLong As Long\nDim MaxDigits As Byte\n\ninLong = CLng(inString)\n\nMaxDigits = 10\n\nReDim Vals(MaxDigits)\n\n' Identify character code for last (right-most) result digit or special case/single-digit results\nIf inLong &gt;= 27 Then\n inLong = inLong - 1\n Vals(0) = inLong Mod 26\n inLong = Int(inLong / 26)\nElse\n Vals(0) = inLong Mod 27\n inLong = Int(inLong / 27)\nEnd If\n\n' Identify character code for all other result digits\nFor i = 1 To MaxDigits\n Vals(i) = inLong Mod 27\n inLong = Int(inLong / 27)\nNext i\n\n' Append character to output string, except for last result digit\nFor i = MaxDigits To 1 Step -1\n If Vals(i) &gt; 0 Then\n outString = outString &amp; Chr(Vals(i) + 64)\n ElseIf Len(outString) &gt; 0 Then\n outString = outString &amp; \"A\"\n End If\nNext i\n\nIf Len(outString) &gt; 0 Then ' Adjust multiple-digit result to account for 0 base when value &gt; 26\n Vals(0) = Vals(0) + 1\nEnd If\n\noutString = outString &amp; Chr(Vals(0) + 64) ' Append final character to output string\n\nNumToAlph = outString\n\nEnd Function\n</code></pre>\n\n<p>I've tested this up to <code>1,000,000,000</code>, which comes out as <code>BRJAHKL</code> (longs don't get any more significant digits...). There might be some improvements that can be bade in the for loops (Why loop twice? Because it's what I could manage for now...), but I like this pretty well the way it is.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T14:09:06.867", "Id": "13537", "ParentId": "13480", "Score": "2" } }, { "body": "<p>I realize this is an old post, but no one mentioned this. </p>\n\n<blockquote>\n<pre><code>' validate input; no negative numbers or decimals\nIf asLong &lt; 0 Or InStr(inString, \".\") Then\n MsgBox \"Cannot process negative values or numbers that include a decimal point.\"\n NumericToAlpha = \"\"\n Exit Function\nEnd If\n</code></pre>\n</blockquote>\n\n<p>VB6 doesn't allow for short circuiting, so you might as well break this into two separate <code>If</code> statements. Both conditions are always being checked anyway. This has an added benefit of giving a more specific error message to the end user as well. </p>\n\n<p>To keep the extra code from cluttering up your main function, I recommend creating a private <code>IsValidInput</code> that returns a boolean. </p>\n\n<pre><code>Private Function IsValidInput(str As String) As Boolean\n ' validate input; no negative numbers or decimals\n If asLong &lt; 0 Then\n MsgBox \"Cannot process negative values.\"\n Exit Function\n End If\n\n If InStr(inString, \".\") Then\n MsgBox \"Cannot process numbers that include a decimal point.\"\n Exit Function\n End If\n\n ' If we've gotten here, input is valid\n IsValidInput = True\n\nEnd Function\n</code></pre>\n\n<p>Personally, I would raise errors rather than show message boxes, but I've not gone through the trouble here, but you should consider it. Especially if your function resides in a class. </p>\n\n<hr>\n\n<p>P.S. You don't use Hungarian notation anywhere except the <code>intDiv</code> variable. Drop the <code>int</code> part and give that variable a more meaningful name. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-03T10:47:51.430", "Id": "61832", "ParentId": "13480", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T21:08:48.460", "Id": "13480", "Score": "3", "Tags": [ "converting", "iterator", "vb6" ], "Title": "Converting base-10 numbers into base-26 letters" }
13480
<p><strong>Question:</strong></p> <hr> <p>I'm attemping to modify a Javascript snippet to more efficiently get the user's current Zipcode. One problem that I am facing however is the lack of understanding around public functions. I am wondering if they are requried, and if they are not, then what would make the code cleaner and more efficient in terms of using or not using <code>public.</code>? </p> <p><strong>Code:</strong></p> <hr> <pre><code>var geoLocateAddress = function () { var public = {}; public.init = function() { public.initEventHandlers(); }; public.initEventHandlers = function() { console.log("Using your browser's GeoLocation API"); navigator.geolocation.getCurrentPosition( public.loadAddressByGeolocation); }; public.loadAddressByGeolocation = function(position) { console.dir(position); console.log("Your browser only returns Long/Lat"); public.loadAddressByLngLat(position); }; public.loadAddressByLngLat = function(position){ var data = { lat : position.coords.latitude, lng : position.coords.longitude }; var url = "http://ws.geonames.org/findNearestAddressJSON"; $.ajax({ url: url, dataType: 'jsonp', data: data, success: function(data, textStatus, xhr) { public.updateAddressFields({ zipCode: data.address.postalcode, }); }, error: function(xhr, textStatus, errorThrown) { console.log(textStatus); } }); return false; }; public.updateAddressFields = function(address) { console.log('Zip: ' + address.zipCode); $("#zip").text(address.zipCode); console.log('Zip Logged'); }; return public; } (); geoLocateAddress.init(); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T21:39:46.113", "Id": "21806", "Score": "0", "body": "What are you getting by making the internal functions here public and available on a global namespace?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T21:40:48.717", "Id": "21807", "Score": "0", "body": "Are you asking what my purpose is for making them public? Or what am I getting as in what's the output?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T22:36:37.077", "Id": "21811", "Score": "0", "body": "What is your purpose. As far as I can tell none of them need to be." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T23:03:52.243", "Id": "21812", "Score": "0", "body": "Not knowing what the syntax was for GeoLocation in JS, I googled it, removed the parts I didn't need, and was left with this (after some other modifications). My question though is why would they be public in the first place, and how could the code improve, especially after removing them?" } ]
[ { "body": "<p>None of this code needs to create any global variables. The pattern you have here is known as <a href=\"http://addyosmani.com/blog/essential-js-namespacing/#beginners\" rel=\"nofollow\">namespace creation</a>.</p>\n\n<p>It often follows the pattern:</p>\n\n<pre><code>var myNamespace = (function () {\n //private stuff\n var public = {}; //or function () ...\n //build up public object\n return public;\n}());\n</code></pre>\n\n<p>But sometimes the public object can be inlined like it can be in your case:</p>\n\n<pre><code>var geoLocateAddress = (function () {\n function init() {\n //...\n }\n return { init: init };//unnecessary to expose the other functions as public\n}());\n</code></pre>\n\n<p>In this case, all you are doing with this namespaced global object is calling the init function. So instead of creating a global (generally considered bad taste in most languages) you can simply initialize the object:</p>\n\n<pre><code>(function () {\n function init() {\n //...\n }\n\n init();//unnecessary to expose the other functions as public\n}());\n</code></pre>\n\n<p>(this pattern of having the function surrounding your code like this is commonly referred to as an <a href=\"http://benalman.com/news/2010/11/immediately-invoked-function-expression/\" rel=\"nofollow\">IIFE</a>)</p>\n\n<p>Aside: for declaring a namespace I prefer the following form:</p>\n\n<pre><code>(function ($, window) {\n 'use strict';\n\n ...\n window['geoLocateAddress'] = window['geoLocateAddress'] || {};\n window['geoLocateAddress'] = $.extend({}, window['geoLocateAddress'], {\n 'init': init\n };\n}(jQuery, window));\n</code></pre>\n\n<p>Back on topic:</p>\n\n<p>In my opinion, it is a bad practice to force the Javascript engine to go looking for your globals when you are not in global scope due to leaving off the window qualifier. Thus everywhere you reference <code>console</code> without calling it <code>window.console</code> (and the same goes for <code>Navigator</code>) or caching it in a local variable is wrong. In the event where you run this script outside of a browser that implements <code>console</code> you will get an exception. <code>Navigator</code> is slightly less of an issue because it is a reasonably safe assumption that you will not run this from a browser that doesn't supply a <code>Navigator</code> global namespace. For this reason I always pass the globals that I am going to use into my IIFE:</p>\n\n<pre><code>(function ($, geolocation, console) {\n ...\n}(jQuery, Navigator.geolocation, window.console));\n</code></pre>\n\n<p>I would modify the rest of the code as follows; please comment if you want me to explain any of it in more detail and I'll try to get to it. Comments dictionary:</p>\n\n<ul>\n<li>pref: personal preference (the opinions of others may vary)</li>\n<li>rule: avoids possible issues with the code</li>\n<li>possibility: potential source for further enhancement, outside of the scope of this question.</li>\n<li>consideration: something I haven't decided one way or the other on yet</li>\n</ul>\n\n<hr>\n\n<pre><code>//pref: don't create global variables that are unnecessary\n(function ($, geolocation, console) {//pref: pass in globals for munging purposes\n 'use strict'; //pref: 100% on JsLint\n\n //pref: instead of defining one object variable and methods on it\n //we could define the methods and export an object at the end\n //this saves us from needing to do some sort of static object call syntax\n var updateAddressFields = function (data) { //pref: remove unused parameters\n console.log('Zip: ' + data.address.postalCode); \n //pref: renaming variable provides very little benefit; \n //outweighed by ability to simplify syntax by inlining to success \n //function and then replacing the success function here\n console.dir(data); //pref: make above a constant string and use this instead of just logging zipcode\n $(function () { //rule: don't update DOM until after the ready event\n $('#zip').text(data.address.postalCode);\n });\n //pref: further logging beyond start of function adds nothing but cruft to your log\n },\n loadAddressByLocation = function (position) { //pref: renamed function for readability\n console.log('loadAddressByLocation:');\n console.dir(position); //pref: inlined function to simplify code\n var data = { //possibility: abstract this as a jQuery helper if it has uses outside of setting zipcode (outside of this question scope)\n lat : position.coords.latitude,\n lng : position.coords.longitude\n },\n url = \"http://ws.geonames.org/findNearestAddressJSON\"; //consideration: variable unnecessary?\n $.ajax({ //consideration: ajax vs getJSON?\n url: url,\n dataType: 'jsonp', //consideration: specify datatype or put callback in the url?\n data: data, //consideration: inline data definition?\n success: updateAddressFields, //pref: extra function wrapping unnecessary\n error: function (xhr, textStatus) {//perf: remove unused parameters\n console.log(textStatus);//consideration: necessity of error function?\n }\n });\n //pref: return false did nothing here; removed\n };\n\n console = console || { //rule: safe to remove shim if you know you're browser compat\n log: function () {}, //otherwise console may not exist under certain browsers\n dir: function () {}\n };\n //perf: removed and inlined \"return { init: init };\" to not create globals\n console.log(\"Using your browser's GeoLocation API\");//pref: inlined init and initEventHandlers for readability\n if (geolocation &amp;&amp; geolocation.getCurrentPosition) { //rule: more behavior detection, also safe to remove if browser compat\n //assume correct api if this passes\n geolocation.getCurrentPosition(loadAddressByLocation);\n }\n}(jQuery, navigator.geolocation, window.console));\n//pref: passing in navigator.geolocation will allow better minification (though I wouldn't minify this version anyway)\n//rule: more behavior detection, referring to console as window.console to not trigger possible error referencing global that doesn't exist\n</code></pre>\n\n<p>Simplified for minification, I don't really see anything \"wrong\" with this version:</p>\n\n<pre><code>(function ($, geolocation) { //console removed\n if (geolocation) { //possibly unsafe if future browser implements geolocation but not getCurrentPosition, perhaps leave this as it was above\n geolocation.getCurrentPosition(function (position) {\n $.getJSON( //using this helper instead of ajax lets us not define an object and property names\n \"http://ws.geonames.org/findNearestAddressJSON?callback=?\",\n //dataType: 'jsonp', unnecessary with callback in url\n { //inlined data to remove var, IMO readability is not affected too much\n lat : position.coords.latitude,\n lng : position.coords.longitude\n },\n function (data) { //unused params dropped from success callback\n $(function () {\n //don't update until after the ready event\n $('#zip').text(data.address.postalcode);\n });\n }\n );\n });\n }\n}(jQuery, navigator.geolocation));\n</code></pre>\n\n<p>which shrinks down to 266 chars (via <a href=\"http://marijnhaverbeke.nl/uglifyjs/\" rel=\"nofollow\">uglifyjs</a>):</p>\n\n<pre><code>(function(e,t){t&amp;&amp;t.getCurrentPosition(function(t){e.getJSON(\n\"http://ws.geonames.org/findNearestAddressJSON?callback=?\",{lat:\nt.coords.latitude,lng:t.coords.longitude},function(t){e(function(){\ne(\"#zip\").text(t.address.postalcode)})})})})(jQuery,navigator.geolocation)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T01:19:02.987", "Id": "21815", "Score": "1", "body": "You're a javascript wizard. First question: So I always need to call `window.console` before `console`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T01:26:46.550", "Id": "21816", "Score": "0", "body": "Question two: Is this code flexible enough to reload the AJAX request, so that the page can we reloaded without actually reloading it? I feel like the code before your improvements would've been a pain to reload." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T02:17:16.800", "Id": "21821", "Score": "1", "body": "1: meh, you should reference a global variable in such a way that you don't have to be concerned when you run it in an environment where it doesn't exist. If you are going to use a variable more than once or twice, your code will probably benefit from caching the variable. The IIFE construct provides a simple cache scheme and gives a way to check existance by making it behave just like any other parameter. See also: http://jsfiddle.net/PCYQs/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T02:21:52.753", "Id": "21822", "Score": "0", "body": "2: I'm not sure I understand your question; if you reload the page then it reloads all javascript and this would run again (and so make the ajax request again)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T04:42:26.690", "Id": "21824", "Score": "0", "body": "2: That's very true, however I might want to reload the `geolocation` function without reloading the rest of the page. Let's say other information on the page doesn't need to be reloaded, or is only there for the session (and I don't feel like dealing with cookies, or localstorage), then could I just reload the AJAX request and therefor get a new zipcode, if the location had changed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T13:07:41.657", "Id": "21844", "Score": "0", "body": "I don't see any reason why you couldn't call this more than once." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T20:58:17.347", "Id": "21887", "Score": "0", "body": "Same, except I don't understand if I would simply call the function again, or if I would put it all into an AJAX request and rerun the AJAX request. Does that make sense?" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T23:27:00.017", "Id": "13483", "ParentId": "13481", "Score": "5" } } ]
{ "AcceptedAnswerId": "13483", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T21:28:56.593", "Id": "13481", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "To use or not to use public variables in javascript?" }
13481
<p>This is my second "first" attempt at starting Java. My first was cut short when I had to go back to a PHP project that required my immediate attention. But perhaps that was a good thing. I learned quite a bit more about OOP, better coding practices, and some other topics. So, after this hiatus, I noticed quite a bit wrong with my first attempt and ended up scraping it and starting from scratch.</p> <p>So here is the first phase of my Java Project: The Second "First" Attempt. Sounds like a horrible sequel to a horrible movie. The project, once complete, will convert a text file to a CSV file. The format is custom, so it is unlikely that preexisting libraries will help me here, so I didn't even bother looking, except for guidelines on how to go about it. This first class is relatively simple and creates a window with some instructions on how to use the program and a button that allows the user to begin the process by loading a text file. Not very exciting yet, but that's why its only the first phase. Please take a look at it and let me know how you think this can be improved.</p> <p>I have some specific questions and concerns, located below the code, however there are a number of them and they are quite lengthy. So if you just wish to review the code and skip the questions, that's fine too.</p> <pre><code>package view; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.JButton; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFileChooser; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; public class JavaFileParser extends JFrame implements ActionListener { /*------------------------------------------------------------------------------ CONSTRUCT ------------------------------------------------------------------------------*/ public static void main( String[] args ) { JavaFileParser parser = new JavaFileParser(); parser.pack(); parser.setVisible( true ); } public JavaFileParser() { System.out.println( "Generating user interface..." ); this.setTitle( "Title" ); this.setLocationRelativeTo( null ); this.setDefaultCloseOperation( EXIT_ON_CLOSE ); JPanel panel = addPanel(); JLabel label = addLabel( "Contents" ); panel.add( label ); JButton button = addButton( "Open File", "Open a file to begin..." ); panel.add( button ); } /*------------------------------------------------------------------------------ PUBLIC METHODS ------------------------------------------------------------------------------*/ public JPanel addPanel() { System.out.println( "Generating frame panel..." ); JPanel panel = new JPanel(); this.getContentPane().add( panel ); panel.setLayout( new FlowLayout() ); return panel; } public JLabel addLabel( String text ) { System.out.println( "Generating label with the following contents: " + text ); return new JLabel( text ); } public JButton addButton( String title, String tooltip ) { System.out.println( "Generating button with the value of: " + title ); JButton button = new JButton( title ); System.out.println( "Generating tooltip for button \"" + title + "\" with a value of: " + tooltip ); button.setToolTipText( tooltip ); button.addActionListener( this ); return button; } public void actionPerformed( ActionEvent e ) { System.out.println( "Generating File Chooser Dialog..." ); JFileChooser filechooser = new JFileChooser(); FileFilter filter = new FileNameExtensionFilter( "Text Files", "txt" ); filechooser.addChoosableFileFilter( filter ); filechooser.setFileFilter( filter ); int returnValue = filechooser.showDialog( this, "Open Report" ); if( returnValue == JFileChooser.APPROVE_OPTION ) { System.out.println( "class and method not yet implemented" ); } } } </code></pre> <p><strong>Some Specific Questions and Concerns</strong></p> <ol> <li><p>You might have noticed the package name is "view". Having just spent a considerable amount of time with MVC, I figured I would see if I couldn't use that design pattern here. However, I don't know how well the PHP version I'm familiar with translates to Java. It feels like there is just too much application logic in here for a view, however, at the same time, this all feels necessary to render it. Is this the proper way to go about it? Is there a similar design pattern or one better suited for this application?</p></li> <li><p>This list of imports seems rather long. It feels like I may have too many dependencies, but I am lost as to how I could separate them, or if its even necessary.</p></li> <li><p>I've seen a number of places say that it is not a good idea to extend common libraries, such as JFrame. Their reasoning being that JFrame is simply too heavy and methods are too easy to override by accident. On that same token, I've seen some people express that it is ok to extend JFrame if your application IS a JFrame. I wrote this program before reading these posts so I decided to leave it and see what you all think. Does this also apply to implementing common libraries, such as what I'm doing with ActionListener?</p></li> <li><p>Normally I would name files/classes based on their purpose. So in this instance, I would want to call this file/class "main" or "index" to indicate this is the first "page" the user will arrive on. However, as this is also first class of the program, it is named after the program. Should I separate this to a "main" or "index" file/class and import it in this current file/class?</p> <pre><code>import view.index; public class JavaFileParser { public static void main( String[] args ) { index index = new index(); index.pack(); index.setVisible( true ); } } </code></pre></li> <li><p>Because this class extends JFrame I can use those methods inherited from it without needing to reference an instance. I found this uncomfortable. Having come from PHP I was so used to doing <code>$this-&gt;method()</code> that I kept finding myself thinking and then typing <code>$this</code> before stopping myself. That was until I found a post where the author used <code>this.method()</code>. I adopted it and haven't had an issue since. What are the pro's and con's of this? Are there any, or is this just a style preference? Am I practicing a bad habit?</p></li> <li><p>Is it considered bad practice to leave <code>println()</code>s in the code? I find it very convenient during debugging to see the progress of the program, but is it something I should remove from the program when it is done? Does it matter? I was actually thinking of eventually converting them to logging methods so that I could easily get log dumps if any errors occured, is this the traditional way this is done, or is there some better way?</p></li> <li><p>I originally was not implementing the ActionListener class and was using a lamda function in the <code>addActionListener()</code> method called within the <code>addButton()</code> method. I didn't like how bulky it made my code, nor am I too terribly impressed with lamda functions in general. I can foresee reasons why I might need to implement lamda functions in Java in the future, say i need multiple action listeners, but is this implementation ok here?</p></li> </ol>
[]
[ { "body": "<h1>Addressing Questions and Concerns</h1>\n\n<ol>\n<li>What you have so far is typical for a Java view. The ActionListener (or any listener for that matter) should be moved to the Controller.</li>\n<li>Your imports ain't nothing. I'm not familiar with PHP, but in Java, every class is its own file (for the most part), so imports get bulky fast. Good job on not using wildcard imports (like <code>javax.swing.*</code>) that pollute the namespace.</li>\n<li>When people say you should only extend JFrame when your class IS a JFrame, they mean you will be fiddling with stuff that only apply to a frame top-level container, such as modding the title bar. The additions you have could easily go into a JApplet. I would switch to subclassing JPanel. BTW, if you plan on doing custom drawing (not applicable here but maybe in the future), it's customary to subclass JComponent rather than JPanel. (see <a href=\"https://stackoverflow.com/a/546738/830988\">Subclass JComponent or JPanel</a>) As for the ActionListener, I would put it in the Controller as I mentioned before. UI goes with the Controller, not the View.</li>\n<li>I would separate the View from the main program. Naming varies for the class with the main method. Some people favor Main, some like suffixing with Program, it's really up to you. (see <a href=\"http://www.coderanch.com/t/412354/java/java/Main-class-naming-convention\" rel=\"nofollow noreferrer\">this</a> discussion on possible names) However, I would avoid naming it index because it's lowercased, and because it's typically used for web-related stuff.</li>\n<li>I tend to see people use less of the <code>this</code> keyword in Java. Sun's <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html\" rel=\"nofollow noreferrer\">tutorial</a> only mentions two uses: disambiguating a field and calling a constructor from another constructor. (see also <a href=\"https://stackoverflow.com/questions/2411270/when-should-i-use-this-in-a-class\">When Should I Use \"This\" In a Class</a>) Personally, I don't see any problem with using this to make instance variables stand out. But I've also seen people use prefixing (e.g. <code>mButton</code>) to distinguish them. The <code>this</code> keyword before methods is kinda strange.</li>\n<li>For this one I'm not sure. <a href=\"https://stackoverflow.com/questions/4589623/debugging-to-system-out-println-or-to-not-system-out-println\">This</a> question kinda gets at what you're asking sorta. It's probably safer to remove them just in case. Sorry.</li>\n<li>I think when you say lambda function you mean anonymous inner class. Java doesn't have lambdas. I've seen some dang long anonymous listeners in my time that made sense in context, but in your case, I'd go with that Controller class I keep mentioning.</li>\n</ol>\n\n<h1>Additional Notes</h1>\n\n<ul>\n<li>Most people just prefix with J rather than Java, e.g. JFrame or JTetris.</li>\n<li><p>Everything related to swing should be in the event-dispatching thread. If you put your call to <code>parser.setVisible(true)</code> in a call to <a href=\"http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingUtilities.html#invokeLater%28java.lang.Runnable%29\" rel=\"nofollow noreferrer\"><code>SwingUtilites.invokeLater(Runnable)</code></a>, it will execute your code in the event-dispatching thread. (see <a href=\"http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html\" rel=\"nofollow noreferrer\">Threads and Swing</a>) This is where either an anonymous inner class or a separate main class will come in handy. You can either do this</p>\n\n<pre><code>public class JFileParserProgram implements Runnable {\n\n @Override\n public void run() {\n JFrame frame = new JFrame(\"Title\");\n frame.setContentPane(new JFileParserView());\n frame.pack();\n frame.setLocationRelativeTo(null);\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setVisible(true);\n }\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(new JFileParserProgram());\n }\n\n}\n</code></pre>\n\n<p>or this</p>\n\n<pre><code>public class JFileParserProgram {\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(new Runnable() {\n\n @Override\n public void run() {\n JFrame frame = new JFrame(\"Title\");\n frame.setContentPane(new JFileParserView());\n frame.pack();\n frame.setLocationRelativeTo(null);\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setVisible(true);\n }\n\n }\n }\n\n}\n</code></pre>\n\n<p>I personally use the first way because when I think of things to run, I think programs.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T16:36:23.383", "Id": "21878", "Score": "0", "body": "Thank you! There is a lot here for me to look through. I've implemented quite a few of these changes already, and will continue to go through the rest. Already I'm more satisfied with the way the code is turning out. Also, I remembered seeing that swing was not thread safe and so at the time I did not pursue threads, but with that link I think I'll have to give it another look." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T16:36:28.733", "Id": "21879", "Score": "1", "body": "I think you are using Runnable wrong here. Since it is an interface it should be implemented rather than extended, no?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T02:13:10.593", "Id": "13487", "ParentId": "13482", "Score": "7" } }, { "body": "<p>1) About the package name, it would probably be a good idea to adopt a more standard and conflict-free naming scheme, like the conventional tld.organization_name.packagename. This minimizes the possibility of namespace clash and harmonizes your packages with others.</p>\n\n<p>You're quite right that it's a good idea to break up UI and logic into different modules. Here are some patterns to look into: <a href=\"http://martinfowler.com/eaaDev/PresentationModel.html\" rel=\"nofollow\">presentation model</a>, \n<a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow\">model-view-controller</a></p>\n\n<p>You can do it like this:</p>\n\n<pre><code>mynamespace.JFileParserApplication (just contains main)\n\nmynamespace.ui.ApplicationController (the go-between bridging UI and model)\nmynamespace.ui.ApplicationFrame (extends JFrame)\nmynamespace.ui.FileSaver (extends JFileChooser)\n...and other UI stuff\n\nmynamespace.model.FileParser (implements actual logic, UI-agnostic)\n...any other stuff you may need for your model\n</code></pre>\n\n<p>2) Separating UI from model should significantly reduce coupling. To go further, it's good to make sure a class doesn't do much beyond what is logical for what it represents. For example, a child class of JFrame ought to delegate tasks like acting as a button listener and handling files to more fitting classes.</p>\n\n<p>But there's no need to get too anxious. Peek at some of the Swing source files. The imports just go on and on and on.</p>\n\n<p>3) Some of this is addressed in 2. I think it's not that JFrame shouldn't be extended, but rather an extension of JFrame ought to be essentially that. E.g., MyJFrame shouldn't be running the whole UI, and on the other hand, there's no need to extend JFrame just to give it a custom title.</p>\n\n<p>4) Application, ApplicationStart, Starter, Launcher, Main, et al should all be fine. For extra clarity, put it either as the only class at the top level under your namespace or in a logical subpackage, e.g. .app or .main.</p>\n\n<p>5) It's generally a matter of preference, but sometimes used for disambiguation. Java is a very verbose language, so it's natural that many just dispense with the often extraneous and syntactically redundant specifier that is frequently redundant, when the situation in context would make the meaning fairly unambiguous and clear without much of a possibility or chance of confusion.</p>\n\n<p><em>koff</em></p>\n\n<p>But it's not that bad a habit. You end up with syntactic noise, not unlike redundant parentheses, which may not be a bad thing if kept at a reasonable level.</p>\n\n<p>6) I'm alright with using println's and leaving them in and commented out in small projects, but if you want a more principled approach, java.util.logging.Logger might be what you're looking for.</p>\n\n<p>7) Java doesn't have lambda expressions yet. What you're describing sounds like anonymous inner classes, which are indeed bulky and inelegant. If they're of a sufficient size and complexity, consider turning them into inner classes or standalone classes.</p>\n\n<p>I don't see any anonymous inner class in your code though. Did you mean implementing ActionListener in the frame class? I agree that's not the best way to do it, and you could either make an inner class or anonymous inner class for that, like so:</p>\n\n<pre><code>private MyActionListener myListener = new MyActionListener();\n//...\nprivate class MyActionListener implements ActionListener\n{\n @Override\n public void actionPerformed(ActionEvent e)\n {\n //implement\n }\n}\n\n//anonymous inner class\nActionListener myListener =\n new ActionListener()\n {\n @Override\n public void actionPerformed(ActionEvent e)\n {\n //implement\n }\n };\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T16:40:58.883", "Id": "21880", "Score": "0", "body": "I wish I could accept both yours and Eva's answers, but sadly I can only accept one :( Both answers are full of detail and provided insight the other did not, so +1 to you both, but I'm afraid Eva posted his first. Thank you though, this was extremely helpful!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T10:03:18.897", "Id": "13489", "ParentId": "13482", "Score": "4" } }, { "body": "<p>+1 to <em>@Eva</em> and <em>@ROBOKiTTY</em> and some additional notes:</p>\n\n<ol>\n<li><p>Comments like the following are just noise:</p>\n\n<pre><code>/*------------------------------------------------------------------------------\n CONSTRUCT\n------------------------------------------------------------------------------*/\n</code></pre>\n\n<p>I'd remove them. (See <em>Clean Code by Robert C. Martin, Chapter 4: Comments, Position Markers</em>)</p>\n\n<p>It's not a performance issue. (Anyway, don't do <a href=\"https://softwareengineering.stackexchange.com/a/80092/36726\">premature optimizations</a>.) It's only for readability and maintainability. If I have to maintain some old code I usually don't believe comments, they are too often outdated and useless. Furthermore, it's really easy to decide whether something is a constructor, a main method, or a public method so comments like this do not really help too much.</p>\n\n<p>If a class getting bigger and bigger and you need these comments to see the structure, um, it's a <a href=\"http://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow noreferrer\">smell</a>. Consider separating the responsibilities and creating smaller classes, methods. (Clean Code is really a great book about this topic.)</p></li>\n<li><p>This:</p>\n\n<pre><code>parser.setVisible( true );\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>parser.setVisible(true);\n</code></pre>\n\n<p>The <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-142311.html#449\" rel=\"nofollow noreferrer\">Code Conventions for the Java Programming Language</a> does not say explicitly (or at least I couldn't find it) that you should not put space around the parameters but I as far as I see it's the standard among the Java developers to omit these spaces and the examples in the linked documentation also omit them.</p></li>\n<li><p>Calling overridable methods (like <code>addPanel</code>) from constructors is not a good practice. Child classes could see partially initialized objects in the overridden method. The <code>addPanel</code> should be <code>final</code> here. See <a href=\"https://stackoverflow.com/q/3404301/843804\">What's wrong with overridable method calls in constructors?</a> and <em>Effective Java 2nd Edition, Item 17: Design and document for inheritance, or else prohibit it</em></p></li>\n<li><p>Methods like <code>addLabel</code> and <code>addButton</code> actually do not add the created label and button to anything. I'd call the former <code>createLabel</code> and <code>createRegisteredButton</code> the latter (since it sets the listener of the button too).</p></li>\n<li><p>It's usually good practice to put <code>@Override</code> annotation to overridden methods, so the <code>actionPerformed</code> method should have one. See: <a href=\"https://stackoverflow.com/q/94361/843804\">When do you use Java's @Override annotation and why?</a></p></li>\n<li><p>Using <code>this.</code> when it's not really necessary also just noise. Modern IDEs use highlighting to separate local variables from instance variables.</p></li>\n<li><p>I'm not too familiar with Swing, so the <code>setLocationRelativeTo(null)</code> looks really weird to me. What does the <code>null</code> parameter means here? It looks like a magic number even it's in the javadoc. I'd create a <code>setLocationToCenter()</code> method for that:</p>\n\n<pre><code>private void setLocationToCenter() {\n setLocationRelativeTo(null);\n}\n</code></pre>\n\n<p>It would document the intention of the developer and easier to read and maintain. The program does the same but the maintainer don't have to know every detail of the API nor check the documentation to understand the code.</p></li>\n<li><p>The title could be a little bit descriptive than the following:</p>\n\n<pre><code>setTitle( \"Title\" );\n</code></pre></li>\n<li><p>Instead of using <code>System.out</code> or <code>java.util.logging</code> consider a better one. I strongly suggest you SLF4J + Logback. It's worth to learn it, it's useful in small projects as well as in bigger ones.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T23:46:40.150", "Id": "21955", "Score": "1", "body": "I'm not sure I really agree with #1. Compiled languages ignore comments so it is not a performance issue and therefore is one of style. I believe this helps add clarity to a program that could otherwise become large and difficult to read by adding visual break points. I do not do it for every function, except JavaDOC when I get around to it, just the logical sections (constructor, public methods, and private methods). I'll have to read that book before I make any final decisions on this one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T23:46:49.030", "Id": "21956", "Score": "0", "body": "I definitely don't agree with #2. I've read that link and it doesn't specifically say not to do what I'm doing. If you were to follow that link to the letter, I could say that the example you gave violates those conventions because you did not add a space between the function and opening parenthesis. I believe they were trying to enforce using braces `{}` here rather than overall format. My way is simply a stylistic choice and in no way impacts performance. Unless you can provide proof that this way could cause problems I'll ignore this point." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T23:46:57.577", "Id": "21957", "Score": "0", "body": "Most of the other points I ended up discovering while researching the other two answers and they are now updated in my current version. I'm still having a bit of trouble with #3. Not in understanding why, but understanding how to fix it. As for #7, I believe this is standard, at least, this is what I've seen in the docs and IDE. #8 was me just fleshing it out and is fixed now. I'll have to take a look at #9, though I'm not sure if I'll be able to implement it here. This is more of a side project for work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T23:47:04.993", "Id": "21958", "Score": "0", "body": "Thank you overall though. Most of these points were very helpful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-13T06:06:15.577", "Id": "22046", "Score": "0", "body": "@showerhead: I've edited the post a little bit. \"I could say that the example you gave violates those conventions because you did not add a space between the function and opening parenthesis.\" - Which convention do you mean?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-13T16:58:23.853", "Id": "22074", "Score": "0", "body": "I meant that line should actually be: `parser.setVisible (true);` It does not explicitly say that what you are doing is wrong. It doesn't give an example one way or the other. All the examples just show it as being so. Ironic that. I'm not 100% sure about Java, but I do know PHP and C# don't care. Well, C# explicitly mentions **keywords** \"for/if/etc\" should be preceded by a space. But Microsoft's C# IDE gives you the option to change the styles to match mine. And seen as C# and Java seem very similar stylistically, I would hazard that there is nothing wrong with this style choice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-13T16:59:03.087", "Id": "22075", "Score": "0", "body": "Thanks for the update. Correct me if I'm wrong, but I don't think I'm violating premature optimization. I only mentioned performance in relation to your suggestions. Not saying these are the only things I'm looking at before making a suggested change, just that they were the only ones left. I believe legibility is always more important than performance, which is the reason I'm arguing so strongly for these two points." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-13T16:59:53.523", "Id": "22076", "Score": "0", "body": "Constructor, Private, and Public comment markers are a convention I brought over from PHP where the code usually runs around 2-300 lines. Not too long, but still a bit of a scroll. I find it easier to scroll to the proper section and begin my search there. I don't see this hindering legibility, if anything, it enhances it. Now, on smaller code I do remove them because then it is just noise. I'm not the only one to do this either. Well documented shared libraries will sometimes have similar markers, which is where I picked it up from." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-13T17:02:25.423", "Id": "22077", "Score": "0", "body": "Having spaces inside parenthesis (), braces [], and brackets <> also enhance legibility. Not just the act of reading, but also because of IDE brace matching. Some simple examples `( ! bool )` Logical operators, such as !, can easily be missed inside a tight parameter list. `[ 0 ] [ 1 ]` Mashed together braces ][ can become difficult to distinguish when right next to each other. And of course, brace matching is difficult to determine when two or more braces are next to each other. Though that last point has a bad smell to it and is not why I do this, just another benefit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-13T17:02:48.200", "Id": "22078", "Score": "0", "body": "Now, this conversation is becoming extremely long and drawn out. If you want to continue this discussion, just let me know and I'll find some way of getting you my email, or meeting you on another forum, or something else." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T22:30:26.407", "Id": "13550", "ParentId": "13482", "Score": "4" } } ]
{ "AcceptedAnswerId": "13487", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T22:00:45.423", "Id": "13482", "Score": "7", "Tags": [ "java", "swing", "beginner" ], "Title": "First Project: JFrame Class" }
13482
<p>I have to store some properties in a database properties table which looks like this:</p> <pre><code>CREATE TABLE `property` ( `id` int(11) NOT NULL AUTO_INCREMENT, `computer_name` varchar(64) NOT NULL, `name` varchar(64) NOT NULL, `value` varchar(1024) NOT NULL, PRIMARY KEY (`id`) ); </code></pre> <p>Sample data:</p> <pre><code>+----+---------------+-----------------+-------+ | id | computer_name | name | value | +----+---------------+-----------------+-------+ | 9 | PC002 | firewall_status | 3 | | 10 | PC011 | firewall_status | 0 | | 11 | PC011 | some_property | 1 | </code></pre> <p>To access data in that table I have a <code>getProperty($computerName, $propertyName)</code> method in a repository, which finds the value of specified property for certain computer. And in different parts of my application I call the method like this: </p> <pre><code>$computer = $repository-&gt;findComputer(); $firewallStatus = $repository-&gt;getProperty($computer-&gt;name, 'firewall_status'); </code></pre> <p>What I don't like here is hard coded name of the property. My solution was to put available property names to a model:</p> <pre><code>class ComputerModel { const PROPERTY_FIREWALL_STATUS = 'firewall_status'; const PROPERTY_SOME_PROPERTY = 'some_property'; } ... $computer = $repository-&gt;findComputer(); $firewallStatus = $repository-&gt;getProperty($computer-&gt;name, ComputerModel::PROPERTY_FIREWALL_STATUS); </code></pre> <p>We discussed storing property names as constants and decided that we have some trade-offs:</p> <p><strong>Good</strong> (mostly for code maintanance):</p> <ul> <li>keep the value in one place which make it more simple to change it;</li> <li>keep available property dictionary in one place (in the model);</li> <li>make the code completion available in IDE instead of searching for correct property name to copy/paste it;</li> </ul> <p><strong>Not good</strong> (mostly for debugging):</p> <ul> <li>by storing a literal values we create extra overhead by storing variable names in new variables; </li> <li>worsen debugging by add one more step to find the object containing debug information;</li> <li>we need to support additional dictionary; possible data inconsistency if someone adds new value to database but forget to update it in the model.</li> </ul> <p><strong>Subjective</strong>:</p> <ul> <li>improves/reduces code readability.</li> </ul> <p>The question is: what is the best way to store such parameter names? Or maybe to use literals.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T01:18:24.683", "Id": "21904", "Score": "0", "body": "Too lazy to write a proper response, but I have a feeling that this may be of use: http://www.scribd.com/doc/2670985/SQL-Antipatterns In particular the section that starts on page 30. In short, unless your set of attributes truly needs to be dynamic, they should usually be columns instead of rows." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T08:13:32.553", "Id": "21928", "Score": "0", "body": "@Corbin thank you for the link, it's really helpful. As to the columns - that solution depends on requirements, but in general I agree with you." } ]
[ { "body": "<blockquote>\n <p>keep the value in one place which make it more simple to change it</p>\n</blockquote>\n\n<p>You will never change it (why would you?) so this is not a valid reason. And if you did change it then search/replace works fine.</p>\n\n<blockquote>\n <p>keep available property dictionary in one place (in the model)</p>\n</blockquote>\n\n<p>This looks like MySQL to me. So I suggest using an enum for this instead of a varchar. It will be much faster, take less storage space, prevent invalid values, and have the benefit of storing the dictionary right in the database.</p>\n\n<blockquote>\n <p>make the code completion available in IDE instead of searching for correct property name to copy/paste it</p>\n</blockquote>\n\n<p>This is nice - however is there no other way to do this? Can you not add some kind of configuration file that will define these?</p>\n\n<p>In the \"not good\" column I would put adds complexity for little gain. You've taken a string, and turned it back into a different string, only uppercase.</p>\n\n<p>Now, if you were going to store these as integers (i.e. do the equivalent of enum yourself) then making constants has value. You are turning a string into a number, so it actually does something.</p>\n\n<p>So, my suggestion:</p>\n\n<p>Either use enums in your database, and just write them as strings, or store integers, and use the constants.</p>\n\n<p>But don't store these properties as strings.</p>\n\n<p>(BTW, suppose you want to convert from one to the other: Search/replace! I've seen too many cases of overengineering things just from fear of search/replace.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T23:32:47.880", "Id": "21895", "Score": "0", "body": "Thank you! Enums is a really good idea, I didn't think about it. As to search/replace, it was one of my arguments - it is easier to find occurrences of a constant than of a certain word (especially when it is not 'firewall_status' but something like 'error'). And overengineering - yes - that's the argument of my opponent :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T01:14:29.320", "Id": "21903", "Score": "0", "body": "Enums are almost never the correct solution in a RDBMS. They're the same functionality (and insignificantly close performance) as a lookup table with none of the maintainability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T01:45:31.507", "Id": "21910", "Score": "0", "body": "@Corbin My rule is if it's hardcoded in the app, it's hardcoded in the database. I hate lookup tables where it's hardcoded in the app, but is editable data in a database table. They also require pre-loading when releasing, and I've found they get out of sync sometimes when adding more entries in new releases. And they allow invalid data. With an enum the database maintains the lookup association over an alter table. If you mean a lookup table in the app, then I don't like those because when working directly in the database you have meaningless numbers, which makes it harder to work with." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T01:49:55.920", "Id": "21912", "Score": "0", "body": "@Ariel A lookup table that resides in a database should never be hard coded in an application. If the entire table is needed for some reason, then it should just be retrieved. The problem with enums is that they're not data. They can't be manipulated in an easy way from application-space. They also cannot have their options enumerated very easily (counter intuitively). How would your application know the possible values of an enum without either hard coding an array or doing some nasty meta-data fetching?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T02:00:43.640", "Id": "21913", "Score": "1", "body": "@Corbin When I say hardcoded I mean the names of the lookup keys. It's not really that hard to enumerate an enum, even though it is meta-data fetching. I made a function specifically for that, rare thought it is that I use it. It's pretty unusual to need to enumerate the enum - it's mainly used when you have a fixed set of values that you use. They could just as easily be integers, but by using an enum it's easier to read the database output." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T02:24:50.867", "Id": "21916", "Score": "0", "body": "@Ariel Well, when it comes down to it, some kind of key will have to be used in code whether it's the key of a lookup table or the key of an enum. Every time I've ever gone with enums, I've regretted it for the fact that enums are basically meta data and lookup tables are data. I suppose discretion can be used in any situation, but I do not feel that enums fit this situation. (Actually, I believe his table model is broken to begin with as the attributes should be their own columns, but that's unrelated to the immediate discussion.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T02:28:51.127", "Id": "21917", "Score": "0", "body": "@Corbin My rule is: If the user can change it (add/remove/edit them) - even a configuration file, then a lookup table. If it requires source code changes, then an enum in the database. Basically the source code and the database \"code\" always match. If you hardcode one, you hardcode the other." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T04:25:10.543", "Id": "21919", "Score": "0", "body": "@Corbin Different things for different purposes. I find enums useful, and for what I use them for, none of the disadvantages listed. If your choice is an enum or an int (with the meaning of the int defined in your app as a constant) then it's no contest. If you use an external table then that's not bad, but there is more hassle, since you'll need an installation script to load it up. And I find it distasteful to hardcode a string in my app, when the corresponding string is a variable in the database." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T04:33:48.690", "Id": "21922", "Score": "0", "body": "@Corbin Some things to help decide: How many options? Will they ever change? Are the options user visible, or just internal? Do you need to support other DBs? Is there extra data that goes along with an option?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T04:54:12.083", "Id": "21923", "Score": "0", "body": "@Ariel All of the disadvantages still apply. And either way you're working with strings magically mapped to integers, just enums handle it more transparently (but also much less flexibly). Anyway, this is obviously a difference in opinion so we should leave it at that." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T19:06:32.250", "Id": "13511", "ParentId": "13491", "Score": "2" } } ]
{ "AcceptedAnswerId": "13511", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T10:37:31.853", "Id": "13491", "Score": "0", "Tags": [ "php" ], "Title": "How to store option key names" }
13491
<p>I have implemented the "[ ]" operator in a class that I have created to return values associated with a key (the same concept of a dictionary, except that it's possible to have the same key more than one time). However, looking at my code I don't think it is as efficient as it could be.</p> <pre><code>public class MyClass { public object[][] Values; public MyClass() { Values = new object[4][]; } public IEnumerable&lt;object&gt; this[string key] { get { var results = new List&lt;object&gt;(); foreach (var value in this.Values) { if (value[0].ToString() == key) { results.Add(value[1]); } } return results; } } } </code></pre> <p>Values can contain a bunch of 2 values arrays.</p> <p>A small example:</p> <pre><code>MyClass class = new MyClass(); class.Values[0] = new object[] { "key1", 25 }; class.Values[1] = new object[] { "key2", 3 }; class.Values[2] = new object[] { "key2", 789 }; class.Values[3] = new object[] { "key4", 12 }; </code></pre> <p>and when I do <code>class["key2"]</code>, it returns a collection containing <code>3</code> and <code>789</code>.</p> <p>What do you think of the way I implemented the this[string key] method? Do you think there is a way to do this without iterating on all the objects in the Values array?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T13:25:25.750", "Id": "21846", "Score": "7", "body": "Read about Generics (http://msdn.microsoft.com/en-US/library/ms379564.aspx) and favor them over storing items of type `object`." } ]
[ { "body": "<p>If you look for performance, you'd better rely on the framework dictionary. You can use the <code>Dictionary&lt;string, List&lt;object&gt;&gt;</code> to do what you need. When you add a new key and value, look if the key already exists. If so, add the value to the array and don't add the key.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T14:14:17.107", "Id": "21862", "Score": "1", "body": "I think you mean `Dictionary<string, List<object>>`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T14:16:41.747", "Id": "21864", "Score": "0", "body": "Yes you're right. Thanks. How do I accept your edit?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T15:01:24.777", "Id": "21871", "Score": "0", "body": "I didn't propose that edit, you could have just edited your answer by yourself. (I have enough reputation on this site, so that my edits are accepted automatically. If I didn't and I made that edit, you would see a number beside the “edit” button, signifying how many people already accepted the edit.)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T13:14:56.980", "Id": "13493", "ParentId": "13492", "Score": "10" } }, { "body": "<p>This is intended as a comment to the answer from @AmiramKorach; here is a reasonable way to get from the list you have to the dictionary you want (without concerning yourself about managing the dictionary details):</p>\n\n<pre><code>Dictionary&lt;string, List&lt;int&gt;&gt; result =\n new[]\n {\n new {Name = \"key1\", Value = 25},\n new {Name = \"key2\", Value = 3},\n new {Name = \"key2\", Value = 789},\n new {Name = \"key3\", Value = 12}\n }\n .GroupBy(p =&gt; p.Name)\n .ToDictionary(\n group =&gt; group.Key,\n values =&gt; values.Select(g =&gt; g.Value).ToList()\n );\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T22:01:46.297", "Id": "13523", "ParentId": "13492", "Score": "1" } } ]
{ "AcceptedAnswerId": "13493", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T13:09:45.290", "Id": "13492", "Score": "1", "Tags": [ "c#", "collections" ], "Title": "Implementing [ ] operator" }
13492
<p>I've got a SQL database that keeps track of which services a client has. I need to create an image using SVG that only displays the services that the client has. The database stores the services in the format <code>1,2,3,6,7,9</code>. Here's what I have:</p> <pre><code> &lt;?php header("Content-type: image/svg+xml"); $db = new PDO(**[redacted]**); $grabServices = $db-&gt;prepare("SELECT services FROM *** where name= :name"); $grabServices-&gt;execute(array(":name" =&gt; "test" )); $services = $grabServices-&gt;fetchAll(); $services = explode(",", $services[0][services]); var_dump($services); ?&gt; //snip... &lt;?php if(in_array(1, $services)){?&gt; &lt;line x1="820" y1="120" x2 ="790" y2="180" class="SaaS"/&gt; &lt;?php }?&gt; &lt;?php if(in_array(2, $services)){?&gt; &lt;line x1="905" y1="180" x2 ="700" y2="370" class="PM"/&gt; &lt;?php }?&gt; //etc, etc, </code></pre> <p>This seems incredibly tedious to me. The only other way I can think to do this would have all the SVG elements created in a PHP array, but that seems even more wasteful. Is there a better way to do this?</p>
[]
[ { "body": "<pre><code>&lt;?php\n$formats = array(\n '1' =&gt; array(\n 'x1' =&gt; 820,\n 'y1' =&gt; 120\n ),\n '2' =&gt; array(\n 'x1' =&gt; 905,\n 'y1' =&gt; 180\n )\n);\n?&gt;\n\n&lt;?php foreach( $formats as $key =&gt; $format ) : ?&gt;\n &lt;?php if ( in_array( (int) $key, $services ) ) : ?&gt;\n &lt;line x1=\"&lt;?php print $format['x1']; ?&gt;\" y1=\"&lt;?php print $format['y1']; ?&gt;\" /&gt;\n &lt;?php endif; ?&gt;\n&lt;?php endforeach; ?&gt;\n</code></pre>\n\n<p>I didn't do it for every field, but you get the idea.</p>\n\n<p>This is tedious to write the array. But you <em>have to</em> write it somewhere. If there is no logic, the computer can't guess.</p>\n\n<p>I think it's easier to read/write a simple array than all this XML though.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T14:29:25.647", "Id": "13505", "ParentId": "13494", "Score": "4" } } ]
{ "AcceptedAnswerId": "13505", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T13:51:25.743", "Id": "13494", "Score": "3", "Tags": [ "php", "svg" ], "Title": "Best way to create SVG from database? (Using PHP)" }
13494
<p>I have a function called <code>FormatCurrency()</code> which I would like to call on each of the following elements:</p> <pre><code> TextBoxA TextBoxB TextBoxC ... TextBoxN </code></pre> <p>My current function performs the following operation</p> <pre><code> function formatALL() { //get the value into var v. call FormatCurrency(v) and store it back var v = document.getElementById("TextBoxA_TextBox").value; document.getElementById("TextBoxA_TextBox").value = FormatCurrency(v); v = document.getElementById("TextBoxB_TextBox").value; document.getElementById("TextBoxB_TextBox").value = FormatCurrency(v); v = document.getElementById("TextBoxC_TextBox").value; document.getElementById("TextBoxC_TextBox").value = FormatCurrency(v); //etc... all the way til my last TextBox } </code></pre> <p>Is it possible to optimize this code? In other words, does anyone know any slick loops/operations/etc. to perform this same task?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T23:59:42.270", "Id": "21849", "Score": "3", "body": "are you familiar with jQuery?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T00:06:09.633", "Id": "21850", "Score": "1", "body": "yes, jQuery would make this infinitely slicker." } ]
[ { "body": "<p>stick all the strings into an array and iterate over them?</p>\n\n<p>something like</p>\n\n<pre><code>var myElems=[\"TextBoxA_TextBox\",\"TextBoxB_TextBox\",\"TextBoxC_TextBox\"];\nfor(var i = 0; i &lt; myElems.list; i++) {\n var v = document.getElementById(i).value;\n document.getElementById(i).value = FormatCurrency(v);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T00:00:07.450", "Id": "13496", "ParentId": "13495", "Score": "1" } }, { "body": "<p>You can loop through the elements using a for loop:</p>\n\n<pre><code>for(var i = 65; i &lt;= 78; i++) {\n var box = document.getElementById(\"TextBox\" + String.fromCharCode(i) + \"_TextBox\");\n box.value = FormatCurrency(box.value); \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T00:01:55.650", "Id": "21851", "Score": "0", "body": "Store the fetch into a variable and you're golden." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T00:04:15.667", "Id": "21852", "Score": "0", "body": "This is JavaScript, nothing with a char type and a ++ operator on it..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T00:06:44.623", "Id": "21853", "Score": "0", "body": "@Bergi: Ah good catch. Been jumping around too many languages lately." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T04:25:54.200", "Id": "21854", "Score": "0", "body": "Well I enumerated them with Alphabets since in actuality, they actually don't have any pattern to their names. I should've been more clear in that regards. Let's say that the names are Jon, steve, mike, etc... \n\nStill this is a good suggestion" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T00:00:18.890", "Id": "13497", "ParentId": "13495", "Score": "6" } }, { "body": "<p>The quickest modification would be to store your elements in a variable:</p>\n\n<pre><code>var obj = document.getElementById(\"TextBoxA_TextBox\");\nobj.value = FormatCurrency(obj.value);\n</code></pre>\n\n<p>The next step would be to create a loop that repeats the process dynamically and not statically as it is currently configured.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T00:01:14.597", "Id": "13498", "ParentId": "13495", "Score": "1" } }, { "body": "<p>Two strategies: loops and variables.</p>\n\n<pre><code>function formatALL() {\n // \"A\".charCodeAt(0) = 65\n // \"N\".charCodeAt(0) = 78\n for (var i=65; i&lt;79; i++) {\n var chr = String.fromCharCode(i);\n var el = document.getElementById(\"TextBox\"+chr+\"_TextBox\");\n el.value = FormatCurrency(el.value);\n }\n}\n</code></pre>\n\n<p>It would be easier if you had enumerated your elements with decimal numbers, not alphanumerical characters. If the element ids grew more complicated (less predictable), you'd need to put them in an array and loop over them:</p>\n\n<pre><code>function formatALL() {\n var ids = [\"Jon\", \"steve\", \"mike\", ...];\n for (var i=0; i&lt;ids.length; i++) {\n var el = document.getElementById(ids[i]+\"_TextBox\");\n el.value = FormatCurrency(el.value);\n }\n}\n</code></pre>\n\n<p>An even better strategy would be to use a class instead of numbered ids (the elements don't seem to be such unique :-)), like \"currency\" in your case. Then you don't need to adjust the array every time you change something in the page. With a class name, you can use something like <code>getElementsByClassName(\"currency\")</code> (or a library equivalent like <code>jQuery(\".currency\")</code>, then iterate over the returned <code>NodeList</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T00:09:58.053", "Id": "21855", "Score": "0", "body": "In terms of optimization, I would eliminate the unnecessary container variables." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T00:13:55.960", "Id": "21856", "Score": "0", "body": "What do you mean with \"container variable\"? The only unnecessary var is \"chr\", which I've used to improve comprehensibility and readability. Nothing to micro-optimize here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T00:16:22.570", "Id": "21857", "Score": "0", "body": "He asked what he could do to optimize the code. Even if it's \"micro-optimization,\" creating unneccessary vars is using unnecessary memory." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T00:27:50.793", "Id": "21858", "Score": "0", "body": "The OP wanted to optimize code, not performance. As you can see in @tskuzzy's answer, the line gets too long for SO - that's not \"good\" code. Depending on your JS knowledge, you might write less code less readable - I might have done the same if it wasn't a answer on a newbies question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T04:20:58.363", "Id": "21859", "Score": "0", "body": "Well I enumerated them with Alphabets since in actuality, they actually don't have any pattern to their names. I should've been more clear in that regards.\n\nLet's say that the names are Jon, steve, mike, etc..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T06:10:44.250", "Id": "21860", "Score": "0", "body": "@RobertHsu don't that, you will eventually run out of letters" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T08:15:25.857", "Id": "21861", "Score": "0", "body": "@RobertHsu: Yes, as I wrote you then would need to use an array (I've added an example for that now)." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T00:03:03.920", "Id": "13499", "ParentId": "13495", "Score": "1" } }, { "body": "<p>You could use a library such as <a href=\"http://jquery.com/\" rel=\"nofollow\">jQuery</a>, which allows you, for example, to select elemts using CSS selectors. In this case you could assign all your elements a class and use:</p>\n\n<pre><code>$('.currency-textbox').each(function() {\n $(this).val(FormatCurrency($(this).val()));\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T00:12:38.250", "Id": "13500", "ParentId": "13495", "Score": "3" } }, { "body": "<p>There are a fews ways to go about it. Since your examining how to create <strong>\"slicker\"</strong> or <strong>DRY</strong> code, I would assume you would want succinct code, but not illegible? And you would also be willing to change code to get it.</p>\n\n<p><strong>Note</strong>: Don't Repeat Yourself (<strong>DRY</strong>).</p>\n\n<blockquote>\n <p>Here are two ways in which to do it. One uses <strong>ID</strong> (current), and one uses <strong>class</strong> (perhaps more slick).</p>\n</blockquote>\n\n<p><strong>Note</strong>: We use Array.from() to create an actual <em>Array</em> from the document node list (ES6), or use the polyfill for legacy browsers <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from?v=control\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// If changing the FormatCurrency function is on the table...\n\nfunction FormatCurrencyWithChange(input){\n // Whatever you do in here, use input.value.\n input.value = '$ ' + (Math.random() * 100).toFixed(2);\n}\n\nArray.from(document.getElementsByClassName(\"currency\")).forEach(FormatCurrencyWithChange);\n\n// OR\n\nArray.from(document.querySelectorAll('[id$=\"TextBox\"]')).forEach(FormatCurrencyWithChange)\n\n// If you cannot change the FormatCurrency function, then you could also wrap it up.\n// Also, if it's not a class, then the function name should be camelCase.\n\nfunction formatCurrency(input){\n input.value = FormatCurrencyNoChange(input.value);\n}\n\nfunction FormatCurrencyNoChange(value){\n // I don't know whats in your function; This one still accepts value.\n return '$ ' + (Math.random() * 100).toFixed(2);\n}\n\nArray.from(document.getElementsByClassName(\"currency-wrap\")).forEach(formatCurrency);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>input, label {\n display: block;\n}\n\ninput {\n margin-bottom: 20px;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;label&gt;Text Box A (ID)&lt;/label&gt;\n&lt;input id=\"#TextBoxA_TextBox\" type=\"text\" /&gt;\n\n&lt;label&gt;Text Box B (ID)&lt;/label&gt;\n&lt;input id=\"#TextBoxB_TextBox\" type=\"text\" /&gt;\n\n&lt;label&gt;Currency (CLASS)&lt;/label&gt;\n&lt;input class=\"currency\" type=\"text\" /&gt;\n\n&lt;label&gt;Currency (CLASS)&lt;/label&gt;\n&lt;input class=\"currency\" type=\"text\" /&gt;\n\n&lt;label&gt;Currency (CLASS) Using Wrapper&lt;/label&gt;\n&lt;input class=\"currency-wrap\" type=\"text\" /&gt;\n\n&lt;label&gt;Currency (CLASS) Using Wrapper&lt;/label&gt;\n&lt;input class=\"currency-wrap\" type=\"text\" /&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-26T05:59:42.887", "Id": "161810", "ParentId": "13495", "Score": "0" } } ]
{ "AcceptedAnswerId": "13497", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T23:57:28.667", "Id": "13495", "Score": "1", "Tags": [ "javascript", "formatting", "form" ], "Title": "Calling a FormatCurrency function on multiple textboses" }
13495
<p>All, I have written some code to get the latest files from a directory, the files I am looking for contain the string <code>sProcScript = "sProcScript"</code> and in the selected directory I might have several versions:</p> <pre><code>sProcScriptBigGuns1001.sql sProcScriptBigGuns1007.sql sProcScriptEdAggVal1006.sql sProcScriptEdAggVal1007.sql ... </code></pre> <p>and I want to pick up the <em>latest version only</em> (the version number being the number after the file name i.e. 1007 etc.). So in the above this would be <code>sProcScriptBigGuns1007.sql</code> and <code>sProcScriptEdAggVal1007.sql</code>. To do this I wrote the following snippet (as part of a larger method), where <code>strPath</code> is the path to the relevant directory</p> <pre><code>DirectoryInfo dirInfo = new DirectoryInfo(strPath); List&lt;FileInfo&gt; listFileInfo = new List&lt;FileInfo&gt;(); listFileInfo = dirInfo.EnumerateFiles().ToList&lt;FileInfo&gt;(); // Loop in to locate special processes. List&lt;FileInfo&gt; specialProcList = new List&lt;FileInfo&gt;(); foreach (FileInfo fi in listFileInfo) if (Path.GetFileNameWithoutExtension(fi.FullName).Contains(sProcScript)) specialProcList.Add(fi); // Get distinct. List&lt;string&gt; nameList = new List&lt;string&gt;(); foreach (FileInfo fi in specialProcList) { string strsProc = Path.GetFileNameWithoutExtension(Regex.Replace(fi.Name, @"[\d]", String.Empty)); if (!nameList.Contains(strsProc)) nameList.Add(strsProc); } List&lt;FileInfo&gt; tmpList; List&lt;string&gt; tmpNameList = new List&lt;string&gt;(); tmpList = specialProcList.OrderByDescending(f =&gt; f.Name).ToList(); foreach (string name in nameList) { foreach (FileInfo fi in tmpList) { if (fi.Name.Contains(name)) { tmpNameList.Add(fi.Name); listFilesFound.Add(fi); break; } } } </code></pre> <p>which works great. However, I think there will be a much better and neater way of doing this using LINQ but I am new to LINQ and can't seem to get started with it (the attempts I have made are poor enough to not want to post them here!). <strong>Can someone demonstate a better way of doing the above operation using LINQ?</strong></p> <p>Thanks for your time.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T14:12:18.437", "Id": "21863", "Score": "0", "body": "This is not a code review question. I have demonstrated a viable solution to illustrate I don't want the work done for me. The question could be answered without the code snippet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T15:04:18.877", "Id": "21872", "Score": "0", "body": "This is part of even larger method? I think writing smaller methods would make your code more readable." } ]
[ { "body": "<p>This should do it:</p>\n\n<pre><code>var selectedFileInfos = listFileInfo\n .Where(x =&gt; { \n var filename = Path.GetFileNameWithoutExtension(x.FullName); \n return specialProcList.Any(y =&gt; filename.Contains(y);})\n .OrderByDescending(x =&gt; x.Name)\n .GroupBy(x =&gt; Path.GetFileNameWithoutExtension(Regex.Replace(x.Name, @\"[\\d]\", String.Empty)) \n .Select(x =&gt; x.First());\n</code></pre>\n\n<p>But be careful: file numbers should be padded with zeros. 0001, 0900, 0999, 1000, 1001. If they are just normally numbered with 1, 900, 999, 1000 etc., even your code will fail.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T14:30:56.177", "Id": "21866", "Score": "0", "body": "Thanks very much, however the edit to you answer was required to get it to work. The edit compiles but returns nothing - can you advise. Again, thanks very much for your time..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T14:17:42.260", "Id": "13502", "ParentId": "13501", "Score": "2" } }, { "body": "<p>Another one (assuming the filename is always <em>SomeCharactersSomeNumbers.extension</em>):</p>\n\n<pre><code>void Main()\n{\n var sProcScript = \"sProcScript\";\n\n var fileNames = new [] {\"sProcScriptBigGuns1001.sql\", \n \"sProcScriptBigGuns1007.sql\",\n \"sProcScriptEdAggVal1006.sql\",\n \"sProcScriptEdAggVal1007.sql\"};\n\n var grouped = from f in fileNames\n where f.Contains(sProcScript)\n let m = new {FileName = f, \n Group = new string(f.TakeWhile(c=&gt;!Char.IsDigit(c)).ToArray()),\n Version = Int32.Parse(new string(f.Where(c=&gt;Char.IsDigit(c)).ToArray()))}\n group m by m.Group;\n\n var files = grouped.Select(g =&gt; g.OrderByDescending(f =&gt; f.Version).First().FileName); \n\n foreach (var file in files)\n Console.WriteLine(file);\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T14:26:04.963", "Id": "13503", "ParentId": "13501", "Score": "2" } }, { "body": "<p>How about:</p>\n\n<pre><code>var files = from file in new DirectoryInfo(strPath).EnumerateFiles()\n let nameWithoutEx = Path.GetFileNameWithoutExtension(file.Name)\n where nameWithoutEx.Contains(sProcScript)\n let key = new string(nameWithoutEx.Reverse()\n .SkipWhile(char.IsDigit)\n .Reverse()\n .ToArray())\n group file by key into versionGroup\n select versionGroup\n .OrderBy(f =&gt; int.Parse(new string(f.Name\n .Skip(versionGroup.Key.Length)\n .TakeWhile(char.IsDigit)\n .ToArray())))\n .Last();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T14:43:18.313", "Id": "21867", "Score": "0", "body": "Thanks but as this stands it won't compile due to a number of errors. Thanks for your time..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T14:45:41.897", "Id": "21868", "Score": "0", "body": "@Killercam: Didn't try, but what are the errors? What version of C# / .NET are you on?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T14:50:33.997", "Id": "21869", "Score": "0", "body": "Framework 4.0, there were a few. I have an answer above working so I wont waste anymore of your time. But thanks you very much for your response it is most appreciated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T14:59:01.087", "Id": "21870", "Score": "0", "body": "@Killercam: The only thing missing was the ToArray() calls. Fine now." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T14:29:19.110", "Id": "13504", "ParentId": "13501", "Score": "2" } }, { "body": "<p>Try:</p>\n\n<pre><code>Directory.EnumerateFiles(filePath)\n .Select(f =&gt; new { FileName = f, SprocName = regex.Replace(Path.GetFileNameWithoutExtension(f), \"\"), Version = int.Parse(regex.Match(f).Value) })\n .Where(f =&gt; f.FileName.Contains(sProcScript))\n .GroupBy(f =&gt; f.SprocName)\n .Select(g =&gt; new { Sproc = g.Key, MaxVersion = g.Max(s =&gt; s.Version) })\n .Dump();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T14:37:30.193", "Id": "13506", "ParentId": "13501", "Score": "2" } } ]
{ "AcceptedAnswerId": "13503", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T14:06:46.927", "Id": "13501", "Score": "3", "Tags": [ "c#", "linq" ], "Title": "Alternative way to extract the most recent file using LINQ" }
13501
<p>I have a number of jQuery animation effects applied to certain elements on the page:</p> <pre><code>jQuery("#bgd_balance").animate({ backgroundPositionY: "0px", backgroundPositionX: "0px", 'background-size':'100%' },800,"swing"); jQuery(".balance_left_box").delay(2000).slideDown(200,"easeInCirc"); jQuery(".balance_left_box p.first-line").delay(2400).slideDown(600,"easeInCirc"); jQuery(".balance_left_box").delay(1000).animate({ height:"270px", top:"64px" },100,"easeInCirc"); </code></pre> <p>The problem I'm facing is that when I'm tweaking delay of a certain element, I have to go through everything and adjust all other delays accordingly.</p> <p>Is it possible to have something like this instead (<strong>pseudocode</strong>):</p> <pre><code>queue.add( delay(2000), jQuery(".balance_left_box").slideDown(200,"easeInCirc"), delay(2000), jQuery(".balance_left_box p.first-line")X.slideDown(600,"easeInCirc"); delay(1000), jQuery(".balance_left_box").animate({ height:"270px", top:"64px" },100,"easeInCirc"); ).run(); </code></pre> <p>I know I can achieve this "queuing" by adding callback function to <code>animate()</code> call but then resulting code will be really bulky and hard to read, in my opinion.</p>
[]
[ { "body": "<p>The way I see it, you have 2 options; either use Deferreds, or store your delay in a variable:</p>\n\n<pre><code>var delay = 0,\n $left_box = $(\".balance_left_box\");\n\n$(\"#bgd_balance\").animate({\n backgroundPositionY: \"0px\",\n backgroundPositionX: \"0px\",\n 'background-size':'100%'\n}, 800, \"swing\");\n\n$left_box.delay(delay += 2000).slideDown(200, \"easeInCirc\");\n\n$left_box.find(\"p.first-line\").delay(delay += 2400).slideDown(600, \"easeInCirc\");\n\n$left_box.delay(delay += 1000).animate({\n height:\"270px\",\n top:\"64px\" \n}, 100, \"easeInCirc\");\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T18:09:32.597", "Id": "13508", "ParentId": "13507", "Score": "4" } }, { "body": "<p>You could create your own queue by creating a temporary element and adding methods to it's queue using promise objects</p>\n\n<pre><code>var queueEl = $(\"&lt;div&gt;&lt;/div&gt;\");\nqueueEl.delay(2000).queue(function(next){\n jQuery(\".balance_left_box\").slideDown(200,\"easeInCirc\").promise().done(next);\n}).delay(2000).queue(function(next){\n jQuery(\".balance_left_box p.first-line\").slideDown(600,\"easeInCirc\").promise().done(next);\n}).delay(1000).queue(function(next){\n jQuery(\".balance_left_box\").animate({\n height:\"270px\",\n top:\"64px\" \n },100,\"easeInCirc\").promise().done(next);\n});\n</code></pre>\n\n<p>Though it might as well just be nested callbacks.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T18:15:22.500", "Id": "13509", "ParentId": "13507", "Score": "2" } }, { "body": "<p>I created this function a <a href=\"https://stackoverflow.com/questions/1218152/how-can-i-animate-multiple-elements-sequentially-using-jquery/11354378#11354378\">little while ago</a>:</p>\n\n<pre><code>function queue(start) {\n var rest = [].splice.call(arguments, 1),\n promise = $.Deferred();\n\n if (start) {\n $.when(start()).then(function () {\n queue.apply(window, rest);\n });\n } else {\n promise.resolve();\n }\n return promise;\n}\n</code></pre>\n\n<p>I think you could do exactly what you are doing like this:</p>\n\n<pre><code>queue(function () {\n return jQuery(\".balance_left_box\").delay(2000).slideDown(200,\"easeInCirc\");\n}, function () {\n return jQuery(\".balance_left_box p.first-line\").delay(2000).slideDown(600,\"easeInCirc\");\n}, function () {\n return jQuery(\".balance_left_box\").delay(1000).animate({\n height:\"270px\",\n top:\"64px\" \n },100,\"easeInCirc\");\n});\n</code></pre>\n\n<p>While that doesn't look so great (I think you should be naming your animations), with an added delay utility function:</p>\n\n<pre><code>function delay(msec) {\n return function () {\n var promise = $.Deferred();\n window.setTimeout(function () { promise.resolve(); }, msec);\n return promise;\n };\n}\n</code></pre>\n\n<p>you could write it like this:</p>\n\n<pre><code>(function ($) {\n function showMessageBox($message) {\n return function () {\n return $message.slideDown(200,\"easeInCirc\");\n };\n }\n\n function showMessageTitle($title) {\n return function () {\n return $title.slideDown(600,\"easeInCirc\");\n };\n }\n\n function resizeMessage($message) {\n return function () {\n return $message.animate({\n height:\"270px\",\n top:\"64px\" \n },100,\"easeInCirc\");\n };\n }\n\n //and then, it is just one more animation ...\n function showMessage($message, $title) {\n return function () {\n return queue(\n delay(2000),\n showMessageBox($message),\n delay(2000),\n showMessageTitle($title),\n delay(1000),\n resizeMessage($message)\n );\n };\n }\n\n $(function () {\n var $message = $(\".balance_left_box\"),\n $title = $message.find(\"p.first-line\"),\n animation = showMessage($message, $title);\n animation(); \n //you could have saved some code by not returning a function \n //but I think it is better to follow a convention wherein \n //all animations are functions that you must call to have them execute\n //because then reusing them is easier later\n });\n}(jQuery));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T19:55:24.200", "Id": "13519", "ParentId": "13507", "Score": "2" } } ]
{ "AcceptedAnswerId": "13508", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T18:04:25.777", "Id": "13507", "Score": "6", "Tags": [ "javascript", "jquery", "animation" ], "Title": "\"Group\" animation events in jQuery" }
13507
<p>I have created a very simple script that will create two columns which are populated by an array. It works, but I am certain that the way that I have gone about it is not the best way. I have been searching for simple, sample scripts which would aide me in understanding how to best approach this, but all of them have been too specific to their application.</p> <p>This is what I have made:</p> <pre><code>$assets = array('Bag', 'Charger', 'Power Cable', 'Video Cable', 'Mouse', 'Keyboard', 'Test', 'Test 2', 'Test 3'); $assets_count = count($assets); $halfway_raw = $assets_count / 2; $halfway = round($halfway_raw, 0) - 1; echo '&lt;ul class="col-1"&gt;'; for($i = 0; $i &lt; $assets_count; $i++) { if($i == $halfway) { echo '&lt;li&gt;' . $assets[$i] . '&lt;/li&gt;'; echo '&lt;/ul&gt;'; echo '&lt;ul class="col-2"&gt;'; } else { echo '&lt;li&gt;' . $assets[$i] . '&lt;/li&gt;'; } } echo '&lt;/ul&gt;'; </code></pre> <p>I'm looking for something that scales easily and is obviously as small as possible, which I don't think my script is.</p>
[]
[ { "body": "<p>Well, this is more concise, and it should be easy enough to scale:</p>\n\n<pre><code>&lt;?php\n$assets = array('Bag', 'Charger', 'Power Cable', 'Video Cable', 'Mouse', 'Keyboard', 'Test', 'Test 2', 'Test 3');\n\n$half = ceil(count($assets)/2);\n\n$columns = array(\n array_slice($assets, 0, $half), // first half\n array_slice($assets, $half) // second half\n);\n\nforeach( $columns as $index =&gt; $column ) {\n $index += 1;\n echo \"&lt;ul class=\\\"col-$index\\\"&gt;&lt;li&gt;\" . implode(\"&lt;/li&gt;&lt;li&gt;\", $column) . \"&lt;/li&gt;&lt;/ul&gt;\";\n}\n?&gt;\n</code></pre>\n\n<p>Basically, it's using more built-in PHP functions and constructs (<code>array_slice</code>, <code>implode</code>, <code>foreach</code>) but is functionally identical to the original.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T20:00:10.253", "Id": "21883", "Score": "0", "body": "Thanks for this. I suppose I just need to make myself more familiar with a lot of the built in functions." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T19:23:13.793", "Id": "13516", "ParentId": "13510", "Score": "2" } }, { "body": "<p>Just a quick note: there is a duplicated line inside the for loop. The following is the same:</p>\n\n<pre><code>for($i = 0; $i &lt; $assets_count; $i++) {\n echo '&lt;li&gt;' . $assets[$i] . '&lt;/li&gt;';\n if ($i == $halfway) {\n echo '&lt;/ul&gt;';\n echo '&lt;ul class=\"col-2\"&gt;';\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T19:51:22.900", "Id": "13518", "ParentId": "13510", "Score": "1" } } ]
{ "AcceptedAnswerId": "13516", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T18:50:44.020", "Id": "13510", "Score": "2", "Tags": [ "php", "algorithm", "html" ], "Title": "Dynamic two-column list, \"Vertical Wrap\"" }
13510
<p>I've been advised that when checking the password hash for a user I should use a string comparison function that always takes the same amount of time, to avoid timing attacks.</p> <p><strong>So I wrote this:</strong></p> <pre><code>//this is a constant time string compare, //it does not exit early even if the strings don't match //it is case sensitve //the time to compare is the time needed for the shorter string //(if they are not the same length) function time_strcmp($str1, $str2) { $res = $str1 ^ $str2; $ret = strlen($str1) ^ strlen($str2); //not the same length, then fail ($ret != 0) for($i = strlen($res) - 1; $i &gt;= 0; $i--) $ret += ord($res[$i]); return !$ret; } </code></pre> <p>(I do it this way instead of checking equality in a loop just in case of optimization. Not sure if PHP does any, but it might in the future.)</p> <p>Anyway, since this is such a critical part of the code, returning true when it shouldn't would completely defeat security.</p> <p>Can anyone give me a code review? Or a better way?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T21:38:16.740", "Id": "21888", "Score": "0", "body": "How long is the hash? strcmp or === is going to have an extremely small difference between a matching string and an early bail. Have you timed to be sure that the string comparison could actually make a significant difference. (Unless of course you're comparing things many many times.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T01:34:22.863", "Id": "21907", "Score": "0", "body": "@Corbin The hash is 28 characters (160bits). I also thought the timing could not make a difference, especially over a net connection. But everything I read disagrees, so I decided it's better to be safe." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T16:19:14.273", "Id": "32537", "Score": "0", "body": "I need to note that, with PHP, the major timing attack would be to provide a list of valid usernames by the time taken to process the info; therefore, even if your comparison function is right, you shouldn't do this: `if (time_strcmp($_POST['username'],$retrievedUserName)) login ();`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-04-06T23:14:16.250", "Id": "233103", "Score": "1", "body": "@Corbin [This article](https://codahale.com/a-lesson-in-timing-attacks/) provides a reasonable explanation of timing attacks, but [this paper](http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf) (pdf) more directly handles the \"it's an extremely small difference\" argument." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-04-07T04:44:06.553", "Id": "233132", "Score": "0", "body": "@XiongChiamiov Wow, I'm embarrassed that I wrote that comment. I'm still very far from an expert on things of this nature now, but apparently I had absolutely 0 clue what I was talking about then o_o. I'm you glad you posted to address this. That comment was harmfully ignorant. Makes me afraid of what else I might have posted. I suppose a periodic \"keep your mouth shut about things you don't understand\" reminder is always good :). Thanks!" } ]
[ { "body": "<p><strong>Disclaimer</strong></p>\n\n<p>I have no formal education in security or cryptography, nor any kind of meaningful experience with either.</p>\n\n<p>This post is basically me rambling, hopefully correctly :-).</p>\n\n<p><strong>Correctness</strong></p>\n\n<p>This is a very informal (and rough) analysis, but hopefully it will assure you that your function is indeed correct.</p>\n\n<hr>\n\n<pre><code>function time_strcmp($str1, $str2)\n{\n $res = $str1 ^ $str2;\n $ret = strlen($str1) ^ strlen($str2); //not the same length, then fail ($ret != 0)\n for($i = strlen($res) - 1; $i &gt;= 0; $i--) $ret += ord($res[$i]);\n return !$ret;\n}\n</code></pre>\n\n<p>Assume that $str1 and $str2 are arrays of bytes, each n1 and n2 bytes long, respectively.</p>\n\n<p>In PHP, the ^ operator is defined for strings such that:</p>\n\n<pre><code>$s1 ^ $s2 == chr(ord($s1[0]) ^ ord($s2[0])) . chr(ord($s1[1]) ^ ord($s2[1])) . ... chr(ord($s1[L]) ^ $s2[L])\nwith L = min(strlen($s1), strlen($s2))\n</code></pre>\n\n<p>You've used this to your advantage in that any matching characters bytes mask to 0, and any non-matching bytes will mask to a value that is greater than 0.</p>\n\n<p>So $res will be filled with 0s only if <code>$s1 === $s2</code> with:</p>\n\n<pre><code>$l = min(strlen($str1), strlen($str2));\n$s1 = substr($str1, 0, $l);\n$s2 = substr($str2, 0, $l);\n</code></pre>\n\n<p><code>(1)</code> So basically $res will be 0-filled only if the strings exactly match or if one of strings in its entirety is a prefix of the other.</p>\n\n<hr>\n\n<pre><code>$ret = strlen($str1) ^ strlen($str2);\n</code></pre>\n\n<p><code>(2)</code> $ret will be 0 only if $str1 and $str2 are of the same length.</p>\n\n<p>(For later, let this be denoted <code>$ret0</code>)</p>\n\n<hr>\n\n<pre><code>for($i = strlen($res) - 1; $i &gt;= 0; $i--) {\n $ret += ord($res[$i]);\n}\n</code></pre>\n\n<p><code>(3)</code> $ret will now be equal to the sum of the value of all of the bytes of $res.</p>\n\n<p>Let the amount added to $ret in this loop be denoted <code>$ret1</code>.</p>\n\n<p><code>(4)</code> From (1), we can conclude that $ret1 will be 0 only if the strings exactly match or one of the strings is a prefix of the other.</p>\n\n<hr>\n\n<p>Recall:</p>\n\n<pre><code>$ret = $ret0 + $ret1;\n</code></pre>\n\n<p>From (2) and (4) we can conclude that $ret will be 0 only if strings are of the same length and no bytes differ in them. This means that $ret will be 0 iff <code>$str1 === $str2</code>.</p>\n\n<p>So yes, your function is functionally correct.</p>\n\n<hr>\n\n<p><strong>Timing</strong></p>\n\n<p>I can't comment much on this. You will of course want to make sure that the length of the shortest string is always the same, otherwise there will be a difference in timing.</p>\n\n<p>Also, I believe strlen() is O(1) in PHP, but you may want to verify that.</p>\n\n<hr>\n\n<p><strong>Minor suggestion #1</strong></p>\n\n<p>There's a very unlikely problem with adding the values of the bytes. If there exist a sufficient number of unequal bytes, their values may exceed the maximum of an integer. Bitwise operators are undefined (I believe) for floating types in PHP. What you could do instead of adding is use bitwise OR.</p>\n\n<p>(I realized the overflow when seeing it, but the bitwise OR, I lifted from: <a href=\"http://code.google.com/p/oauth/issues/attachmentText?id=178&amp;aid=4891045672803142608&amp;name=timing_leak_fix.patch&amp;token=1JKGoSby92-A-d8ZcPOl4vhimoo:1341958471445\">here</a>)</p>\n\n<hr>\n\n<p><strong>Ponderings</strong></p>\n\n<p>Typically hashing algorithms output hashes of the same length for all inputs. This means that a difference in values is likely your concern.</p>\n\n<p>For example, with a short circuited comparison:</p>\n\n<pre><code>'abcd' === 'abce' \n'abcd' === 'bbcd'\n</code></pre>\n\n<p>The first one will take more time to execute than the second since the second will bail out on the first letter.</p>\n\n<p>Consider now what this timing attack would allow you to determine. It would allow you to determine part of the hash, not the password (though if you could actually determine the hash in full, you would have already found a collision and thus have gotten into the system).</p>\n\n<p>This seems fairly harmless to me just because of the cascading changes in hashing algorithms.</p>\n\n<p>Just because I know that A is more of the hash than B is does not mean that I'm any closer to finding the hash unless I know how to change A in a manner such that the first N bytes of hash(A) do not change. Being able to figure that out would be a major security problem for any cryptographic hash.</p>\n\n<p>I feel like there's something I'm missing here, so if I've completely missed the point in this section, please tell me.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T01:31:15.113", "Id": "21906", "Score": "1", "body": "Thank you! Comments in order: I think `L = max(strlen($s1), strlen($s2))` should be min, not max. The hash is always the same length, and the attacker controls the min length (and knows the normal length), so I'm not leaking information if it's quicker for a short string. I really like the OR idea and I will change it. (Although even without it maxint32 / 265 = 8MB which is more than enough for me.) Re the ponderings: The user sends me a hash (from a cookie I set earlier), not a password. i.e. the hash is the password, so via a timing attack they could guess the letters one at a time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T01:35:17.320", "Id": "21908", "Score": "1", "body": "@Ariel It was indeed supposed to be `min`. If the hash is a fixed length, I would kick out non-correct lengths immediately. The timing of that request would of course be way shorter than normal, but the attacker wouldn't gain any knowledge out of that other than what a correct hash length is (which they already know)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T01:43:39.717", "Id": "21909", "Score": "1", "body": "@Ariel Are you sending the actual hashed password in the cookie? Hashed passwords are obviously safer to send around than plain text passwords, but they're still not safe. In fact, if anyone intercepted that cookie, they could permanently log in as the user. What you should do instead of using the actual password hash is create a list of temporary keys that are valid for authentication. For example, create a table of (user_id INT, auth_key char(128), valid_until TIMESTAMP). That way if one of those is leaked, the damage is relatively minimized." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T02:08:46.267", "Id": "21914", "Score": "1", "body": "it's not the password hash, I wouldn't do that. It's short term authentication hash (like a random session key). The hash is made up of: the users hashed password, so if they change their password, (even back to what it was) the hash is invalided, their username, user_id, which is then used with a secret key in an hmac. For time limited hashes I also include a timestamp when calculating the hash, and an extra cookie with what the timestamp should be so I can verify." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T02:09:01.743", "Id": "21915", "Score": "1", "body": "This way even if you had access to the database it still would not be enough to let you login - you also need access to the secret key. (And I'm working on making that key available only by executing code, not just by reading the source code. So you need not just read access, but also write access to get it.)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T22:31:14.467", "Id": "13525", "ParentId": "13512", "Score": "5" } }, { "body": "<p>Starting from the top:</p>\n\n<pre><code>function time_strcmp($str1, $str2)\n</code></pre>\n\n<p>It's important to distinguish between the known and given string; the length of a given string is public, but the length of the known string must be secret. Therefore both arguments should have a name that conveys this difference.</p>\n\n<pre><code>$res = $str1 ^ $str2;\n</code></pre>\n\n<p>Doing this will clip <code>$res</code> to the shortest of both strings and so the number of loop cycles is not solely dependent on the given string length.</p>\n\n<pre><code>$ret = strlen($str1) ^ strlen($str2); //not the same length, then fail ($ret != 0)\n</code></pre>\n\n<p>This is a good approach, because bit representations are always different when the numbers they represent are different (assuming all bits are used in the operation).</p>\n\n<pre><code>for($i = strlen($res) - 1; $i &gt;= 0; $i--) $ret += ord($res[$i]);\n</code></pre>\n\n<p>This may lead to an integer overflow, e.g. a 4MB+ string comprising <code>255</code> characters on a 32-bit system.</p>\n\n<p><strong>Proposal</strong></p>\n\n<p>Consider the following function:</p>\n\n<pre><code>function time_strcmp($known_str, $given_str)\n{\n if (strlen($known_str) == 0) {\n throw new InvalidArgumentException(\"This function cannot safely compare against an empty given string\");\n }\n\n $res = strlen($given_str) ^ strlen($known_str);\n $given_len = strlen($given);\n $known_len = strlen($known);\n\n for ($i = 0; $i &lt; $given_len; ++$i) {\n $res |= ord($known_str[$i % $known_len]) ^ ord($given_str[$i]);\n }\n\n return $res === 0;\n}\n</code></pre>\n\n<p>The caveat is that the known string must not be empty, which is quite unlikely :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T09:09:59.210", "Id": "39645", "ParentId": "13512", "Score": "3" } }, { "body": "<p>It's a lovely little implementation: short and sweet. However, I see a core weakness. </p>\n\n<p>There is a strong argument that constant time string comparisons need to be <strong>constant for the length of the given string — not the known string</strong>. That's because the given string is under an attackers control.</p>\n\n<h3>Argument names</h3>\n\n<p>It's important to differentiate which string you have control over, and which string an attacker has control over. I'd like to echo Jack's naming suggestion:</p>\n\n<pre><code>function time_strcmp($known_str, $given_str)\n</code></pre>\n\n<h3>Protecting the length of known</h3>\n\n<p>Because your implementation picks the shortest length to compare it opens up the possibility of leaking the length of the known string. The attacker picks an arbitrarily long length for the given string, and simply reduces the length till timing normalizes: known length leaked. I'll defer to @Jack's rewrite as an example to solve this issue.</p>\n\n<p>Now, depending on a given situation length leaks may not matter much (if for instance the attacker can glean what the given string's length should be — like of a session cookie of uniform size or some other fixed length public token) but it's a weakness in the current design.</p>\n\n<p>The best implementation I've found — I am not the author <a href=\"http://blog.ircmaxell.com/2012/12/seven-ways-to-screw-up-bcrypt.html\" rel=\"nofollow\">only linking and copy/pasting for the sake of richness in comparison</a> — makes the security details more explicit:</p>\n\n<pre><code>function timingSafeEquals($safe, $user) {\n // Prevent issues if string length is 0\n $safe .= chr(0);\n $user .= chr(0);\n\n $safeLen = strlen($safe);\n $userLen = strlen($user);\n\n // Set the result to the difference between the lengths\n $result = $safeLen - $userLen;\n\n // Note that we ALWAYS iterate over the user-supplied length\n // This is to prevent leaking length information\n for ($i = 0; $i &lt; $userLen; $i++) {\n // Using % here is a trick to prevent notices\n // It's safe, since if the lengths are different\n // $result is already non-0\n $result |= (ord($safe[$i % $safeLen]) ^ ord($user[$i]));\n }\n\n // They are only identical strings if $result is exactly 0...\n return $result === 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-30T07:08:57.710", "Id": "124688", "Score": "0", "body": "Yes, my code does assume that the attacker knows the correct string length. In my application it's always the same length. Note that this code will be MUCH slower because of all the mod divisions, so it should not be used unless needed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-30T07:20:19.577", "Id": "124690", "Score": "0", "body": "A problem: The idiv instruction (for the mod %) takes a variable amount of time on a CPU. So this is not actually a constant time comparison. I would solve this differently: I would string append as many spaces as the length of the $user string to the $safe string. That avoids the constant modulus command - if they are not the same length it will anyway fail. I would add that to my code rather than this because the PHP string xor is faster than doing it individually in the loop like here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-30T08:13:55.273", "Id": "124692", "Score": "0", "body": "Interesting. Is the time variability of modulus deterministic based on the expression? At any rate sounds like you've got a good handle on things! My suggestion is problem more pedantry than practical in your case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-30T08:45:17.020", "Id": "124700", "Score": "0", "body": "Yes, deterministic. Some divisors are easier than others, specifically those that divide evenly. Which is a problem because it's is precisely those that are sensitive to the string length." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-30T02:42:08.583", "Id": "68333", "ParentId": "13512", "Score": "1" } } ]
{ "AcceptedAnswerId": "13525", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T19:13:13.150", "Id": "13512", "Score": "14", "Tags": [ "php", "strings", "security" ], "Title": "Constant time string comparision in PHP to prevent timing attacks" }
13512
<p>I have an object array that contains various types of objects (primitives, strings, other object arrays) at arbitrary levels of nesting. I need to pull all objects of type <code>System.Web.UI.Pair</code> from this array and am having a heck of a time writing the method. This is especially difficult because the Pair class itself can contain other Pairs or enumerable of Pairs. </p> <p>A picture is worth a thousand words:</p> <p><a href="https://i.stack.imgur.com/hcItE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hcItE.png" alt="enter image description here"></a></p> <p><em>(Original URL: <a href="http://postimage.org/image/i7fuad3b9/)_" rel="nofollow noreferrer">http://postimage.org/image/i7fuad3b9/)</em></a></p> <p>Here's the method I came up with, but it feels inelegant and incomplete. Any improvements, especially ones that can leverage LINQ are welcome.</p> <pre><code> public static IEnumerable&lt;Pair&gt; Flatten(this object root, List&lt;Pair&gt; list) { if (root == null) { return list; } if (root is Pair) { var pair = root as Pair; list.Add(pair); if (pair.First is IEnumerable) { Flatten((root as Pair).First, list); } else if (pair.First is Pair) { list.Add(pair.First as Pair); } if (pair.Second is IEnumerable) { Flatten((root as Pair).Second, list); } else if (pair.Second is Pair) { list.Add(pair.Second as Pair); } } if (root.GetType().IsArray || root is IEnumerable) { foreach (object o in (IEnumerable) root) { Flatten(o, list); } } return list; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T20:35:15.613", "Id": "21881", "Score": "2", "body": "Why are you using this old, forgotten class with a tool like LINQ? You could replace it for example with a [`Tuple<T1, T2>`](http://msdn.microsoft.com/en-us/library/dd268536.aspx)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T20:47:46.840", "Id": "21882", "Score": "0", "body": "One of our 3rd party assemblies is using the Pair class." } ]
[ { "body": "<ol>\n<li><p>You don't need to return anything. The list you initially pass in is a reference, which you can use after the function returns. The function can be of type <code>void</code>.</p></li>\n<li><p>You can recurse on <code>First</code> and <code>Second</code>.</p></li>\n<li><p><code>root.GetType().IsArray</code> isn't needed</p></li>\n</ol>\n\n<p>new code:</p>\n\n<pre><code>public static void Flatten(this object root, List&lt;Pair&gt; list)\n{\n if (root == null)\n {\n return;\n }\n if (root is Pair)\n {\n var pair = root as Pair;\n list.Add(pair);\n Flatten(pair.First, list);\n Flatten(pair.Second, list);\n return;\n }\n if (root is IEnumerable)\n {\n foreach (object o in (IEnumerable) root)\n {\n Flatten(o, list);\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T20:43:19.403", "Id": "13514", "ParentId": "13513", "Score": "1" } }, { "body": "<p>You might consider making this an extension method on <code>Pair</code> instead of <code>object</code>. You could simplify it to this:</p>\n\n<pre><code>public static IEnumerable&lt;Pair&gt; Flatten(this Pair p, List&lt;Pair&gt; toBuild = null)\n{\n if (toBuild == null)\n toBuild = new List&lt;Pair&gt;();\n\n if (p.First is Pair)\n {\n (p.First as Pair).Flatten(toBuild);\n }\n else if (p.First is IEnumerable)\n {\n foreach (object o in (p.First as IEnumerable).OfType&lt;object&gt;().Where(ob =&gt; ob is Pair))\n {\n (o as Pair).Flatten(toBuild);\n }\n }\n\n //repeat for p.Second\n\n toBuild.Add(p);\n return toBuild;\n}\n</code></pre>\n\n<p>You can use it like this:</p>\n\n<pre><code>var result = myPair.Flatten();\n</code></pre>\n\n<p>Or on an <code>IEnumerable&lt;Pair&gt;</code>:</p>\n\n<pre><code>var result = myList.SelectMany(p =&gt; p.Flatten());\n</code></pre>\n\n<p>Or on a regular <code>IEnumerable</code>:</p>\n\n<pre><code>var result = myList.OfType&lt;object&gt;().Where(o =&gt; o is Pair)\n .SelectMany(p =&gt; (p as Pair).Flatten());\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T20:53:13.910", "Id": "13515", "ParentId": "13513", "Score": "2" } }, { "body": "<h2>Review</h2>\n\n<blockquote>\n <p>Here's the method I came up with, but it feels inelegant and\n incomplete. Any improvements, especially ones that can leverage LINQ\n are welcome.</p>\n</blockquote>\n\n<p>You could write it more elegantly by using recursion for your pair members.</p>\n\n<blockquote>\n<pre><code> if (pair.First is IEnumerable)\n {\n Flatten((root as Pair).First, list);\n }\n else if (pair.First is Pair)\n {\n list.Add(pair.First as Pair);\n }\n if (pair.Second is IEnumerable)\n {\n Flatten((root as Pair).Second, list);\n }\n else if (pair.Second is Pair)\n {\n list.Add(pair.Second as Pair);\n }\n</code></pre>\n</blockquote>\n\n<pre><code>if (root is Pair)\n{ \n var pair = root as Pair;\n list.Add(pair); \n Flatten(pair.First, list);\n Flatten(pair.Second, list);\n}\n</code></pre>\n\n<p>You are right that it is incomplete. You are missing:</p>\n\n<ul>\n<li>pairs in dictionaries <code>KeyValuePair&lt;T, Pair&gt;</code></li>\n<li>pairs in complex objects <code>Tuple&lt;T, Pair&gt;</code>, <code>MyPairWrapper</code></li>\n<li>pairs in anonymous objects</li>\n</ul>\n\n<p><em>code</em></p>\n\n<pre><code>public class MyPairWrapper {\n public Pair Value { get; }\n // ..\n}\n</code></pre>\n\n<p>Your search strategy expects a tree structure, not a graph. In the following example you will get an infinite cycle.</p>\n\n<pre><code>var pair = new Pair();\npair.First = pair;\n</code></pre>\n\n<hr>\n\n<h2>Proposed Solution</h2>\n\n<p>I suggest to make a graph traversal walker that is able to deal with:</p>\n\n<ul>\n<li>cyclic graphs as well as trees</li>\n<li>any reference type you want to flatten</li>\n<li>any kind of sequence (<code>Array</code>, <code>IEnumerable</code>, <code>IQueryable</code>, <code>IDictionary</code>, ..)</li>\n<li>anonymous types</li>\n<li>common structs and classes (<code>Tuple&lt;T1,T2,..&gt;</code>, <code>KeyValuePair&lt;TKey,TValue&gt;</code>, ..)</li>\n<li>complex types (traverse public fields and readable properties)</li>\n</ul>\n\n<p><em>Let's start..</em></p>\n\n<p>I adapted the method signature of the extension method and redirected the implementation to <code>ObjectGraphWalker</code>.</p>\n\n<pre><code>public static class LinqExtension\n{\n public static IEnumerable&lt;T&gt; Flatten&lt;T&gt;(this object root) where T : class {\n return ObjectGraphWalker.Flatten&lt;T&gt;(root);\n }\n}\n</code></pre>\n\n<p>The graph walker <code>ObjectGraphWalker</code> traverses any graph (tree, acyclic or cyclic) and keeps track of <code>visited</code> objects to avoid infinite loops. Recursion is used to traverse sequences and complex objects.</p>\n\n<pre><code>public static class ObjectGraphWalker\n{\n public static IEnumerable&lt;T&gt; Flatten&lt;T&gt;(object root) where T : class {\n var results = new List&lt;T&gt;();\n var visited = new ArrayList();\n FlattenWalk(root, results, visited);\n return results.ToArray();\n }\n\n private static void FlattenWalk&lt;T&gt;(object source, IList&lt;T&gt; results, IList visited) \n where T : class \n {\n if (source == null) return;\n if (visited.Contains(source)) return;\n visited.Add(source);\n\n // source is instance of T or any derived class\n if (typeof(T).IsInstanceOfType(source)) {\n results.Add((T)source);\n }\n\n // source is a sequence of objects\n if (source is IEnumerable) {\n // includes Array, IDictionary, IList, IQueryable\n FlattenWalkSequence((IEnumerable)source, results, visited);\n }\n\n // dive into the object's properties\n FlattenWalkComplexObject(source, results, visited);\n }\n\n private static void FlattenWalkSequence&lt;T&gt;(IEnumerable source, \n IList&lt;T&gt; results, IList visited) \n where T : class \n {\n if (source == null) return;\n foreach (var element in source) {\n FlattenWalk(element, results, visited);\n }\n }\n\n private static void FlattenWalkComplexObject&lt;T&gt;(object source, \n IList&lt;T&gt; results, IList visited) \n where T : class \n {\n if (source == null) return;\n var type = source.GetType();\n var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)\n .Where(x =&gt; x.CanRead &amp;&amp; !x.GetIndexParameters().Any());\n var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);\n // search its public fields and properties\n foreach (var field in fields) {\n FlattenWalk(field.GetValue(source), results, visited);\n }\n foreach (var property in properties) {\n FlattenWalk(property.GetValue(source), results, visited);\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<h2>Test Case</h2>\n\n<p>Let's create a derived class <code>Triad</code> and a complex object <code>PairProvider</code> that has a <code>Pair</code> as property.</p>\n\n<pre><code>public class PairProvider\n{\n public Pair Value;\n}\n\npublic class Triad : Pair\n{\n public object Third;\n}\n\npublic class Pair\n{\n public object First;\n public object Second;\n}\n</code></pre>\n\n<p>Test method:</p>\n\n<pre><code>public static void Main() {\n\n var pair1 = new Pair { First = 1, Second = 2 }; // 1\n var pair2 = new Pair { First = 3, Second = pair1 }; // 2\n var triad = new Triad { First = \"John\", Second = \"Doe\" }; // 3\n triad.Third = triad;\n\n var dynamicObject = new {\n pair = new Pair { // 4\n First = pair1,\n Second = new[] { pair1, pair2 }\n },\n adapter = new PairProvider { Value = triad },\n items = new Dictionary&lt;int, IEnumerable&gt; {\n { 1, new object[] { 1, 2, new Pair { First = 1, Second = triad } } }, // 5\n { 2, new int[] { 1, 2, 3 } },\n { 3, new object[] { Tuple.Create&lt;Pair, Pair&gt;(pair2, new Pair()) } } // 6\n }\n };\n\n var flattened = dynamicObject.Flatten&lt;Pair&gt;();\n var count = flattened.Count(); // = 6\n\n Console.ReadKey();\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-26T08:47:00.077", "Id": "221044", "ParentId": "13513", "Score": "2" } } ]
{ "AcceptedAnswerId": "13515", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-07-06T20:26:20.720", "Id": "13513", "Score": "3", "Tags": [ "c#", "linq", "recursion" ], "Title": "Recursively find all objects of type System.Web.UI.Pair in an object array" }
13513
<p>I'm doing a sort of exercise where I'm given a question, and I have to answer it by writing an SQL query using a database that I was given.</p> <p>This is the question:</p> <blockquote> <p>What is the cheapest fare for a one way flight from Boston to Baltimore?</p> </blockquote> <p>Here's what I came up with:</p> <pre><code>SELECT DISTINCT fare.one_direction_cost, fare.fare_id, flight.flight_id, flight.departure_time, flight.arrival_time, flight.airline_flight, flight.airline_code FROM flight, fare WHERE flight.flight_id IN ( SELECT DISTINCT flight_id FROM flight WHERE from_airport IN ( SELECT airport_code FROM airport_service WHERE city_code = 'BBOS' ) AND to_airport IN ( SELECT airport_code FROM airport_service WHERE city_code = 'BBWI' ) ) AND fare.round_trip_required = 'NO' AND fare.from_airport IN ( SELECT airport_code FROM airport_service WHERE city_code = 'BBOS' ) AND fare.to_airport IN ( SELECT airport_code FROM airport_service WHERE city_code = 'BBWI' ) AND fare.one_direction_cost = ( SELECT MIN(fare.one_direction_cost) FROM flight, fare WHERE flight.flight_id IN ( SELECT DISTINCT flight_id FROM flight WHERE from_airport IN ( SELECT airport_code FROM airport_service WHERE city_code = 'BBOS' ) AND to_airport IN ( SELECT airport_code FROM airport_service WHERE city_code = 'BBWI' ) ) AND fare.round_trip_required = 'NO' AND fare.from_airport IN ( SELECT airport_code FROM airport_service WHERE city_code = 'BBOS' ) AND fare.to_airport IN ( SELECT airport_code FROM airport_service WHERE city_code = 'BBWI' ) ) ; </code></pre> <p>I'm a beginner at SQL (this is my second day working with the language), but what I came up with feels really verbose and unnecessarily bulky to me, and I've had to copy-and-paste several times, which I dislike. Does anybody have any tips in general for shortening it or making it look neater in general?</p> <p>I'm working with sqlite3, and here are the relevant tables that I'm working with:</p> <pre><code>CREATE TABLE airport_service ( city_code character(4) NOT NULL, airport_code character(3) NOT NULL, miles_distant numeric(4,1), direction character(3), minutes_distant numeric(3), PRIMARY KEY (city_code, airport_code) ); CREATE TABLE fare ( fare_id character(8) NOT NULL, from_airport character(3) NOT NULL, to_airport character(3) NOT NULL, fare_basis_code character(3) NOT NULL, fare_airline character(2), restriction_code character(5), one_direction_cost numeric(7,2), round_trip_cost numeric(8,2), round_trip_required character(3), PRIMARY KEY (fare_id) ); CREATE TABLE flight ( flight_id character(8) NOT NULL, flight_days character(12), from_airport character(3), to_airport character(3), departure_time numeric(4), arrival_time numeric(4), airline_flight character(20), airline_code character(2), flight_number numeric(4), aircraft_code_sequence character(11), meal_code character(4), stops numeric(1), connections numeric(1), dual_carrier character(3), time_elapsed numeric(4), PRIMARY KEY (flight_id) ); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T21:39:02.043", "Id": "21889", "Score": "1", "body": "I assume you've never heard of a join?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T21:39:45.163", "Id": "21890", "Score": "4", "body": "A small tip: If you have to use `DISTINCT` you are probably doing it wrong. Not always, but in most cases." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T21:50:34.963", "Id": "21891", "Score": "0", "body": "@ChaosPandion -- not really, no. I'm googling it right now, but I'm not sure if I'm really getting how to use it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T21:51:37.433", "Id": "21892", "Score": "0", "body": "The question seems to only ask for a fare; why are you involving flights at all? And what is the value for `round_trip_required` that would mean `false`? Also, I don't see a way to connect a flight to a fare besides the `from_airport` and `to_airport`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T21:58:45.560", "Id": "21893", "Score": "0", "body": "@Mr. Jefferson: Good point -- the answer returned related data about flights, so I thought I'd do the same. I also don't see an easy way to connect a flight to a fare (although I'll check again)." } ]
[ { "body": "<p>If the question is only asking for fares, you select the first result row of the fares allowing one-way tickets where the from airport is in Boston and the to airport is in Baltimore, sorted ascending by one way cost.</p>\n\n<p>Since this is tagged homework, I'll let you translate that to SQL. :-)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T22:05:57.723", "Id": "13524", "ParentId": "13520", "Score": "3" } }, { "body": "<p>Can you please let me know how the 2 tables - <code>flight</code> and <code>fare</code> are connected?</p>\n\n<p>Every <code>flight</code> has its <code>fare</code> which it charges while flying from one city to another. So, actually the primary key of <code>fare</code> table i.e. <code>fare_id</code> should act as a foreign key in <code>flight</code> table. If it is, let me know. Then I can provide you the right query.</p>\n\n<p>If that is not required then you can use the <code>MIN()</code> function to get the query as below:</p>\n\n<pre><code>SELECT MIN(one_direction_cost) \n FROM fare \n WHERE from_airport='Boston' \n AND to_airport='Baltimore';\n</code></pre>\n\n<p>Here, you need to provide the codes for Boston and Baltimore. I have put them as it is as I don't have their codes.</p>\n\n<p>Let me know if it works.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T04:52:32.117", "Id": "13528", "ParentId": "13520", "Score": "0" } } ]
{ "AcceptedAnswerId": "13524", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T21:21:39.047", "Id": "13520", "Score": "3", "Tags": [ "beginner", "sql", "homework", "sqlite" ], "Title": "Finding the cheapest one-way air flight fare" }
13520
<p>Below are two implementations of the problem "find the characters in common between two strings" - in Clojure without using collections / set operations.</p> <p>Are these approaches sufficiently idiomatic and could the be more concise? (aside from using collections functions).</p> <p>Also, is there a Clojure library that wraps or provides an alternative to <code>java.util.BitSet</code>?</p> <pre class="lang-lisp prettyprint-override"><code>;; Approach #1 BitSets ;; - use a bitsets for each string, ;; - flip the bit for each character in each string ;; - then "and" the two bitsets. Theoretically O(N + M) performance (defn string-to-charbits [s] (loop [[f &amp; rest] s bits (java.util.BitSet.)] (if f (recur rest (do (.set bits (int f)) bits)) bits))) (defn process-bitset [bitset] (loop [bitset bitset count 0 result '[]] (if (&lt; count (.length bitset)) (recur bitset (inc count) (if (.get bitset count) (conj result (char count)) result)) result))) (defn find-matching-chars [s1 s2] (let [b1 (string-to-charbits s1) b2 (string-to-charbits s2)] (do (.and b1 b2) (process-bitset b1)))) ;; Approach #2 - Brute Force ;; For each character in string 1, linear search (via .indexOf) of string 2 ;; Theoretically O(N * M) performance (defn find-matching-chars-brute [s1 s2] (loop [[f &amp; rest] s1 s2 s2 result []] (if f (if (&gt; (.indexOf s2 (int f)) -1) (recur rest s2 (conj result f)) (recur rest s2 result)) (distinct result)))) ;; Might need to sort the results of each function call to make this pass (assert (= (find-matching-chars "abcd" "cde") (find-matching-chars-brute "abcd" "cde")) "expected [\\c \\d]") </code></pre>
[]
[ { "body": "<p>I would create two arrays size ALPHABET (one for each string) and just set the corresponding array element to 1 if a char exists in string (like char_array[c - 'A'] = 1). Then scan two arrays parallel and check if the same element is set for both strings.</p>\n\n<p>Pseudocode in python: </p>\n\n<pre><code>def find_matching_chars(s1, s2):\n ALPHABET = 'abcdefghijklmnopqrstuvwxyz'\n ALPHABET_LEN = len(ALPHABET)\n char_array1 = [0]*ALPHABET_LEN\n char_array2 = [0]*ALPHABET_LEN\n for c in s1:\n char_array1[ord(c)-ord('a')] = 1\n for c in s2:\n char_array2[ord(c)-ord('a')] = 1\n result = [] \n for index in xrange(len(char_array1)):\n if char_array1[index] != 0 and char_array2[index] != 0:\n result.append(ALPHABET[index]) \n return result\n\nprint find_matching_chars(\"abcd\", \"cde\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T12:35:19.833", "Id": "21932", "Score": "0", "body": "Sorry, but downvote. I'm not looking for new techniques to solve the problem, I'm looking for feedback on my Clojure style / idiomatic usage." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T13:24:26.467", "Id": "21935", "Score": "0", "body": "It's not a 'new techniques', it's just a simple BitSet alternative :) You don't need to use BitSet for limited alphabet - it's overhead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T13:35:38.013", "Id": "21937", "Score": "0", "body": "Why are you assuming the alphabet is limited to a-z lower case. When I thought of this problem, I originally attempted to allocate an array of Character.MAX_VALUE" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T13:45:38.093", "Id": "21938", "Score": "0", "body": "It was just an example - you can use alphabet any size:)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T09:21:35.193", "Id": "13533", "ParentId": "13521", "Score": "0" } }, { "body": "<p>With your restrictions, yes, that seems fairly idiomatic. I am not aware of a good bitset implementation yet -- wrapping java.util.BitSet wouldn't work that well, since a clojure version would want to be persistent. That said, your restrictions are not idiomatic at all. Presumably, you don't want to use clojure.set/intersection (and completely trivializing the problem), but something like</p>\n\n<pre><code>(defn find-matching-chars [s1 s2]\n (distinct (filter (into #{} s1) s2)))\n</code></pre>\n\n<p>really would be far more idiomatic. I could see using something like your BitSet code if <code>find-matching-chars</code> was actually causing significant performance issues, but short of that, some form of collections manipulation really is the idiomatic way to solve this issue.</p>\n\n<p>In all honesty, my probable course in a situation like this would be to build filter and linked lists from scratch if I couldn't use the built-in versions, but at this point, I am probably straying away from idiomatic code myself.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-07T22:24:41.033", "Id": "14426", "ParentId": "13521", "Score": "2" } }, { "body": "<p>I prefer <code>doseq</code> to <code>loop</code>\nwhen iterating over either a collection or a sequence.</p>\n\n<pre><code>(defn string-to-charbits [s] \n (let [bits (java.util.BitSet.)] \n (doseq [c s] \n (.set bits (int c))) \n bits))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-03T01:03:36.957", "Id": "16131", "ParentId": "13521", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T21:36:32.390", "Id": "13521", "Score": "4", "Tags": [ "clojure" ], "Title": "Find the common characters between two strings without using set operations" }
13521