body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I have </p>
<pre><code>public static class TupleExtensions {
public static IEnumerable<T> SelectMany<T>(this IEnumerable<Tuple<T, T>> te)
{
foreach (var t in te)
{
yield return t.Item1;
yield return t.Item2;
}
}
public static IEnumerable<T> SelectMany<T, U>(this IEnumerable<U> source, Func<U, Tuple<T, T>> fn)
{
foreach (var s in source)
{
var t = fn(s);
yield return t.Item1;
yield return t.Item2;
}
}
public static IEnumerable<T> SelectMany<T, U>(this IEnumerable<U> source, Func<U, Tuple<T, T, T>> fn)
{
foreach (var s in source)
{
var t = fn(s);
yield return t.Item1;
yield return t.Item2;
yield return t.Item3;
}
}
public static IEnumerable<T> SelectMany<T, U>(this IEnumerable<U> source, Func<U, Tuple<T, T, T,T>> fn)
{
foreach (var s in source)
{
var t = fn(s);
yield return t.Item1;
yield return t.Item2;
yield return t.Item3;
yield return t.Item4;
}
}
}
</code></pre>
<p>I can then do as a trivial example</p>
<pre><code>IEnumerable<int> source = ...
source.SelectMany(i=>Tuple.Create(i, i+1, i+2))
</code></pre>
<p>Obviously the tuple must have the same types throughout. My use
case is where I have a mathematical solver which will always return
two solutions for a given input. Returning a list makes it unclear
how many solutions would be returned.</p>
<p>However in the end I would want all my solutions merged. For example</p>
<pre><code>static Tuple<Point,Point> Intersect(this Shape shape, Line other);
Shape shape = ...
IEnumerable<Line> lines = ...
IEnumerable<Point> intersections = lines.SelectMany(line=>shape.Intersect(line));
</code></pre>
<p>Is there some good reason not to treat <code>Tuple<T,T,T....></code> as a container that we can flatten?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T09:58:48.080",
"Id": "42989",
"Score": "0",
"body": "I'd rather use collections (perhaps immutable, perhaps simple arrays)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T10:00:59.283",
"Id": "42990",
"Score": "2",
"body": "No, there's no good reason not to consider tuples this way. If it seems \"wrong\" somehow, it's only because C# has such limited support for tuples. In a functional language, or one with better tuple support, this would seem very natural."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T10:06:19.437",
"Id": "42992",
"Score": "0",
"body": "@CodesInChaos the problem with collections is that the length is not considered part of the type. If my function should always return two values but I return a List<Point> should the client of that code put in a check that there are in fact two values or risk an index out of bounds exception?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T10:10:21.143",
"Id": "42993",
"Score": "0",
"body": "if you really want length to be part of the type, then create a custom type. Else simply go with `T[]` or `ReadOnlyCollection<T>`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T10:58:16.113",
"Id": "42996",
"Score": "1",
"body": "@CodesInChaos Can you explain why you think Tuple is wrong for this? In C++ I could create a type with an integer type parameter with a recursive template definition. In C# that is not possible. How would you make a generic Container<T,length> type other than with Tuple?"
}
] |
[
{
"body": "<p>In general, I think this pattern makes sense, because it clearly expresses what the method returns and lets you easily do the computation you want to do with the result.</p>\n\n<p>Some thoughts:</p>\n\n<ol>\n<li><p>I don't see any reason why your extension methods should only work on a collection of <code>Tuple</code>s and not on a single <code>Tuple</code>. Because of that, I would probably write extension methods that convert a single <code>Tuple</code> to <code>IEnumerable</code>:</p>\n\n<pre><code>public static IEnumerable<T> ToEnumerable<T>(this Tuple<T, T> tuple)\n{\n yield return tuple.Item1;\n yield return tuple.Item2;\n}\n</code></pre>\n\n<p>Since this would make the code you showed more complicated, it might make sense to also keep <code>SelectMany()</code>, but express it using <code>ToEnumerable()</code>:</p>\n\n<pre><code>public static IEnumerable<T> SelectMany<T>(\n this IEnumerable<Tuple<T, T>> tuples)\n{\n return tuples.SelectMany(t => t.ToEnumerable());\n}\n\npublic static IEnumerable<T> SelectMany<T, U>(\n this IEnumerable<U> source, Func<U, Tuple<T, T>> selector)\n{\n return source.SelectMany(x => selector(x).ToEnumerable());\n}\n</code></pre></li>\n<li><p>It might make sense to create custom types that mean “pair (triple, …) of items of the same type”. As a side benefit, you wouldn't need custom <code>ToEnumerable()</code> or <code>SelectMany()</code> extensions, since those types could implement <code>IEnumerable<T></code> directly.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T11:35:57.320",
"Id": "42998",
"Score": "0",
"body": "I like this. Shame that we can't create an implicit cast to IEnumerable<T> and all this would work automagically."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T13:32:05.660",
"Id": "42999",
"Score": "0",
"body": "Isn't all you need `ToEnumerable`? \n`IEnumerable<Point> intersections = lines.SelectMany(line=>shape.Intersect(line).ToEnumerable());`\nlooks all right to me. What does all the rest give?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T13:54:55.067",
"Id": "43000",
"Score": "0",
"body": "@abuzittingillifirca Yes, that works fine, but I think an overload of `SelectMany()` makes sense to make the code shorter, especially since the `Tuple` can be considered a sequence, so the `SelectMany()` does logically make sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-30T18:15:17.867",
"Id": "48546",
"Score": "1",
"body": "@bradgonesurfing To be consistent with existing LINQ APIs you should use the semantics `AsEnumerable` instead of `ToEnumerable` : http://msdn.microsoft.com/en-us/library/bb335435.aspx , http://msdn.microsoft.com/en-us/library/system.data.datatableextensions.asenumerable.aspx, http://stackoverflow.com/questions/9873930/why-are-asobservable-and-asenumerable-implemented-differently ,"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T11:23:59.140",
"Id": "27589",
"ParentId": "27586",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27589",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T09:10:55.433",
"Id": "27586",
"Score": "3",
"Tags": [
"c#",
"linq"
],
"Title": "I've started Tuples to LINQ and I'm not sure if it's an anti pattern"
}
|
27586
|
<p>This service object allows users without a session to create a comment, and register OR login at the same time.</p>
<p>If a user is signed out he must enter an email and a password along with the comment.</p>
<p>The service checks if a user exists using the email, then attempts to authenticate the user. Otherwise, it creates a new user.</p>
<p>Three code smells:</p>
<ol>
<li>User errors are added to the comment. There is no user object in the view, just a params hash with that name.</li>
<li>If user validation fails, comment validation does not trigger, meaning if the comment was also blank they need another round trip to find out. Probably not significant though.</li>
<li>User data is not repopulated on validation failure.</li>
</ol>
<p>Question: I'm proud of writing a nifty object like that, but it stills feels a little 'wrong-ish' if there is such a word. Is there a better way to handle this type of scenario?</p>
<pre><code>class CommentService
def self.by(params, user)
if user
new params, user
else
new params, find_or_new(params)
end
end
def self.find_or_new(params)
User.find_by(email: params[:user][:email]) || User.new
end
attr_reader :params, :comment, :user
def initialize(params, user)
@params, @user = params, user
@comment = Comment.new(comment_params)
end
def save
if user.new_record?
self.user.attributes = user_params
user.save ? persist : add_user_errors
else
if params[:user].present?
user.authenticate(params[:user][:password]) ? persist : add_auth_error
else
persist
end
end
end
def post
@post ||= Post.find(params[:post_id])
end
private
def add_user_errors
user.errors.each do |k,v|
comment.errors.add(k, v)
end
false
end
def add_auth_error
comment.errors[:base] << "Invalid email or password."
false
end
def user_params
params.require(:user).permit(:name, :email, :password)
end
def comment_params
params.require(:comment).permit(:text)
end
def persist
comment.author = user
comment.post = post
comment.save
end
end
</code></pre>
<p>Controller code:</p>
<pre><code> def create
service = CommentService.by(params, current_user)
@post = service.post
if service.save
redirect_to @post
else
@comment = service.comment
render 'new'
end
end
</code></pre>
<p>View code:</p>
<pre><code>= form_for [@post, @comment] do |f|
= f.text_area :comment
/ No user object here. Just tossing a user hash into the params.
- unless signed_in?
= fields_for :user do |uf|
= uf.text_field :email
= uf.password_field :password
= f.submit
</code></pre>
|
[] |
[
{
"body": "<p>My opinions:</p>\n\n<ol>\n<li>The class methods <code>by</code> and others are unnecessary.</li>\n<li>The service object should be initialized by feeding objects instead of params.</li>\n<li>Build a guest user is not job of CommentService.</li>\n</ol>\n\n<p>Then code like these:</p>\n\n<pre><code># Controller\ndef create\n user = current_user || build_guest_user\n @comment = user.new(params[:comment])\n service = CommentService.new(@comment, user)\n if service.save\n if user.guest?\n redirect_to 'guest_user_sign_in_or_register'\n else\n redirect :back, notice: \"Comment created\"\n end\n else\n # blah blah\n end\nend\n\n# ApplicationController\ndef build_guest_user\n # your logic here\nend\n\n# CommentService\ndef initialize(comment, user)\n @comment = comment\n @user = user\nend\n\ndef save\n if @comment.save\n # extra service logic here\n else\n false\n end\nend\n</code></pre>\n\n<h2>Add</h2>\n\n<p>Mohamad, think about this, when a visitor hit a \"Post Comment\" button, he will reach <code>create</code>. </p>\n\n<p>If he's logged in, that's fine. </p>\n\n<p>If he not logged in, he will be treated as a guest user, no matter registered or not. -- Then treated by <code>build_guest_user</code> method.</p>\n\n<p>Then, after comment saved, the controller can judge if he is a guest user or not. If not, nothing to do. If he is, an Ajax template will be rendered back asking his signing in or register.</p>\n\n<p>If he signed in, the comment under the guest will be moved to his user account. And this guest user will be deleted, guest session be replaced by user session.</p>\n\n<p>If he register, same as above.</p>\n\n<p>If he refuse to either sign in or register, the guest user and his comment will be kept there. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T14:23:52.817",
"Id": "43006",
"Score": "0",
"body": "Thanks. But how would you handle logging in for existing users? In other words, users who are already registered but not signed in."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T14:26:57.220",
"Id": "43007",
"Score": "0",
"body": "Not just that, how do we handle an existing user with a login failure?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T14:34:34.780",
"Id": "43009",
"Score": "0",
"body": "@Mohamad, check my updates."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T14:43:59.403",
"Id": "43010",
"Score": "0",
"body": "@Mohamad, I revised some. The judging guest work is better for controller in my opinion. If no other things needed for comment, service object seems not necessary for this case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T17:13:59.210",
"Id": "43019",
"Score": "0",
"body": "I tend to agree with you in principle, although this requires creating the notion of a 'guest user' with special validation and additional logic. You will also need to track the comment id in the session to reassign it if the user signs in. I does add a fair amount of complexity."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T17:20:47.237",
"Id": "43021",
"Score": "0",
"body": "@Mohamad, yes a bit more work to do :) But I think it worth the effort."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T14:21:57.590",
"Id": "27597",
"ParentId": "27592",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27597",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T13:50:39.080",
"Id": "27592",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Registering or logging in when creating a new comment object"
}
|
27592
|
<p>I have come across the following piece of code</p>
<pre><code> if (Region.Current == Region.EU)
{
return RegionalPriceLN;
}
else if (Region.Current == Region.NY)
{
return RegionalPriceNY;
}
else if (Region.Current == Region.HK)
{
return RegionalPriceHK;
}
else if (Region.Current == Region.TK)
{
return RegionalPriceTK;
}
return null;
</code></pre>
<p>And want to refactor it to use a Dictionary. Was thinking of something like below:</p>
<pre><code>return Map.TryGetValue(Region.Current, out func) ? func() : null;
</code></pre>
<p>And the dictionary being initialized like this:</p>
<pre><code> Map = new Dictionary<Region, Func<double?>>
{
{Region.EU, () => RegionalPriceLN},
{Region.NY, () => RegionalPriceNY},
{Region.HK, () => RegionalPriceHK},
{Region.TK, () => RegionalPriceTK}
};
</code></pre>
<p>Another approach, to optimize memory usage would be to hold a static dictionary instead of an instance one:</p>
<pre><code>private static readonly Dictionary<Region, Func<TickingBasket, double?>> Map = new Dictionary<Region, Func<TickingBasket,double?>>
{
{Region.EU, t_ => t_.RegionalPriceLN},
{Region.NY, t_ => t_.RegionalPriceNY},
{Region.HK, t_ => t_.RegionalPriceHK},
{Region.TK, t_ => t_.RegionalPriceTK}
};
</code></pre>
<p>This would require for us to pass "this" to the delegate:</p>
<pre><code>return Map.TryGetValue(Region.Current, out func) ? func(this) : null;
</code></pre>
<p>Can you think of a more elegant way to do this? </p>
<p>Regards.</p>
<p>UPDATE: Region is a reference type.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T09:34:42.030",
"Id": "43064",
"Score": "0",
"body": "What is the rationale for storing anonymous functions rather than the objects themselves?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T18:46:10.257",
"Id": "43091",
"Score": "0",
"body": "Your solution is concise, but it hurts my eyes to read it. Replacing the if/else if with a switch statement would simplify the code *slightly* but it would be very readable and easy to understand even for a novice programmer."
}
] |
[
{
"body": "<p>Second option is definitely a preferred way over first one. Also you may consider a <code>switch</code> statement.</p>\n\n<p><strong>UPDATE</strong>. Since Region is a class then the only good way to avoid long <code>if...else</code> is the mapping like in your second variant</p>\n\n<p>First option that you proposed (<code>Map = new Dictionary<Region, Func<double?>></code>) requires the construction of <code>Dictionary</code> each time the method is executed. It is a waste of resources and time, and for this case even the <code>if..else..if..else</code> statements don't look that ugly :).</p>\n\n<p>Second option (static <code>Dictionary</code> with fixed mappings) is a traditional way to branch the logic for your case. Moreover in certain cases <a href=\"https://stackoverflow.com/questions/3366376/are-net-switch-statements-hashed-or-indexed\">C# compiler will compile</a> the <code>switch</code> statement into static <code>Dictionary</code> to run lookups.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T14:20:05.363",
"Id": "43004",
"Score": "0",
"body": "Switch is not possible because Region is a reference type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T14:23:42.040",
"Id": "43005",
"Score": "0",
"body": "You haven't provided the code for `Region`, and it looked like enum... Now that you mentioned it I see that you actually use `Region.Current`. So the only good option is your second variant"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T14:27:20.623",
"Id": "43008",
"Score": "0",
"body": "Have just updated the question to reflect that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T08:22:06.370",
"Id": "43061",
"Score": "0",
"body": "*\"Second option is definitely a preferred way over first one.\"* Could you elaborate on this statement?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T08:34:45.753",
"Id": "43062",
"Score": "0",
"body": "@MattDavey updated my answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T08:52:22.750",
"Id": "43063",
"Score": "0",
"body": "@almaz nice one, removed my downvote and added +1 :)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T14:14:56.813",
"Id": "27595",
"ParentId": "27594",
"Score": "3"
}
},
{
"body": "<p>Is there a reason why you cant encapsulate this logic into <code>Region</code> class? Calling <code>Region.Current.GetPrice(basket)</code> (or, to go even further, <code>Region.Current.PricingStrategy.GetPrice(basket)</code>) looks so much cleaner to me. </p>\n\n<p>Or, at least, you can wrap your last line into an extension method.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T11:37:10.267",
"Id": "43072",
"Score": "0",
"body": "That would make region aware of things it shouldn't be, and a possible violation of SRP. He could get away with it *IF* the Region and the Price were ALWAYS together. In this case it does not appear to be that way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T12:25:01.400",
"Id": "43076",
"Score": "0",
"body": "@Robert Snyder, thats why i'm asking :) For me its hard to tell from the code provided, what `Region` should and should not \"know\". Your explanation makes sense tho, this is probably the case."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T09:13:49.033",
"Id": "27622",
"ParentId": "27594",
"Score": "1"
}
},
{
"body": "<p>To me. the design as far as I get it, seems a little bit smelly. I do not know engough of your code or the domain and your concrete implementations, but I would prefer other solutions to the dictionary-lookup or switch-statements.</p>\n\n<p>Perhaps you could make use of the decorator-Pattern:</p>\n\n<pre><code>class Product\n{\n // ...\n decimal price;\n decimal virtual Price\n {\n get\n {\n return price;\n }\n }\n}\n</code></pre>\n\n<p>And for the EU-Region you generate an EU-Product-Decorator like</p>\n\n<pre><code>class EUProduct:Product\n{\n Product product;\n\n //other stuff\n\n public override decimal Price\n {\n get\n {\n return Decimal.Multiply(product.Price,new decimal(1.15));\n }\n }\n\n public Region Region\n {\n get\n {\n return Region.EU;\n }\n }\n\n // more stuff to go \n\n public EUProduct(Product product)\n {\n this.product = product;\n }\n}\n</code></pre>\n\n<p>And the Class Region could be refactored to a simple Enum (as it goes along with your further domainlogic).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T15:51:52.787",
"Id": "27639",
"ParentId": "27594",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T14:06:19.547",
"Id": "27594",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Refactoring from if-else-if to Dictionary"
}
|
27594
|
<p>I am new to learning Repository Pattern. I am developing a site in MVC 4 (I'm new to it as well).</p>
<p>The way I am using Repository pattern as follows:</p>
<ol>
<li><p>I created <code>IRepository<T></code> interface as follows:</p>
<pre><code>public interface IRepository<T>
{
void Insert(T entity);
void Delete(T entity);
IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate);
IQueryable<T> GetAll();
T GetById(int id);
}
</code></pre></li>
<li><p>Then I created a base class which implements the above interface as follows:</p>
<pre><code>public class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : class
{
private readonly DbContext _dbContext;
public BaseRepository(DbContext dbContext)
{
_dbContext = dbContext;
}
public void Insert(TEntity entity)
{
_dbContext.Set<TEntity>().Add(entity);
_dbContext.SaveChanges();
}
public void Delete(TEntity entity)
{
_dbContext.Set<TEntity>().Remove(entity);
_dbContext.SaveChanges();
}
public IQueryable<TEntity> SearchFor(Expression<Func<TEntity, bool>> predicate)
{
return _dbContext.Set<TEntity>().Where(predicate);
}
public IQueryable<TEntity> GetAll()
{
return _dbContext.Set<TEntity>();
}
public TEntity GetById(int id)
{
return _dbContext.Set<TEntity>().Find(id);
}
}
</code></pre></li>
<li><p>Now for each repository I want to create, I create another interface which contains methods specific to that class. E.g if I want to create a <code>CustomersRepository</code>, I create an interface <code>ICustomersRepository</code> as follows:</p>
<pre><code>public interface ICustomersRepository: IRepository<Customer>
{
IEnumerable<Customer> GetRecentCustomers();
Customer GetByName(string customerName);
}
</code></pre></li>
<li><p>Now I create <code>CustomersRepository</code> class, derive it from <code>BaseRepository</code> and implement <code>ICustomersRepository</code>. as follows:</p>
<pre><code>public class CustomersRepository : BaseRepository<Customer>, ICustomersRepository
{
private readonly DbContext _dbContext;
public CustomersRepository(DbContext dbContext) : base(dbContext)
{
_dbContext = dbContext;
}
public IEnumerable<Customer> GetRecentCustomers()
{
// implementation
}
public Customer GetByName(string customerName)
{
//
}
}
</code></pre></li>
</ol>
<p>Now to create another Repository, I will have to create an interface for it, then create that repository class which will implement <code>BaseRepository<TEntity></code> class, implement the specific repository interface.</p>
<p>Issues:</p>
<ol>
<li>This is not the proper way. But I use it as I get a <code>BaseRepository<TEntity></code> which gives me many functions implemented.</li>
<li>I have to pass <code>DbContext</code> for each repository class.</li>
<li>not satisfied</li>
</ol>
<p>Can you please guide me have this code corrected? I will be using the same approach in almost all of my future projects where I use an ORM.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-22T19:49:33.403",
"Id": "148044",
"Score": "0",
"body": "Implementation seem fine to me but if you like you could drop the `IRepository<T>` and have only `abstract BaseRepository<T>`."
}
] |
[
{
"body": "<ol>\n<li><p>You can make <code>DbContext</code> protected property in your base implementation, so you don't have to declare it in every single derived class.</p></li>\n<li><p>You might want to consider extracting <code>Insert</code> and <code>Delete</code> methods to separate interface, because often you want to make some of your repositories readonly.</p>\n\n<p>Implementation may look like that:</p>\n\n<pre><code>interface IRepository<T> \n{ \n IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate);\n IQueryable<T> GetAll();\n T GetById(int id);\n}\n\ninterface IEditableRepository<T> : IRepository<T>\n{\n void Insert(T entity);\n void Delete(T entity);\n}\n\nclass ReadOnlyRepositoryBase<T> : IRepository<T>\n{...}\n\nclass EditableRepositoryBase<T> : ReadOnlyRepositoryBase<T>, IEditableRepository<T>\n{...}\n</code></pre>\n\n<p>this way you can distinct readonly repositories from non-readonly at compilation time. </p></li>\n<li><p>Passing <code>dbContext</code> to every repository is not normally an issue, because usually in addition to your repositories, you also implement factory object, which creates your repositories for you, so you don't have to call constructor explicitly. This factory can be made a singleton, so you can access it at any point in your code. Alternatively, you can register your repositories in some container, or you can use both approaches. \nIf you are familiar with inversion of control and dependency injection (because there is definitely a learning curve), your best bet is to use a container.</p>\n\n<p>Here is an example (using <a href=\"http://docs.castleproject.org/Windsor.MainPage.ashx\">Castle Windsor</a>):</p>\n\n<pre><code>public class RepositoryFactory : IDisposable\n{\n private IWindsorContainer _container;\n\n public void Open()\n {\n _container = new WindsorContainer();\n\n //register dependencies\n _container.Register(Component.For<DbContext>().ImplementedBy<DbContext>());\n\n //register repositories\n _container.Register(Component.For<ICustomersRepository>().ImplementedBy<CustomersRepository>());\n }\n\n public TRepository GetRepository<TRepository>() where TRepository : class\n {\n return _container.Resolve<TRepository>();\n }\n\n public Dispose()\n {\n if (_container == null) return;\n _container.Dispose();\n _container = null;\n }\n\n public void Close()\n {\n Dispose();\n }\n}\n</code></pre>\n\n<p>Then you can use it like this:</p>\n\n<pre><code>var f = new RepositoryFactory();\nf.Open();\nvar rep = f.GetRepository<ICustomersRepository>();\nf.Close();\n</code></pre>\n\n<p>Alternatively, you can implement your own container using reflection to instantiate your repositories, or you can use a dictionary. Or w/e, really. This implementation is obviously no singleton, but nothing stops you making one, if you feel like it.</p></li>\n</ol>\n\n<p>Apart from that, your implementation looks fine to me. I didn't quite get your first issue though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T10:54:04.027",
"Id": "43068",
"Score": "0",
"body": "Thanks a lot for the answer. The first issue is that I cannot use only interface in any controller's constructor. like \"public myController(ICustomersRepository repository\". because the \"ICustomersRepository\" has only a few methods. Is'nt this bad?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T11:30:15.430",
"Id": "43071",
"Score": "0",
"body": "@Aamir why only a few? `ICustomersRepository` extends `IRepository<Customer>` so it should give you access to both: methods declared in base interface (`GetAll()`, etc..) and methods declared in derived interface (`GetByName()`, etc). Or am missing your point?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T18:30:16.143",
"Id": "43090",
"Score": "0",
"body": "thanks a lot ... it was indeed my mistake... i m ashamed for that silly question. OK .. I will implement your first advice. I am not sure about your second advice.. i mean y would i need to create a separate interface? ... and can u please give me an example of your third advice?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-22T13:21:52.163",
"Id": "236079",
"Score": "0",
"body": "#2 is a great idea."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T07:26:24.143",
"Id": "27618",
"ParentId": "27598",
"Score": "14"
}
}
] |
{
"AcceptedAnswerId": "27618",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T14:53:13.667",
"Id": "27598",
"Score": "18",
"Tags": [
"c#",
"design-patterns",
"asp.net-mvc-4"
],
"Title": "Following Repository Pattern properly"
}
|
27598
|
<p>I wrote the following code to take the heading of an object, and determine which direction <code>(x,y)</code> it needs to move to be heading forward in a 2D plane. I have debugged the code and know that it functions as expected, but as far as readability/maintainability is concerned, I feel like it could be better. Thoughts/opinions?</p>
<pre><code> /*
* map($orgLow, $orgHigh, $newLow, $newHigh, $value)
* Take existing range of values and remap to new range of values
* Requires original high range value, original low range value
* new high range value, new low range value, value to be mapped
* Returns newly mapped integer value
*/
function map($orgLow, $orgHigh, $newLow, $newHigh, $value) {
return $newLow + ($value - $orgLow) * ($newHigh - $newLow) / ($orgHigh - $orgLow);
}
/*
* coordsToMoveFromDeg($deg)
* Take heading and return movement on a (-1 to 1, -1 to 1) plane
* Requires heading to be scaled
* Optional precision to be given
* Returns array consisting of x and y values to change by
*/
function coordsToMoveFromDeg($deg, $precision = false) {
//Rotate plane 90º CCW by remapping the degree value
$xdeg = map(0,360,-90,270,$deg);
if ($xdeg < 0) {
//When xdeg is negative, add 360 to get proper angle
$xdeg += 360;
}
if ($xdeg > 180) {
//Remap values larger than 180 to their mirrored
//value prior to getting final movement values
$xdeg = map(180,360,180,0,$xdeg);
}
$ydeg = $deg;
if ($ydeg > 180) {
//Remap values larger than 180 to their mirrored
//value prior to getting final movement values
$ydeg = map(180,360,180,0,$deg);
}
//Remap x and y to how much to move by, -1 to 1
$x = map(180,0,-1,1,$xdeg);
$y = map(180,0,-1,1,$ydeg);
//Show equal amount of decimal points always for
//easier readability if precision is set, recommended
//to only be set when in debug environment
if ($precision) {
$x = number_format($x,$precision);
$y = number_format($y,$precision);
}
return array('x'=>$x,'y'=>$y);
}
//Show the mapped values for all degrees value 0 to 359 (360 = 0)
for ($i = 0; $i < 360; $i++) {
var_dump(coordsToMoveFromDeg($i,4));
}
</code></pre>
|
[] |
[
{
"body": "<p>I'll separate this into two sections: readability and maintainability. I'm not exactly sure of the usage, so I don't feel I can comment on that.</p>\n<h2>Readability</h2>\n<p>Personally, I think the largest burden on the cleanliness of this code, is the comments. I think they're too large and there's too many.</p>\n<p>One way to improve this, is PHPDocs. Just like JavaDocs, they help organize the functionality of code properties.</p>\n<p>Another way to reduce them is to make your variables as meaningful as possible. What exactly is <code>$deg</code>? What kind of degree is it? Same principle for <code>$xdeg</code> and <code>$x</code>.</p>\n<p>Breaking apart one large method into several smaller functions can also improve the cleanliness, not to mention the benefits of modularized code and improved organization.</p>\n<p>One last note: I see a lot of numbers. What's the decision behind these numbers. Making some of the numbers in <code>map(180,360,180,0</code> constants or variables at the top can help readers understand the meaning.</p>\n<h2>Maintainability</h2>\n<p>You code is very simple (as in it takes care of one thing), and I think this is the greatest tool to avoiding confusion in the future.</p>\n<p>Having well documented code is also great, just make sure your wording is clear and concise. Sometimes referencing to other code in the comments can help. Explain <em>why</em>, not <em>how</em>.</p>\n<p>I don't think there's too much else you can do to future-proof this!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-21T19:42:22.773",
"Id": "57612",
"ParentId": "27600",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T16:13:00.217",
"Id": "27600",
"Score": "7",
"Tags": [
"php",
"optimization"
],
"Title": "Remapping Heading Angle to Coordinates to Move By"
}
|
27600
|
<p>The rules for this script are simple:</p>
<ul>
<li>If geocode is hit, then just geocode</li>
<li>If geocode and submit is hit, then geocode and then submit</li>
<li>If an autosuggest link is hit, then geocode instantly</li>
<li>In this case, do not re-geocode later when the button is hit</li>
</ul>
<p>This is my code, based on help and advice from here: </p>
<p><a href="http://jsfiddle.net/spadez/Jfdbz/14/" rel="nofollow">http://jsfiddle.net/spadez/Jfdbz/14/</a></p>
<pre><code>$(function () {
var lastQuery = null,
lastResult = null, // new!
autocomplete,
processLocation = function (callback) { // accept a callback argument
var input = $("#loc"),
lat = $("#lat"),
long = $("#lng");
var query = $.trim(input.val()),
geocoder;
// if query is empty or the same as last time...
if (!query || query === lastQuery) {
if (callback) {
callback(lastResult); // send the same result as before
}
return; // and stop here
}
lastQuery = query; // store for next time
geocoder = new google.maps.Geocoder();
geocoder.geocode({
address: query
}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
lat.val(results[0].geometry.location.lat());
long.val(results[0].geometry.location.lng());
lastResult = true; // success!
} else {
alert("Sorry - We couldn't find this location. Please try an alternative");
lastResult = false; // failure!
}
if (callback) {
callback(lastResult); // send the result back
}
});
},
ctryiso = $("#ctry").val(),
options = {
types: ["geocode"]
};
if (ctryiso !== '') {
options.componentRestrictions = {
'country': ctryiso
};
}
autocomplete = new google.maps.places.Autocomplete($("#loc")[0], options);
google.maps.event.addListener(autocomplete, 'place_changed', processLocation);
$('#search').click(function (e) {
var form = $(this).closest('form');
e.preventDefault(); // stop the submission
processLocation(function (success) {
if (success) { // if the geocoding succeeded, submit the form
form.submit();
}
});
});
$('#geosearch').click(function (e) {
var form = $(this).closest('form');
e.preventDefault(); // stop the submission
processLocation();
});
});
</code></pre>
<p>I think I have reached the point where it works correctly, and I can't seem to make it any more structured, any more readable, any more efficient or compact. However, I am new to javascript and I would be really open to hear if anyone feels that they can improve on this. </p>
<p>I must admit I a bit pedantic and get a lot of satisfaction out of the refining process!</p>
<p>EDIT: I pasted the code wrong - fixed</p>
|
[] |
[
{
"body": "<p>Just a few things in no particular order:</p>\n\n<ul>\n<li>Don't use <code>long</code> as a variable name. It's a reserved word in Javascript and can cause confusion.</li>\n<li>If you're going to disable the country input in your form, you should probably just put the US keyword straight in your code. That is if you don't intend on enabling it.</li>\n<li>You set <code>ctryiso = $(\"#ctry\").val()</code> and then test <code>ctryiso !== ''</code>. Since you hard coded the country value in, that will always be true. Therefore, unnecessary test.</li>\n<li>You don't need to initialize your <code>lastQuery</code> and <code>lastResult</code> to null. Any falsy value will do just fine in JS, including <code>undefined</code>.</li>\n<li>If you look at the jQuery source code you'll see that the <code>.click()</code> simply calls another method and passes the values on. You can save a few function calls if you just call that other method directly.</li>\n</ul>\n\n<p>Like so:</p>\n\n<pre><code>$('#search').click(function (e) {\n //Do stuff\n}\n\n//Do this one instead\n$('#search').on('click', function (e) {\n //Do stuff\n}\n</code></pre>\n\n<p>The 'click' can be replaced with any event of you're choosing. This gives you enormous power and control when setting up custom events.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T21:01:04.363",
"Id": "27648",
"ParentId": "27601",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27648",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T16:21:35.363",
"Id": "27601",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"optimization",
"performance",
"functional-programming"
],
"Title": "Jquery Geocoding Script"
}
|
27601
|
<p>In the case that Type is not an option, data must exist so I just use an assert to clarify and throw an exception if data is missing. Is there a better way to do this? I think in Java this would be acceptable but I know the scala crowd tends to have a different idea of what idiomatic use of the language is.</p>
<pre><code>private def convertData(dataOption: Option[ByteString], tpe: Type): Any = {
if(tpe.<:<(typeOf[Option[Any]])){
dataOption match{
case Some(x) => ???
case None => None
}
} else{
assert(dataOption.isDefined)
???
}
}
</code></pre>
|
[] |
[
{
"body": "<p>In short: yes, assertions make perfect sense outside testing and can raise the confidence that the code is actually correct.</p>\n\n<h2>Design by contract</h2>\n\n<p>What you like to assert, namely, that <em>\"<code>dataOption</code> must be defined if <code>tpe</code> does not represent a subtype of <code>Option[Any]</code>\"</em> can be considered a <a href=\"https://en.wikipedia.org/wiki/Precondition\" rel=\"nofollow noreferrer\">precondition</a> of your method. That is, a condition over the parameters (and fields and global state) that needs to hold in order for your method to run successfully. The method implementer states such conditions and can then rely on them, whereas the caller is responsible for ensuring that they hold. The dual concept are <a href=\"https://en.wikipedia.org/wiki/Postcondition\" rel=\"nofollow noreferrer\">postconditions</a>, where the caller gets the guarantee which the implementer must ensure.</p>\n\n<p>Languages such as <a href=\"https://en.wikipedia.org/wiki/Eiffel_%28programming_language%29\" rel=\"nofollow noreferrer\">Eiffel</a> and <a href=\"https://en.wikipedia.org/wiki/Spec_sharp\" rel=\"nofollow noreferrer\">Spec#</a> natively support this so-called <a href=\"https://en.wikipedia.org/wiki/Design_by_contract\" rel=\"nofollow noreferrer\">design by contract</a> approach to programming. Natively, because contract elements such as preconditions, postconditions and invariants are built into the language. There is a significant difference, however, when the contracts are looked at. Eiffel <em>checks</em> contracts at run-time, which is quite similar to testing in the sense that only concrete executions are considered. Spec#, on the other hand, <em>verifies</em> contracts statically, which means that it tries to assert that the contract holds for all possible executions. The latter is very challenging and not always possible, but it yields much stronger guarantees in case it is. The former is easier, but gives you weaker guarantees.</p>\n\n<p>Other languages lack native support for such contracts, for example Java or C#. In order to design by contract, Java developers can use <a href=\"http://www.eecs.ucf.edu/~leavens/JML/index.shtml\" rel=\"nofollow noreferrer\">JML</a> and C# developers can use <a href=\"http://www.infoq.com/articles/code-contracts-csharp\" rel=\"nofollow noreferrer\">Code Contracts</a>. JML is based on Java annotations and can be used for static verification and run-time checking, as can Code Contracts be, but they are implemented as a regular library.</p>\n\n<h2>Scala</h2>\n\n<p>Scala also lacks built-in support for contracts, but there are quite a few projects that try to work around this. Amongst others, there are:</p>\n\n<ul>\n<li><p>Very simple run-time checked pre- and postconditions described in the paper <a href=\"http://link.springer.com/chapter/10.1007/978-3-642-16612-9_5#page-1\" rel=\"nofollow noreferrer\">Contracts for Scala</a></p></li>\n<li><p>Static verification of functional Scala code with <a href=\"http://lara.epfl.ch/w/leon\" rel=\"nofollow noreferrer\">Leon</a></p></li>\n<li><p>Run-time checking of Scala with a Code-Contracts-like library (<a href=\"http://www.pm.inf.ethz.ch/education/theses/student_docs/Rokas_Matulis/Rokas_Matulis_MA_report\" rel=\"nofollow noreferrer\">project report</a>)</p></li>\n<li><p>Static verification of possibly non-functional Scala code (<a href=\"http://www.pm.inf.ethz.ch/education/theses/student_docs/Bernhard_Brodowsky/MA_description_Bernhard_Brodowsky\" rel=\"nofollow noreferrer\">project description</a>, the report will be only soon)</p></li>\n</ul>\n\n<h2>The answer</h2>\n\n<p>Back to your question: You use assertions (and the control flow) to check the precondition of your method, hence, you kind of do design by contract - which is good, because it makes it more likely that errors are detected close to where they are caused. These checks are basically like small unit tests and thus can increase the confidence in your code.</p>\n\n<p>In order to make the method's precondition as explicit as possible, I would move the assertion to the begin of the method</p>\n\n<pre><code>private def convertData(dataOption: Option[ByteString], tpe: Type): Any = {\n assert(tpe.<:<(typeOf[Option[Any]]) || dataOption.isDefined,\n \"<put helpful error message here>\")\n\n ...\n}\n</code></pre>\n\n<p>You could also put assertions at all return points of the method in order to mimic postconditions.</p>\n\n<p>In case you worry about performance, you can use the fact the <code>assert</code> is annotated as <a href=\"https://stackoverflow.com/questions/8388952/what-does-the-elidable-annotation-do-in-scala-and-when-should-i-use-it\"><code>@elidable</code></a> and thus can be removed by the compiler, for example, for a production build.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T13:59:35.427",
"Id": "43082",
"Score": "0",
"body": "Incredible answer - thanks for filling this in for me and giving me suggestions on how to improve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T07:40:19.973",
"Id": "392472",
"Score": "0",
"body": "On the other hand, assertions are making code less functional as it introduces side effects. Can/Should the similar effect be achieved with Partial Functions? https://stackoverflow.com/a/15972055/160596"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T08:02:49.593",
"Id": "392475",
"Score": "0",
"body": "@xvga I don't see that PFs have an advantage here: a PF that is applied outside its domain will raise a corresponding exception. Callers could check that a PF is applicable, but that also applies to a function with an assertion at the beginning. With the difference, that the assertion can give you a meaningful error message where the PF will (in general) just report a `MatchError`. IMO, an assertion that checks a function's precondition effectively makes that function partial."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T12:51:09.380",
"Id": "392518",
"Score": "0",
"body": "@MalteSchwerhoff Could you please clarify how caller can check if function (with assertion at the beginning) is applicable? (except for trying calling it and catching exceptions). Otherwise, it might be just a matter of preference . So far, IMO, assertions are friendlier/easier to use."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T06:23:10.733",
"Id": "392595",
"Score": "0",
"body": "@xvga Conceptually, a precondition (analogously, a postcondition) only makes sense if it is public, i.e. known to caller & callee. If it were private, a caller would not know how to systematically establish a callee's pre. Pres/posts are sometimes called *contracts*, a term that, IMO, conveys good intuition: a contract that caller & callee need to agree on to cooperate. A callee can implement a `checkPre(...)` method that both callee and caller can use to check if the pre is satisfied. A Scala PF essentially does that: `isDefinedAt` is the caller's `checkPre`, the `MatchError` is the callee's."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T19:01:37.550",
"Id": "392685",
"Score": "0",
"body": "@MalteSchwerhoff Still, what about checking applicability by caller for assertions as you mentioned that it is possible? (_\"Callers could check that a PF is applicable, but that also applies to a function with an assertion at the beginning.\"_)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T08:41:58.707",
"Id": "393154",
"Score": "0",
"body": "As I said: to support this, the callee would have to provide an appropriate `checkPre` method. Scala does not have built-in support for contracts."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T07:52:00.047",
"Id": "27619",
"ParentId": "27602",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "27619",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T17:02:02.393",
"Id": "27602",
"Score": "0",
"Tags": [
"scala"
],
"Title": "Scala: Are assertions acceptable outside of test context?"
}
|
27602
|
<p>For my classes, I had to finish this task:</p>
<blockquote>
<p><strong>Directory's disk usage list</strong></p>
<p>For indicated directory print a list of files and subdirectories in
descending order according to their total disk usage. Disk usage of a
simple file is equivalent to its size, for a subdirectory - a sum of
the sizes of all files in its filesystem branch (subtree). Printed
list format:</p>
<p><code><disk usage> <holder name> <type> <name></code> In the preceding print format
is in case of a file not being a directory an owner, otherwise, the
holder of a directory is the owner of the files having greatest total
disk usage in it. <code><type></code> is a letter: d for a directory, - for a
standard file, l - for a symbolic link etc.</p>
<p><strong>Below file disk usage list, print a summary:</strong></p>
<p>Total disk usage of the files in directory's subtree, the list of
total disk usage of files in directory's subtree with respect to the
owners (sums over owners). CAUTION: during recursive directories
listing do not dereference symbolic links.</p>
</blockquote>
<p>Here is my code:</p>
<pre><code>#!/bin/bash
cd "$1"
ls -lA | awk 'NR != 1{
name=$8
for ( i=9; i<=NF; i++) name=name " " $i
type=substr($1,1,1)
if (type!="d")
{
print $5,$3,type,name
sum_all+=$5
usr_sum_all[$3]+=$5
}
else
{
sum=0;delete usr_sum;
find_proc="find " name " -printf \"%s %u\\n\" 2>/dev/null"
while ( find_proc | getline )
{
sum+=$1;usr_sum[$2]+=$1;
sum_all+=$1;usr_sum_all[$2]+=$1;
}
close(find_proc)
owner=""
owner_sum=-1
for ( iowner in usr_sum ) if ( usr_sum[iowner] > owner_sum ) {owner = iowner; owner_sum=usr_sum[iowner]}
print sum " " owner " d " name
}
}
END {
print "Space taken: " sum_all
for ( iowner in usr_sum_all ) print "\t user: " iowner " " usr_sum_all[iowner]
}' | sort -gr
</code></pre>
<p>Is it ok? Should I make any changes?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T19:24:38.167",
"Id": "43025",
"Score": "0",
"body": "I guess they want you to use recursion? \"CAUTION: during recursive directories listing do not dereference symbolic links.\" : your solution is iterative"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T19:34:42.707",
"Id": "43030",
"Score": "0",
"body": "Yeah. I mailed my tutor about that he said i can use iteration as long as I will fulfil all the requirements? Are they fulfilled?"
}
] |
[
{
"body": "<p>I just copied your code, pasted it in to a terminal, ran it, and it did exactly what it is supposed to do. Now, how to make it better?</p>\n<p>You don't mention it in the question, but using <code>ls</code>, <code>awk</code>, <code>find</code>, and <code>sort</code> together somehow seems unlikely to be the answer your tutor expected. You don't mention what your course is in, but I would have expected there to be a less 'cobbled together' solution, using perhaps bash only, or perl, python, or something else.</p>\n<p>I certainly would not have solved this problem this way (I would have used perl).</p>\n<p>Still, assuming your code meets the expectations for tool use (as in, you are supposed to use awk), there are some things that are off.</p>\n<h2>Single-line multi-statements</h2>\n<p>You have a number of 1-liners that you should have expanded. You already have the massive awk code-block, why mix the compact 1-liner and block statements like you have done?</p>\n<blockquote>\n<pre><code>for ( iowner in usr_sum ) if ( usr_sum[iowner] > owner_sum ) {owner = iowner; owner_sum=usr_sum[iowner]}\n</code></pre>\n</blockquote>\n<p>The above should be:</p>\n<pre><code>for ( iowner in usr_sum )\n{\n if ( usr_sum[iowner] > owner_sum )\n {\n owner = iowner\n owner_sum=usr_sum[iowner]\n }\n}\n</code></pre>\n<p>Note, the use of block <code>{}</code> braces for the single <code>if</code> statement, and not using the semi-colon <code>;</code> to separate statements on a single line.</p>\n<p>These other statements should also be on their own lines (and the for statement should have a <code>{}</code> block):</p>\n<blockquote>\n<pre><code>for ( i=9; i<=NF; i++) name=name " " $i\n...\nsum=0;delete usr_sum;\n...\nsum+=$1;usr_sum[$2]+=$1;\nsum_all+=$1;usr_sum_all[$2]+=$1;\n</code></pre>\n</blockquote>\n<h2>Negative if</h2>\n<p>Your main if-block would be better if done as a positive check, not a negative check. your code is:</p>\n<blockquote>\n<pre><code>if (type!="d")\n{\n ... do not a directory stuff\n}\nelse\n{\n ... do directory stuff\n}\n</code></pre>\n</blockquote>\n<p>but would be more readable as:</p>\n<pre><code>if (type == "d")\n{\n ... do directory stuff\n}\nelse\n{\n ... do not a directory stuff\n}\n</code></pre>\n<h2>Breathing space</h2>\n<p>Your code is suffocating since it has little breathing space. Many of your statements are compressed around the operators and other symbols. Consider lines like:</p>\n<blockquote>\n<pre><code> print $5,$3,type,name\n sum_all+=$5\n usr_sum_all[$3]+=$5\n</code></pre>\n</blockquote>\n<p>Which should be written as:</p>\n<pre><code> print $5, $3, type, name\n sum_all += $5\n usr_sum_all[$3] += $5\n</code></pre>\n<h2>Performance</h2>\n<p>The multiple calls to <code>find</code> may be hurting your performance. In general I can't help but think there's a better way to do this without all the nested OS calls.</p>\n<p>Still, it ran fast enough for me on my machine, so it is probably not a real problem.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-11T21:05:42.430",
"Id": "59723",
"ParentId": "27603",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T17:40:07.467",
"Id": "27603",
"Score": "5",
"Tags": [
"bash",
"linux",
"file-system",
"awk"
],
"Title": "Directory's disk usage list"
}
|
27603
|
<p>We are beginning to learn Node.js and we are not always sure if we do it the right way. We have a strong object oriented background so the adoption is not always easy. Right now we implemented a factory method, but we are not completely sure if our approach is good. </p>
<p>Factory Method:</p>
<pre><code>var fs = require('fs');
module.exports.getHandler = function(type,callback) {
if(!type) {
throw new Error('Please specifiy a type');
}
var nodeModule = type.ucFirst()+'FieldHandler';
var file = __dirname+'/'+nodeModule+'.js';
fs.exists(file, function(exists) {
if (exists) {
var handler = require('./'+nodeModule);
var instance = new handler;
callback(instance);
} else {
throw new Error('Handler for "'+type+'" does not exist. ' +
'Expect file of handler to have the name "'+file+'"');
}
});
};
</code></pre>
<p>Object which uses the factory method:</p>
<pre><code>var FieldhandlerFactory = require('./fieldhandler/Factory');
...
...
...
var handleField = function (actualField) {
var callbackHandler = function (handler) {
handler.setJson(actualField);
handler.check();
fieldString += handler.toView() + '\n';
actual++;
if (amountFields == actual) {
// WE ARE READY DO SOMETHING
}
};
var handler = FieldhandlerFactory.getHandler(type, callbackHandler);
}
for (var index in fields) {
var field = fields[index];
type = field.type;
if (!type) {
throw new Error('Field on index "' + index + '" has no attribute type');
}
var string = handleField(field);
}
...
...
...
</code></pre>
<p>The code works, so we are quite happy. Is this a good approach or do we stick too much to the classical OOP style? Especially with testing we face some problems. How to test the function handleField isolated? And with jasmine-node I'm not able to catch the exception in the factory method when the file is not found.</p>
<p>So we think there are tons of improvements. We are looking forward to learn from you and to exchange experiences.</p>
|
[] |
[
{
"body": "<p>When using callbacks, the first parameter is the error. So instead of throwing the error, you should pass it as the first argument. The signature of the callback should look like this <code>function(err, all, other, arguments)</code>.</p>\n\n<p>So instead of this</p>\n\n<pre><code>var fs = require('fs');\n\nmodule.exports.getHandler = function(type,callback) {\n if(!type) {\n throw new Error('Please specifiy a type');\n }\n var nodeModule = type.ucFirst()+'FieldHandler';\n var file = __dirname+'/'+nodeModule+'.js';\n fs.exists(file, function(exists) {\n if (exists) {\n var handler = require('./'+nodeModule);\n var instance = new handler;\n callback(instance);\n } else {\n throw new Error('Handler for \"'+type+'\" does not exist. ' +\n 'Expect file of handler to have the name \"'+file+'\"');\n }\n });\n};\n</code></pre>\n\n<p>You should have something like</p>\n\n<pre><code>var fs = require('fs');\n\nmodule.exports.getHandler = function(type,callback) {\n if(!type) {\n callback(new Error('Please specifiy a type');\n }\n var nodeModule = type.ucFirst()+'FieldHandler';\n var file = __dirname+'/'+nodeModule+'.js';\n fs.exists(file, function(exists) {\n if (exists) {\n var handler = require('./'+nodeModule);\n var instance = new handler;\n callback(null, instance);\n } else {\n callback(new Error('Handler for \"'+type+'\" does not exist. ' +\n 'Expect file of handler to have the name \"'+file+'\"');\n }\n });\n};\n</code></pre>\n\n<p>Then it should become pretty easy to test. As a bonus, you can have a look at <a href=\"https://github.com/cjohansen/Sinon.JS\" rel=\"nofollow\">https://github.com/cjohansen/Sinon.JS</a>. It's a good module for mocks, stubs and spies.</p>\n\n<p>Also, I realized that you are doing a synchronous for loop calling asynchronous functions. <code>var aString = handleField(field);</code> will never do what you are expected. <code>handleField</code> does not return anything. You should expect it in a callback. If you want a tip to handle the flow properly, use <a href=\"https://github.com/caolan/async\" rel=\"nofollow\">https://github.com/caolan/async</a>. With this module, you will stay away of the mythical \"callback-hell\".</p>\n\n<p>Enjoy, node.js!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T14:30:26.453",
"Id": "41153",
"ParentId": "27604",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T17:44:58.140",
"Id": "27604",
"Score": "1",
"Tags": [
"javascript",
"design-patterns",
"unit-testing",
"node.js",
"asynchronous"
],
"Title": "Is this factory method a good approach?"
}
|
27604
|
<p>I have these classes that have a boilerplate way of initialization. So, instead of writing it each time, I wrote a class called <code>MockUtil.java</code>, and I put the boilerplate mocks in there.</p>
<p><code>MockUtil</code> has static variables and methods which can be called to do the mocking for the test classes. So, when writing a new test class setup, <code>MockUtil</code>'s setup, boilerplate expectations, replays, and verifications of mock are being called from the <code>Test</code> class.</p>
<p>I feel like this reduces a lot of boilerplate burden on the test classes. But, I still feel like the code structure/code pattern can be improved. I am not sure if it has to be a util class or something else, because two tests can't run simultaneously because of static variables and methods and I feel like it reduces the scope of enhancements, if any, that has to be done. Could you give me suggestions on what I can improve in my code? </p>
<p><strong>MockUtil.java</strong></p>
<pre><code>public class MockUtil {
public static JdbcTransactionImpl transaction;
public static Connection connection;
public static PreparedStatement statement;
public static ResultSet resultSet;
public static Connection getConnection() {
return connection;
}
public static ResultSet getResultSet() {
return resultSet;
}
public static PreparedStatement getStatement() {
return statement;
}
public static void createMocks() {
//more boilerplate mocks to create services to be used in each Test -- which are ignored here.
//boilerplate tx mocks
transaction = createMockBuilder(JdbcTransactionImpl.class)
.addMockedMethod("getConnection").createMock();
connection = createMock(Connection.class);
statement = createMock(PreparedStatement.class);
resultSet = createMock(ResultSet.class);
}
public static void setContextualExpectations(String...sqls) throws Exception {
//boilerplate tx expectations.
expect(context.getTransaction()).andReturn(transaction).anyTimes();
expect(transaction.getConnection()).andReturn(connection).anyTimes();
for(String sql: sqls) {
expect(connection.prepareStatement(sql)).andReturn(statement);
}
expect(statement.executeQuery()).andReturn(resultSet).anyTimes();
}
public static void setReplays() throws SQLException {
replay(transaction);
replay(connection);
replay(statement);
replay(resultSet);
}
public static void closeResources() throws SQLException {
//boilerplate resource closing.
statement.close();
resultSet.close();
}
public static void verifyMocks() {
//boilerplate verification of mocks.
verify(transaction);
verify(connection);
verify(statement);
verify(resultSet);
}
}
</code></pre>
<p>One of the several test classes:</p>
<p><strong>Class1Test</strong></p>
<pre><code>private void setCustomExpectationsForTest1XXX() throws SQLException {
PreparedStatement stmt = MockUtil.getStatement();
ResultSet rs = MockUtil.getResultSet();
checkExp(stmt, rs);
}
private void checkExp(PreparedStatement stmt, ResultSet rs)
throws SQLException {
stmt.setString(1, in.getCode());
expect(rs.next()).andReturn(true);
expect(rs.getString(1)).andReturn(customVal);
MockUtil.closeResources();
}
@Before
public void setUp() throws Exception {
MockUtil.createMocks();
createImportExportObj();
}
@After
public void tearDown() throws Exception {
in = null;
out = null;
}
@Test
public void test1XXX() throws Exception {
MockUtil.setContextualExpectations(calcPbValForGldSqls);
setCustomExpectationsForTest1XXX();
MockUtil.setReplays();
program.execute(in, out);
BigDecimal expected = new BigDecimal("85000").setScale(4);
BigDecimal actual = out.getAmt();
assertEquals(expected, actual);
MockUtil.verifyMocks();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T07:44:46.983",
"Id": "43059",
"Score": "0",
"body": "If you are telling a mocked object to return another mocked object you are doing it wrong. Also all this code does not seem to do anything useful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T16:25:32.787",
"Id": "43084",
"Score": "0",
"body": "@abuzittingillifirca I am asking a util class to return a mock object. I didn't understand what you meant by usefulness, could you please elaborate? I am setting custom expectations and executing the program in my Test class and verifying assertions."
}
] |
[
{
"body": "<p>You are right about the problem with static variables and methods possibly causing problems in a multithreaded environment. I recommend turning your MockUtil into an abstract class with no static methods and then have your test classes extend that. That way you are guaranteed to have fresh mocks for all your test classes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T21:59:25.697",
"Id": "27681",
"ParentId": "27608",
"Score": "2"
}
},
{
"body": "<ol>\n<li><p>You should have a new abstraction level in your code. Move all of your database related logic into a separate class (or maybe more than one classes) and access your database through that class(es). It would provide some benefits:</p>\n\n<ul>\n<li>easier testing: don't have to mock <code>Connection</code>/<code>PreparedStatement</code>/<code>ResultSet</code> classes all the time,</li>\n<li>more robusts test: when modifying the database layer you don't have to modify business logic classes,</li>\n<li>be able to change the program to use another data storage easily.</li>\n</ul>\n\n<p>See also: <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">single responsibility principle</a>.</p></li>\n<li><p>If you're using JUnit and <code>in</code> and <code>out</code> are instance field (they are not <code>static</code>) you don't need that</p>\n\n<blockquote>\n<pre><code>@After\npublic void tearDown() throws Exception {\n in = null;\n out = null;\n}\n</code></pre>\n</blockquote>\n\n<p>JUnit creates new instances of the test class for every <code>@Test</code> method.</p></li>\n<li><p><code>@Before</code> and <code>@After</code> methods are usually at the beginning of the test class. Hiding them in the middle of the class could require extra effort to understand the code.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-15T15:25:14.120",
"Id": "44445",
"ParentId": "27608",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27681",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T20:38:18.980",
"Id": "27608",
"Score": "3",
"Tags": [
"java",
"design-patterns",
"unit-testing",
"junit"
],
"Title": "Mocking utility class for database testing"
}
|
27608
|
<p>I'm going to implement something like the Unity3D component model for my C++ game engine. Please, review my draft of the <code>Component</code> base class:</p>
<pre><code>class Component
{
public:
template<class T>
static T* create(void)
{
if (Type<T>::id == 0)
Type<T>::id = ++_idCounter;
T* component = new T();
component->_id = Type<T>::id;
return component;
}
template<class T>
inline bool is(void) const
{
return Type<T>::id == _id;
}
protected:
Component(void) {}
private:
static unsigned int _idCounter;
unsigned int _id;
template<class T> struct Type { static unsigned int id; };
};
unsigned int Component::_idCounter = 0;
template<class T> unsigned int Component::Type<T>::id = 0;
</code></pre>
<p>It has some RTTI-like functionality, and I can use it this way:</p>
<pre><code>class ComponentA: public Component {};
class ComponentB: public Component {};
...
ComponentA* a = Component::create<ComponentA>();
ComponentB* b = Component::create<ComponentB>();
std::cout << a->is<ComponentA>() << std::endl; // 1
std::cout << b->is<ComponentB>() << std::endl; // 1
std::cout << b->is<ComponentA>() << std::endl; // 0
std::cout << a->is<ComponentB>() << std::endl; // 0
</code></pre>
<p>And I have a question. How can I prevent any construction of any descendant of <code>Component</code> outside of <code>Component::create</code>?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T22:28:38.357",
"Id": "43043",
"Score": "2",
"body": "Any particular reason why you’re rolling your own RTTI, when C++ has a perfectly good built in facility for that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T22:30:40.820",
"Id": "43044",
"Score": "0",
"body": "By “prevent any construction of any descendant of Component”, if you mean just those under your control, you can prevent that by declaring the constructors of your descendants private, with class Component as a friend. If you want to prevent constructions of descendants implemented by others, you’re SOL."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T22:55:36.467",
"Id": "43045",
"Score": "0",
"body": "I don't want to get RTTI overhead. I think that comparison of two uints much more faster than comparsion of two typeids."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T23:53:13.287",
"Id": "43046",
"Score": "2",
"body": "If the performance of your code critically depends on the speed of type identity comparisons, I suspect that your design is rather fundamentally misguided. In most C++ code, typeid comparisons are incredibly rare."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T09:54:38.973",
"Id": "43065",
"Score": "2",
"body": "A bit of nitpicking: Leading underscores are in many cases reserved for the compiler/implementation. If I recall the rules correctly, _x (single underscore followed by lower-case) is reserved when in global scope, and __x, __X and _X (double underscore followed by anything and single underscore followed by upper-case) is always reserved, regardless of scope. Since it's pointless to memorize these rules, I think leading underscores are bad practice in general. Make them a suffix instead: `idCounter_`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T18:26:10.977",
"Id": "43124",
"Score": "1",
"body": "@Lstor: The rules. http://stackoverflow.com/a/228797/14065. Summry: As you said \"avoid the use of leading underscore\". Even if you can remember the rules a lot of people don't get it correct."
}
] |
[
{
"body": "<p>Sorry, but this is simply not a good design.</p>\n\n<p>Your reliance on memory-owning raw pointers means that the library is easy to use wrongly, and that the user will leak memory. This is a big no-no in modern C++. First, because it’s harmful and makes user code brittle and complex; and second, because it is unnecessary. Modern C++ gives you all the tools to avoid manual memory management.</p>\n\n<p>Think carefully about ownership in your component model and choose an appropriate smart pointer. Since you control the object hierarchy, <a href=\"http://www.boost.org/doc/libs/1_53_0/libs/smart_ptr/intrusive_ptr.html\"><code>boost::intrusive_ptr</code></a> may be the best match, but consider other alternatives which are less generic (such as <code>std::unique_ptr</code>).</p>\n\n<p>Finally think about ways to avoid pointer use completely, if possible. In fact, the code you’ve shown doesn’t use runtime polymorphism at all so there is no use of pointers. Just handle objects directly.</p>\n\n<p>Regarding your implementation of RTTI: Without knowing the detailed requirements of your object model it’s hard to comment here; however, you say that you don’t want to get the RTTI overhead. What makes you think C++ RTTI has more overhead than your solution? In fact the implementation you’ve shown is, if anything, <em>less</em> efficient than C++ RTTI because your use-case can be resolved at compile-time.</p>\n\n<p>But let’s assume that you just forgot to make your classes polymorphic, and that the real code cannot resolve the type information at compile time. Then your RTTI mechanism stores redundant information and is <em>still</em> less efficient than C++’ built-in mechanism.</p>\n\n<p>Finally, if you are afraid of RTTI overhead (and have data to back this up) then the real solution is not to roll your own system, it’s to <em>avoid</em> RTTI be redesigning your classes such that they have a uniform interface and don’t need to be distinguished at runtime. In fact, this is the idiomatic solution in C++, and RTTI is the exception rather than the norm.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T09:43:47.710",
"Id": "27623",
"ParentId": "27612",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T22:13:42.793",
"Id": "27612",
"Score": "4",
"Tags": [
"c++"
],
"Title": "Component implementation"
}
|
27612
|
<p>This is the console program that I've written in C++. It's a game where you have to guess a randomly picked number within the range 0-200. I just took a look at syntax and how to get started with C++ and VS and I was able to write this game almost immediately, but tweaking and improving it took me some time. I have a lot of experience with PAWN.</p>
<p>Anyway, does my code look alright? Please let me know if there are any bad practices that you notice or anything wrong.</p>
<pre class="lang-c prettyprint-override"><code>#include <iostream> // cin(), cout(), printf()
#include <time.h> // time()
#include <windows.h> // Sleep()
/* Variables */
int number;
int tries;
int max_tries;
/* Functions */
void game_init(int try_count);
void game_process();
void game_decide();
int game_check(char input);
int main()
{
srand((unsigned int)time(NULL));
game_init(8);
game_process();
}
void game_init(int try_count)
{
number = rand() % 200;
tries = 1;
max_tries = try_count;
printf("You have %d tries to guess a random number we've picked for you. (withing a range 0-200)\n", max_tries);
}
void game_process()
{
do
{
printf("\nTry %d/%d: ", tries, max_tries);
int input;
scanf_s("%d", &input);
if (game_check(input) == 1)
{
std::cin.get();
break;
}
if (tries == 9)
{
printf("\n\n\nUnfortunately, you weren't able to guess the number.\nIt was %d!", number);
printf("\n\nI wish you more luck the next time. Wanna try again? Type \"yes\" or \"no\".");
printf("\nDo you want to try again? ");
game_decide();
}
}
while (tries <= max_tries);
}
int game_check(char input)
{
if (input == number)
{
printf("\nCongratulations! You've guessed the number, it was %d!", number);
printf("\n\nDo you want to play again? ");
game_decide();
return 1;
}
else if (input < number)
{
printf("\nThe number %d you've entered is lower than the number we're looking for.", input);
tries ++;
std::cin.ignore();
}
else if (input > number)
{
printf("\nThe number %d you've entered is higher than the number we're looking for.", input);
tries ++;
std::cin.ignore();
}
return 0;
}
void game_decide()
{
char decision[3];
std::cin >> decision;
if (!strcmp(decision, "yes"))
{
std::cout << "\n\n\n";
game_init(8);
game_process();
}
else if (!strcmp(decision, "no"))
{
printf("Quitting...");
// Close the console after 1 second
Sleep(1000);
exit(0);
}
else
{
printf("\n\nI'm not sure I understand what are you saying... Can you repeat that again, just \"yes\" or \"no\", please?");
printf("\nDo you want to try again? ");
game_decide();
}
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>There's no need for <code>printf()</code> and <code>scanf()</code> in C++. Instead, use:</p>\n\n<ul>\n<li><code>std::cout << \"Some text...\" << aVariable;</code> for outputting, or</li>\n<li><code>std::cin >> aVariable;</code> for inputting</li>\n</ul></li>\n<li><p>In C++, use <code><ctime></code> instead of <code><time.h></code>. The latter is a C library.</p></li>\n<li><p><em>Never</em> use global variables, unless they're constants. Instead, pass <code>number</code> and <code>tries</code> to their relevant functions.</p></li>\n<li><p>If <code>max_tries</code> is supposed to be a constant, initialize it below the <code>#include</code>s as such:</p>\n\n<pre><code>const int max_tries = 8;\n</code></pre></li>\n<li><p>Since you're using <code>std::rand()</code>, which returns non-negative numbers, you could change <code>number</code>'s type to <code>unsigned int</code>.</p></li>\n<li><p>You should move <code>game_init()</code>'s contents to <code>main()</code> instead for clarity and easier program termination (via <code>return X</code>).</p></li>\n<li><p><code>game_check()</code> should return a <code>bool</code> since it's conditional. For <code>bool</code>s, 0 corresponds to <code>false</code> and 1 corresponds to <code>true</code>.</p>\n\n<p>It shouldn't need to display anything since that's not its purpose. Instead, move those outputs to <code>game_process()</code>, remove the <code>std::cin.ignore()</code>s, and return the appropriate <code>bool</code>s.</p>\n\n<p>Remove the <code>return 0</code>; it should now return a value of <code>true</code> or <code>false</code> instead.</p>\n\n<p>The parameter for its prototype and definition should be an <code>int</code>, which you're already passing into it from <code>game_process()</code>.</p></li>\n<li><p>In <code>game_decide()</code>: instead of using a <code>char</code> array to hold <code>decision</code>, just make it a single <code>char</code> variable. A \"y\" or \"Y\" could mean yes, and an \"n\" or \"N\" could mean no. Then, your conditional statements could look like this:</p>\n\n<pre><code>if (decision == 'y' || decision == 'Y')\n// do something\nelse if (decision == 'n' || decision == 'N')\n// do something else\nelse\n// try again\n</code></pre>\n\n<p>You're doing a recursive call, which is absolutely unnecessary for this situation. Instead, use a <code>while</code> or <code>do-while</code> loop to handle this.</p>\n\n<p>It should return a <code>bool</code> instead (for the same reason as <code>game_check()</code>).</p>\n\n<p>Clear everything from the \"yes\" and \"no\" blocks and instead have them respectively return <code>true</code> and <code>false</code>. Then, back at <code>game_process()</code>, allow the loop to end if <code>game_decide()</code> returns <code>false</code> (meaning that the user no longer wants to play). Thus, the program will fall back to <code>main()</code> and terminate nicely. You would then no longer need <code>#include <windows.h></code>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T01:42:06.300",
"Id": "27614",
"ParentId": "27613",
"Score": "17"
}
},
{
"body": "<p>Jamal has many good points. Listen to them. In addition:</p>\n\n<p>I'd argue that this is barely C++. Your code is written as if it was C, only with some C++ function calls instead.</p>\n\n<p><strong>1: Take advantage of C++.</strong> Your <code>game_</code> functions should probably be member functions in a <code>Game</code> class. You can make more use of the C++ standard library. In short, strive towards writing C++.</p>\n\n<p><strong>2: Use <code>std::string</code> instead of <code>char[]</code>.</strong> C++ strings are dynamic and can grow, they take care of memory management for you and generally make your life much easier. They can also be turned into a C-style string (i.e. a <code>char[]</code>) by calling <code>mystring.c_str()</code>.</p>\n\n<p>3: In C++, we use <code>0</code> instead of <code>NULL</code>. In C++11, use <code>nullptr</code> instead.</p>\n\n<p><strong>4: Avoid literal constants.</strong> Consider for example your <code>if (tries == 9)</code>. Why exactly is this 9? Is that the maximum number of tries? Does it hold some magic meaning? If you declare <code>const int MAX_TRIES = 9;</code> somewhere, <code>if (tries == MAX_TRIES)</code> will become much easier to read. As an added bonus, you only have to change the code one place to change the maximum number of tries. I'm also wondering: Why are you checking <code>tries</code>against <code>9</code>, and not against your <code>max_tries</code> variable?</p>\n\n<p><strong>5:</strong> Regarding constants and Jamal's answer: C++ doesn't have a set coding convention. You don't <em>have</em> to write constants in <code>UPPERCASE_UNIX_CASE</code>. However, it's a common convention and I think it's a good one. I still think you should restrict the constant's scope as much as possible. It is okay to have a global or semi-global constant, but there's no reason to do so just because you can. If a constant is only used in a function or other restricted scope, then restrict the constant to that scope.</p>\n\n<p><strong>6:</strong> Using a <code>while</code> loop is generally more readable than a <code>do...while</code> loop. Unless you really need to force a first iteration (which you don't in this case), prefer <code>while</code> loops.</p>\n\n<p><strong>7:</strong> Use a loop inside <code>game_decide</code> instead of having it call itself. Recursion is in many cases wonderful, but this is not the place nor use for it.</p>\n\n<p><strong>8:</strong> On a game design level, consider telling the user if a guess is too high or too low, and remember the upper and lower bounds for him/her.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T12:30:53.457",
"Id": "43077",
"Score": "1",
"body": "I don't agree with `ALL_UPPERCASE` being a common convention in C++ for constants. Rather, usage is conventionally reserved exclusively for macros."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T18:46:18.623",
"Id": "43125",
"Score": "1",
"body": "Avoid all uppercase identifiers unless they are macros. The convention is `MACRO NAMES` are all uppercase. This is because macros have no scope thus your identifiers can potentially be trampled. So to avoid clashes with normal identifiers and those used by the pre-processor the convention is used. What you are seeing is that macros often define constants (in C). With C++ constants are more normally `type const` and thus don't have all uppercase names."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T18:51:59.070",
"Id": "43127",
"Score": "1",
"body": "I disagree with using `0` as NULL pointer value. It makes no difference to the compiler (they are the same value). So the only reason to use one over the other is to help poor humans. The use of a name gives valuable context that makes the code easier to read (you know it is a pointer rather than an integer). But nullptr is the correct solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T18:55:20.490",
"Id": "43128",
"Score": "1",
"body": "Can't agree that `do..while()` is any more/less common than `while` or even `for` (well for is probably the most prevalent (but just in my experience others may have totally different experience)). The point: Any is fine. Use the one that makes the most sense in the given context and makes the code easy to understand."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T21:33:51.500",
"Id": "43143",
"Score": "0",
"body": "@Yuushi, @LokiAstari: I may very well be affected by the code bases I usually work in, and biased to believe that `UNIX_CASE` is common for constants. I'll keep in mind that both of you object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T21:37:25.533",
"Id": "43144",
"Score": "0",
"body": "@LokiAstari: I'm saying that `while` is more readable than `do..while()`, not that it is more common. I suspect it is more common as well, but that's beside the point. I think reading the condition first works better with how people parse code in their heads. I have even been criticized myself by using it in cases where it makes absolute sense. Therefore I stand by my comment: Unless `do..while()` makes sense, prefer `while`."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T07:24:44.177",
"Id": "27617",
"ParentId": "27613",
"Score": "4"
}
},
{
"body": "<p>The other two have made all the points I would have made.</p>\n\n<p>I would strongly follow the advice of <code>@Lstor</code> to make the a <code>Game</code> class.</p>\n\n<p>The only addition I have is about reading user input.<br>\nWhen dealing with user input (manual were errors can happen) it is best to deal with line input (users are used to typing something followed by a return). So write your code on the same model. When user input is expected read a line and validate. If its not what you expect print an error and try again.</p>\n\n<p>The issue with <code>operator>></code> for interactive user input is that it often leaves <code>\\n</code> character on the input (or when you least expect it skips passed the <code>\\n</code> (or multiple <code>\\n</code>) looking for more user input)`.</p>\n\n<pre><code> std::string line;\n do \n {\n std::cout << \"Do you want to continue 'Y/N'\\n\";\n std::getline(std::cin, line); // Get users input.\n std::transform(line.begin(), line.end(), ::toupper); // uppercase answer\n }\n while (line != \"Y\" || line != \"N\");\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T19:04:40.967",
"Id": "27671",
"ParentId": "27613",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "27614",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T01:13:12.033",
"Id": "27613",
"Score": "7",
"Tags": [
"c++",
"game",
"number-guessing-game"
],
"Title": "Console guess game"
}
|
27613
|
<p>It works and does what is supposed what to do btw.</p>
<pre><code><?php
ob_start();
session_start();
include("php/connect.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Welcome to albsocial</title>
<link rel="stylesheet" href="css/main.css"/>
<link rel="stylesheet" href="css/menubar.css"/>
<script type="text/javascript" src="../js/analytic.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<script type="text/javascript">
setTimeout(function() {
$('#error_check').fadeOut('slow');
}, 5000);
</script>
<body>
<div id="header">
<div id="user_logged">
</div>
<?php
if(isset($_SESSION['username']) && $_SESSION['username'] != ''){
if(!isset($_GET['user'])){
echo "
<div id='ligat'>
<ul>
<li class='first'><a href='seria.php'>Seria A</a></li>
<li><a href='laliga.php'>La liga</a></li>
<li><a href='#'>Premier Liga</a></li>
<li><a href='#'>Bundesliga</a></li>
<li><a href='#'>Ligue 1</a></li>
</ul>
</div>
";
}
}else{
echo "";
}
?>
</div>
</div>
<div id="wrapper">
<div id="logo">
<a href="/">Albsocial</a>
</div>
<div id="login">
<?php
if (isset($_SESSION['username']) && $_SESSION['username'] != ''){
$username = $_SESSION['username'];
echo "<h4><a href='member.php?user=".$username."'>".$username."</a></h4><a href='logout.php'>LogOut</a>";
}else{
echo "<a href='login.php'>Login</a> <a href='#'>Register</a>";
}
?>
</div>
<div id="menubar">
<?php include("php/bar.php");?>
</div>
<div id="content_wrap">
<div id="content_member">
<?php
//MARRIM USERNAME QE E VEJM NE ADRESS BARS
if (isset($_GET['user'])){
$username = mysql_real_escape_string($_GET['user']);
if(ctype_alnum($username)){
$check = "SELECT `username` FROM user WHERE username='$username'";
$get = mysql_query($check)or die(mysql_error());
if(mysql_num_rows($get)===1){
$row = mysql_fetch_assoc($get);
$username = $row['username'];
}else{
echo "Ky profil nuk ekziston.";
}
}
}
?>
<?php
if (isset($_SESSION['username']) && $_SESSION['username'] != ''){
if (!isset($_GET['user'])){
//Ndeshjet e fituara ose jo
echo "<h3>Ndeshjet e vendosura nga <b>$username</b> dhe Rezultatet:</h3><br/>";
$matches = "SELECT * FROM match_select WHERE user_id='$username'";
$query_match = mysql_query($matches)or die(mysql_error());
while ($row = mysql_fetch_assoc($query_match)){
$id = $row['match_id'];
$liga = $row['liga'];
if ($row['result'] == $row['final']){
$hey = "style='color: green;' ";
$match = "SELECT * FROM `winner` WHERE `user_id` = '$username' AND `match_id` = '$id' AND `liga`='$liga'";
$matchResult = mysql_query($match)or die(mysql_error());
if($_POST['submit']){
if(mysql_num_rows($matchResult)) {
$error1 = "<div id='error_check'>I keni marre piket ose Nuk jeni fitues.</div>";
}else{
mysql_query("INSERT INTO winner (user_id, match_id, final, liga) VALUE ('$username','$id', '1', '$liga')");
$error1 = "<div id='error_check'>Piket u shtuan ne database</div>";
}
}
}else if($row['final'] == ""){
$hey = " style='color: #333;'";
$n = "?";
}else{
$hey = " style='color: red;'";
}
echo "
<div id='my_selection'><h4>
".$home = $row['home']."
-
".$away = $row['away']." -
".$input = $row['result'] ."
</h4>
</div>
<div id='results'>
<h4 $hey>".$home = $row['home']."
-
".$away = $row['away']."
-
".$result = $row['final']." $n
</h4>
</div>
";
}
echo $error1;
echo "
<form action='member.php' method='post'>
<input type='submit' name='submit[$id]' id='match_check' value='Terhiq Piket'>
</form>
";
}
}else{
header("Location: index.php");
}
?>
</div>
<?php if(!isset($_GET['user'])){
$result = mysql_query("SELECT SUM(final) AS value_sum FROM winner WHERE user_id='$username'");
$row = mysql_fetch_assoc($result);
$sum = $row['value_sum'];
$resul1 = mysql_query("SELECT SUM(dummy) AS value FROM match_select WHERE user_id='$username'");
$row1 = mysql_fetch_assoc($resul1);
$dummy = $row1['value'];
if($dummy['value'] == ""){
echo "";
}else{
echo "
<div id='adds'>
<h3>Statistikat e $username</h3>
<br/>
<h4 style='margin-left: 10px;'>Gjithsej keni vene: ".$dummy." ndeshje.
<br/>
<br/>
Te sakta jane: ".$sum1 = $sum1 + $sum['test_value']." ndeshje.
<br/>
<br/>
Te pa sakta ose akoma skane mbaruar jane: ".$no = $dummy - $sum['test_value']." ndeshje.
</h4>
</div>
";
}
}
?>
</div>
</div>
<div id="footer">
<div id="footerWrapp">
<div id="copyrights"><center>©Te gjitha te drejtat jane te rezervuara nga <a href="#">ALALA</a> , 2013</center></div>
</div>
</div>
</body>
</html>
</code></pre>
|
[] |
[
{
"body": "<p>It was not easy, but the first step for improving your code is to split the layout from the logic:</p>\n\n<p>layout.php</p>\n\n<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\n<head>\n <title>Welcome to albsocial</title>\n <link rel=\"stylesheet\" href=\"css/main.css\"/>\n <link rel=\"stylesheet\" href=\"css/menubar.css\"/>\n <script type=\"text/javascript\" src=\"../js/analytic.js\"></script>\n <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js\"></script>\n</head>\n<script type=\"text/javascript\">\n setTimeout(function() {\n $('#error_check').fadeOut('slow');\n }, 5000);\n</script>\n<body>\n\n <div id=\"header\">\n <div id=\"user_logged\">\n <!--removed div//-->\n <?php if($noUserAndLoggedIn) :?>\n <div id='ligat'>\n <ul>\n <li class='first'><a href='seria.php'>Seria A</a></li>\n <li><a href='laliga.php'>La liga</a></li>\n <li><a href='#'>Premier Liga</a></li>\n <li><a href='#'>Bundesliga</a></li>\n <li><a href='#'>Ligue 1</a></li>\n </ul>\n </div>\n <? endif ?>\n </div>\n </div>\n\n <div id=\"wrapper\">\n <div id=\"logo\"><a href=\"/\">Albsocial</a></div>\n <div id=\"login\">\n <?php if ($isLoggedin) :?>\n <h4><a href='member.php?user=\".$username.\"'><?=$username?></a></h4><a href='logout.php'>LogOut</a>\";\n <?php else: ?>\n <a href='login.php'>Login</a> <a href='#'>Register</a>\n <?php endif: ?>\n </div>\n\n <div id=\"menubar\">\n <?php include(\"php/bar.php\");?>\n </div>\n\n <div id=\"content_wrap\">\n <div id=\"content_member\">\n <?php if ( $unknownUser ) :?> Ky profil nuk ekziston. <?php endif ?>\n\n <?php if ($noUserAndLoggedIn) :?>\n <h3>Ndeshjet e vendosura nga <b>$username</b> dhe Rezultatet:</h3><br/>\n <?php foreach ($lines as $line): ?>\n <div id='my_selection'>\n <h4><?=$line['selection']['home']?> - <?=$line['selection']['away']?> - <?=$line['selection']['result']?></h4>\n </div>\n <div id='results'>\n <h4 style='color: <?=$line['result']==1?'green':(($line['result']==-1)?'red':'#333')?> ;'>\n <?=$line['result']['home']?> - <?=$line['result']['away']?> - <?=$line['result']['final']?>\n <?php if ($line['result']['uncertain']): ?>?<?php endif;?>\n </h4>\n </div>\n <?php if ($line['error']!=null): ?>?<?=$line['error'];?>\n\n <form action='member.php' method='post'>\n <input type='submit' name='submit[<?=$line['id'];?>' id='match_check' value='Terhiq Piket'>\n </form>\n <?php endforeach; ?>\n <?php endif; ?>\n </div>\n\n <?php if($noUser && $stats!=null):?>\n <div id='adds'> \n <h3>Statistikat e $username</h3>\n <br/>\n <h4 style='margin-left: 10px;'>Gjithsej keni vene: <?=$stats['s1']?> ndeshje.\n <br/> \n <br/>\n Te sakta jane: <?=$stats['s2']?> ndeshje.\n <br/>\n <br/>\n Te pa sakta ose akoma skane mbaruar jane: <?=$stats['s3']?> ndeshje.\n </h4>\n </div>\n <?php endif; ?>\n </div>\n </div>\n <div id=\"footer\">\n <div id=\"footerWrapp\">\n <div id=\"copyrights\"><center>©Te gjitha te drejtat jane te rezervuara nga <a href=\"#\">ALALA</a> , 2013</center></div>\n </div>\n </div>\n</body>\n</html>\n</code></pre>\n\n<p>content.php</p>\n\n<pre><code><?\n$isLoggedin=isset($_SESSION['username']) && $_SESSION['username'] != '';\nif (!$isLoggedin) \n{\n header(\"Location: index.php\");\n die();\n}\n$noUser=!isset($_GET['user'])\n$noUserAndLoggedIn= $isLoggedin && $noUser;\n\n$username = $isLoggedin?$_SESSION['username']:\"\";\n\n$unknownUser=false;\n if (isset($_GET['user'])) {\n $username = mysql_real_escape_string($_GET['user']);\n if(ctype_alnum($username)){\n $check = \"SELECT `username` FROM user WHERE username='$username'\";\n $get = mysql_query($check)or die(mysql_error());\n\n if(mysql_num_rows($get)===1){\n $row = mysql_fetch_assoc($get);\n $username = $row['username'];\n }else{\n $unknownUser=true;\n }\n }\n}\n\n$lines=array();\nif ($noUserAndLoggedIn) {\n $matches = \"SELECT * FROM match_select WHERE user_id='$username'\";\n $query_match = mysql_query($matches)or die(mysql_error());\n while ($row = mysql_fetch_assoc($query_match)){\n $id = $row['match_id'];\n $liga = $row['liga']; \n $uncertain = false; \n $error1=null;\n if ($row['result'] == $row['final']){\n $hey = 1;\n\n $match = \"SELECT * FROM `winner` WHERE `user_id` = '$username' AND `match_id` = '$id' AND `liga`='$liga'\";\n $matchResult = mysql_query($match)or die(mysql_error());\n\n if($_POST['submit']){\n if(mysql_num_rows($matchResult)) {\n $error1 = \"I keni marre piket ose Nuk jeni fitues.\";\n }else{\n mysql_query(\"INSERT INTO winner (user_id, match_id, final, liga) VALUE ('$username','$id', '1', '$liga')\"); \n $error1 = \"Piket u shtuan ne database\";\n } \n }\n\n }else if($row['final'] == \"\"){ \n $hey = 0; \n $uncertain = true;\n }else{\n $hey = -1;\n }\n\n $lines[]=array('selection'=>array ('home'=>$row['home'],'away'=>$row['away'],'result'=>$row['result']),\n 'result'=>array ('home'=>$row['home'],'away'=>$row['away'],'result'=>$row['final'],'uncertain'=>$uncertain),\n 'error'=>$error1,\n 'status'=>$hey,\n 'id'=>$id);\n\n }\n}\n$stats=null;\nif ($noUser) {\n $result = mysql_query(\"SELECT SUM(final) AS value_sum FROM winner WHERE user_id='$username'\"); \n $row = mysql_fetch_assoc($result); \n $sum = $row['value_sum'];\n\n $resul1 = mysql_query(\"SELECT SUM(dummy) AS value FROM match_select WHERE user_id='$username'\");\n $row1 = mysql_fetch_assoc($resul1);\n $dummy = $row1['value'];\n\n if ($dummy != \"\"){\n $stats=array(\n 's1'=>$dummy, \n 's2'=>$sum1 + $sum['test_value'], \n 's3'=>$dummy - $sum['test_value']\n ); //better names!! but I don't understand you language\n }\n}\n\ninclude \"layout.php\";\n</code></pre>\n\n<p>Now you have a separate file for the representation of your data and one for the calculation. The first file is now only a simple template without any business logic. In the words of the Model-View-Controller paradigm this is the view. The model and the controller are now combined in your content.php.</p>\n\n<p>In a second step you would split the content.php into two files. One is getting the data from your database (model) and the other is connecting the data from the database with then view (controller).</p>\n\n<p>Unfortunately I have no time to continue this at this point. But after you have splitted this file we should concentrate on some conceptual details. But this will be far easier than now, if the responsibility are divided into this three files.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T12:31:12.253",
"Id": "43078",
"Score": "0",
"body": "Would've given +2 if I could.. :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T10:14:43.073",
"Id": "43103",
"Score": "0",
"body": "Beautiful work my friend .. THanks a bunch man"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T11:41:21.577",
"Id": "27627",
"ParentId": "27615",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "27627",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T05:12:01.453",
"Id": "27615",
"Score": "1",
"Tags": [
"php",
"sql",
"authentication",
"session"
],
"Title": "Social football site with authentication and user statistics"
}
|
27615
|
<p>I am trying to make a textbox which filters user input to match specified type, so I can discard some of my validation logic.</p>
<p>For example, if I specify <code>ushort</code> I want my textbox to only accept text changes which result in a valid <code>ushort</code> value and nothing else.</p>
<p>This is what I've ended up with:</p>
<pre><code>public abstract class CustomTextBox<T> : TextBox
{
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(T), typeof(CustomTextBox<T>), new FrameworkPropertyMetadata(default(T), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Inherits, OnValueChanged));
public T Value
{
get { return (T)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e)
{
if (_regex != null && !_regex.IsMatch(e.Text))
{
e.Handled = true;
}
else
{
base.OnPreviewTextInput(e);
}
}
protected override void OnTextChanged(TextChangedEventArgs e)
{
if (String.IsNullOrEmpty(Text))
{
return;
}
T val;
if (!TryParse(out val))
{
var index = CaretIndex;
Text = _validText;
CaretIndex = index > 0 ? index - 1 : 0;
e.Handled = true;
}
else
{
Value = val;
_validText = Text;
}
}
protected CustomTextBox(string regexPattern = null)
{
if (!String.IsNullOrEmpty(regexPattern))
{
_regex = new Regex(regexPattern);
}
_validText = ToString(Value);
Loaded += OnTextboxLoaded;
}
protected override void OnLostFocus(RoutedEventArgs e)
{
ValidateText();
base.OnLostFocus(e);
}
protected virtual string ToString(T value)
{
return value.ToString();
}
protected abstract bool TryParse(out T val);
private readonly Regex _regex;
private string _validText;
private void ValidateText()
{
T val;
if (!TryParse(out val))
{
Text = ToString(Value);
}
}
private void OnTextboxLoaded(object sender, RoutedEventArgs e)
{
ValidateText();
}
private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var tb = (CustomTextBox<T>)d;
if (!e.OldValue.Equals(e.NewValue))
{
var str = tb.ToString((T)e.NewValue);
if (!str.Equals(tb.Text))
{
tb.Text = str;
}
}
}
}
</code></pre>
<p><code>ushort</code> implementation:</p>
<pre><code>public sealed class UshortTextBox : CustomTextBox<ushort>
{
public UshortTextBox()
: base(@"^[0-9]$")
{
}
protected override bool TryParse(out ushort val)
{
return UInt16.TryParse(Text, out val);
}
}
</code></pre>
<p>I'm new to this whole custom-control-making, so if you see some rookie mistakes or ways to improve my code, please let me know.</p>
|
[] |
[
{
"body": "<p>I think what your code is missing the most is documentation and some better naming. The constructor takes a regex string (with a very generic name <code>regexPattern</code>) and you <em>also</em> have to override <code>TryParse()</code>. There is absolutely no indication of why both are needed, without looking at the source of <code>CustomTextBox</code>.</p>\n\n<p>Also, the name <code>CustomTextBox</code> pretty much doesn't say anything, I think you should think of a better name for it, one that actually describes how is the type different from normal <code>TextBox</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T11:45:27.627",
"Id": "27628",
"ParentId": "27620",
"Score": "2"
}
},
{
"body": "<p>I think you can avoid inheritance here (\"Favor Composition Over Inheritance\") and use Attached Behavior instead. </p>\n\n<p>Also, did you take a look at MaskedTextBox from Extended WPF Toolkit (<a href=\"http://wpftoolkit.codeplex.com/wikipage?title=MaskedTextBox\" rel=\"nofollow\">http://wpftoolkit.codeplex.com/wikipage?title=MaskedTextBox</a>)?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T06:33:21.533",
"Id": "43394",
"Score": "0",
"body": "Yes, i did look at the masked textbox, but it is not quite what i needed. It filters input, based on string format specified. And i wanted to filter input, based on parsing logic of specified type. But i kind of like your idea about attached behaviors. I've never made my own, but i'll certainly give it a try. Hopefully i will be able to keep my implementation generic. Thx for your answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T19:38:26.067",
"Id": "27816",
"ParentId": "27620",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "27816",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T08:23:14.993",
"Id": "27620",
"Score": "5",
"Tags": [
"c#",
"wpf"
],
"Title": "Filtered WPF textbox"
}
|
27620
|
<p>I am working on a project that needs algebra operations. I have coded a <code>Matrix</code> class (only needed 4x4 matrix), and a <code>Vector4</code> class. The classes working fine, but I would know if there are some bad practices that I use, and want you to help me improve this classes. Last time I encountered some problem when wanted to code something like this:</p>
<pre><code>Matrix m; // (4x4 matrix)
Vector4 v; // (4-elements vector)
m(0) = v; // replace first 4-elements matrix row by vector v
v = m(0); // replace vector v by first 4-elements matrix row
</code></pre>
<p>I found some solution to get this to work:</p>
<p><strong>Matrix.h</strong></p>
<pre><code>#pragma once
#include <cmath>
#include "Vector3.h"
#include "Vector4.h"
class Matrix
{
public:
Matrix();
Matrix(float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float);
Matrix(float m[16]);
Matrix(const Vector4& v1, const Vector4& v2, const Vector4& v3, const Vector4& v4);
~Matrix() {}
const Matrix operator* ( const Matrix &m) const;
float& operator() (unsigned row, unsigned col);
float operator() (unsigned row, unsigned col) const;
Vector4 operator() (unsigned row);
Vector4 operator() (unsigned row) const;
void translate(float x, float y, float z);
void translate(const Vector3 &v);
void rotate(float a, const Vector3& v);
void transpose();
const static Matrix IDENTITY;
static Matrix createTranslation(const Vector3 &v);
static Matrix createTranslation(float x, float y, float z);
static Matrix createScale(const Vector3 &v);
static Matrix createScale(float x, float y, float z);
static Matrix createRotationX(float a);
static Matrix createRotationY(float a);
static Matrix createRotationZ(float a);
static Matrix createRotation(float a, const Vector3& v);
static Matrix createLookAt(const Vector3& eye, const Vector3& center, const Vector3& up);
static Matrix createPerspective(float fovy, float aspect, float near, float far);
// Euler angles //
inline float getRoll() {return atan2(-(*this)(2,0),(*this)(0,0));} // X //
inline float getPitch() {return asin((*this)(1,0));} // Y //
inline float getYaw() {return atan2(-(*this)(1,2),(*this)(1,1));} // Z //
void show();
private:
float mat[4][4];
};
</code></pre>
<p><strong>Matrix.cpp</strong></p>
<pre><code>#include "Matrix.h"
#include <iostream>
#include "Math.h"
const Matrix Matrix::IDENTITY = Matrix(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);
Matrix::Matrix()
{
*this = IDENTITY;
}
Matrix::Matrix(float _00,float _01,float _02,float _03,float _10,float _11,float _12,float _13,float _20,float _21,float _22,float _23,float _30,float _31,float _32,float _33)
{
(*this)(0,0) = _00;
(*this)(0,1) = _01;
(*this)(0,2) = _02;
(*this)(0,3) = _03;
(*this)(1,0) = _10;
(*this)(1,1) = _11;
(*this)(1,2) = _12;
(*this)(1,3) = _13;
(*this)(2,0) = _20;
(*this)(2,1) = _21;
(*this)(2,2) = _22;
(*this)(2,3) = _23;
(*this)(3,0) = _30;
(*this)(3,1) = _31;
(*this)(3,2) = _32;
(*this)(3,3) = _33;
}
Matrix::Matrix(float m[16])
{
int index = 0;
for ( int i = 0; i < 4; ++i)
for ( int j = 0; j < 4; ++j)
{
(*this)(i,j) = m[index++];
}
}
Matrix::Matrix(const Vector4& v1, const Vector4& v2, const Vector4& v3, const Vector4& v4)
{
(*this)(0) = v1;
(*this)(1) = v2;
(*this)(2) = v3;
(*this)(3) = v4;
}
float& Matrix::operator() (unsigned row, unsigned col)
{
return mat[row][col];
}
float Matrix::operator() (unsigned row, unsigned col) const
{
return mat[row][col];
}
// this one only needed for something like this: m(0) = Vector4(1,1,1,1) //
Vector4 Matrix::operator() (unsigned row)
{
return Vector4 (&mat[row][0], &mat[row][1], &mat[row][2], &mat[row][3]);
}
Vector4 Matrix::operator() (unsigned row) const
{
return Vector4 (mat[row][0], mat[row][1], mat[row][2], mat[row][3]);
}
const Matrix Matrix::operator* ( const Matrix &m) const
{
Matrix a;
float sum;
for ( int i = 0; i < 4; ++i)
for ( int j = 0; j < 4; ++j)
{
sum = 0;
for ( int k = 0; k < 4; ++k)
sum += (*this)(k,i) * m(j,k);
a(j,i) = sum;
}
return a;
}
void Matrix::translate(float x, float y, float z)
{
float xx = ( x * (*this)(0,0) + y * (*this)(1,0) + z * (*this)(2,0) );
float yy = ( x * (*this)(0,1) + y * (*this)(1,1) + z * (*this)(2,1) );
float zz = ( x * (*this)(0,2) + y * (*this)(1,2) + z * (*this)(2,2) );
float ww = ( x * (*this)(0,3) + y * (*this)(1,3) + z * (*this)(2,3) );
(*this)(3,0) += xx;
(*this)(3,1) += yy;
(*this)(3,2) += zz;
(*this)(3,3) += ww;
}
void Matrix::translate(const Vector3 &v)
{
this->translate(v.x, v.y, v.z);
}
void Matrix::transpose()
{
Matrix trans;
for( int i = 0 ; i < 4 ; ++i )
for( int j = 0 ; j < 4 ; ++j )
trans.mat[i][j] = this->mat[j][i];
(*this) = trans;
}
void Matrix::show()
{
std::cout << std::endl;
for ( int i = 0; i < 4; ++i)
{
for ( int j = 0; j < 4; ++j)
std::cout << this->mat[i][j] << " ";
std::cout << std::endl;
}
}
Matrix Matrix::createTranslation(const Vector3 &v)
{
return Matrix
(
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
v.x, v.y, v.z, 1
);
}
Matrix Matrix::createTranslation(float x, float y, float z)
{
return Matrix::createTranslation(Vector3(x,y,z));
}
Matrix Matrix::createScale(const Vector3 &v)
{
return Matrix
(
v.x, 0, 0, 0,
0, v.y, 0, 0,
0, 0, v.z, 0,
0, 0, 0, 1
);
}
Matrix Matrix::createScale(float x, float y, float z)
{
return Matrix::createScale(Vector3(x,y,z));
}
Matrix Matrix::createRotationX(float a)
{
return Matrix
(
1, 0, 0, 0,
0, cos(a), sin(a), 0,
0, -sin(a), cos(a), 0,
0, 0, 0, 1
);
}
Matrix Matrix::createRotationY(float a)
{
return Matrix
(
cos(a), 0, -sin(a), 0,
0, 1, 0, 0,
sin(a), 0, cos(a), 0,
0, 0, 0, 1
);
}
Matrix Matrix::createRotationZ(float a)
{
return Matrix
(
cos(a), sin(a), 0, 0,
-sin(a), cos(a), 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
);
}
Matrix Matrix::createRotation(float angle, const Vector3& v)
{
float a = angle;
float c = cos(a);
float s = sin(a);
Vector3 axis = v;
axis.normalize();
Vector3 temp = axis * (1.0f - c);
Matrix Rotate;
Rotate(0,0) = c + temp.x * axis.x;
Rotate(0,1) = 0 + temp.x * axis.y + s * axis.z;
Rotate(0,2) = 0 + temp.x * axis.z - s * axis.y;
Rotate(1,0) = 0 + temp.y * axis.x - s * axis.z;
Rotate(1,1) = c + temp.y * axis.y;
Rotate(1,2) = 0 + temp.y * axis.z + s * axis.x;
Rotate(2,0) = 0 + temp.z * axis.x + s * axis.y;
Rotate(2,1) = 0 + temp.z * axis.y - s * axis.x;
Rotate(2,2) = c + temp.z * axis.z;
Matrix identity;
Matrix m;
m(0) = (identity)(0) * Rotate(0,0) + (identity)(1) * Rotate(0,1) + (identity)(2) * Rotate(0,2);
m(1) = (identity)(0) * Rotate(1,0) + (identity)(1) * Rotate(1,1) + (identity)(2) * Rotate(1,2);
m(2) = (identity)(0) * Rotate(2,0) + (identity)(1) * Rotate(2,1) + (identity)(2) * Rotate(2,2);
m(3) = (identity)(3);
return m;
}
void Matrix::rotate(float angle, const Vector3& v)
{
float a = angle;
float c = cos(a);
float s = sin(a);
Vector3 axis = v;
axis.normalize();
Vector3 temp = axis * (1.0f - c);
Matrix Rotate;
Rotate(0,0) = c + temp.x * axis.x;
Rotate(0,1) = 0 + temp.x * axis.y + s * axis.z;
Rotate(0,2) = 0 + temp.x * axis.z - s * axis.y;
Rotate(1,0) = 0 + temp.y * axis.x - s * axis.z;
Rotate(1,1) = c + temp.y * axis.y;
Rotate(1,2) = 0 + temp.y * axis.z + s * axis.x;
Rotate(2,0) = 0 + temp.z * axis.x + s * axis.y;
Rotate(2,1) = 0 + temp.z * axis.y - s * axis.x;
Rotate(2,2) = c + temp.z * axis.z;
Matrix m;
m(0) = (*this)(0) * Rotate(0,0) + (*this)(1) * Rotate(0,1) + (*this)(2) * Rotate(0,2);
m(1) = (*this)(0) * Rotate(1,0) + (*this)(1) * Rotate(1,1) + (*this)(2) * Rotate(1,2);
m(2) = (*this)(0) * Rotate(2,0) + (*this)(1) * Rotate(2,1) + (*this)(2) * Rotate(2,2);
m(3) = (*this)(3);
*this = m;
}
Matrix Matrix::createLookAt(const Vector3& eye, const Vector3& center, const Vector3& up)
{
Vector3 f = center - eye;
f.normalize();
Vector3 u = up;
u.normalize();
Vector3 s = Vector3::cross(f, u);
s.normalize();
u = Vector3::cross(s, f);
Matrix Result;
Result(0,0) = s.x;
Result(1,0) = s.y;
Result(2,0) = s.z;
Result(0,1) = u.x;
Result(1,1) = u.y;
Result(2,1) = u.z;
Result(0,2) = -f.x;
Result(1,2) = -f.y;
Result(2,2) = -f.z;
Result(3,0) = -Vector3::dot(s, eye);
Result(3,1) = -Vector3::dot(u, eye);
Result(3,2) = Vector3::dot(f, eye);
Result(3,3) = 1.0f;
return Result;
}
Matrix Matrix::createPerspective(float fovy, float aspect, float near, float far)
{
float angle = (fovy / 180.0f) * PI;
float f = 1.0f / tan( angle * 0.5f );
return Matrix
(
f/aspect, 0, 0, 0,
0, f, 0, 0,
0, 0, (far+near)/(near-far), -1,
0, 0, 2*far*near/(near-far), 0
);
}
</code></pre>
<p><strong>Vector4.h</strong></p>
<pre><code>#pragma once
#include "Vector3.h"
#include <iostream>
class Vector4 : public Vector3
{
public:
Vector4();
Vector4(float x, float y, float z, float w);
Vector4(float x, float y, float z);
Vector4(float* x, float* y, float* z, float* w);
~Vector4() {}
Vector4 operator= ( const Vector4& v);
const Vector4 operator* ( const float &scalar) const;
const Vector4 operator+ (const Vector4 &v) const;
inline void show() {std::cout << this->x << " " << this->y << " " << this->z << " " << this->w << std::endl;}
private:
float w;
// only to allow do that: m(0) = Vector4(1,1,1,1) //
float* px;
float* py;
float* pz;
float* pw;
bool pointer; // to check what constructor was called //
};
</code></pre>
<p><strong>Vector4.cpp</strong></p>
<pre><code>#include "Vector4.h"
Vector4::Vector4()
{
x = 0.0f;
y = 0.0f;
z = 0.0f;
w = 1.0f;
pointer = false;
}
Vector4::Vector4 (float x, float y, float z, float w)
{
this->x = x; this->y = y; this->z = z; this->w = w;
pointer = false;
}
Vector4::Vector4 (float x, float y, float z)
{
this->x = x; this->y = y; this->z = z; this->w = 1.0f;
pointer = false;
}
Vector4::Vector4(float* x, float* y, float* z, float* w)
{
this->px = x; this->py = y; this->pz = z; this->pw = w;
this->x = *x; this->y = *y; this->z = *z; this->w = *w;
pointer = true;
}
Vector4 Vector4::operator= ( const Vector4& v)
{
if ( pointer )
{
*px = x = v.x;
*py = y = v.y;
*pz = z = v.z;
*pw = w = v.w;
}
else
{
x = v.x;
y = v.y;
z = v.z;
w = v.w;
}
}
const Vector4 Vector4::operator* ( const float &scalar) const
{
return Vector4(x*scalar, y*scalar, z*scalar, w*scalar);
}
const Vector4 Vector4::operator+ (const Vector4 &v) const
{
Vector4 vec;
vec.x = this->x + v.x;
vec.y = this->y + v.y;
vec.z = this->z + v.z;
vec.w = this->w + v.w;
return vec;
}
</code></pre>
<p>You can see that <code>Vector4</code> has some funny methods. Is there a better solution to write that code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T04:17:51.583",
"Id": "387120",
"Score": "1",
"body": "How come `w` is `1.0f` by default instead of `0.0f` like the other components?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T19:38:31.253",
"Id": "387154",
"Score": "0",
"body": "Hi @AaronFranke, right now I don't remember why the default value for `w` is `1.0` as I was programming this 5 years ago, but probably you have right and it should also be `0.0`"
}
] |
[
{
"body": "<p>For the <code>Matrix</code>, I’d consider replacing the 16 <code>float</code> constructor with an <code>initializer_list</code> constructor, and adding a copy constructor.</p>\n\n<p>I agree that your <code>Vector4</code> class is rather ugly. Two ways of accomplishing what you want:</p>\n\n<ol>\n<li>Define a <code>MatrixRow</code> proxy class (e.g. storing a reference to the Matrix and a row number) with a <code>Vector4</code> assignment operator.</li>\n<li>Fundamentally reorganize your <code>Matrix</code> and <code>Vector4</code> classes to make them <em>views</em> into an underlying, reference counted, storage object, so the row <code>Vector4</code> shares the storage object of the <code>Matrix</code>, along with an offset into it. The exact details of this can be rather intricate, but I hope you get the general idea. </li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T17:34:12.947",
"Id": "43116",
"Score": "0",
"body": "Thank you for your answer, I thought about an initializer_list, but how can I be sure that the list has exactly 16 elements in compile-time? ...or maybe I just don't need to know the list size at the compile-time"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T19:08:24.143",
"Id": "43130",
"Score": "0",
"body": "That’s a good question. Not sure whether such a constraint can be enforced, or whether one would just zero-pad / truncate otherwise."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T11:41:26.567",
"Id": "27661",
"ParentId": "27625",
"Score": "2"
}
},
{
"body": "<p>Don't write the destructor if you don't need it:</p>\n\n<pre><code>~Matrix() {}\n</code></pre>\n\n<p>This is ugly:</p>\n\n<pre><code>Vector4::Vector4 (float x, float y, float z, float w)\n{\n this->x = x; this->y = y; this->z = z; this->w = w;\n pointer = false;\n}\n\n// try:\n\nVector4::Vector4 (float x, float y, float z, float w)\n : x(x), y(y), z(z), w(w)\n , pointer(false)\n{}\n</code></pre>\n\n<p>Don't bother to use the <code>inline</code> keyword.</p>\n\n<pre><code>inline float getRoll() {return atan2(-(*this)(2,0),(*this)(0,0));} // X //\ninline float getPitch() {return asin((*this)(1,0));} // Y //\ninline float getYaw() {return atan2(-(*this)(1,2),(*this)(1,1));} // Z //\n</code></pre>\n\n<p>The code is automatically declared as inline inside the class. The keyword has no real meaning in terms of the compiler in-lining your code. Humans are useless at understanding when in-lining should (should not be done). So let the machine work it out.</p>\n\n<p>Rather than just being able to dump to stdard out. You may want to pramertize that with any stream. Also provide a standard <code>operator<<()</code> that calls it.</p>\n\n<pre><code>void show(std::ostream& out = std::cout);\n\nstd::ostream& operator<<(std::ostream& stream, Matrix const& m)\n{\n m.show(stream);\n return stream;\n}\n</code></pre>\n\n<p>I don't like the duality of Vector4.<br>\nYou have controlled it by allowing very limited access into the class. But with a slight tweak you can make the pointer representation the normal without worrying about leaking (any more than you do currently).</p>\n\n<ol>\n<li>If you pass it pointer to the constructor use those.</li>\n<li>If you pass in values save them locally but set the pointers up to point at the internal values.</li>\n<li>When doing operations always use them via the pointers (as the pointers point at the correct place always).</li>\n</ol>\n\n<p>Look like this now:</p>\n\n<pre><code>Vector4::Vector4()\n : x(0f), y(0f), z(0f), w(0f)\n , px(&x), py(&y), pz(&z), pw(&w)\n{}\n\nVector4::Vector4 (float ix, float iy, float iz, float iw = 1.0f)\n : x(ix), y(iy), z(iz), w(iw)\n , px(&x), py(&y), pz(&z), pw(&w)\n{}\n\nVector4::Vector4(float* ix, float* iy, float* iz, float* iw)\n : x(0f), y(0f), z(0f), w(0f)\n , px(ix), py(iy), pz(iz), pw(iw)\n{}\n\n// This should now always work as expected.\nVector4 Vector4::operator= ( const Vector4& v)\n{\n *px = *v.px;\n *py = *v.py;\n *pz = *v.pz;\n *pw = *v.pw;\n}\n</code></pre>\n\n<p>I would go one step further.<br>\nConsider converting the pointers into references (this only works if the pointers should never be NULL). But it seems like that is the case and will make the code even more readable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T19:13:26.270",
"Id": "27672",
"ParentId": "27625",
"Score": "3"
}
},
{
"body": "<p>Small additional point that was not mentioned in the other answers: since your classes have non trivial constructors, they are not considered as POD (<a href=\"http://en.cppreference.com/w/cpp/concept/PODType\" rel=\"nofollow noreferrer\">http://en.cppreference.com/w/cpp/concept/PODType</a>), which by itself is not much of a problem. But, that means that your IDENTITY constant will not be stored in the static data section. It will be initialised at the start of the program. And unfortunately, the order of global constant initialisation in C++ is not defined. So if in another module you define another constant which relies on IDENTITY to be constructed, it may use it before it's defined, and lead to some weird behaviour.</p>\n\n<p>I ran into that problem myself a few days ago, and lost 2h trying to figure out what was happening. So I'd just thought I share.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-07T07:31:50.543",
"Id": "326474",
"Score": "0",
"body": "Thank you for sharing your knowledge, these are definitely useful information"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-06T06:48:33.023",
"Id": "172208",
"ParentId": "27625",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27672",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T11:12:10.640",
"Id": "27625",
"Score": "2",
"Tags": [
"c++",
"matrix"
],
"Title": "Matrix and Vector4 classes"
}
|
27625
|
<p>This Lua code runs in redis. It iterates over some JSON docs, and applies some logic based on the user (if any) making the request. I'm sure there's a lot I can improve here.</p>
<pre><code>local function iterAll(limit)
local start = 0
local stop = limit-1
local ids = redis.call('zrevrange', 'questions-by-latest', start, stop)
local i = 0
local function it()
i = i+1
if i <= #ids then
return ids[i]
elseif i > #ids then
start = start+limit
stop = stop+limit
i = 1
ids = redis.call('zrevrange', 'questions-by-latest', start, stop)
if #ids > 0 then
return ids[i]
end
end
end
return it
end
local function filter(qid, optUid)
local q = cjson.decode(redis.call('hget', 'questions', qid))
if not q['is-active'] then return false end
if optUid then
local u = cjson.decode(redis.call('hget', 'users', optUid))
if #u['ignored-tags'] > 0 then
for idx, itag in ipairs(u['ignored-tags']) do
for jdx, qtag in ipairs(q['tags']) do
if itag == qtag then return false end
end
end
end
end
return true
end
local offset = tonumber(ARGV[1])
local limit = tonumber(ARGV[2])
local optUid = false
if #ARGV == 3 then
optUid = tonumber(ARGV[3])
end
local i = 0
local j = 0
local ids = {}
for qid in iterAll(limit) do
if filter(qid, optUid) then
i = i+1
if i > (offset+limit) then break end
if i > offset then
j = j+1
ids[j] = qid
end
end
end
return ids
</code></pre>
|
[] |
[
{
"body": "<p>Firstly, you've hard-coded all of your key names instead of using the <code>KEYS</code> table for passing them to the script - this is both hard to maintain as well as incompatible with clustering.</p>\n\n<p>Next, consider using MessagePack (<code>cmsgpack</code> in Redis' Lua) instead of JSON when serialiazing/deserializing questions (<code>q</code>) and users (<code>u</code>) - it is leaner and faster.</p>\n\n<p>Also, the <code>jdx, qtag</code> loop looks like a membership test, so it should be replaced with a check against an associative table instead.</p>\n\n<p>Overall, the code appears to be quite complex with multiple nested loops. Without more information on the values' sizes, it is hard to make an educated guess whether this is a viable approach, but intuitively I'd be hesitant about this. Furthermore, it is hard to understand the logic's purpose - it is perfectly possible that there are more efficient ways to do/model what you want/need, but it would be better if you'd provide an overview of the context and requirements before.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-05-19T14:17:08.000",
"Id": "163756",
"ParentId": "27632",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T13:23:38.323",
"Id": "27632",
"Score": "6",
"Tags": [
"beginner",
"lua",
"redis"
],
"Title": "Iterating over JSON docs"
}
|
27632
|
<p>I have this code:</p>
<pre><code>if(listObj.Any(x => x.id < 0))
{
foreach(ModelClass item in listObj)
{
if(item.id < 0)
{
// code to create a new Obj in the database
}
}
}
</code></pre>
<p>But, should I use like this?</p>
<pre><code>foreach(ModelClass item in listObj)
{
if(item.id < 0)
{
// code to create a new Obj in the database
}
}
</code></pre>
<p><strong>NOTE:</strong> It's unusual to exist <code>id < 0</code> (I use this to create a temp <code>id</code> for manipulation in the page), but there is a possibility.</p>
<hr />
<p>Extra info that I found:</p>
<ul>
<li><a href="https://docs.microsoft.com/en-us/archive/blogs/ericlippert/query-transformations-are-syntactic" rel="nofollow noreferrer">Query transformations are syntactic</a></li>
<li><a href="http://www.headspring.com/improve-your-linq-with-any/" rel="nofollow noreferrer">IMPROVE YOUR LINQ WITH .ANY()</a></li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any?redirectedfrom=MSDN&view=net-5.0" rel="nofollow noreferrer">MSDN Documentation - Enumerable.Any Method</a></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T10:16:59.033",
"Id": "501676",
"Score": "0",
"body": "us a simple for loop and not a foreach and remove any linq code if you need performance\nand if you need to do it really fast use an unmanaged for loop"
}
] |
[
{
"body": "<p>Use <code>.Where</code> extension method to filter the records you need:</p>\n\n<pre><code>foreach(ModelClass item in listObj.Where(x => x.id < 0))\n{\n // code to create a new Obj in the database\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T17:55:46.110",
"Id": "43089",
"Score": "1",
"body": "Related: [LINQ extension methods - Any() vs. Where() vs. Exists()](http://stackoverflow.com/questions/3703256/linq-extension-methods-any-vs-where-vs-exists)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T10:14:51.460",
"Id": "501675",
"Score": "0",
"body": "that would kill performance as you effectively create a 2nd loop plus an object that needs to be allocated and managed by the GC"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T14:46:26.553",
"Id": "502106",
"Score": "0",
"body": "@WalterVehoeven There are no inner loops, the collection is scanned once. There is a certain performance penalty for executing a delegate and having an iterator but in most real-world cases its effect is negligible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T05:57:25.013",
"Id": "502175",
"Score": "0",
"body": "well you have 2 loops, one in your where linq statement and one in the foreach.LINQ is no \"free ride\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T07:49:16.087",
"Id": "502303",
"Score": "0",
"body": "Let's measure it in O notation. The statement is O(N), where N is the number of elements in the `listObj`. Same as in the original statement. For most scenarios that's what matters."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T14:24:06.393",
"Id": "27635",
"ParentId": "27633",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "27635",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-06-21T14:14:06.610",
"Id": "27633",
"Score": "1",
"Tags": [
"c#",
"performance",
".net",
"linq"
],
"Title": "Should I use and loop, or just a loop?"
}
|
27633
|
<p>This is one of my first steps with GUI. I've tried an implementation of <a href="http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" rel="nofollow">Conway's Game of Life</a> with TkInter.
I would appreciate any opinions about my code, especially about the separation of GUI and logic.</p>
<pre><code>import Tkinter as tk
from copy import deepcopy
from random import randrange
def random_fields(width):
"""
Returns a set of tuples of random integers, eg: set((2,4), (6,1)).
These tuples are meant as coordiantes.
The parameter width is the maximum value of x and y.
"""
fields_alive = width * width // 6
fields = set()
for _ in range(fields_alive):
x = randrange(width)
y = randrange(width)
fields.add((x,y))
return fields
class Field(object):
""" Represents a field in Game of Life. """
def __init__(self, x, y):
""" Constructs a "dead" field at coords x, y """
self.x = x
self.y = y
self.is_alive = False
def __str__(self):
return "Field: \n x: {0}; y: {1}; is_alive: {2}\n".format(self.x, self.y, self.is_alive)
def change(self):
""" Changes from dead to alive and vice-versa. """
if self.is_alive:
self.is_alive = False
else:
self.is_alive = True
class GameOfLifeMatrix(object):
"""
Represents a matrix in Game of Life and contains the logic.
The global STARTFIELDS is a dict, with some well known repeating patterns like:
"blinker" and "toad"
"""
STARTFIELDS = { "blinker": ((2,1), (2,2), (2,3)),
"toad": ((2,2), (3,2), (4,2), (1,3), (2,3), (3,3))
}
def __init__(self, width = 25, start_fields = "random"):
"""
Constructs a new square matrix for Game Of Life.
parameters:
width: integer, the width and height of the matrix
start_fields, you can provide:
- "blinker" or "toad" for the well known patterns
- "random" to create a random matrix
- a set of tuples containing specified "alive" coordinates
"""
if not self.STARTFIELDS.get(start_fields) is None:
self.start_fields = self.STARTFIELDS[start_fields]
elif start_fields == "random":
self.start_fields = random_fields(width)
else:
self.start_fields = start_fields
self.width = width
self.generation = 0
self.matrix = list()
for x in range(width):
row = list()
self.matrix.append(row)
for y in range(width):
field = Field(x, y)
if (x, y) in self.start_fields:
field.change()
row.append(field)
def _should_change(self, field):
""" Determines if a given field should be changed according to the rules of the game"""
if ( field.x == 0
or field.y == 0
or field.x == self.width - 1
or field.y == self.width - 1):
# i.e.: field is at the border -> should not change?
return False
alive_neighbours = 0
for x in range(field.x -1, field.x +2):
for y in range(field.y -1, field.y +2):
if x == field.x and y == field.y:
# field is not neighbour of itself
continue
if self.matrix[x][y].is_alive:
alive_neighbours += 1
if (not field.is_alive) and alive_neighbours == 3:
return True
elif field.is_alive and (alive_neighbours < 2 or alive_neighbours > 3):
return True
else:
return False
def next_generation(self):
""" Evolves the matrix to the next generation. """
self.generation += 1
new_matrix = deepcopy(self.matrix)
for field in self.fields():
if self._should_change(field):
new_matrix[field.x][field.y].change()
self.matrix = new_matrix
def fields(self):
""" Generator, yields all fields of the matrix. """
for row in self.matrix:
for field in row:
yield field
class GameOfLifeApp(tk.Frame):
""" Represents the TkInter-Version of the game """
def __init__(self, game, generation_interval_ms = 600, color_alive = "#000", color_dead = "#fff"):
"""
Constructs the TkInter app.
parameters:
game: an object of type GameOfLifeMatrix
generation_interval_ms: integer time in milliseconds to display the next genereation
color_alive and color_dead: TkInter-color-strings for alive and dead fields
default dead: white "#fff"; default alive: black "#000"
"""
self.game = game
self.generation_interval_ms = generation_interval_ms
self.color_alive = color_alive
self.color_dead = color_dead
self.widgets = dict()
self.root = tk.Tk()
tk.Frame.__init__(self, self.root)
self.grid()
for field in self.game.fields():
widget = tk.Label(height = 1, width = 2, bg = self.color_dead, relief = "ridge")
widget.grid(column = field.x, row = field.y)
if field.is_alive:
widget.configure(bg = self.color_alive)
self.widgets[(field.x, field.y)] = widget
self.root.after(self.generation_interval_ms, self.draw)
def draw(self):
""" Draws the new generation. """
for field in self.game.fields():
if field.is_alive:
self.widgets[(field.x, field.y)].configure(bg = self.color_alive)
else:
self.widgets[(field.x, field.y)].configure(bg = self.color_dead)
self.game.next_generation()
self.root.after(self.generation_interval_ms, self.draw)
if __name__ == "__main__":
game = GameOfLifeMatrix()
app = GameOfLifeApp(game)
app.mainloop()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T15:49:11.673",
"Id": "43083",
"Score": "0",
"body": "I'd advice you to have a look at http://www.youtube.com/watch?v=o9pEzgHorH0 from the 17th minute."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T17:12:51.027",
"Id": "43085",
"Score": "0",
"body": "Yes, i thought about converting \"Field\" to a dictionary, but i asked myself if that verbosity has any major drawbacks? In fact in this module i tried to be as \"readable\" as possible"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T14:40:18.927",
"Id": "61891",
"Score": "0",
"body": "You might be interested in [this answer](http://codereview.stackexchange.com/a/31952/11728) which uses Pygame instead Tkinter."
}
] |
[
{
"body": "<p>In terms of your specific question, I think you have done a good job of separating out the simulation and the presentation. However, you have a few slightly awkward bits of code:</p>\n\n<pre><code>def change(self):\n \"\"\" Changes from dead to alive and vice-versa. \"\"\"\n if self.is_alive:\n self.is_alive = False\n else:\n self.is_alive = True\n</code></pre>\n\n<p>could be simplified to</p>\n\n<pre><code>def change(self):\n \"\"\" Changes from dead to alive and vice-versa. \"\"\"\n self.is_alive = not self.is_alive\n</code></pre>\n\n<p>and</p>\n\n<pre><code>if not self.STARTFIELDS.get(start_fields) is None:\n</code></pre>\n\n<p>to</p>\n\n<pre><code>if start_fields in self.STARTFIELDS:\n</code></pre>\n\n<p>and</p>\n\n<pre><code> self.matrix = list()\n for x in range(width):\n row = list()\n self.matrix.append(row)\n for y in range(width):\n field = Field(x, y)\n if (x, y) in self.start_fields:\n field.change()\n row.append(field)\n</code></pre>\n\n<p>to</p>\n\n<pre><code>matrix = [[Field(x, y) for y in range(width)] for x in range(width)]\nfor x, y in self.start_fields:\n matrix[x][y].change()\n</code></pre>\n\n<p>Your approach to <code>next_generation</code> could be improved; if you made a list of <em>all</em> cells that <code>_should_change</code>, <em>then</em> changed them, you could do it in-place and wouldn't need the <code>deepcopy</code>. Separating out <code>_should_change</code> was a good idea, but you could make more of it. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T12:52:49.663",
"Id": "37410",
"ParentId": "27638",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T15:26:46.153",
"Id": "27638",
"Score": "6",
"Tags": [
"python",
"game-of-life",
"tkinter"
],
"Title": "Game of Life, separation of logic / GUI"
}
|
27638
|
<p>I am currently trying to improve on a query that is being used to build a view. The query is in PL/SQL, in an Oracle database. There are 3 different types of reports (100,200, and 300) that are generated at each building. We track the consecutive years that each report is generated, and based on the combination of (1) the type(s) of report(s) generated for a given year and (2) the consecutive years each report has been generated, we arrive at a Result type for that building.</p>
<p>Here is a description of the criteria for the Result types:</p>
<blockquote>
<p>Result 600 - If all 3 report types have been generated in the current year, where: Level 1: all reports were generated in 1 consecutive year (this is the first year) Level 2: at least 1 report type has been generated for 2 consecutive years (none have 3 consecutive years) Level 3: at least one report type has been generated for 3 consecutive years</p>
<p>Result 100 - Only report type 100 has been generated in the current year, where: Level 1 - 1 consecutive year Level 2 - 2 consecutive years Level 3 - 3 consecutive years</p>
<p>Result 200 - Only report type 200 has been generated in the current year, where: Level 1 - 1 consecutive year Level 2 - 2 consecutive years Level 3 - 3 consecutive years</p>
<p>Result 300 - Only report type 300 has been generated in the current year, where: Level 1 - 1 consecutive year Level 2 - 2 consecutive years Level 3 - 3 consecutive years</p>
<p>Result 400 - Only reports 100 and 200 have been generated, where: Level 1: both reports were generated in 1 consecutive year (this is the first year) Level 2: at least 1 report type has been generated for 2 consecutive years (neither have 3 consecutive years) Level 3: at least one report type has been generated for 3 consecutive years</p>
<p>Result 500 - Only reports 100 and 300 have been generated, where: Level 1: both reports were generated in 1 consecutive year (this is the first year) Level 2: at least 1 report type has been generated for 2 consecutive years (neither have 3 consecutive years) Level 3: at least one report type has been generated for 3 consecutive years</p>
<p>Result 700 - Only reports 200 and 300 have been generated, where: Level 1: both reports were generated in 1 consecutive year (this is the first year) Level 2: at least 1 report type has been generated for 2 consecutive years (neither have 3 consecutive years) Level 3: at least one report type has been generated for 3 consecutive years</p>
</blockquote>
<p>Here is the current code that is used to generate this view, which is simply a display of the result:</p>
<pre><code>CREATE OR REPLACE FORCE VIEW REPORTS.REPORT_RESULT_VIEW
(
BUILDING,
BUILDING_NAME,
GROUP,
YEAR,
TYPE,
SUBTYPE,
CONSEC,
RESULT
)
AS
WITH cte1
AS (SELECT 1 ID_100,
1 ID_200,
1 ID_300,
'600 Level 1' RESULT
FROM DUAL
UNION ALL
SELECT 2 ID_100,
2 ID_200,
2 ID_300,
'600 Level 2' RESULT
FROM DUAL
UNION ALL
SELECT 3 ID_100,
3 ID_200,
3 ID_300,
'600 Level 3' RESULT
FROM DUAL
UNION ALL
SELECT 1 ID_100,
1 ID_200,
2 ID_300,
'600 Level 2' RESULT
FROM DUAL),
</code></pre>
<p>(note - there are 63 total combinations that are listed in the actual code... I only entered the first few to give you an idea of how it is set up)</p>
<pre><code> cte2
AS ( SELECT MAX (ID_100) ID_100_CONSEC,
MAX (ID_200) ID_200_CONSEC,
MAX (ID_300) ID_300_CONSEC,
YEAR,
BUILDING
FROM (SELECT CONSEC ID_100,
NULL ID_200,
NULL ID_300,
YEAR,
TYPE || SUBTYPE TYPE,
BUILDING
FROM REPORT_MASTER_VIEW
WHERE TYPE || SUBTYPE = '100'
UNION
SELECT NULL ID_100,
CONSEC ID_200,
NULL ID_300,
YEAR,
TYPE || SUBTYPE TYPE,
BUILDING
FROM REPORT_MASTER_VIEW
WHERE TYPE || SUBTYPE = '200'
UNION
SELECT NULL ID_100,
NULL ID_200,
CONSEC ID_300,
YEAR,
TYPE || SUBTYPE TYPE,
BUILDING
FROM REPORT_MASTER_VIEW
WHERE TYPE || SUBTYPE = '300')
GROUP BY YEAR, BUILDING),
cte3
AS (SELECT c2.*, c1.RESULT
FROM cte2 c2
JOIN
cte1 c1
ON NVL (c2.ID_100_CONSEC, 0) = c1.ID_100
AND NVL (c2.ID_200_CONSEC, 0) = c1.ID_200
AND NVL (c2.ID_300_CONSEC, 0) = c1.ID_300)
SELECT t1."BUILDING",
t1."BUILDING_NAME",
t1."GROUP",
t1."YEAR",
t1."TYPE",
t1."SUBTYPE",
t1."CONSEC",
t2.RESULT
FROM REPORT_MASTER_VIEW t1
JOIN
cte3 t2
ON t1.BUILDING = t2.BUILDING AND t1.YEAR = t2.YEAR
WHERE T1.TYPE IN ('100', '200' '300')
ORDER BY t1.BUILDING;
</code></pre>
<p>Now, because for every report combination, it has to run through all the possible combinations, this view takes about 24 seconds to build. In the app that it is referenced in, it takes nearly a minute to load the page. For this reason, I am trying to figure out ways to make the query more efficient. At first, I was thinking of using nested <code>CASE</code> statements, but I wasn't really sure how that would work.</p>
|
[] |
[
{
"body": "<p><code>cte1</code>, besides needing a better name, needs to just be a fully-fledged table. With 63 combinations, it takes a while to process how to get all these in correctly. Putting this in a view doesn't speed up that CTE at all. So, just create a permanent table in the database preloaded with these values.</p>\n\n<p>That should cut a massive chunk out of your query time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-12T03:10:15.607",
"Id": "107807",
"Score": "0",
"body": "So, then a process would have to be put in place to keep the table in sync with the rest of the data. Is the performance gain worth the increased complexity?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-12T11:24:14.080",
"Id": "107875",
"Score": "1",
"body": "I don't understand what has to be kept in sync? Am I looking at `cte1` wrong? It looks like it's just a set of constant values, right? But to your question \"Is the performance gain worth the increased complexity?\" In this specific case since I'm certain that this is a huge chunk of the really long query time, **yes**. In SQL in general, if the query runs slow enough that it is noticeable to the user (anything over 1 second), any performance game that will make a noticeable difference to the end user is usually worth it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-12T11:27:05.760",
"Id": "107877",
"Score": "0",
"body": "You're right. I should have looked closer. Everything is being selected from `DUAL`. It should be a table."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-12T00:04:10.270",
"Id": "59735",
"ParentId": "27640",
"Score": "6"
}
},
{
"body": "<p>I'll compliment in saying that formatting, capitalization, etc. are consistent. </p>\n\n<p><strong>Nitpicking</strong></p>\n\n<p><code>cte1</code> and <code>cte2</code> are not very good names. Aliases should reflect what they actually represent. </p>\n\n<h1><strong><code>UNION</code></strong></h1>\n\n<p>To me the gorilla in the room is that <code>UNION</code> is used <strong>64 times</strong> to explicitly spell out every possible scenario instead of using logic. Let me illustrate.</p>\n\n<p><em>PS: Note I'm using PL/pgSQL (a.k.a. PostgreSQL) so the syntax might need a few adjustments. I don't have access to an Oracle machine.</em></p>\n\n<pre><code>-- making cte1\ndrop table if exists numbers;\ncreate temporary table numbers(\n counter serial,\n n int\n);\ninsert all\ninto numbers (n) values (null), -- no report of any type\ninto numbers (n) values (1),\ninto numbers (n) values (2),\ninto numbers (n) values (3)\n;\ndrop table if exists NumbersWithResults;\ncreate table NumbersWithResults as\n select \n ID_100.n as ID_100,\n ID_200.n as ID_200,\n ID_300.n as ID_300\n from numbers as ID_100\n cross join numbers as ID_200\n cross join numbers as ID_300\n;\n-- Query returned successfully: 64 rows affected, 17 ms execution time.\n-- if you need to check results, uncomment this:\n-- select * from NumbersWithResults\n-- order by ID_100, ID_200, ID_300;\n</code></pre>\n\n<p>As you can see, execution is fast, and you just now need to work in a few logical rules to <code>add column</code> and <code>update</code> values based on a set of conditions... for example:</p>\n\n<pre><code>alter table NumbersWithResults\n add column RESULT text\n;\n-- working in your business rules\n-- examples only, add to or change as needed\nupdate NumbersWithResults\n set RESULT = '600 Level 1'\n where ID_100 = ID_200 and ID_200 = ID_300,\n set RESULT = '600 Level 2'\n where COUNT(ID_100, ID_200, ID_300) = 2,\n set RESULT = '600 Level 3'\n where COUNT(ID_100, ID_200, ID_300) = 3\n -- etc.\n</code></pre>\n\n<p>Hope this helps. </p>\n\n<p><em>PS: Like @nhgriff said, this should be a permanent table, not a CTE, if this is getting called regularly. Also consider making a stored procedure/function.</em></p>\n\n<p><em>PPS: Some of my conditions at the end may be wrong... make sure you test.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-12T02:02:43.143",
"Id": "107799",
"Score": "0",
"body": "Oracle doesn't support multiple rows in `VALUES`, the way PostgreSQL does."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-12T04:30:58.217",
"Id": "107824",
"Score": "0",
"body": "I changed the `insert` code to factor this in, thanks @200_success."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-12T01:37:48.247",
"Id": "59754",
"ParentId": "27640",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T16:03:50.503",
"Id": "27640",
"Score": "5",
"Tags": [
"performance",
"sql",
"oracle",
"plsql"
],
"Title": "Query for building a view"
}
|
27640
|
<blockquote>
<p>A company sells iPods online. There are 100 stocks maintained at
Argentina and Brazil. A single iPod costs $100 in Brazil and $50 in
Argentina. The cost of exporting stocks from one country to the other
will cost $400 per 10 blocks. The transportation is always done in the
multiples of 10. Calculate the minimum cost for purchasing the given
no of units. Assume that for each transaction, the available stock in
each country is maintained to be 100.</p>
<p>Input and output format:</p>
<ul>
<li>The country from which the order is being placed: No of units</li>
<li>Minimum costs:No of stock left in Brazil: No of stock left at Argentina</li>
</ul>
<p>Sample input and output:</p>
<pre class="lang-none prettyprint-override"><code>Brazil:5
500:95:100
Brazil:50
4500:100:50
</code></pre>
</blockquote>
<pre class="lang-python prettyprint-override"><code>class Country:
shp=40
def country_details(self,numberofitems,sellingprice):
self.sp=sellingprice
self.no=numberofitems
def display(self):
print self.sp
print self.no
print self.shp
Brazil=Country()
Brazil.country_details(100,100)
Brazil.display()
Argentina=Country()
Argentina.country_details(100,50)
Argentina.display()
print "Enter the country from which you order from"
x=raw_input()
if x=="Brazil":
c=1
else:
c=2
print "Enter the amount of products needed"
y=raw_input()
y=int(y)
def profit(y):
if c==1:
if y%10==0:
P=orderfromArgentinafb(y);
else:
P=orderfromBrazil(y);
if c==2:
P=orderfromArgentina(y);
return P
def calculate(y):
if (y<101):
Pr=profit(y)
return Pr
else:
Pr=profit(y-(y%100))+orderfromBrazil(y-100)
return Pr
def orderfromBrazil(y):
Cost=y*Brazil.sp
if c==2:
Cost=Cost+y*Brazil.shp
Brazil.no=Brazil.no-y
return Cost
def orderfromArgentina(y):
Cost=y*Argentina.sp
Argentina.no=Argentina.no-y
return Cost
def orderfromArgentinafb(y):
Cost=y*Argentina.sp+(y*Argentina.shp)
Argentina.no=Argentina.no-y
if Argentina.no <0:
Argentina.no=0
return Cost
Pr=calculate(y)
print Pr
print "%d:%d:%d" %(Pr,Brazil.no,Argentina.no)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-20T06:37:17.327",
"Id": "122618",
"Score": "1",
"body": "[Apparent source of the challenge](http://permalink.gmane.org/gmane.comp.programming.algogeeks/18046)"
}
] |
[
{
"body": "<p>You can write</p>\n\n<pre><code>if raw_input(\"Enter the country from which you order from\") == \"Brazil\":\n c = 1\nelse:\n c = 2\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>print \"Enter the country from which you order from\"\nx=raw_input()\nif x==\"Brazil\":\n c=1\nelse:\n c=2\n</code></pre>\n\n<p>as you are not using x anywhere. I less variable and raw_input has optional string so why not use that?</p>\n\n<p>In function profit instead of using</p>\n\n<pre><code>if y%10==0:\n P=orderfromArgentinafb(y);\nelse:\n P=orderfromBrazil(y);\n</code></pre>\n\n<p>you can use</p>\n\n<pre><code>if y % 10:\n return orderfromBrazil(y)\nelse:\n return orderfromArgentinafb(y)\n</code></pre>\n\n<ul>\n<li>You don't need the variable P when you are just returning it. </li>\n<li>Why are there semicolons at the end? This isn't C</li>\n<li>Notice the changing the order of return. It gives the same result but with one less comparison.</li>\n</ul>\n\n<p>Same thing can be done in function calculate. </p>\n\n<p>Use if...elif... in case you are just doing one of the things. Using as it is leads to more comparisons than are needed. </p>\n\n<p>In both the functions orderfromArgentina and orderfromArgentinafb a simple reordering of statements can lead to removal of additional variable Cost.</p>\n\n<p>You need to read a style guide. Check for official tutorials of Python. They contain brief style guide. That is also an optimization. It doesn't effect memory or time complexity but it leads to better maintenance</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T18:57:28.843",
"Id": "27645",
"ParentId": "27642",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27645",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T17:23:18.953",
"Id": "27642",
"Score": "1",
"Tags": [
"python",
"programming-challenge"
],
"Title": "Stocks of iPods for various countries"
}
|
27642
|
<p>I'm still learning jQuery and am wondering if there are other ways to put <code>.each()</code> inside another <code>.each()</code> function:</p>
<p>JavaScript:</p>
<pre><code>$("ul").each(function(index){
$("#uid" + index + " li").each(function(listItemIndex){
var listItemWidth = $(this).width();
var listItemPosition = listItemIndex * listItemWidth;
if (listItemIndex > 0){
$(this).css("left", listItemPosition + (10 * listItemIndex));
};
});
});
</code></pre>
<p>HTML:</p>
<pre><code><ul id="uid0">
<li>
Lorem ipsum dolor sit amet
</li>
<li>
Lorem ipsum dolor sit amet
</li>
</ul>
<ul id="uid1">
<li>
Lorem ipsum dolor sit amet
</li>
</ul>
<ul id="uid2">
<li>
Lorem ipsum dolor sit amet
</li>
<li>
Lorem ipsum dolor sit amet
</li>
<li>
Lorem ipsum dolor sit amet
</li>
<li>
Lorem ipsum dolor sit amet
</li>
</ul>
</code></pre>
|
[] |
[
{
"body": "<pre><code>$(\"ul\").each(function() {\n var ul = this;\n $(ul).children('li').each(function(listItemIndex) {\n if (listItemIndex > 0) {\n var listItemWidth = $(this).width();\n var listItemPosition = listItemIndex * (listItemWidth + 10);\n $(this).css(\"left\", listItemPosition);\n };\n });\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-05T09:06:24.213",
"Id": "215177",
"Score": "0",
"body": "(Yes, I know it's over 2 years old now, doesn't matter). Code-only answers are generally not good because they do not explain **how** or **why** they improve upon the OP's code. Even a short explanation of what your solution does and why would be far better than no explanation at all."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T19:20:54.913",
"Id": "27647",
"ParentId": "27643",
"Score": "-2"
}
}
] |
{
"AcceptedAnswerId": "27647",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T17:35:22.377",
"Id": "27643",
"Score": "-2",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": ".each() inside another .each() function"
}
|
27643
|
<p>I was doing this particular problem <a href="http://www.spoj.com/problems/AIBOHP/">AIBOHP</a> and used a dp approach based on checking the ends of a substring of length i starting from 1. Although my time complexity is fine at O(n^2) but space is taking too much because of which I am getting RTE if I am declaring it dynamically or TLE if I am declaring it as global static which needs to be reduced because the dp size can be 6100*6100 . Any suggestions how to optimize my below code for this purpose .</p>
<p>The problem statement is:</p>
<blockquote>
<p>He now asks the doctors to insert the minimum number of characters
needed to make S a palindrome. Help the doctors accomplish this task.</p>
<p>For instance, if S = "fft", the doctors should change the string to
"tfft", adding only 1 character.</p>
</blockquote>
<p>My code:</p>
<pre><code>static int dp[6101][6101];
main()
{
int tc;
scanf("%d",&tc);
while(tc--)
{
char s[6102];
scanf("%s",s);
int len=strlen(s);
memset(dp,0,sizeof dp);
for(int i=1;i<len;i++)
for(int j=0,k=i;k<len;k++,j++)
dp[j][k]=(s[j]==s[k])?dp[j+1][k-1]:min(dp[j][k-1],dp[j+1][k])+1;
printf("%d\n",dp[0][len-1]);
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T02:30:46.110",
"Id": "46698",
"Score": "0",
"body": "Maybe you can reduce the memory consumption by a constant factor, but I'm not sure about reducing the space complexity. A simple hint could be: use `short int` instead of `int`, because your answer won't go more than length of your string, right?"
}
] |
[
{
"body": "<h1>Things you did well:</h1>\n\n<ul>\n<li><p>Usage of <code>static</code>.</p></li>\n<li><p>Using <code>memset()</code> instead of some <code>for</code> loops for initialization of your <code>int[][]</code>.</p></li>\n</ul>\n\n<h1>Things you could improve:</h1>\n\n<h3>User Experience:</h3>\n\n<ul>\n<li><p>You don't indicate to the user that they should enter a number first.</p>\n\n<pre><code>printf(\"Enter the number of test cases: \");\n</code></pre></li>\n<li><p>You don't indicate that the user should enter a string after then enter a number.</p>\n\n<pre><code>printf(\"Enter test case string: \");\n</code></pre></li>\n</ul>\n\n<h3>Variables:</h3>\n\n<ul>\n<li><p>I don't expect <code>dp</code> will ever contain negative numbers:</p>\n\n<blockquote>\n<pre><code>static int dp[6101][6101];\n</code></pre>\n</blockquote>\n\n<p>You also don't need the full range of <code>int</code>. Using a <code>unsigned short</code> will half your memory usage.</p>\n\n<pre><code>static unsigned short dp[6101][6101];\n</code></pre></li>\n<li><p>Always initialize your variables when you create them.</p>\n\n<pre><code>int tc = 0;\n</code></pre></li>\n</ul>\n\n<h3>Readability:</h3>\n\n<ul>\n<li><p>You don't declare what <code>main</code> will return or take in as parameters.</p>\n\n<blockquote>\n<pre><code>main()\n</code></pre>\n</blockquote>\n\n<p>I know that when the type specifier is missing for what you will return, it defaults to an <code>int</code>. You should still declare it for more readability. Also, whenever you don't take in any parameters, declare them as <code>void</code>.</p>\n\n<pre><code>int main(void)\n</code></pre></li>\n<li><p>Your <code>for</code> loop is hard to follow.</p>\n\n<blockquote>\n<pre><code>for(int i=1;i<len;i++)\n for(int j=0,k=i;k<len;k++,j++)\n dp[j][k]=(s[j]==s[k])?dp[j+1][k-1]:min(dp[j][k-1],dp[j+1][k])+1;\n</code></pre>\n</blockquote>\n\n<p>Braces will help, and will reduce the likelihood of you unintentionally adding bugs in the future.</p>\n\n<pre><code>for(int i=1; i<len; i++)\n{\n for(int j=0,k=i; k<len; k++, j++)\n {\n dp[j][k] = (s[j] == s[k]) ? dp[j+1][k-1] : fmin(dp[j][k-1], dp[j+1][k])+1;\n }\n}\n</code></pre></li>\n<li><p>Don't use the ternary operator for longer statements.</p>\n\n<blockquote>\n<pre><code>dp[j][k] = (s[j] == s[k]) ? dp[j+1][k-1] : fmin(dp[j][k-1], dp[j+1][k])+1;\n</code></pre>\n</blockquote>\n\n<p>This makes it hard to follow and understand what you are trying to do. Just use the normal <code>if-else</code> statements.</p>\n\n<pre><code>if (s[j] == s[k]) dp[j][k] = dp[j+1][k-1];\nelse dp[j][k] = fmin(dp[j][k-1], dp[j+1][k]) + 1;\n</code></pre></li>\n<li><p>Use more space in your code. Let it <em>breathe</em> a bit. But don't go overboard.</p></li>\n<li><p>Use more comments to explain your code.</p></li>\n</ul>\n\n<h3>Syntax/Styling:</h3>\n\n<ul>\n<li><p>You have some <a href=\"https://en.wikipedia.org/wiki/Magic_number_%28programming%29\" rel=\"nofollow\">magic numbers</a> in your code.</p>\n\n<blockquote>\n<pre><code>static int dp[6101][6101];\n</code></pre>\n</blockquote>\n\n<p>With the help of macros, we can easily get rid of them.</p>\n\n<pre><code>#define ARRAYSIZE 6101\nstatic int dp[ARRAYSIZE][ARRAYSIZE];\n</code></pre></li>\n<li><p>Don't use the function <code>min()</code>.</p>\n\n<blockquote>\n<pre><code>dp[j][k]=(s[j]==s[k])?dp[j+1][k-1]:min(dp[j][k-1],dp[j+1][k])+1;\n</code></pre>\n</blockquote>\n\n<p><code>min()</code> and <code>max()</code> functions are not included in standard C. To make things simple for your code, use the standard math function <a href=\"http://en.cppreference.com/w/c/numeric/math/fmin\" rel=\"nofollow\"><code>fmin()</code></a>.</p>\n\n<pre><code>dp[j][k] = (s[j] == s[k]) ? dp[j+1][k-1] : fmin(dp[j][k-1], dp[j+1][k])+1;\n</code></pre></li>\n<li><p>You have an implicit conversion that loses integer precision: </p>\n\n<blockquote>\n<pre><code>int len=strlen(s);\n</code></pre>\n</blockquote>\n\n<p>You aren't converting your <code>unsigned long</code> that <code>strlen()</code> returns to an <code>int</code>.</p>\n\n<pre><code>int len = (int) strlen(s);\n</code></pre></li>\n<li><p>Use <code>fgets()</code> instead of <code>scanf()</code>. This way we can specify the maximum number of characters to be copied into our string (including the terminating null-character).</p>\n\n<pre><code>fgets(s, 6101, stdin);\n</code></pre></li>\n<li><p>You should always check for superfluous input and get rid of it.</p>\n\n<pre><code>while (getchar() != '\\n');\n</code></pre></li>\n</ul>\n\n<h3>Preprocessor:</h3>\n\n<ul>\n<li><p>Whenever you include functions such as <code>scanf()</code> and <code>printf()</code> that deal with input or output, you need included the standard I/O header.</p>\n\n<pre><code>#include <stdio.h> \n</code></pre></li>\n<li><p>Whenever you include functions that deal with strings, there is a good chance you will have to include the string header.</p>\n\n<pre><code>#include <string.h>\n</code></pre></li>\n<li><p>Whenever you include math functions, you need to include the math header.</p>\n\n<pre><code>#include <math.h>\n</code></pre></li>\n</ul>\n\n<h1>Final Code:</h1>\n\n<pre><code>#include <stdio.h>\n#include <string.h>\n#include <math.h>\n\n#define ARRAYSIZE 6101\n\nstatic unsigned short dp[ARRAYSIZE][ARRAYSIZE];\nchar s[ARRAYSIZE] = {0};\nint main(void)\n{\n int tc = 0;\n printf(\"Enter the number of test cases: \");\n scanf(\"%d\",&tc);\n while (getchar() != '\\n');\n while(tc--)\n {\n printf(\"Enter test case string: \");\n fgets(s, ARRAYSIZE, stdin);\n int len = (int) strlen(s);\n memset(dp, 0, sizeof dp);\n for(int i=1; i<len; i++)\n {\n for(int j=0, k=i; k<len; k++, j++)\n {\n if (s[j] == s[k]) dp[j][k] = dp[j+1][k-1];\n else dp[j][k] = fmin(dp[j][k-1], dp[j+1][k]) + 1;\n }\n }\n printf(\"%d\\n\", dp[0][len-1]);\n }\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T01:45:41.273",
"Id": "75862",
"Score": "0",
"body": "I don't follow your O(_n_) algorithm at all. But isn't `i - 1 >= 0` always true?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T02:08:19.173",
"Id": "75863",
"Score": "0",
"body": "@200_success It turns out my O(n) program was buggy. It has now been removed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T23:56:24.273",
"Id": "43826",
"ParentId": "27644",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T18:28:34.710",
"Id": "27644",
"Score": "7",
"Tags": [
"optimization",
"c",
"algorithm",
"strings",
"palindrome"
],
"Title": "Checking ends of a substring"
}
|
27644
|
<p>I have written a Custom Log4J Appender which is responsible for sending the log message to a third party service asynchronously. It is expected to be called every millisecond.</p>
<p>I ran FindBugs on this code, it didn't report anything unusual. But before releasing this code to production, how can I know if this code has any issues with it?</p>
<pre><code>package com;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;
public class MyAppender extends AppenderSkeleton {
public MyAppender() {
}
public void append(LoggingEvent event) {
ArrayList<LoggingEvent> buffer = new ArrayList<LoggingEvent>();
buffer.add(event);
flushBuffer(buffer);
}
public void flushBuffer(ArrayList<LoggingEvent> buffer) {
for (Iterator<LoggingEvent> i = buffer.iterator(); i.hasNext();) {
try {
LoggingEvent logEvent = (LoggingEvent) i.next();
String messageRecievied = (String) logEvent.getMessage();
//System.out.println(messageRecievied);
} catch (Exception e) {
}
}
}
@Override
public void close() {
}
@Override
public boolean requiresLayout() {
return false;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T05:06:59.537",
"Id": "43097",
"Score": "0",
"body": "If you want a very simple check if whether your code has any issues then test it against this very simple checklist http://www.codinghorror.com/blog/2006/05/code-smells.html Code smells As you gain experience with that you will find locationg code smells easier"
}
] |
[
{
"body": "<p>Add source code comments. Why does the class exist? What does it do? What do each of the methods do? What are their pre- and post-conditions?</p>\n\n<p>This code:</p>\n\n<pre><code>ArrayList<LoggingEvent> buffer = new ArrayList<LoggingEvent>();\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>List<LoggingEvent> buffer = new ArrayList<LoggingEvent>();\n</code></pre>\n\n<p>Similarly:</p>\n\n<pre><code>public void flushBuffer(ArrayList<LoggingEvent> buffer) {\n</code></pre>\n\n<p>As:</p>\n\n<pre><code>public void flushBuffer(List<LoggingEvent> buffer) {\n</code></pre>\n\n<p>Next up:</p>\n\n<pre><code> } catch (Exception e) {\n\n }\n</code></pre>\n\n<p>Allow that Exception to bubble up:</p>\n\n<pre><code>public void flushBuffer(List<LoggingEvent> buffer) throws Exception {\n</code></pre>\n\n<p>But, be as specific as possible about the exception that can be thrown (i.e., if isn't Exception itself that is thrown, but a subclass, then opt to throw that subclass instead).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T01:17:20.647",
"Id": "27654",
"ParentId": "27650",
"Score": "1"
}
},
{
"body": "<p>First, I don't think the <code>close()</code> method is following the contract, <a href=\"http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/AsyncAppender.html#close%28%29\" rel=\"nofollow\">from the javadoc</a>: </p>\n\n<blockquote>\n <p>It is a programming error to append to a closed appender.</p>\n</blockquote>\n\n<p>Therefore, your <code>close()</code> method should be implemented like this:</p>\n\n<pre><code>@Override\npublic void close() {\n this.closed = true;\n}\n</code></pre>\n\n<p>Note that <code>closed</code> is a protected field in <code>AppenderSkeleton</code>. </p>\n\n<p>Then, change <code>append</code> to something like (add the <code>@Override</code> as well):</p>\n\n<pre><code>@Override\npublic void append(LoggingEvent event) {\n if (!this.closed) {\n ArrayList<LoggingEvent> buffer = new ArrayList<LoggingEvent>();\n buffer.add(event);\n flushBuffer(buffer);\n } else {\n // It is a programming error to append to a closed appender.\n throw new RuntimeException(\"Attempting to append to a closed Appender.\");\n }\n}\n</code></pre>\n\n<p>Next, does <code>flushBuffer</code> need to be <code>public</code>? It should probably be <code>private</code>.</p>\n\n<p>Finally—and this is more of a nitpick—you don't need to declare the default constructor since it's empty and the compiler will create one for you. It'll make your code a little cleaner as well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T14:24:34.793",
"Id": "27663",
"ParentId": "27650",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27663",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T22:27:06.407",
"Id": "27650",
"Score": "0",
"Tags": [
"java"
],
"Title": "Custom Log4J Appender"
}
|
27650
|
<p>Write a program that lets users keep track of the last time they talked to each of their friends. Users should be able to add new friends (as many as they want!) and store the number of days ago that they last talked to each friend. Let users update this value (but don't let them put in bogus numbers like negative values). Make it possible to display the list sorted by the names of the friends of by how recently it was since they talked to each friend.</p>
<p>This is the code I have written so far. I'm having problems with the array size not growing as it should do. Also I'm unsure about how to go about list the names with numbers of days out.</p>
<pre><code>#include <iostream>
#include <string>
using namespace std;
int *growArray (int * friends, int * size)
{
*size *= 2;
int *new_friends = new int[*size];
for (int i=0; i < *size; i++) {
new_friends[i] = friends[i];
}
delete [] friends;
return new_friends;
}
string *growArray2 (string * name1, int * size)
{
*size *= 2;
string *new_name2 = new string[*size];
for (int i=0; i < *size; i++) {
new_name2[i] = name1[i];
}
delete [] name1;
return new_name2;
}
void printArray (string *name1, int *friends,int size, int element_set)
{
cout << "the total size of the array is: " << size << endl;
cout << "Values in the array: " << endl;
for (int i = 0; i < element_set; ++i)
{
cout << name1[i] << "[" << i << "] = " << friends[i] << " days since you last spoke to them" << endl;
}
}
int main()
{
string exit = "X";
string name;
int noDays;
int next_element = 0;
int size = 4;
int *friends = new int[size];
string *name1 = new string [size];
cout << "Please enter your friends name" << endl;
cin >> name;
cout << "Please enter no of days you last spoke to them" << endl;
cin >> noDays;
while(true) {
if (size == next_element+1) {
friends = growArray(friends, &size);
name1 = growArray2(name1, &size);
}
friends[next_element] = noDays;
name1[next_element] = name;
next_element++;
printArray(name1, friends, size , next_element);
cout << "Please enter your friends name or X to exit" << endl;
cin >> name;
if (name == exit) {
break;
}
cout << "Please enter no of days you last spoke to them" << endl;
cin >> noDays;
}
delete name1;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T16:33:00.657",
"Id": "43115",
"Score": "1",
"body": "Why are you writing your own primitive version of `vector`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T19:37:49.373",
"Id": "43136",
"Score": "1",
"body": "Is this an class exercise in memory management? If not then use std::vector"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T19:41:48.360",
"Id": "43137",
"Score": "0",
"body": "To make `User` sortable. Just define the `bool operator<(User const& lhs, User const& rhs)`. Now you will be able to sue `std::sort` on any container of User."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T19:45:06.357",
"Id": "43138",
"Score": "0",
"body": "This code is definitely not off topic as `It works`. Admittedly not very well but it runs and needs a review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T11:56:24.063",
"Id": "43155",
"Score": "0",
"body": "Thanks for the help guys. I have made edits up top as suggested. The reason for not using vectors is because I am currently working through an e-book which has not covered that topic yet so I am guessing I am not supposed to use them. @LokiAstari this is the chapter on dynamic memory allocation and pointer to pointers. So maybe I should use a pointer to pointer? I am not sure."
}
] |
[
{
"body": "<p>First of all the \"growArray\" function will never be called since you put it inside an if block that runs only once. when the if statement is evaluated your size is 10 and your next_element+1 is 1 and you never check for (size == next_element+1) again.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T00:47:14.673",
"Id": "27653",
"ParentId": "27651",
"Score": "3"
}
},
{
"body": "<p>A few considerations here. Probably the most important is: Don't write your own low-level data structures. It is difficult to do correctly and the standard library has lots of choices. In this case, <a href=\"http://en.cppreference.com/w/cpp/container/vector\" rel=\"nofollow noreferrer\"><code>std::vector</code></a> seems like the best choice (in fact, it grows its underlying data store in the same way, by doubling its size when it runs out of room).</p>\n\n<p>If for some reason you had to implement your own version of <code>vector</code>, you should implement it as a class, not as a bunch of free functions. Another general rule is</p>\n\n<blockquote>\n <p>Guideline: Don’t use explicit new, delete, and owning * pointers, except in rare cases encapsulated inside the implementation of a low-level data structure.</p>\n</blockquote>\n\n<p>as Herb Sutter puts it in <a href=\"http://herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers/\" rel=\"nofollow noreferrer\">his excellent article about smart pointers</a>. There are a number of reasons, including that it's easy to add bugs when passing around raw pointers and that exception safety is an issue when calling <code>new</code>.</p>\n\n<p>Another error, as <a href=\"https://codereview.stackexchange.com/users/26433/dima\">Dima</a> points out, is that you are calling <code>growArray</code> outside your <code>for</code> loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T17:05:20.903",
"Id": "27666",
"ParentId": "27651",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T23:22:00.013",
"Id": "27651",
"Score": "0",
"Tags": [
"c++"
],
"Title": "keep track of friends and number of days not spoken to, dynamic memory location"
}
|
27651
|
<p>I'm a photographer doing many backups. Over the years I found myself with a lot of hard drives. Now I bought a NAS and copied all my pictures on one 3TB RAID 1 using rsync. According to my script, about 1TB of those files are duplicates. That comes from doing multiple backups before deleting files on my laptop and being very messy. I do have a backup of all those files on the old hard drives, but it would be a pain if my script messes things up.</p>
<p>Can you please have a look at my duplicate finder script and tell me if you think I can run it or not? I tried it on a test folder and it seems ok, but I don't want to mess things up on the NAS.</p>
<p>The script has three steps in three files. In this first part I find all image and metadata files and put them into a shelve database (<code>datenbank</code>) with their size as key.</p>
<p>If it's somehow important: It's a synology 713+ and has an ext3 or ext4 filesystem.</p>
<pre><code>import os
import shelve
datenbank = shelve.open(os.path.join(os.path.dirname(__file__),"shelve_step1"), flag='c', protocol=None, writeback=False)
#path_to_search = os.path.join(os.path.dirname(__file__),"test")
path_to_search = "/volume1/backup_2tb_wd/"
file_exts = ["xmp", "jpg", "JPG", "XMP", "cr2", "CR2", "PNG", "png", "tiff", "TIFF"]
walker = os.walk(path_to_search)
counter = 0
for dirpath, dirnames, filenames in walker:
if filenames:
for filename in filenames:
counter += 1
print str(counter)
for file_ext in file_exts:
if file_ext in filename:
filepath = os.path.join(dirpath, filename)
filesize = str(os.path.getsize(filepath))
if not filesize in datenbank:
datenbank[filesize] = []
tmp = datenbank[filesize]
if filepath not in tmp:
tmp.append(filepath)
datenbank[filesize] = tmp
datenbank.sync()
print "done"
datenbank.close()
</code></pre>
<p>This is the second part. Now I drop all file sizes which only have one file in their list and create another shelve database with the MD5 hash as a key and a list of files as a value.</p>
<pre><code>import os
import shelve
import hashlib
datenbank = shelve.open(os.path.join(os.path.dirname(__file__),"shelve_step1"), flag='c', protocol=None, writeback=False)
datenbank_step2 = shelve.open(os.path.join(os.path.dirname(__file__),"shelve_step2"), flag='c', protocol=None, writeback=False)
counter = 0
space = 0
def md5Checksum(filePath):
with open(filePath, 'rb') as fh:
m = hashlib.md5()
while True:
data = fh.read(8192)
if not data:
break
m.update(data)
return m.hexdigest()
for filesize in datenbank:
filepaths = datenbank[filesize]
filepath_count = len(filepaths)
if filepath_count > 1:
counter += filepath_count -1
space += (filepath_count -1) * int(filesize)
for filepath in filepaths:
print counter
checksum = md5Checksum(filepath)
if checksum not in datenbank_step2:
datenbank_step2[checksum] = []
temp = datenbank_step2[checksum]
if filepath not in temp:
temp.append(filepath)
datenbank_step2[checksum] = temp
print counter
print str(space)
datenbank_step2.sync()
datenbank_step2.close()
print "done"
</code></pre>
<p>And finally the most dangerous part. For every MD5 key, I retrieve the file list and do an additional SHA1. If it matches, I delete every file in that list except the first one and create a hard link to replace the deleted files.</p>
<pre><code>import os
import shelve
import hashlib
datenbank = shelve.open(os.path.join(os.path.dirname(__file__),"shelve_step2"), flag='c', protocol=None, writeback=False)
def sha1Checksum(filePath):
with open(filePath, 'rb') as fh:
m = hashlib.sha1()
while True:
data = fh.read(8192)
if not data:
break
m.update(data)
return m.hexdigest()
for hashvalue in datenbank:
switch = True
for path in datenbank[hashvalue]:
if switch:
original = path
original_checksum = sha1Checksum(path)
switch = False
else:
if sha1Checksum(path) == original_checksum:
os.unlink(path)
os.link(original, path)
print "delete: ", path
print "done"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T18:25:49.593",
"Id": "43217",
"Score": "0",
"body": "Python 2.7.5 right?"
}
] |
[
{
"body": "<p>Your code is very risky because you use a weak checksum (md5 - see <a href=\"http://en.wikipedia.org/wiki/Cryptographic_hash_function#Cryptographic_hash_algorithms\" rel=\"nofollow noreferrer\">wikipedia for own study</a>), but since an error would be devastating please use sha256.</p>\n<p>Let me quote <a href=\"https://stackoverflow.com/questions/3431825/python-generating-a-md5-checksum-of-a-file\">this</a>:</p>\n<blockquote>\n<p>I strongly question your use of MD5. You should be at least using\nSHA1. Some people think that as long as you're not using MD5 for\n'cryptographic' purposes, you're fine. But stuff has a tendency\nto end up being broader in scope than you initially expect,\nand your casual vulnerability analysis may prove completely\nflawed. It's best to just get in the habit of using the right\nalgorithm out of the gate. It's just typing a different bunch of<br />\nletters is all. It's not that hard.</p>\n</blockquote>\n<p>Second I have added an "inspection loop" in the main code, so that it creates a csv file which you can play around with to check what the code will do (I checked the csv-data using a pivot table in excel).</p>\n<p>So in summary I have rewritten your code as follows:</p>\n<H1>Python 2.7.4</H1>\n<pre><code>import os\nimport os.path\nimport hashlib\nimport csv\n\n"""\nRecipe:\n1. We identify all files on your system and store those with the wanted\n extensions in a table with this structure:\n\n sha256 | filename.ext | keep | link | size | filepath\n ----------+--------------+-------+-------+------+------\n 23eadf3ed | summer.jpg | True | False | 1234 | /volume1/backup_2tb_wd/randomStuff/\n 23eadf3ed | summer.jpg | False | False | 1234 | /volume1/backup_2tb_wd/Stuff/\n 23eadf3ed | summer.jpg | False | False | 1234 | /volume1/backup_2tb_wd/Holiday/\n\n To spot a link: os.path.islink('path+filename') # returns True if link.\n To get filesize: os.path.getsize(join(root, name)) # returns bytes as integer.\n\n Why links? Because os.link doesn't like soft link. The hard links will\n survive, but any soft links will leave you in a mess.\n\n Then we select 1 record from the distinct list of sha256s and update the\n value for the column "Keep" to "Y". To make sure that we do not catch a\n symlink we check that it is not a link.\n\n2. Now we cycle through the records in the following manner:\n\n3. Now I would like to know how much space you saved. So we create a summary:\n"""\n\ndef hashfile(afile, blocksize=2*1024*1024): # load 2Mb\n with open(afile, 'rb') as f:\n buf = [1]\n shasum = hashlib.sha256()\n while len(buf)>0:\n buf = f.read(blocksize)\n shasum.update(buf)\n return str(shasum.hexdigest()) # hashlib.sha256('foo').hexdigest()\n\ndef convert_to_a_lowercase_set(alist):\n for item in alist:\n alist[alist.index(item)]=item.lower()\n aset = set(alist) \n return aset\n\ndef get_the_data(path_to_search, file_exts):\n file_exts = convert_to_a_lowercase_set(file_exts)\n \n data=[]\n shas=set()\n for root, dirs, files in os.walk(path_to_search):\n for name in files:\n if name[-3:].lower() in file_exts:\n filepath = os.path.join(root, name)\n filename = name\n link = os.path.islink(filepath) # returns True or False\n if link==False:\n size = os.path.getsize(filepath) # returns Int\n sha256 = hashfile(filepath) # returns hexadecimal\n if sha256 not in shas:\n shas.add(sha256)\n keep = True # we keep the first found original file.\n else:\n keep = False # we overwrite soft links with hard links.\n else:\n size = 0\n sha256 = 'aaaaaaaaaaaaaaaaaaa' # returns hexadecimal\n keep = False\n data.append((sha256, filename, keep, link, size, filepath)) #! order matters!\n return data\n\ndef writeCSVfile(data, datafile):\n with open(datafile, 'wb') as f:\n writer = csv.writer(f)\n writer.writerow(('sha256', 'filename', 'keep', 'link', 'size', 'filepath'))\n writer.writerows(data)\n\ndef spaceSaved(data):\n return sum([row[4] for row in data if row[2]==False])\n \ndef relinkDuplicateFiles(data):\n sha256s = (row for row in data if row[2]==True) # unique set of sha256's\n for sha in sha256s:\n original_file = sha[5]\n redudant_copies = [row[5] for row in data if row[0]==sha[0] and row[2]==False and row[3]==False]\n for record in redudant_copies:\n os.remove(record)\n os.link(original_file, record)\n\ndef main():\n # (0) Loading your starting values.\n path_to_search = r'/volume1/backup_2tb_wd/'\n datafile = path_to_search+'data.csv'\n file_exts = ["xmp", "jpg", "JPG", "XMP", "cr2", "CR2", "PNG", "png", "tiff", "TIFF"]\n \n # (1) Get the data\n print "getting the data...\\nThis might take a while..."\n data = get_the_data(path_to_search, file_exts) \n\n # (2) Hard link duplicates in stead of having redundant files.\n msg = """\n --------------------\n Data captured. Initiate Relinking of redundant files...?\n Options:\n Press D + enter to view data file and exit\n Press N + enter to exit\n Press Y + enter to clean up...\n --------------------\n Choice: """\n\n # (3) Providing a panic button...\n while True:\n print msg\n response = raw_input("Response: ")\n if response == "D":\n print "writing CSV file..."\n writeCSVfile(data, datafile)\n print "file written: "+datafile\n elif response == "N":\n print "exiting...."\n data=None\n break\n elif response == "Y":\n print "relinking duplicate files..."\n relinkDuplicateFiles(data)\n print "space saved: "+str(spaceSaved(data))+"bytes"\n break\n else:\n print "no such option. Retry: "\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>I'm sure you will recognise the code of the function: relinkDuplicateFiles(), but beyond that there is little resemblance.</p>\n<H1>Test</H1>\nI have tested the code on a test library on Ubuntu-13.04 with 2.7.4.\n<p>The test was performed as follows:\nBefore running the python script I bash'ed:</p>\n<blockquote>\n<p>ls -liR</p>\n</blockquote>\n<p>This enables me to see the number of links just behind the rights (bold 2)</p>\n<p>3541475 -rw-r--r-- <strong>2</strong> bjorn bjorn 64209 Jun 26 17:20 05hardlink.jpg</p>\n<p><strong>Bash before</strong>:</p>\n<pre><code>bjorn@EEEbox:~/ownCloud/Test$ ls -liR\n.:\ntotal 44\n3541027 drwxr-xr-x 4 bjorn bjorn 4096 Jun 26 13:50 2001\n3541474 drwxr-xr-x 2 bjorn bjorn 4096 Jun 26 17:25 2001b\n3542165 -rw-rw-r-- 1 bjorn bjorn 7054 Jun 26 16:35 data(after).csv\n3542163 -rw-rw-r-- 1 bjorn bjorn 7054 Jun 26 16:34 data(before).csv\n3542168 -rw-rw-r-- 1 bjorn bjorn 8036 Jun 26 17:52 data.csv\n3542164 -rw-rw-r-- 1 bjorn bjorn 7054 Jun 26 16:27 data (org).csv\n3542166 -rwxrw-r-- 1 bjorn bjorn 571 Jun 26 16:57 findhardlinks.sh\n\n./2001:\ntotal 944\n3541401 -rw-r--r-- 1 bjorn bjorn 347991 Apr 23 18:10 008_05a.jpg\n3541320 -rw-r--r-- 1 bjorn bjorn 33055 Apr 23 18:10 04.jpg\n3541261 -rw-r--r-- 1 bjorn bjorn 64209 Apr 23 18:10 05.jpg\n3541234 -rw-r--r-- 1 bjorn bjorn 70573 Apr 23 18:10 06.jpg\n3541454 -rw-r--r-- 1 bjorn bjorn 70906 Apr 23 18:11 07.jpg\n3541694 -rw-r--r-- 1 bjorn bjorn 78251 Apr 23 18:10 08.jpg\n3541393 -rw-r--r-- 1 bjorn bjorn 61995 Apr 23 18:11 09.jpg\n3541737 -rw-r--r-- 1 bjorn bjorn 67659 Apr 23 18:10 10.jpg\n3541790 -rw-r--r-- 1 bjorn bjorn 68620 Apr 23 18:11 11.jpg\n3541086 -rw-r--r-- 1 bjorn bjorn 74453 Apr 23 18:11 12.jpg\n3541028 drwxr-xr-x 3 bjorn bjorn 4096 Jun 26 17:26 2001\n\n./2001/2001:\ntotal 1216\n3541920 -rw-r--r-- 1 bjorn bjorn 347991 Apr 23 18:10 008_05a.jpg\n3541854 -rw-r--r-- 1 bjorn bjorn 95391 Apr 23 18:10 01.jpg\n3541415 -rw-r--r-- 1 bjorn bjorn 68238 Apr 23 18:11 02.jpg\n3541196 -rw-r--r-- 1 bjorn bjorn 74282 Apr 23 18:11 03.jpg\n3541834 -rw-r--r-- 1 bjorn bjorn 33055 Apr 23 18:10 04.jpg\n3541544 -rw-r--r-- 6 bjorn bjorn 33055 Apr 23 18:10 04pyoslink4.jpg\n3541871 -rw-r--r-- 1 bjorn bjorn 64209 Apr 23 18:10 05.jpg\n3541461 -rw-r--r-- 1 bjorn bjorn 70573 Apr 23 18:10 06.jpg\n3541560 -rw-r--r-- 1 bjorn bjorn 70906 Apr 23 18:11 07.jpg\n3541670 -rw-r--r-- 1 bjorn bjorn 78251 Apr 23 18:11 08.jpg\n3541441 -rw-r--r-- 1 bjorn bjorn 61995 Apr 23 18:11 09.jpg\n3541863 -rw-r--r-- 1 bjorn bjorn 67659 Apr 23 18:10 10.jpg\n3541836 -rw-r--r-- 1 bjorn bjorn 68620 Apr 23 18:11 11.jpg\n3541841 -rw-r--r-- 1 bjorn bjorn 74453 Apr 23 18:10 12.jpg\n\n./2001b:\ntotal 312\n3541544 -rw-r--r-- 6 bjorn bjorn 33055 Apr 23 18:10 04hardlink.jpg\n3541544 -rw-r--r-- 6 bjorn bjorn 33055 Apr 23 18:10 04.jpg\n3541961 -rw-r--r-- 1 bjorn bjorn 1220 Jun 26 14:02 04.lnk\n3541544 -rw-r--r-- 6 bjorn bjorn 33055 Apr 23 18:10 04pyoslink2.jpg\n3541544 -rw-r--r-- 6 bjorn bjorn 33055 Apr 23 18:10 04pyoslink3.jpg\n3541544 -rw-r--r-- 6 bjorn bjorn 33055 Apr 23 18:10 04pyoslink.jpg\n3542167 lrwxrwxrwx 1 bjorn bjorn 14 Jun 26 17:16 04softlink.jpg -> ./2001b/04.jpg\n3541475 -rw-r--r-- 2 bjorn bjorn 64209 Jun 26 17:20 05hardlink.jpg\n3541475 -rw-r--r-- 2 bjorn bjorn 64209 Jun 26 17:20 05.jpg\n</code></pre>\n<p>So after running the script you can run the same bash command again:</p>\n<blockquote>\n<p>ls -liR</p>\n</blockquote>\n<p>and get...</p>\n<p><strong>Bash after</strong>:</p>\n<pre><code>bjorn@EEEbox:~/ownCloud/Test$ ls -liR\n.:\ntotal 44\n3541027 drwxr-xr-x 4 bjorn bjorn 4096 Jun 26 18:04 2001\n3541474 drwxr-xr-x 2 bjorn bjorn 4096 Jun 26 18:04 2001b\n3542165 -rw-rw-r-- 1 bjorn bjorn 7054 Jun 26 16:35 data(after).csv\n3542163 -rw-rw-r-- 1 bjorn bjorn 7054 Jun 26 16:34 data(before).csv\n3542168 -rw-rw-r-- 1 bjorn bjorn 8036 Jun 26 17:52 data.csv\n3542164 -rw-rw-r-- 1 bjorn bjorn 7054 Jun 26 16:27 data (org).csv\n3542166 -rwxrw-r-- 1 bjorn bjorn 571 Jun 26 16:57 findhardlinks.sh\n\n./2001:\ntotal 944\n3541401 -rw-r--r-- 2 bjorn bjorn 347991 Apr 23 18:10 008_05a.jpg\n3541544 -rw-r--r-- 8 bjorn bjorn 33055 Apr 23 18:10 04.jpg\n3541475 -rw-r--r-- 4 bjorn bjorn 64209 Jun 26 17:20 05.jpg\n3541234 -rw-r--r-- 2 bjorn bjorn 70573 Apr 23 18:10 06.jpg\n3541454 -rw-r--r-- 2 bjorn bjorn 70906 Apr 23 18:11 07.jpg\n3541694 -rw-r--r-- 2 bjorn bjorn 78251 Apr 23 18:10 08.jpg\n3541393 -rw-r--r-- 2 bjorn bjorn 61995 Apr 23 18:11 09.jpg\n3541737 -rw-r--r-- 2 bjorn bjorn 67659 Apr 23 18:10 10.jpg\n3541790 -rw-r--r-- 2 bjorn bjorn 68620 Apr 23 18:11 11.jpg\n3541086 -rw-r--r-- 2 bjorn bjorn 74453 Apr 23 18:11 12.jpg\n3541028 drwxr-xr-x 3 bjorn bjorn 4096 Jun 26 18:04 2001\n\n./2001/2001:\ntotal 1216\n3541401 -rw-r--r-- 2 bjorn bjorn 347991 Apr 23 18:10 008_05a.jpg\n3541854 -rw-r--r-- 1 bjorn bjorn 95391 Apr 23 18:10 01.jpg\n3541415 -rw-r--r-- 1 bjorn bjorn 68238 Apr 23 18:11 02.jpg\n3541196 -rw-r--r-- 1 bjorn bjorn 74282 Apr 23 18:11 03.jpg\n3541544 -rw-r--r-- 8 bjorn bjorn 33055 Apr 23 18:10 04.jpg\n3541544 -rw-r--r-- 8 bjorn bjorn 33055 Apr 23 18:10 04pyoslink4.jpg\n3541475 -rw-r--r-- 4 bjorn bjorn 64209 Jun 26 17:20 05.jpg\n3541234 -rw-r--r-- 2 bjorn bjorn 70573 Apr 23 18:10 06.jpg\n3541454 -rw-r--r-- 2 bjorn bjorn 70906 Apr 23 18:11 07.jpg\n3541694 -rw-r--r-- 2 bjorn bjorn 78251 Apr 23 18:10 08.jpg\n3541393 -rw-r--r-- 2 bjorn bjorn 61995 Apr 23 18:11 09.jpg\n3541737 -rw-r--r-- 2 bjorn bjorn 67659 Apr 23 18:10 10.jpg\n3541790 -rw-r--r-- 2 bjorn bjorn 68620 Apr 23 18:11 11.jpg\n3541086 -rw-r--r-- 2 bjorn bjorn 74453 Apr 23 18:11 12.jpg\n\n./2001b:\ntotal 312\n3541544 -rw-r--r-- 8 bjorn bjorn 33055 Apr 23 18:10 04hardlink.jpg\n3541544 -rw-r--r-- 8 bjorn bjorn 33055 Apr 23 18:10 04.jpg\n3541961 -rw-r--r-- 1 bjorn bjorn 1220 Jun 26 14:02 04.lnk\n3541544 -rw-r--r-- 8 bjorn bjorn 33055 Apr 23 18:10 04pyoslink2.jpg\n3541544 -rw-r--r-- 8 bjorn bjorn 33055 Apr 23 18:10 04pyoslink3.jpg\n3541544 -rw-r--r-- 8 bjorn bjorn 33055 Apr 23 18:10 04pyoslink.jpg\n3542167 lrwxrwxrwx 1 bjorn bjorn 14 Jun 26 17:16 04softlink.jpg -> ./2001b/04.jpg\n3541475 -rw-r--r-- 4 bjorn bjorn 64209 Jun 26 17:20 05hardlink.jpg\n3541475 -rw-r--r-- 4 bjorn bjorn 64209 Jun 26 17:20 05.jpg\n</code></pre>\n<p>Which is what you wanted, right?</p>\n<H1>Python 3.4+ as command line option</H1>\n<p>Edit 2015/09/06:</p>\n<p>As some time has passed I choose to add another, maybe slightly more generic answer to the problem as a Linux command-line tool for the user who is not just looking for images, but duplicate files in general.</p>\n<p>If run as</p>\n<pre><code>:~$ python3.4 /path/to/directory/root/that/needs/cleanup\n</code></pre>\n<p>the code will:</p>\n<ul>\n<li>Find every file in the tree</li>\n<li>Keep all (unique) files</li>\n<li>Hard-link all duplicate files to the first found unique file.</li>\n<li>Delete duplicate copies.</li>\n</ul>\n<p>The hard-links give the advantage that the file-system will keep track of the links and only delete the file the day where there are no more hard links pointing at it. The only risk the user needs to think about is that if he/she changes the file, it affects all linked pointers. So make a copy with a new name before changing any files.</p>\n<p>The core operations are:</p>\n<pre><code>def clean_up(root_path, dryrun=False, verbose=False):\n seen_files = {}\n for root, dirs, files in walk(root_path):\n for fname in files:\n fpath = path.join(root,fname)\n link = path.islink(fpath)\n if not link:\n s256 = sha256sum(fpath)\n if s256 not in seen_files:\n seen_files[s256] = fpath # we've found a new file!\n else:\n old_pointer = fpath # there's a new name for a known file.\n new_pointer = seen_files[s256] # let's save the space by symlinking, but keep the name.\n</code></pre>\n<p>The full command-line tool looks like this:</p>\n<pre><code>import sys\nimport hashlib\nfrom os import walk, remove, link, path\n\ndef clean_up(root_path, dryrun=False, verbose=False):\n stats = {'space saved': 0, 'files found': 0, 'space used': 0, 'dryrun': dryrun, 'verbose': verbose}\n seen_files = {}\n for root, dirs, files in walk(root_path):\n for fname in files:\n stats['files found'] += 1\n fpath = path.join(root,fname)\n link = path.islink(fpath)\n size = path.getsize(fpath)\n if not link:\n s256 = sha256sum(fpath)\n if s256 not in seen_files:\n seen_files[s256] = fpath # we've found a new file!\n stats['space used'] += size\n else:\n old_pointer = fpath # there's a new name for a known file.\n new_pointer = seen_files[s256] # let's save the space by symlinking, but keep the name.\n stats['space saved'] += size\n if not dryrun:\n symlink(old_pointer, new_pointer)\n if verbose:\n print("relinked {} to {}".format(old_pointer, new_pointer))\n if verbose:\n if not link:\n type = "file"\n else:\n type = "link"\n print(type, fpath, size, sha256sum)\n if verbose:\n for k, v in sorted(stats):\n print("{}: {}".format(k, v))\n\ndef symlink(old, new):\n remove(old)\n link(new, old)\n\ndef sha256sum(target, blocksize=2*1024*1024):\n with open(target, 'rb') as f:\n buf = [1]\n shasum = hashlib.sha256()\n while len(buf) > 0:\n buf = f.read(blocksize)\n shasum.update(buf)\n return str(shasum.hexdigest())\n\n\nif __name__ == "__main__":\n if len(sys.argv) < 2:\n print("usage: python3.4 {} <path> [--dryrun][--verbose]".format(sys.argv[0]))\n sys.exit(1)\n if not path.exists(sys.argv[1]) or path.isfile(sys.argv[1]):\n print("Can't find the supplied path: {}".format(sys.argv[1]))\n sys.exit(1)\n\n root_path = sys.argv[1]\n dryrun, verbose = False, False\n if "--dryrun" in sys.argv:\n dryrun = True\n if "--verbose" in sys.argv:\n verbose = True\n\n clean_up(root_path, dryrun, verbose)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-06-26T17:35:12.317",
"Id": "27811",
"ParentId": "27652",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T00:07:19.347",
"Id": "27652",
"Score": "5",
"Tags": [
"python",
"linux",
"file-system"
],
"Title": "Replacing duplicate files with hard links"
}
|
27652
|
<p>The code works but I want to split it into functions and make it more reusable. The way it is now, the code is not reusable. I want the parts which replaces the query string and the part that populates with the number of items to be reusable for other classes, so ideally I want to make'em functions but then I suppose I must pass the template variable to those functions?</p>
<pre><code>class RegionSearch(SearchBaseHandler):
"""Handles regional search requests."""
def get(self):
"""Handles a get request with a query."""
category = None
cityentity = None
country = ''
if self.request.host.find('hipheap') > -1: country = 'USA'
elif self.request.host.find('koolbusiness') > -1: country = 'India'
elif self.request.host.find('montao') > -1: country = 'Brasil'
regionID = 0
cityID = 0
categoryID = 0
regionname = None
cityname = None
categoryname = None
region = None
cursor = self.request.get("cursor")
uri = urlparse(self.request.uri)
query = ''
regionid = self.request.get("regionid")
cityid = self.request.get("cityid")
categoryid = self.request.get("category")
if uri.query:
query = parse_qs(uri.query)
try:
query = query['query'][0]
except KeyError, err:
query = ''
#logging.info('KeyError')
#Try find region ID and/or cityID and categoryID a.s.a.p.
if regionid or query.find('regionID') > -1:
regionID = re.sub("^regionID=(\d+).*", r'\1', query)
region = Region.get_by_id(long(regionID))
regionname = region.name
if regionid:
regionID = regionid
region = Region.get_by_id(long(regionID))
regionname = region.name
if cityid or query.find('cityID') > -1:
cityID = re.sub("^.*cityID=(\d+).*", r'\1', query)
if cityid: cityID = cityid
city = montaomodel.City.get_by_id(long(cityID))
cityID = city.key().id()
cityentity = city
cityname = city.name
region = Region.get_by_id(long(city.region.key().id()))
regionID = region.key().id()
regionname = region.name
regionentity = region
regionname = region.name
if categoryid or query.find('category') > -1:
categoryID = re.sub("^.*category=(\d+).*", r'\1', query)
if categoryid: categoryID = categoryid
logging.debug('categoryID %s' , str(categoryID))
#logging.debug('region id %s' , regionID)
#logging.debug('city id %s' , cityID)
#logging.debug('regionname %s' , regionname)
#logging.debug('cityname %s' , cityname)
if cursor: results = find_documents(query, 50, search.Cursor(cursor))
else: results = find_documents(query, 50, search.Cursor())
next_cursor = None
if results and results.cursor: next_cursor = results.cursor.web_safe_string
number_returned = 0
if results: number_returned = len(results.results)
namedquery = query
query = query.replace(' and company_ad=0','').replace(' and company_ad=1','').replace(' and category:(6010 OR 6020 OR 6030 OR 6040 OR 6090)','').replace(' and category:(6010 OR 6020 OR 6030 OR 6040 OR 6090)','').replace(' and category:(1020 OR 1010 OR 1030 OR 1050 OR 1080 OR 1100 OR 1090)','').replace(' and category:(2010 OR 2030 OR 2040 OR 2080 OR 2070)','').replace(' and category:(3040 OR 3050 OR 3030 OR 3060)','').replace(' and category:(4010 OR 4020 OR 4040 OR 4030 OR 4090 OR 4060 OR 4070)','')
query = re.sub("regionID=\d+", "", query)
query = query.replace('category and','')
query = query.replace('type=s','')
query = query.replace('type=w','')
query = query.replace('type=r','')
query = query.replace('type=b','')
query = query.replace('cityID and','')
query = query.replace('and','')
query = query.replace('regionID','')
query = query.replace('=','%3D')
namedquery = namedquery.replace('=','%3D')
query = re.sub("cityID%3D\d+", "", query)
query = re.sub("category%3D\d+", "", query)
query = query.replace(' ',' ')
if regionID == '4703187': regionname = 'Andaman &amp; Nicobar Islands'
elif regionID == '4694186': regionname = 'Andhra Pradesh'
elif regionID == '4699188': regionname = 'Arunachal Pradesh'
elif regionID == '4692186': regionname = 'Assam'
elif regionID == '4702186': regionname = 'Bihar'
elif regionID == '4698185': regionname = 'Chandigarh'
elif regionID == '4676188': regionname = 'Chhattisgarh'
elif regionID == '4691190': regionname = 'Dadra &amp; Nagar Haveli'
elif regionID == '4704183': regionname = 'Daman &amp; Diu'
elif regionID == '4699183': regionname = 'Delhi'
elif regionID == '4702187': regionname = 'Goa'
elif regionID == '4691189': regionname = 'Gujarat'
elif regionID == '4700186': regionname = 'Haryana'
elif regionID == '4703185': regionname = 'Himachal Pradesh'
elif regionID == '4694187': regionname = 'Jammu &amp; Kashmir'
elif regionID == '4699189': regionname = 'Jharkhand'
elif regionID == '4701185': regionname = 'Karnataka'
elif regionID == '4695189': regionname = 'Kerala'
elif regionID == '4700189': regionname = 'Lakshadweep'
elif regionID == '4697186': regionname = 'Madhya Pradesh'
elif regionID == '4694184': regionname = 'Maharashtra'
elif regionID == '4700187': regionname = 'Manipur'
elif regionID == '4703186': regionname = 'Meghalaya'
elif regionID == '4698184': regionname = 'Mizoram'
elif regionID == '4692187': regionname = 'Nagaland'
elif regionID == '4696185': regionname = 'Orissa'
elif regionID == '4676189': regionname = 'Pondicherry'
elif regionID == '4693185': regionname = 'Punjab'
elif regionID == '4701186': regionname = 'Rajasthan'
elif regionID == '4701187': regionname = 'Sikkim'
elif regionID == '4701188': regionname = 'Tamil Nadu'
elif regionID == '4697187': regionname = 'Tripura'
elif regionID == '4699190': regionname = 'Uttaranchal'
elif regionID == '4692188': regionname = 'Uttar Pradesh'
elif regionID == '4700188': regionname = 'West Bengal'
elif regionID and query.find('cityID') < 1:
region = Region.get_by_id(long(regionID))
regionname = region.name
form = SearchForm()
form.w.choices = [
('4703187', u'Andaman & Nicobar Islands'),
('4694186', u'Andhra Pradesh'),
('4699188', u'Arunachal Pradesh'),
('4692186', u'Assam'),
('4702186', u'Bihar'),
('4698185', u'Chandigarh'),
('4676188', u'Chhattisgarh'),
('4691190', u'Dadra & Nagar Haveli'),
('4704183', u'Daman & Diu'),
('4699183', u'Delhi'),
('4702187', u'Goa'),
('4691189', u'Gujarat'),
('4700186', u'Haryana'),
('4703185', u'Himachal Pradesh'),
('4694187', u'Jammu & Kashmir'),
('4699189', u'Jharkhand'),
('4701185', u'Karnataka'),
('4695189', u'Kerala'),
('4700189', u'Lakshadweep'),
('4697186', u'Madhya Pradesh'),
('4694184', u'Maharashtra'),
('4700187', u'Manipur'),
('4703186', u'Meghalaya'),
('4698184', u'Mizoram'),
('4692187', u'Nagaland'),
('4696185', u'Orissa'),
('4676189', u'Pondicherry'),
('4693185', u'Punjab'),
('4701186', u'Rajasthan'),
('4701187', u'Sikkim'),
('4701188', u'Tamil Nadu'),
('4697187', u'Tripura'),
('4699190', u'Uttaranchal'),
('4692188', u'Uttar Pradesh'),
('4700188', u'West Bengal'),
]
jobs_count = None
estate_count = None
electronics_count = None
home_count = None
leisure_count = None
vehicles_count = None
if (region or cityentity):
#to do:use memcache
form.area.choices = [] # to do: use memcache for the list
for cityitem in City.all().filter('region =', region.key()).order('-vieworder').order('name').fetch(99999):
form.area.choices.append([str(cityitem.key().id()), cityitem.name])
if cityentity: form.area.data = str(cityentity.key().id())
if self.request.host.find('hipheap') > -1:
if region and (str(region.key().id()), region.name) in form.w_us.choices: form.w_us.choices.remove((str(region.key().id()), region.name))
else:
if region and (str(region.key().id()), region.name) in form.w.choices: form.w.choices.remove((str(region.key().id()), region.name))
if cityID and int(cityID) > 0:
jobs_count_gql = db.GqlQuery("SELECT * FROM Ad WHERE category IN ('6010', '6020', '6030', '6040', '6090') AND cities = KEY('City', :1) AND published = True AND modified > :2 ", cityID, datetime.now() - timedelta(days=609))
jobs_count= jobs_count_gql.count(limit=40000)
estate_count_gql = db.GqlQuery("SELECT * FROM Ad WHERE category IN ('1010', '1020', '1030', '1050', '1080', '1090', '1100') AND cities = KEY('City', :1) AND published = True AND modified > :2 ", cityID, datetime.now() - timedelta(days=609))
estate_count= estate_count_gql.count(limit=40000)
electronics_count_gql = db.GqlQuery("SELECT * FROM Ad WHERE category IN ('5010', '5020', '5030', '5040') AND cities = KEY('City', :1) AND published = True AND modified > :2 ", cityID, datetime.now() - timedelta(days=609))
electronics_count= electronics_count_gql.count(limit=40000)
home_count_gql = db.GqlQuery("SELECT * FROM Ad WHERE category IN ('3030', '3040', '3050', '3060') AND published = True AND cities = KEY('City', :1) AND modified > :2 ", cityID, datetime.now() - timedelta(days=609))
home_count= home_count_gql.count(limit=40000)
leisure_count_gql = db.GqlQuery("SELECT * FROM Ad WHERE category IN ('4010', '4020', '4030', '4040', '4060', '4090') AND cities = KEY('City', :1) AND published = True AND modified > :2 ", cityID, datetime.now() - timedelta(days=609))
leisure_count= leisure_count_gql.count(limit=40000)
vehicles_count_gql = db.GqlQuery("SELECT * FROM Ad WHERE category IN ('2010', '2030', '2040', '2070', '2080') AND cities = KEY('City', :1) AND published = True AND modified > :2 ", cityID, datetime.now() - timedelta(days=609))
vehicles_count= vehicles_count_gql.count(limit=40000)
elif regionID and int(regionID) > 0:
logging.debug('regionID: %d', int(regionID))
regionID = int(regionID)
jobs_count_gql = db.GqlQuery("SELECT * FROM Ad WHERE category IN ('6010', '6020', '6030', '6040', '6090') AND regions = KEY('Region', :1) AND published = True AND modified > :2 ", regionID, datetime.now() - timedelta(days=609))
jobs_count= jobs_count_gql.count(limit=40000)
estate_count_gql = db.GqlQuery("SELECT * FROM Ad WHERE category IN ('1010', '1020', '1030', '1050', '1080', '1090', '1100') AND regions = KEY('Region', :1) AND published = True AND modified > :2 ", regionID, datetime.now() - timedelta(days=609))
estate_count= estate_count_gql.count(limit=40000)
electronics_count_gql = db.GqlQuery("SELECT * FROM Ad WHERE category IN ('5010', '5020', '5030', '5040') AND regions = KEY('Region', :1) AND published = True AND modified > :2 ", regionID, datetime.now() - timedelta(days=609))
electronics_count= electronics_count_gql.count(limit=40000)
home_count_gql = db.GqlQuery("SELECT * FROM Ad WHERE category IN ('3030', '3040', '3050', '3060') AND published = True AND regions = KEY('Region', :1) AND modified > :2 ", regionID, datetime.now() - timedelta(days=609))
home_count= home_count_gql.count(limit=40000)
leisure_count_gql = db.GqlQuery("SELECT * FROM Ad WHERE category IN ('4010', '4020', '4030', '4040', '4060', '4090') AND regions = KEY('Region', :1) AND published = True AND modified > :2 ", regionID, datetime.now() - timedelta(days=609))
leisure_count= leisure_count_gql.count(limit=40000)
vehicles_count_gql = db.GqlQuery("SELECT * FROM Ad WHERE category IN ('2010', '2030', '2040', '2070', '2080') AND regions = KEY('Region', :1) AND published = True AND modified > :2 ", regionID, datetime.now() - timedelta(days=609))
vehicles_count= vehicles_count_gql.count(limit=40000)
template_values = {
'results': results,'cursor':next_cursor, 'country' : country,'user': self.current_user,
'number_returned': number_returned,'loggedin': self.logged_in, 'VERSION': VERSION,
'region' : region,'regionname' : regionname,'jobs_count':jobs_count,'estate_count':estate_count,'electronics_count':electronics_count,
'home_count':home_count,'leisure_count':leisure_count,'vehicles_count':vehicles_count,
'cityentity': cityentity, 'request' : self.request, 'categoryID' : categoryID,
'form' : form, 'query' : query, 'namedquery' : namedquery, 'cityname' : cityname,'category': category, 'jobs_count': jobs_count,
}
self.render_template('q.htm', template_values)
</code></pre>
<h2>Update 1</h2>
<p>I could make functions that call memcache for the GQL parts so it's a <a href="http://pastebin.com/VNAgYQcL">bit better now</a>. </p>
|
[] |
[
{
"body": "<p>Start with making a dictionary for the regionId-to-name part:</p>\n\n<pre><code>region_id_to_name = {'4694186': 'Andhra Pradesh', ... } #very long\n</code></pre>\n\n<p>And put it, along the <code>form.w.choices</code> list (which is actually exactly the same dictionary) outside the class, or as an instance variable. It should probably be read from a file, but that's a different story.</p>\n\n<p>You can turn most of the local variables into instance variables.</p>\n\n<p>The most basic thing is to ask \"what am I doing here\" in each part of this function. if you can answer, take this description, add a <code>def</code> before and arguments after, and you'll have a function/method.</p>\n\n<p>Here's a simple example:</p>\n\n<pre><code>def mutate_query(self, query):\n query = query.replace(...) # whatever you are doing here\n query = re.sub(\"regionID=\\d+\", \"\", query)\n to_remove = ['category and', 'type=s', 'type=w', 'type=r','type=b','cityID and','and','regionID']\n for s in to_remove:\n query = query.replace(s,'')\n query = query.replace('=','%3D')\n query = re.sub(\"cityID%3D\\d+\", \"\", query)\n query = re.sub(\"category%3D\\d+\", \"\", query)\n query = query.replace(' ',' ')\n return query\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T02:25:59.230",
"Id": "43170",
"Score": "0",
"body": "Thank you but if I put the `form.w.choices` outside the class it won't refresh and I need it to refresh since I'm putting things in and out of the options. So I think the variable must be in the class anyhow. The region_id dictionary is whwat I'm working with now doing as you advice here, and I've also made functions that use memcache and updated the question with the refactored code. Thanks a lot for all the help and do comment if I said something here that you want to elaborate on or discuss."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T19:39:07.240",
"Id": "27675",
"ParentId": "27657",
"Score": "6"
}
},
{
"body": "<p>Without checking any further, you can already save yourself 10 lines if you don't first initialize all local variables and afterwards override all of them anyway by assigning the (potentially defaulted) result from the request. \nE.g. as in <code>regionid = self.request.get(\"regionid\", 0)</code>.</p>\n\n<p>While being at it, you should plan what you want to do with all these local variables afterwards. If you don't want to process them already in <code>get()</code> (and you probably don't want this) and if you don't want to pass them all as separate args to another processing function (probably not wanted too), you might consider putting them into instance variables, a dict, another helper object, a named tuple, or whatever fits your follow up processing best.</p>\n\n<p>And the country and url processing should be factorized out in helpers, so that all processing in <code>get()</code> is on one logical level - fetch a (potentially defaulted) result from the request and assign it, no more details here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T02:27:36.940",
"Id": "43171",
"Score": "0",
"body": "That is very good advice indeed thanks a lot. You saved me many lines. I could also update the question with a new version of the class where it's using functions and memcache so it should be both faster and more modular now. I've made the changes that you mention put they are not part of an update yet, the changes will be part of the next update."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T04:28:51.513",
"Id": "43172",
"Score": "1",
"body": "Happy to hear that, you're very welcome."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T20:46:44.103",
"Id": "27678",
"ParentId": "27657",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "27675",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T09:31:07.527",
"Id": "27657",
"Score": "6",
"Tags": [
"python",
"search",
"google-app-engine"
],
"Title": "Handling regional search requests"
}
|
27657
|
<p>I'm using JPA 2.0, Mojarra 2.1.9 and its component library Primefaces 3.5. I have a table in MySQL database named <code>state_table</code> with three columns.</p>
<ul>
<li>state_id (BigInt)</li>
<li>state_name (Varchar)</li>
<li>country_id (BigInt)</li>
</ul>
<p><code>state_id</code> is a auto-generated primary key and <code>country_id</code> is a foreign key that references a primary key of the <code>country</code> table.</p>
<hr>
<p>This table is mapped by its corresponding entity class named <code>StateTable</code> and the data held by this table are displayed in a Primefaces <code>DataTable</code>, <code><p:dataTable>...</p:dataTable></code>.</p>
<p>The <code>DataTable</code> column header contains a clickable sort area, <code><div></code> for each column with a sort direction for sorting, when this area is clicked, a String, either <code>ASCENDING</code> or <code>DESCENDING</code> representing the sort order is rendered and a text box for filtering (searching) in which a user enters a search item for each column.</p>
<hr>
<p>So ultimately, what I get in JSF managed bean is a List of type <code>java.util.List<org.primefaces.model.SortMeta></code> representing sort orders of the columns of the <code>DataTable</code> that a user wishes.</p>
<p>And a Map of type <code>java.util.Map<java.lang.String, java.lang.String></code> representing the search column names as keys and search items of the corresponding columns as values (a search item is entered by a user in a text box on the column header of each column of <code>DataTable</code>).</p>
<hr>
<p>In short, I use <code>List<SortMeta></code> for sorting and <code>Map<String, String></code> for filtering/searching.</p>
<p>My code in one of the DAOs to get a list of rows after sorting and filtering is as follows.</p>
<pre><code>@Override
@SuppressWarnings("unchecked")
public List<StateTable> getList(int first, int pageSize, List<SortMeta> multiSortMeta, Map<String, String>filters)
{
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<StateTable> criteriaQuery = criteriaBuilder.createQuery(StateTable.class);
Metamodel metamodel=entityManager.getMetamodel();
EntityType<StateTable> entityType = metamodel.entity(StateTable.class);
Root<StateTable>root=criteriaQuery.from(entityType);
Join<StateTable, Country> join = null;
//Sorting
List<Order> orders=new ArrayList<Order>();
if(multiSortMeta!=null&&!multiSortMeta.isEmpty())
{
for(SortMeta sortMeta:multiSortMeta)
{
if(sortMeta.getSortField().equalsIgnoreCase("stateId"))
{
orders.add(sortMeta.getSortOrder().equals(SortOrder.ASCENDING)?criteriaBuilder.asc(root.get(StateTable_.stateId)):criteriaBuilder.desc(root.get(StateTable_.stateId)));
}
else if(sortMeta.getSortField().equalsIgnoreCase("stateName"))
{
orders.add(sortMeta.getSortOrder().equals(SortOrder.ASCENDING)?criteriaBuilder.asc(root.get(StateTable_.stateName)):criteriaBuilder.desc(root.get(StateTable_.stateName)));
}
else if(sortMeta.getSortField().equalsIgnoreCase("country.countryName")) // Yes, Primefaces DataTable renders this ugly name in case of a nested property representing a foreign key relationship.
{
join = root.join(StateTable_.countryId, JoinType.INNER);
orders.add(sortMeta.getSortOrder().equals(SortOrder.ASCENDING)?criteriaBuilder.asc(join.get(Country_.countryName)):criteriaBuilder.desc(join.get(Country_.countryName)));
}
}
}
//Filtering/searching
List<Predicate>predicates=new ArrayList<Predicate>();
if(filters!=null&&!filters.isEmpty())
{
for(Entry<String, String>entry:filters.entrySet())
{
if(entry.getKey().equalsIgnoreCase("stateId"))
{
predicates.add(criteriaBuilder.equal(root.get(StateTable_.stateId), Long.parseLong(entry.getValue())));
}
else if(entry.getKey().equalsIgnoreCase("stateName"))
{
predicates.add(criteriaBuilder.like(root.get(StateTable_.stateName), "%"+entry.getValue()+"%"));
}
else if(entry.getKey().equalsIgnoreCase("country.countryName"))// Yes, Primefaces DataTable renders this ugly name in case of a nested property representing a foreign key relationship.
{
if(join==null)
{
join = root.join(StateTable_.countryId, JoinType.INNER);
}
predicates.add(criteriaBuilder.like(join.get(Country_.countryName), "%"+entry.getValue()+"%"));
}
}
}
if(predicates!=null&&!predicates.isEmpty())
{
criteriaQuery.where(predicates.toArray(new Predicate[0]));
}
if(orders!=null&&!orders.isEmpty())
{
criteriaQuery.orderBy(orders);
}
else
{
criteriaQuery.orderBy(criteriaBuilder.desc(root.get(StateTable_.stateId)));
}
TypedQuery<StateTable> typedQuery = entityManager.createQuery(criteriaQuery).setFirstResult(first).setMaxResults(pageSize);
return typedQuery.getResultList();
}
</code></pre>
<p>This works as expected but as it can be noticed, the <code>if-else if</code> ladder inside the <code>foreach</code> loop can contain many conditional checks as the number of columns in a database table are increased.</p>
<p>Each column requires a conditional check for both sorting and searching. Is there an efficient way to get rid of these conditional checks that can ultimately remove or at least minimize this <code>if-else if</code> ladder?</p>
<p>P.S. In case of country, I'm doing sorting and searching on <code>countryName</code> (which is available in the parent table <code>country</code>) rather than <code>countryId</code>. Hence, I'm using <code>Join</code>, in this case. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T14:39:14.253",
"Id": "46715",
"Score": "0",
"body": "You probably have to use introspection (or Commons BeanUtils), to get rid of the if-else-if's. Something like: \"if the key does not contain a dot, get the property with this name from the main table; if it contains a dot, get the property from the joined table\". This will create a constant-size algorithm for any number of properties."
}
] |
[
{
"body": "<p>I believe, you should not mix your architecture layers. \n<code>SortMeta</code> is a GUI class. If you want to change your GUI-Framework, or use another one, you have to refactor your Finder. Therefore you should not use <code>SortMeta</code> (GUI-Class) in your business layer. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-09T06:05:34.153",
"Id": "32446",
"ParentId": "27659",
"Score": "3"
}
},
{
"body": "<p>I suggest you to wrap parameters</p>\n\n<pre><code>int first, int pageSize, List<SortMeta> multiSortMeta, Map<String, String>filters\n</code></pre>\n\n<p>And don't mix classes from primefeaces and dao as suggested in axels comment.\nWhen creating this wrapper convert this view classes to some custom backend classes.</p>\n\n<p>in some object. I have <code>DataTableProperites</code> class. It is much readible and convenient to use.\nInstead of <code>multiSortMeta!=null&&!multiSortMeta.isEmpty()</code> use <a href=\"http://commons.apache.org/proper/commons-collections/javadocs/api-3.2.1/org/apache/commons/collections/CollectionUtils.html#isEmpty%28java.util.Collection%29\" rel=\"nofollow\">CollectionUtils.isEmpty</a></p>\n\n<p>I recommend you to extract nested ifs and loops to methods. Maybe when you extract them you will find some place where you can remove duplication.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-22T20:08:28.690",
"Id": "110342",
"Score": "0",
"body": "Regarding CollectionUtils.isEmpty: or you can just leave your null check as is and remove !multiSortMeta.isEmpty() that doesn't do anything anyway... And leave the \"commons\" dependency for what it is (something not *that* common)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-09T07:24:42.260",
"Id": "32448",
"ParentId": "27659",
"Score": "1"
}
},
{
"body": "<p>This part of your code is not very readable:</p>\n\n<pre><code>if(sortMeta.getSortField().equalsIgnoreCase(\"stateId\"))\n{\n orders.add(sortMeta.getSortOrder().equals(SortOrder.ASCENDING)?criteriaBuilder.asc(root.get(StateTable_.stateId)):criteriaBuilder.desc(root.get(StateTable_.stateId)));\n}\nelse if(sortMeta.getSortField().equalsIgnoreCase(\"stateName\"))\n{\n orders.add(sortMeta.getSortOrder().equals(SortOrder.ASCENDING)?criteriaBuilder.asc(root.get(StateTable_.stateName)):criteriaBuilder.desc(root.get(StateTable_.stateName)));\n}\nelse if(sortMeta.getSortField().equalsIgnoreCase(\"country.countryName\")) // Yes, Primefaces DataTable renders this ugly name in case of a nested property representing a foreign key relationship.\n{\n join = root.join(StateTable_.countryId, JoinType.INNER);\n orders.add(sortMeta.getSortOrder().equals(SortOrder.ASCENDING)?criteriaBuilder.asc(join.get(Country_.countryName)):criteriaBuilder.desc(join.get(Country_.countryName)));\n}\n</code></pre>\n\n<p>What I would do is to store several things in local variables, so you don't have to repeat calls to getters over and over again. Since your call to <code>orders.add</code> is performed in all if-statements, it can be placed after the ifs to reduce code duplication.</p>\n\n<pre><code>String sortField = sortMeta.getSortField();\nYourType sortOrder = sortMeta.getSortOrder();\nYourType id = null;\nif(sortField.equalsIgnoreCase(\"stateId\") || )\n{\n id = root.get(StateTable_.stateId);\n}\nelse if(sortField.equalsIgnoreCase(\"stateName\"))\n{\n id = root.get(StateTable_.stateName);\n}\nelse if(sortField.equalsIgnoreCase(\"country.countryName\")) \n{\n // Yes, Primefaces DataTable renders this ugly name in case of a nested property representing a foreign key relationship.\n join = root.join(StateTable_.countryId, JoinType.INNER);\n id = join.get(Country_.countryName);\n}\n\nif (id != null)\n orders.add(sortOrder.equals(SortOrder.ASCENDING) ? criteriaBuilder.asc(id) : criteriaBuilder.desc(id));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T20:36:24.077",
"Id": "35717",
"ParentId": "27659",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T10:50:19.320",
"Id": "27659",
"Score": "3",
"Tags": [
"java",
"jpa",
"jsf-2"
],
"Title": "Efficient way of handling multiple sorting and filtering using JPA"
}
|
27659
|
<p>I was asking if the following code has a correct semantically markup, or can it better, and so yes, how:</p>
<pre><code> <!-- Start container website -->
<header id="header">
<div class="container_12">
<div class="grid_12">
<a href="#" id="logo"><img src="images/logo.png" alt="Logo"></a>
<a href="#" id="nav-icon"><img src="images/list-icon.png" alt="Responsive list icon"></a>
<nav id="primary-navwrapper" class="inactive">
<ul id="listnav">
<li><a href="index.html" id="current">Home</a></li>
<li><a href="pages/portfolio.html">Portfolio</a></li>
<li><a href="pages/blog.html">Blog</a></li>
<li><a href="pages/service.html">Service</a></li>
<li><a href="pages/about.html">About</a></li>
<li><a href="pages/contact.php">Contact</a></li>
</ul><!-- End ul#listnav -->
</nav><!-- End nav#primary-navwrapper -->
</div><!-- End div.grid_12 -->
<div class="clear"></div><!-- End div.clear -->
</div><!-- End div.container_12 -->
</header><!-- End header#header -->
<div id="container">
<section id="hero">
<div class="flexslider">
<ul class="slides">
<li>
<img src="images/flexslider/slide-1.jpg" alt="" />
<div class="flex-caption">
<div class="container_12">
<header class="grid_12">
<h1>Fris. Responsive. Retina Ready.</h1>
<p>
Donec sed odio dui. Nulla vitae elit libero, a pharetra augue. Nullam id dolor id nibh ultricies vehicula ut id elit.
Integer posuere erat a ante venenatis dapibus posuere velit aliquet.
</p>
<a href="#" class="button tertiaire custom">Read the blog &rarr;</a>
</header><!-- End header.grid_12 flex-caption -->
<div class="clear"></div><!-- End div.clear -->
</div><!-- End div.container_12 -->
</div><!-- End div.flex-caption -->
</li>
<li>
<img src="images/flexslider/slide-5.jpg" alt="" />
</li>
</ul><!-- End ul.slides -->
</div><!-- End div.flexslider -->
</section><!-- End section#hero -->
<section id="introduce">
<div class="container_12">
<ul id="featured-list">
<li class="grid_4 centered">
<img src="images/branding.png" alt="Branding & Logo">
<h3>Branding & Logo</h3>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus quis ante eros. Aliquam in eros mauris, sed adipiscing neque. Donec tristique bibendum vulputate.
<br>
<br>
Vivamus aliquam semper sapien, quis aliquet purus rutrum id.
</p>
</li><!-- End li.grid_4 -->
<li class="grid_4 centered">
<img src="images/webdesign.png" alt="Web Design">
<h3>Web Design</h3>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus quis ante eros. Aliquam in eros mauris, sed adipiscing neque. Donec tristique bibendum vulputate.
<br>
<br>
Vivamus aliquam semper sapien, quis aliquet purus rutrum id.
</p>
</li><!-- End li.grid_4 -->
<li class="grid_4 centered">
<img src="images/webdevelopment.png" alt="Web Development">
<h3>Web Development</h3>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus quis ante eros. Aliquam in eros mauris, sed adipiscing neque. Donec tristique bibendum vulputate.
<br>
<br>
Vivamus aliquam semper sapien, quis aliquet purus rutrum id.
</p>
</li><!-- End li.grid_4 -->
</ul><!-- End ul#featured-list -->
<div class="grid_12">
<div id="flick-through">
<div id="placer"><img src="images/flick/flick.jpg" alt=""></div>
<ul id="image-loop">
<li><img src="images/flick/image-1.jpg" alt=""></li>
<li><img src="images/flick/image-2.jpg" alt=""></li>
<li><img src="images/flick/image-3.jpg" alt=""></li>
<li><img src="images/flick/image-4.jpg" alt=""></li>
<li><img src="images/flick/image-5.jpg" alt=""></li>
<li><img src="images/flick/image-6.jpg" alt=""></li>
<li><img src="images/flick/image-7.jpg" alt=""></li>
<li><img src="images/flick/image-8.jpg" alt=""></li>
</ul><!-- End #image-loop -->
</div><!-- End div#flick-through -->
<img src="images/large-cinema-display.png" alt="Cinema Display" id="cinema-display">
</div><!-- End div.grid_12 -->
<div class="clear"></div><!-- End div.clear -->
</div><!-- End div.container_12 -->
</section><!-- End section#introduce -->
<hr>
<section id="portfolio-entry" class="alt">
<div class="container_12">
<header class="centered">
<h1>Latest work</h1>
<p>
Donec sed odio dui. Nulla vitae elit libero, a pharetra augue. Nullam id dolor id nibh ultricies vehicula ut id elit.
<br>
Integer posuere erat a ante venenatis dapibus posuere velit aliquet.
</p>
</header><!-- End header.centered -->
<ul class="entrybox">
<li class="grid_4 portfolio-post">
<header class="post-thumb">
<a href="#"><img src="images/portfolio-thumb.png" alt="Post thumbnail"></a>
</header><!-- End header.post-thumb -->
<aside>
<h3><a href="#" title="">Title Project</a></h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</aside><!-- End aside -->
</li><!-- End li.grid_4 portfolio-post -->
<li class="grid_4 portfolio-post">
<header class="post-thumb">
<a href="#"><img src="images/portfolio-thumb.png" alt="Post thumbnail"></a>
</header><!-- End header.post-thumb -->
<aside>
<h3><a href="#" title="">Title Project</a></h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</aside><!-- End aside -->
</li><!-- End li.grid_4 portfolio-post -->
<li class="grid_4 portfolio-post">
<header class="post-thumb">
<a href="#"><img src="images/portfolio-thumb.png" alt="Post thumbnail"></a>
</header><!-- End header.post-thumb -->
<aside>
<h3><a href="#" title="">Title Project</a></h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</aside><!-- End aside -->
</li><!-- End li.grid_4 portfolio-post -->
</ul><!-- End ul.entrybox -->
<div class="grid_12">
<a href="#" class="button primary">View the Portfolio &rarr;</a>
</div><!-- End div.grid_12 -->
<div class="clear"></div><!-- End div.clear -->
</div><!-- End div.container_12 -->
</section><!-- End section#portfolio-entry .alt -->
<hr>
<section id="blog-entry">
<div class="container_12">
<header class="centered">
<h1>Recent blog posts</h1>
<p>
Donec sed odio dui. Nulla vitae elit libero, a pharetra augue. Nullam id dolor id nibh ultricies vehicula ut id elit.
<br>
Integer posuere erat a ante venenatis dapibus posuere velit aliquet.
</p>
</header><!-- End header.centered -->
<ul class="entrybox">
<li class="grid_12 blog-post">
<header class="post-thumb">
<a href="#"><img src="images/blog-thumb.png" alt="Post thumbnail"></a>
</header><!-- End header.post-thumb -->
<aside class="entry-post">
<span class="capitalize">Entry</span>
<h1 class="entry-title">
<a href="#" title="">Fris. Responsive. Retina Ready.</a>
</h1><!-- End h2 .entry-title -->
<ul class="entry-meta">
<li class="author">
By <a href="#">Casper Biemans</a>
</li>
<li class="published">
On <a href="#">September 1, 2012</a>
</li>
<li class="entry-categories">
In <a href="#">Digital Art</a>
</li>
<li class="comment-count">
With <a href="#">22 Comments</a>
</li>
<li class="permalink">
<img src="images/permalink_icon.png" alt="Permalink post"> <a href="#">Permalink</a>
</li>
</ul><!-- End ul.entry-meta -->
</aside><!-- End aside.entry-post -->
</li><!-- End li.grid_12 blog-post -->
<li class="grid_12 blog-post">
<header class="post-thumb">
<a href="#"><img src="images/blog-thumb.png" alt="Post thumbnail"></a>
</header><!-- End header.post-thumb -->
<aside class="entry-post">
<span class="capitalize">Entry</span>
<h1 class="entry-title">
<a href="#" title="">Fris. Responsive. Retina Ready.</a>
</h1><!-- End h2 .entry-title -->
<ul class="entry-meta">
<li class="author">
By <a href="#">Casper Biemans</a>
</li>
<li class="published">
On <a href="#">September 1, 2012</a>
</li>
<li class="entry-categories">
In <a href="#">Digital Art</a>
</li>
<li class="comment-count">
With <a href="#">22 Comments</a>
</li>
<li class="permalink">
<img src="images/permalink_icon.png" alt="Permalink post"> <a href="#">Permalink</a>
</li>
</ul><!-- End ul.entry-meta -->
</aside><!-- End aside.entry-post -->
</li><!-- End li.grid_12 blog-post -->
</ul><!-- End ul.entrybox -->
<div class="grid_12">
<a href="#" class="button primary">View the Blog &rarr;</a>
</div><!-- End div.grid_12 -->
<div class="clear"></div><!-- End div.clear -->
</div><!-- End div.container -->
</section><!-- End section#blog-entry -->
<section id="twitter" class="alt">
<div class="container_12">
<div class="grid_12 centered">
<img src="images/twitter.png" alt="Tweet birdie">
<article id="tweet"></article>
<p>You should follow us on <a href="#">Twitter</a> for our latest updates.</p>
</div><!-- End div.grid_12 centered -->
<div class="clear"></div><!-- End div.clear -->
</div><!-- End div.container_12 -->
</section><!-- End section#twitter -->
<hr>
<section id="hire-me">
<div class="container_12">
<div class="grid_8">
<h3>Get in touch</h3>
</div><!-- End div.grid_8 -->
<div class="grid_4 button-group">
<a href="#" class="button tertiaire grid_2">About</a>
<a href="#" class="button tertiaire custom grid_2">Contact</a>
</div><!-- End div.grid_4 -->
<div class="clear"></div><!-- End div.clear -->
</div><!-- End div.container_12 -->
</section><!-- End section#hire-me -->
</div><!-- End div#container -->
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T14:04:35.417",
"Id": "43107",
"Score": "0",
"body": "Your HTML is not valid. You should [validate](http://validator.w3.org/check) it and correct the errors first (e.g. your `div` with the ID `image-loop` contains `li` elements, which is not allowed)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T15:19:21.050",
"Id": "43109",
"Score": "0",
"body": "@unor thank you for your feedback. Your right. I have edit the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T10:00:24.703",
"Id": "43152",
"Score": "0",
"body": "When you are pasting so much code, why not the complete document? It doesn't matter if the markup is correct, if the surrounding document isn't."
}
] |
[
{
"body": "<p>First of all: You have a lot of meaningless div elements nested in eachother. I'm sure you can remove most of them and just add those classes to their parent or child element.</p>\n\n<p>Then some semantical tips. Please note that semantic is somewhat an opinion, so I'm just posting my thoughts:</p>\n\n<ul>\n<li>Why do you have anchor elements around the images in the header? Anchors mean links to places on the docs, not just links to <code>#</code>.</li>\n<li>an element for clearing is codesmell imo. I'd recommend to use pseudo-elements (like <code>#header::after</code>)</li>\n<li>The header element in <code>.flex-caption</code> is not correct. There is no sectioning-element before it.</li>\n<li>Use <code>figure</code> and <code>figcaption</code> for the <code>.flexsider</code> slides</li>\n<li><p>Put the list items in <code>#featured-list</code> in an article element. And then use <code>h1</code> for the headline, to follow the new document outline:</p>\n\n<pre><code><div id=introduce>\n <ul id=featured-list>\n <li>\n <article>\n <header>\n <img ...>\n <h1>...</h1>\n </header>\n ...\n </article>\n </li>\n </ul>\n</div>\n</code></pre></li>\n<li><code>#portfolio-entry</code> is an article with multiple sections in a list.</li>\n<li><code>aside</code> is incorrect used. The content in it is the main content for that portfolio item</li>\n<li><code>#blog-entry</code> is also an article and the previous 2 comments are related to this one too</li>\n<li><code>article#tweet</code> is empty and should be removed</li>\n<li><code>#hire-me</code> is an article too</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T10:19:57.673",
"Id": "27687",
"ParentId": "27660",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27687",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T11:32:05.293",
"Id": "27660",
"Score": "2",
"Tags": [
"html5"
],
"Title": "Is the HTML5 markup right implemented and semantically correct?"
}
|
27660
|
<p>I recently created the following code, which is supposed to implement a Pong variation for one player. How can I improve or optimize my code?</p>
<p><code>Pong</code> class:</p>
<pre><code>import javax.swing.JFrame;
public class Pong extends JFrame {
private static final int HEIGHT = 500, WIDTH = 900;
public Pong() {
super("Pong");
setSize(WIDTH, HEIGHT);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(new PongPanel(this));
setVisible(true);
}
public static void main(String[] args) {
new Pong();
}
}
</code></pre>
<p><code>PongPanel</code> class:</p>
<pre><code>import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
public class PongPanel extends JPanel {
private Racket racket;
private Ball ball;
private JLabel scoreLabel;
private int score = 0;
public PongPanel(Pong game) {
racket = new Racket(game, game.getHeight() - 100);
ball = new Ball(game);
scoreLabel = new JLabel(Integer.toString(score));
scoreLabel.setFont(new Font("sansserif", Font.PLAIN, 30));
add(scoreLabel);
Timer timer = new Timer(5, new TimerHandler());
timer.start();
addKeyListener(new KeyHandler());
setFocusable(true);
}
private void update() {
racket.updatePosition();
ball.updatePosition();
checkCollisionBallSides();
checkCollisionBallRacket();
repaint();
}
private void checkCollisionBallSides() {
if (ball.getX() < 0 || ball.getX() > getWidth() - ball.getWidth() - (getInsets().left + getInsets().right))
ball.setXA(-ball.getXA());
else if (ball.getY() < 0)
ball.setYA(-ball.getYA());
else if (ball.getY() > getHeight() - ball.getHeight()) {
JOptionPane.showMessageDialog(null, "Game Over. You scored " + score + ".", "Pong", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
private void checkCollisionBallRacket() {
if (ball.getBounds().y + ball.getHeight() == racket.getBounds().y &&
ball.getBounds().x + ball.getWidth() > racket.getBounds().x &&
racket.getBounds().x + racket.getWidth() > ball.getBounds().x) {
ball.setYA(-ball.getYA());
score++;
scoreLabel.setText(Integer.toString(score));
}
}
@Override
public void paint(Graphics g) {
super.paint(g);
racket.paint(g);
ball.paint(g);
}
private class KeyHandler implements KeyListener {
@Override
public void keyPressed(KeyEvent e) {
racket.pressed(e);
}
@Override
public void keyReleased(KeyEvent e) {
racket.released(e);
}
@Override
public void keyTyped(KeyEvent e) {
}
}
private class TimerHandler implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
update();
}
}
}
</code></pre>
<p><code>Racket</code> class:</p>
<pre><code>import java.awt.Graphics;
import java.awt.event.KeyEvent;
public class Racket extends Sprite {
private final Pong game;
public Racket(Pong game, int y) {
super((game.getWidth() - 60) / 2, y, 0, 0, 60, 10);
this.game = game;
}
public void pressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
setXA(-1);
else if (key == KeyEvent.VK_RIGHT)
setXA(1);
}
public void released(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT || key == KeyEvent.VK_RIGHT)
setXA(0);
}
public void updatePosition() {
if (getX() + getXA() >= 0 && getX() + getXA() < game.getWidth() - getWidth())
setX(getX() + getXA());
}
public void paint(Graphics g) {
g.fillRect(getX(), getY(), getWidth(), getHeight());
}
}
</code></pre>
<p><code>Ball</code> class:</p>
<pre><code>import java.awt.Graphics;
public class Ball extends Sprite {
public Ball() {
super(0, 0, 1, 1, 30, 30);
}
public void updatePosition() {
setX(getX() + getXA());
setY(getY() + getYA());
}
public void paint(Graphics g) {
g.fillOval(getX(), getY(), getWidth(), getHeight());
}
}
</code></pre>
<p><code>Sprite</code> class:</p>
<pre><code>import java.awt.Rectangle;
public class Sprite {
private int x, y, xa, ya, width, height;
public Sprite(int x, int y, int xa, int ya, int width, int height) {
this.x = x;
this.y = y;
this.xa = xa;
this.ya = ya;
this.width = width;
this.height = height;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getXA() {
return xa;
}
public int getYA() {
return ya;
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public Rectangle getBounds() {
return new Rectangle(x, y, width, height);
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setXA(int xa) {
this.xa = xa;
}
public void setYA(int ya) {
this.ya = ya;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T21:50:55.583",
"Id": "43145",
"Score": "0",
"body": "I reviewed another Pong program just a couple of weeks ago, you might want to check that out: http://codereview.stackexchange.com/questions/27197/code-review-for-pong-in-java/27211"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-16T20:13:53.173",
"Id": "44880",
"Score": "1",
"body": "It's not a good idea in my opinion to extend the `JFrame` class; it is usually better to compose your class with a `JFrame` instance. See this: https://www.coderanch.com/t/491015/java/java/extends-JFrame-JFrame"
}
] |
[
{
"body": "<p>A few observations</p>\n\n<p>In the <code>PongPanel</code> class, I had to change the following line</p>\n\n<pre><code>ball = new Ball(game);\n</code></pre>\n\n<p>to </p>\n\n<pre><code>ball = new Ball();\n</code></pre>\n\n<p>to remove the error. I'm not sure whether the error was in the constructor or the new statement.</p>\n\n<p>In your <code>Pong</code> class, you need to put the Swing components on the Event Dispatch thread (EDT). </p>\n\n<p>In your <code>Pong</code> class, there's no reason to extend JFrame. You can use a JFrame. Here's how I've coded your Pong class now.</p>\n\n<pre><code>package com.ggl.pong;\n\nimport javax.swing.JFrame;\nimport javax.swing.SwingUtilities;\n\nimport com.ggl.pong.view.PongPanel;\n\npublic class Pong {\n\n private JFrame frame;\n\n public Pong() {\n frame = new JFrame();\n frame.setTitle(\"Pong\");\n frame.setResizable(false);\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n frame.add(new PongPanel(this));\n frame.pack();\n frame.setVisible(true);\n }\n\n public JFrame getFrame() {\n return frame;\n }\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n new Pong();\n } \n }); \n }\n}\n</code></pre>\n\n<p>Finally, a piece of advice. Have your paddle move a little faster than the ball on the horizontal axis.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T12:00:56.997",
"Id": "27692",
"ParentId": "27665",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T16:54:29.107",
"Id": "27665",
"Score": "0",
"Tags": [
"java",
"object-oriented",
"game",
"swing"
],
"Title": "Single-player Pong game in Java"
}
|
27665
|
<p>I'm looking for some opinions on this bit of code that I wrote and if there are any ways it can be improved.</p>
<p>The scripts aim is to run the function runme() every 60 seconds with a random interval anywhere between -20 seconds to +40 seconds so it could run randomly anywhere between 40 seconds and 100 seconds.</p>
<pre><code>import sched, time
import random
s = sched.scheduler(time.time, time.sleep)
def periodically(runtime, intsmall, intlarge, function):
runtime += random.randrange(intsmall, intlarge)
s.enter(runtime, 1, function, ())
s.run()
def runme():
print "hi"
while True:
periodically(60, -20, +40, runme)
</code></pre>
|
[] |
[
{
"body": "<p>I don't think you do need the scheduler for that, at least not for how you use it.\nYour loop schedules 1 event and just afterwards waits until it's finished, since run() waits until the scheduled event(s) are completed.</p>\n\n<p>You can achieve the same by just sleeping for <code>runtime</code> seconds and calling <code>runme()</code> afterwards (you have to sleep before, since the scheduler delays the action for <code>runtime</code> seconds).</p>\n\n<p>Also note that <code>random.randrange(intsmall, intlarge)</code> will return a value between <code>intsmall</code> and <code>intlarge - 1</code>, so your random time will be between 40 seconds and 99 seconds.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T21:06:53.417",
"Id": "43139",
"Score": "0",
"body": "Hi,\n\nThanks for your reply. I don't quite understand are you saying that s.run and s.enter are the wrong way round?\n\nI want to avoid: `def periodically(runtime, intsmall, intlarge):\n runtime += random.randrange(intsmall, intlarge)\n sleep(runtime)\n runme()`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T22:06:16.923",
"Id": "43147",
"Score": "0",
"body": "You're welcome. I'm not saying that `s.run()` and `s.enter()` are the wrong way round - they are fine as written. But if you replace them with `sleep()` and `runme()`, that sequence should be changed. The scheduler delays first and then runs, so you need the sleep before the run, if not using the scheduler but just sleeping and running."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T20:30:42.643",
"Id": "27676",
"ParentId": "27673",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T19:13:31.650",
"Id": "27673",
"Score": "2",
"Tags": [
"python",
"random",
"timer",
"python-2.x"
],
"Title": "Opinions/Improvements on a run periodically/timer function in Python 2.7"
}
|
27673
|
<p>I implemented a strongly connected graph code in C++.</p>
<p><strong>matrix_graph.h</strong></p>
<pre><code>#pragma once
#include "stdafx.h"
class matrix_graph
{
private:
int** v;
int vertexes;
public:
matrix_graph(int**, int);
~matrix_graph(void);
void reverse();
int get_max_vertexes();
bool is_connected(int i,int j);
};
</code></pre>
<p><strong>matrix_graph.cpp</strong></p>
<pre><code>#include "stdafx.h"
#include <iostream>
#include "matrix_graph.h"
using namespace std;
matrix_graph::matrix_graph(int** g, int N)
{
v = g;
vertexes = N;
}
matrix_graph::~matrix_graph(void)
{}
void matrix_graph::reverse()
{
for(int i=0;i<vertexes;i++)
for(int j=0;j<vertexes;j++)
{
if(v[i][j] == 1 && v[j][i]==0){
v[j][i] = -1;
v[i][j] = 0;
}
}
for(int i=0;i<vertexes;i++)
for(int j=0;j<vertexes;j++)
{
if(v[i][j] == -1 )
v[i][j] = 1;
}
}
int matrix_graph::get_max_vertexes()
{
return vertexes;
}
bool matrix_graph::is_connected(int i,int j)
{
return (v[i][j]==1);
}
</code></pre>
<p><strong>Main code:</strong></p>
<pre><code>enum Color {WHITE,GREY,BLACK};
void matrix_dfs_visit(matrix_graph m , int i , std::list<int>& q , Color* c)
{
int N = m.get_max_vertexes();
c[i] = GREY;
for(int j=0;j<N;j++){
if(i!=j){
if( m.is_connected(i,j))
if(c[j] == WHITE)
matrix_dfs_visit(m,j,q,c);
}
}
c[i] = BLACK;
q.push_front(i);
}
void dfs(matrix_graph m, std::list<int>& visited_vertexes_in_order )
{
int N = m.get_max_vertexes();
Color* c = new Color[N];
for(int i=0;i<N;i++)
c[i] = WHITE;
for(int i=0;i<N;i++)
if(c[i] == WHITE)
matrix_dfs_visit(m,i,visited_vertexes_in_order ,c);
}
void dfs_transpose(matrix_graph &m , std::list<int> &visited_vertexes_in_order)
{
int N = m.get_max_vertexes();
Color* c = new Color[N];
for(int i=0;i<N;i++)
c[i] = WHITE;
for(list<int>::iterator iter = visited_vertexes_in_order.begin();iter != visited_vertexes_in_order.end();iter++){
int scc_head = *iter;
if(c[scc_head] == WHITE){
list<int> scc;
matrix_dfs_visit(m,scc_head ,scc,c);
print_scc(scc);
}
}
}
void print_scc(list<int> & l){
cout << "Strongly Connected Component:";
for(list<int>::iterator iter=l.begin(); iter !=l.end();iter++)
cout<< " "<<*iter;
cout<<"\n";
}
void get_strongly_connected_component(matrix_graph &m)
{
list<int> visited_vertexes_in_order;
dfs(m,visited_vertexes_in_order);
m.reverse();
dfs_transpose(m,visited_vertexes_in_order);
}
void process()
{
int v[7][7] = {
{0,1,0,0,0,0,0},
{0,0,1,1,0,0,0},
{1,0,0,0,0,0,0},
{0,0,0,0,1,0,0},
{0,0,0,0,0,1,0},
{0,0,0,1,0,0,1},
{0,0,0,0,0,0,0}
};
int* v_ptr[7] = {v[0],v[1],v[2],v[3],v[4],v[5],v[6]};
matrix_graph m(&v_ptr[0],7);
get_strongly_connected_component(m);
}
</code></pre>
<p>Please give any reviews, especially on the reverse function and the whole design. Naming convention here is also pretty weak I think.</p>
|
[] |
[
{
"body": "<p>Firstly, I think you class name can be improved somewhat. Sure, it tells you the underlying data structure that the graph will use (sort of, anyway), but it doesn't tell you anything about what <strong>kind</strong> of graph it is. Unless you read the source, you won't know that this is supposed to represent a directed graph - so why not put that in the name: <code>directed_matrix_graph</code>. </p>\n\n<p>Speaking of underlying data structure, simply taking an <code>int**</code> that you don't copy, but simply use as-is, is generally not good practice. Most users of a class like this will assume that it manages its own memory. This puts the onus on the user to make sure everything used in your class remains within scope. I'd recommend replacing this with a <code>std::vector<std::vector<int>></code> which manages its own memory. This should probably have a constructor which it initializes from a template; something like:</p>\n\n<pre><code>class matrix_graph\n{\nprivate:\n std::vector<std::vector<int>> vertexes;\n\npublic:\n template <typename Iterator>\n matrix_graph(Iterator begin, Iterator end)\n {\n std::vector<int> v(begin, end);\n for(std::size_t i = 0; i < v.size(); ++i) {\n vertexes.push_back(v);\n }\n }\n\n...\n};\n</code></pre>\n\n<p>Destructors shouldn't take parameters (even <code>void</code>), and you shouldn't declare one if it isn't going to do anything: the compiler generated one will suffice in this case.</p>\n\n<p>Both <code>int get_max_vertexes()</code> and <code>bool is_connected(int i,int j)</code> should be <code>const</code> methods, as these don't change the underlying <code>matrix_graph</code>:</p>\n\n<pre><code>int get-max_vertexes() const;\nbool is_connected(int i, int j) const;\n</code></pre>\n\n<p>On to the main code: your <code>dfs</code> has a memory leak: you declare <code>new Color[N]</code> but never <code>delete[]</code> it. Again, using a <code>std::vector</code> will make these sorts of problems go away. It will also simplify the code:</p>\n\n<pre><code>void dfs(matrix_graph m, std::list<int>& visited_vertexes_in_order )\n{\n std::vector<Color> c(m.get_max_vertexes(), WHITE);\n for(int i = 0;i < N; i++) \n if(c[i] == WHITE)\n matrix_dfs_visit(m, i, visited_vertexes_in_order, c);\n}\n</code></pre>\n\n<p>In <code>matrix_dfs_visit</code> and <code>dfs</code>, you pass your <code>matrix_graph</code> by value and call it recursively. If you were actually storing graph vertexes in your class, this would get very slow very quickly. You aren't modifying the underlying <code>matrix_graph</code> here, so you should pass it by const-reference instead: <code>const matrix_graph& m</code>. </p>\n\n<p>You have another memory leak in <code>dfs_transpose</code>, same solution applies as above. You pass your <code>matrix_graph</code> here by reference, but it is never changed. Since <code>bool is_connected(int i, int j)</code> should be <code>const</code> (if you change it per the advice given above), you can now pass by <code>const matrix_graph&</code>.</p>\n\n<p>Similar complaint for <code>void print_scc(list<int> & l)</code>, should be <code>const list<int>& l</code>. Anything that doesn't change should always be passed by <code>const</code>, this will make sure that the underlying object isn't changed (well, as long as people don't start <code>const_cast</code>ing things, but you have bigger problems in that case).</p>\n\n<p>The algorithms themselves look like they come straight from CLRS so I won't bother going over them. </p>\n\n<p>Some other general comments:</p>\n\n<ul>\n<li>Use whitespace in loops: <code>for(int i=0;i<vertexes;i++)</code> is so much harder to read than <code>for(int i = 0; i < vertexes; i++)</code>. </li>\n<li>Avoid <code>using namespace std</code> as much as possible, even in <code>.cpp</code> files. In fact, you don't even use any standard library components in your <code>matrix_graph.cpp</code> file, so it doesn't even need to be there in the first place. Even if you did, the absolutely tiny time savings you get by not having to type out <code>std::</code> in a few places is not worth the potential name clashes.</li>\n<li>Put your code in a namespace, it's generally good practice.</li>\n<li>In general, be careful of memory leaks. Use <code>new</code> as little as possible. Prefer <code>std::vector</code> to manually dealing with arrays: they stop memory leaks and offer much better exception safety.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T14:44:59.750",
"Id": "43162",
"Score": "0",
"body": "Thanks..I take all your points...basically avoid arrays..use const references and avoid std namespace... is making a typedef of std containers a good idea?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T14:47:31.097",
"Id": "43163",
"Score": "0",
"body": "@sethi Sure, if it makes things easier and/or clearer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T14:05:33.167",
"Id": "27695",
"ParentId": "27677",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27695",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T20:34:44.313",
"Id": "27677",
"Score": "2",
"Tags": [
"c++",
"graph"
],
"Title": "Strongly-connected component for a graph"
}
|
27677
|
<p>First of all, I'm really new to SFML and making GUIs. This is my first real program using this.</p>
<p>Right now, when I click outside the window when the program is first run, the first piece is placed in the top left corner without clicking that square. It works as I want it to every time after that, with an error message appearing when you click on a square already taken. In the <code>takeTurn()</code> function, I set a value to the <code>left</code> variable as a way to detect that the position is already taken.</p>
<p>I know that's the problem, but I can't think of another way right now. Maybe if anyone can help point me in the right direction? Also, I know this code is pretty ugly, so if anyone is familiar with SFML, I'd appreciate some pointers on how to clean this up.</p>
<pre><code>#include <SFML/Graphics.hpp>
#include <iostream>
class Game {
private:
sf::RenderWindow window;
sf::Texture gameBoard, pieceX, pieceO;
sf::Sprite addBoard, addX, addO, piece[9];
sf::Font fontType;
sf::Text message;
sf::IntRect square[9];
sf::Vector2i position[9];
sf::Event event;
public:
void loadGameWindow();
bool loadPieceFiles();
bool loadFontFile();
void setGamePieces();
void setUserPrompt();
void rectangleCoordinates();
void setRectCoordinates(sf::IntRect &rect, int left, int top, int width, int height);
void setPositionPieces(sf::Vector2i &pos, int left, int top);
void positionPiece();
bool isClickInBounds(int boardPos);
bool takeTurn(int player);
void updateUserPrompt(int turn, bool invalidPos);
void gameLoop();
};
void Game::loadGameWindow(){
window.create(sf::VideoMode(400, 500), "Tic-Tac-Toe");
}
bool Game::loadPieceFiles(){
return (gameBoard.loadFromFile("board.png") &&
pieceX.loadFromFile("x.png") && pieceO.loadFromFile("o.png"));
}
bool Game::loadFontFile(){
return (fontType.loadFromFile("3rd Man.ttf"));
}
void Game::setGamePieces(){
addBoard.setTexture(gameBoard);
addX.setTexture(pieceX);
addO.setTexture(pieceO);
}
void Game::setUserPrompt(){
message.setString("Player 1's turn");
message.setFont(fontType);
message.setCharacterSize(40);
message.setColor(sf::Color::Black);
message.move(95, 410);
}
void Game::updateUserPrompt(int turn, bool invalidPos){
std::string playerPrompt;
if(invalidPos){
playerPrompt = "Position already\n taken!";
} else {
playerPrompt = turn % 2 == 0? "Player 1's turn" : "Player 2's turn";
}
message.setString(playerPrompt);
}
void Game::setRectCoordinates(sf::IntRect &rect, int rectLeft, int rectTop, int rectWidth, int rectHeight){
rect.left = rectLeft;
rect.top = rectTop;
rect.width = rectWidth;
rect.height = rectHeight;
}
void Game::rectangleCoordinates(){
setRectCoordinates(square[0], 0, 0, 113, 120);
setRectCoordinates(square[1], 126, 0, 262, 120);
setRectCoordinates(square[2], 276, 0, 400, 120);
setRectCoordinates(square[3], 0, 133, 113, 270);
setRectCoordinates(square[4], 126, 133, 262, 270);
setRectCoordinates(square[5], 276, 133, 400, 270);
setRectCoordinates(square[6], 0, 283, 113, 400);
setRectCoordinates(square[7], 126, 283, 262, 400);
setRectCoordinates(square[8], 276, 283, 400, 400);
}
void Game::setPositionPieces(sf::Vector2i &pos, int left, int top){
pos.x = left;
pos.y = top;
}
void Game::positionPiece(){
setPositionPieces(position[0], 15, 20);
setPositionPieces(position[1], 162, 20);
setPositionPieces(position[2], 300, 20);
setPositionPieces(position[3], 15, 166);
setPositionPieces(position[4], 162, 166);
setPositionPieces(position[5], 300, 166);
setPositionPieces(position[6], 15, 316);
setPositionPieces(position[7], 162, 316);
setPositionPieces(position[8], 300, 316);
}
bool Game::isClickInBounds(int boardPos){
return event.mouseButton.x >= square[boardPos].left
&& event.mouseButton.x <= square[boardPos].width
&& event.mouseButton.y >= square[boardPos].top
&& event.mouseButton.y <= square[boardPos].height;
}
bool Game::takeTurn(int turn){
for(int boardPos = 0; boardPos < 9; boardPos++){
if(isClickInBounds(boardPos)){
if(square[boardPos].left != -500){
piece[turn] = turn % 2 == 0? addX : addO;
piece[turn].move(position[boardPos].x, position[boardPos].y);
square[boardPos].left = -500;
updateUserPrompt(turn, false);
return true;
} else {
updateUserPrompt(turn, true);
return false;
}
}
}
}
void Game::gameLoop(){
int turn = 0;
setUserPrompt();
rectangleCoordinates();
positionPiece();
while(window.isOpen()){
while(window.pollEvent(event)){
if(event.type == sf::Event::Closed){
window.close();
}
if(sf::Mouse::isButtonPressed(sf::Mouse::Left) && turn < 9){
if(takeTurn(turn)){
turn++;
}
}
}
window.clear(sf::Color(0, 150, 0));
window.draw(addBoard);
window.draw(message);
for(int pieceIdx = 0; pieceIdx < 9; pieceIdx++)
window.draw(piece[pieceIdx]);
window.display();
}
}
int main(int argc, char *argv[]){
Game game;
game.loadGameWindow();
if(!game.loadPieceFiles())
return EXIT_FAILURE;
game.setGamePieces();
if(!game.loadFontFile())
return EXIT_FAILURE;
game.gameLoop();
return EXIT_SUCCESS;
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Click Event</strong></p>\n\n<p>I apologize, the computer I'm on doesn't have SFML installed but I'll try to get to this later(probably tomorrow). One thing I noticed, though, is in isClickInBounds you do:</p>\n\n<pre><code> event.mouseButton.x >= square[boardPos].left \n&& event.mouseButton.x <= square[boardPos].width\n...\n</code></pre>\n\n<p>Here you're reinventing the wheel, and I'm not entirely sure it's correct. It could be, but I can't test it atm so I'm skeptical. One thing you can try for sure is this(add parenthesis - see parenthesis section below):</p>\n\n<pre><code>return (event.mouseButton.x >= square[boardPos].left \n && event.mouseButton.x <= square[boardPos].width \n && event.mouseButton.y >= square[boardPos].top \n && event.mouseButton.y <= square[boardPos].height);\n</code></pre>\n\n<p>The documentation for sf::Rect has a <code>.contains</code> that takes an x, y coordinate, so you can just call that. Ie.</p>\n\n<pre><code>return (square[boardPos].contains(event.mouseButton.x, event.mouseButton.y));\n</code></pre>\n\n<p><strong>Player Turn</strong></p>\n\n<p>Also of note, using an int as a decider of whose turn it is isn't a very clear way of determining whose turn it is. Usually in a more complex game, there would be a Player class, which would have some sort of <code>.takeTurn()</code> method. Then it's a simple matter of iterating through the list of players(in this case 2), calling the .takeTurn() method on each player, and checking for a win condition after each turn.</p>\n\n<p>In your case, you could use an <a href=\"http://www.cprogramming.com/tutorial/enum.html\" rel=\"nofollow\">enum</a>. The previous link is a good source of information on enums in C++. In this enum I added a default value just for the sake of putting one in there:</p>\n\n<pre><code>enum players_t {NO_PLAYER, PLAYER_ONE, PLAYER_TWO};\n</code></pre>\n\n<p>Then you can have a nextPlayer function that toggles between PLAYER_ONE and PLAYER_TWO. It then becomes easier to check whose turn it is, and the code is more descriptive:</p>\n\n<pre><code>playerPrompt = (turn == PLAYER_ONE) ? \"Player 1's turn\" : \"Player 2's turn\";\n</code></pre>\n\n<p>Though I will admit this will require quite a few changes to your code.</p>\n\n<p><strong>Parenthesis</strong></p>\n\n<p>And on that note, it's always a good idea to surround conditional statements with <code>()</code>. Some examples:</p>\n\n<pre><code>int result = (ternary) ? 1 : 2;\nif(somethingIsTrue){\nif( (oneThingIsTrue) && (anotherThingIsTrue) ){\nreturn ( (someInt > 0) && (anotherInt < 0) );\n</code></pre>\n\n<p>Similarly, it's a good idea to use curly braces on all if..else statements, even if they happen to be one-liners. You were good on this point when it came to if..elses(I don't see one that doesn't use curly braces), but you do have a for loop that doesn't use curly braces.</p>\n\n<p><strong>Conventions</strong></p>\n\n<p>Overall your coding conventions are great. You use proper indentations, you're consistent with putting the opening brace on the same line as the statement(Ie. <code>if(...){</code>), but there are a few places where trailing white space should be removed. At the end of any code blocks, you should get rid of any empty lines just for the sake of cleanliness.</p>\n\n<p>But I would say this code looks pretty good as-is.</p>\n\n<p>Again, I apologize about the SFML. I'll take a better look at it later.</p>\n\n<p><strong>Edit #1:</strong></p>\n\n<p>Sorry it took so long to get back to this. I just tried running your application. I don't have your various resource files like board.png, x.png or o.png. Is there any way you could send those to me(imgur will host em for free)?</p>\n\n<p>Also, there are two warnings from compiling. In takeTurn, there is an implicit cast from int to float:</p>\n\n<pre><code>piece[turn].move(position[boardPos].x, position[boardPos].y);\n</code></pre>\n\n<p>Which should instead read as:</p>\n\n<pre><code>piece[turn].move((float)position[boardPos].x, (float)position[boardPos].y);\n</code></pre>\n\n<p>Also, takeTurn has a path that doesn't return a value. It's easy to fix though:</p>\n\n<pre><code>bool Game::takeTurn(int turn){\n for(int boardPos = 0; boardPos < 9; boardPos++){\n if(isClickInBounds(boardPos)){\n if(square[boardPos].left != -500){\n piece[turn] = turn % 2 == 0? addX : addO;\n piece[turn].move((float)position[boardPos].x, (float)position[boardPos].y);\n square[boardPos].left = -500;\n updateUserPrompt(turn, false);\n return true;\n } else {\n updateUserPrompt(turn, true);\n return false;\n }\n } \n }\n return false;\n}\n</code></pre>\n\n<p>I know it may seem silly, but you should get in the habit of treating any and all warnings as if they're errors. As you become more comfortable with various compiler settings, I would encourage you to turn on as many warnings as possible. GCC has some great ones, like -Wall. For things like -Wall, you don't have to fix everything it complains about, but you should be aware that there's a large enough body that considers those things to be a warning about code in order to make its way into a mainstream compiler's warning system.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T21:02:39.137",
"Id": "27864",
"ParentId": "27679",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T20:55:27.040",
"Id": "27679",
"Score": "3",
"Tags": [
"c++",
"game",
"gui",
"tic-tac-toe",
"sfml"
],
"Title": "Graphical Tic-Tac-Toe game using SFML"
}
|
27679
|
<pre><code> trait Comonad[M[_]] {
// map
def >>[A,B](a: M[A])(f: A => B): M[B]
// extract | coeta
def counit[A](a:M[A]): A
// coflatten | comu
def cojoin[A](a: M[A]): M[M[A]]
}
object Comonad {
implicit def listComonad[A]: Comonad[List]
=
new Comonad[List] {
def counit[A](lsa: List[A])
=
lsa match { case List(a) => a }
def cojoin[A](lsa:List[A]): List[List[A]]
=
List(lsa)
def >>[A,B](lsa: List[A])(f: A => B): List[B]
=
lsa map f
}
}
</code></pre>
<p>So yeah I'm looking at this and I don't have that correct feeling... </p>
<p>Anyone mind correcting this and maybe offerring one or two other simple comonads? </p>
|
[] |
[
{
"body": "<p>I believe, what's bothering you is a non-total definition of <code>counit</code>, right? (for <code>cojoin</code> one possible variation is <code>lsa.tails</code>) Indeed, a <code>List</code> does not have a valid comonad instance specifically bacause of that. It does have a valid <a href=\"http://mth.io/talks/zippers-and-comonads/#/44\" rel=\"nofollow\">semicomonad</a> <a href=\"http://mth.io/talks/zippers-and-comonads/#/46\" rel=\"nofollow\">instance</a> though.</p>\n\n<p>Things that have a valid comonad instance are, for example: <a href=\"https://github.com/scalaz/scalaz/blob/scalaz-seven/core/src/main/scala/scalaz/Id.scala#L16\" rel=\"nofollow\">Identity</a>, <a href=\"https://github.com/scalaz/scalaz/blob/scalaz-seven/core/src/main/scala/scalaz/NonEmptyList.scala#L117\" rel=\"nofollow\">NonEmptyList</a>, <a href=\"https://github.com/scalaz/scalaz/blob/scalaz-seven/core/src/main/scala/scalaz/Zipper.scala#L365\" rel=\"nofollow\">Zipper</a>, <a href=\"https://github.com/scalaz/scalaz/blob/scalaz-seven/core/src/main/scala/scalaz/std/Tuple.scala#L65-L76\" rel=\"nofollow\">Tuple</a>. Here's a <a href=\"http://www.reddit.com/r/haskell/comments/18mtrb/comonad_questions/\" rel=\"nofollow\">reddit question</a> with more examples of comonads.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T11:52:45.560",
"Id": "27691",
"ParentId": "27685",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27691",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T02:57:33.950",
"Id": "27685",
"Score": "3",
"Tags": [
"functional-programming",
"scala"
],
"Title": "Simple Comonads in Scala?"
}
|
27685
|
<p>I was wondering about on how to organise the code on my site, to make it clearer as possible and clearly readable. </p>
<p>I'm organising it with <code>namespace</code>, separating every single section of the page. </p>
<p>For example:</p>
<pre><code>var Header = {
//code relative to the header
}
var CentralBody = {
//code relative to the CentralBody
}
$(function(){
//code to execute on doc ready
});
</code></pre>
<p>First of all, I would know if it is a good way to organise code. In second instance, I was thinking about "what must be placed where". I explain: If, for example, I have to assign some tooltip or to <code>bind</code> event with code like</p>
<pre><code>$('someclass').tooltip()
$('someclass').on( 'event' , ... );
</code></pre>
<p>where do I have to place this kind of "<em>functions</em>"? Do I have to place them in the concerning <code>namespace</code>? Do I have to place them on <code>document.ready</code>? Or writing <code>functions</code> in <code>namespace</code> and then <code>call</code> them on <code>document.ready</code>?</p>
|
[] |
[
{
"body": "<p>A conceptual question, those are always tricky.</p>\n\n<p>Organizing by namespace is not a bad idea, though I would lowercase your namespace ( <code>Header</code> -> <code>header</code> etc. )</p>\n\n<p>Furthermore, I would suggest to look into <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow\">Movel View Controller</a> and let each namespace have a <code>model</code>, <code>view</code> and <code>controller</code>.</p>\n\n<p>The binding of events is in the realm of the controller. So when you initialize the controller, that is where can you do all the binding.</p>\n\n<p>So in <code>document.ready</code> you can call <code>centralBody.init()</code> which could call <code>centralBody.controller.init()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T13:58:51.320",
"Id": "39217",
"ParentId": "27688",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T10:36:01.400",
"Id": "27688",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"object-oriented"
],
"Title": "Organise site's module"
}
|
27688
|
<p>I am writing a <a href="http://en.wikipedia.org/wiki/Nonogram" rel="nofollow">Nonogram</a> game in JavaScript.</p>
<p>I would like to know your opinions on the code and suggestions on how to improve it.</p>
<p>I'm using a MVC approach.</p>
<ul>
<li>the Model has two matrices (represented as linear arrays): one with the actual Nonogram cells and the other with the guesses of the player;</li>
<li>cells are just strings: Nonogram cells can be either "filled" or "empty"; player guesses can be either "unknown", "filled" or "empty"</li>
<li>by <em>sequence</em> I mean a sequence of consecutive filled cells</li>
<li>by <em>definition</em> I mean the series of <em>sequences</em> a row/column has</li>
</ul>
<p>Here is the source code (I am going to release it under the GNU GPL license):</p>
<p><strong>utils.js</strong></p>
<pre><code>if (!window.koala) {
window.koala = {};
}
koala.utils = {
randomIntegerInRange: function (min, max) {
return min + Math.floor(Math.random() * (max - min + 1));
}
};
koala.utils.Event = function (sender) {
this._sender = sender;
this._listeners = [];
};
koala.utils.Event.prototype = {
attach: function (listener) {
this._listeners.push(listener);
},
notify: function (args) {
for (var index = 0, nlisteners = this._listeners.length; index < nlisteners; index++) {
this._listeners[index](this._sender, args);
}
}
};
</code></pre>
<p><strong>nonograms.js</strong></p>
<pre><code>if (!window.koala) {
window.koala = {};
}
koala.nonograms = {};
/*
The game uses the MVC pattern.
*/
/*
__ __ _ _
| \/ | | | | |
| \ / | ___ __| | ___| |
| |\/| |/ _ \ / _` |/ _ \ |
| | | | (_) | (_| | __/ |
|_| |_|\___/ \__,_|\___|_|
*/
koala.nonograms.Model = function (opts) {
if (!opts) opts = {};
this._opts = opts;
this.width = opts.width = (opts.width ? Number(opts.width) : 10);
this.height = opts.height = (opts.height ? Number(opts.height) : 10);
// Events fired by the model
this.events = {};
// The ussr guessed the content of a cell
this.events.guessChanged = new koala.utils.Event(this);
// The nonogram has been changed
this.events.nonogramChanged = new koala.utils.Event(this);
// The user solved the nonogram
this.events.nonogramSolved = new koala.utils.Event(this);
// The nonogram was solved but now it isn't
this.events.nonogramUnsolved = new koala.utils.Event(this);
};
koala.nonograms.Model.prototype = {
getCellAt: function (x, y) {
var index = this._indexFromXY(x, y);
var cell = this._actual[index];
return (cell === undefined) ? "empty" : cell;
},
getGuessAt: function (x, y) {
var index = this._indexFromXY(x, y);
var guess = this._guess[index];
return (guess === undefined) ? "unknown" : guess;
},
setGuessAt: function (x, y, guess) {
var oldGuess = this.getGuessAt(x, y);
var index = this._indexFromXY(x, y);
this._guess[index] = guess;
this.events.guessChanged.notify({
x: x,
y: y,
oldGuess: oldGuess,
newGuess: guess
});
var was_solved = this.isSolved();
this._checkIfSolved();
var is_solved = this.isSolved();
if (was_solved && !is_solved) {
this.events.nonogramUnsolved.notify();
} else if (!was_solved && is_solved) {
this.events.nonogramSolved.notify();
}
},
isSolved: function () {
return this._solved;
},
getRowDefinition: function (row) {
var definition = [];
var sequenceBegin;
var sequenceEnd;
var sequenceSolved;
var sequenceLength = 0;
for (var x = 0; x < this.width; x++) {
if (this.getCellAt(x, row) === "filled") {
if (sequenceLength === 0) sequenceBegin = x;
sequenceLength++;
} else if (sequenceLength) {
sequenceEnd = x-1;
sequenceSolved = false;
if ((sequenceBegin === 0 || this.getGuessAt(sequenceBegin-1, row) === "empty")
&& (sequenceEnd === this.width-1 || this.getGuessAt(sequenceEnd+1, row) === "empty")) {
sequenceSolved = true;
for (var index = sequenceBegin; index <= sequenceEnd; index++) {
if (this.getGuessAt(index, row) != "filled") {
sequenceSolved = false;
break;
}
}
}
definition.push({
length: sequenceLength,
solved: sequenceSolved
});
sequenceLength = 0;
}
}
if (sequenceLength) {
sequenceEnd = x-1;
sequenceSolved = false;
if ((sequenceBegin === 0 || this.getGuessAt(sequenceBegin-1, row) === "empty")
&& (sequenceEnd === this.width-1 || this.getGuessAt(sequence_end+1, row) === "empty")) {
sequenceSolved = true;
for (var index = sequenceBegin; index <= sequenceEnd; index++) {
if (this.getGuessAt(index, row) != "filled") {
sequenceSolved = false;
break;
}
}
}
definition.push({
length: sequenceLength,
solved: sequenceSolved
});
}
return definition;
},
getColumnDefinition: function (col) {
var definition = [];
var sequenceBegin;
var sequenceEnd;
var sequenceSolved;
var sequenceLength = 0;
for (var y = 0; y < this.height; y++) {
if (this.getCellAt(col, y) === "filled") {
if (sequenceLength === 0) sequenceBegin = y;
sequenceLength++;
} else if (sequenceLength) {
sequenceEnd = y-1;
sequenceSolved = false;
if ((sequenceBegin === 0 || this.getGuessAt(col, sequenceBegin-1) === "empty")
&& (sequenceEnd === this.height-1 || this.getGuessAt(col, sequenceEnd+1) === "empty")) {
sequenceSolved = true;
for (var index = sequenceBegin; index <= sequenceEnd; index++) {
if (this.getGuessAt(col, index) != "filled") {
sequenceSolved = false;
break;
}
}
}
definition.push({
length: sequenceLength,
solved: sequenceSolved
});
sequenceLength = 0;
}
}
if (sequenceLength) {
sequenceEnd = y-1;
sequenceSolved = false;
if ((sequenceBegin === 0 || this.getGuessAt(col, sequenceBegin-1) === "empty")
&& (sequenceEnd === this.height-1 || this.getGuessAt(col, sequenceEnd+1) === "empty")) {
sequenceSolved = true;
for (var index = sequenceBegin; index <= sequenceEnd; index++) {
if (this.getGuessAt(col, index) != "filled") {
sequenceSolved = false;
break;
}
}
}
definition.push({
length: sequenceLength,
solved: sequenceSolved
});
}
return definition;
},
randomize: function (density) {
this._setupNonogram();
var ncells = this.width * this.height;
var to_be_filled = Math.floor(ncells * density);
if (to_be_filled > ncells) to_be_filled = ncells;
var index;
while (to_be_filled) {
index = this._getRandomIndex();
if (this._actual[index] === undefined) {
this._actual[index] = "filled";
to_be_filled--;
}
}
this.events.nonogramChanged.notify();
},
// Private methods
_setupNonogram: function () {
var ncells = this.width * this.height;
this._actual = new Array(ncells);
this._guess = new Array(ncells);
this._solved = false;
},
_indexFromXY: function (x, y) {
return y * this.width + x;
},
_getRandomIndex: function () {
var ncells = this.width * this.height;
return koala.utils.randomIntegerInRange(0, ncells - 1);
},
_checkIfSolved: function () {
for (var index = 0, ncells = this._actual.length; index < ncells; index++) {
if ((this._actual[index] === "filled" && this._guess[index] != "filled") ||
(this._actual[index] != "filled" && this._guess[index] == "filled")) {
this._solved = false;
return;
}
}
this._solved = true;
},
};
/*
__ ___
\ \ / (_)
\ \ / / _ _____ __
\ \/ / | |/ _ \ \ /\ / /
\ / | | __/\ V V /
\/ |_|\___| \_/\_/
*/
koala.nonograms.View = function (model, container) {
this._model = model;
this._container = $(container);
this._id = "nonogram" + koala.utils.randomIntegerInRange(0, 1000000);
this._theme = "default";
// Events fired by the View
this.events = {};
this.events.clickOnCell = new koala.utils.Event(this);
this.events.mouseDownOnCell = new koala.utils.Event(this);
this.events.mouseUp = new koala.utils.Event(this);
this.events.mouseEntersCell = new koala.utils.Event(this);
this.events.mouseLeavesCell = new koala.utils.Event(this);
}
koala.nonograms.View.prototype = {
show: function () {
this.rebuildNonogram();
},
setSolved: function () {
$("#" + this._id).removeClass("nonogram_playing").addClass("nonogram_solved");
},
setUnsolved: function () {
$("#" + this._id).removeClass("nonogram_solved").addClass("nonogram_playing");
},
setTheme: function (theme) {
$("#" + this._id).removeClass(this._theme).addClass(theme);
this._theme = theme;
},
highlightColumn: function (col) {
this._container.find(".nonogram_column_" + col + "_cell").addClass("nonogram_hovered_column");
this._container.find("#" + this._idOfColumnDefinition(col)).addClass("nonogram_hovered_column");
},
unhighlightColumn: function (col) {
this._container.find(".nonogram_column_" + col + "_cell").removeClass("nonogram_hovered_column");
this._container.find("#" + this._idOfColumnDefinition(col)).removeClass("nonogram_hovered_column");
},
setGuessAt: function (x, y, newGuess) {
var cell = $("#" + this._idOfCell(x, y));
var oldGuess = cell.data().guess;
cell
.removeClass("nonogram_correct_guess")
.removeClass(this._guessToCSSClass(oldGuess))
.addClass(this._guessToCSSClass(newGuess))
.data({guess: newGuess});
if (this._model.getCellAt(x, y) === newGuess) {
cell.addClass("nonogram_correct_guess");
}
// Update row & column definitions
$("#" + this._idOfRowDefinition(y)).html(this._rowDefinitionToHTML(this._model.getRowDefinition(y)));
$("#" + this._idOfColumnDefinition(x)).html(this._columnDefinitionToHTML(this._model.getColumnDefinition(x)));
},
rebuildNonogram: function () {
var width = this._model.width,
height = this._model.height;
var x, y, tr;
var table = $("<table/>").attr("id", this._id).addClass("nonogram").addClass(this._theme);
if (this._model.isSolved())
table.addClass("nonogram_solved");
else
table.addClass("nonogram_playing");
// Column Definitions Row
tr = $("<tr/>").addClass("nonogram_row");
// Top Left cell
$("<td>").addClass("nonogram_top_left_cell").appendTo(tr);
for (x = 0; x < width; x++) {
if (x && x % 5 === 0) {
$("<td/>").addClass("nonogram_separation_column").appendTo(tr);
}
$("<td/>")
.attr("id", this._idOfColumnDefinition(x))
.addClass("nonogram_definition nonogram_column_definition")
.html(this._columnDefinitionToHTML(this._model.getColumnDefinition(x)))
.appendTo(tr);
}
tr.appendTo(table);
for (y = 0; y < height; y++) {
// Separate groups of five rows
if (y && y % 5 == 0) {
$("<tr/>")
.addClass("nonogram_separation_row")
.append($("<td colspan='" + (width + width - 1) + "'/>"))
.appendTo(table);
}
// Create new row
tr = $("<tr/>").addClass("nonogram_row");
// Create definition for the current row
$("<td/>")
.attr("id", this._idOfRowDefinition(y))
.addClass("nonogram_definition nonogram_row_definition")
.html(this._rowDefinitionToHTML(this._model.getRowDefinition(y)))
.appendTo(tr);
for (x = 0; x < width; x++) {
// Separate groups of five columns
if (x && x % 5 === 0) {
$("<td/>")
.addClass("nonogram_separation_column")
.appendTo(tr);
}
// Build the actual nonogram cell
$("<td/>")
.attr("id", this._idOfCell(x, y))
.addClass(this._CSSClassesForCell(x, y))
.data({
x: x,
y: y,
guess: this._model.getGuessAt(x, y)
})
.appendTo(tr);
}
tr.appendTo(table);
}
this._container
.hide()
.empty()
.append(table)
.fadeIn(500);
// Events firing code
var view = this;
table.click(function (e) {
if (e.target.nodeName != "TD") return;
e.preventDefault();
var cellData = $(e.target).data();
view.events.clickOnCell.notify(cellData);
});
table.mousedown(function (e) {
if (e.target.nodeName != "TD") return;
e.preventDefault();
var cellData = $(e.target).data();
view.events.mouseDownOnCell.notify(cellData);
});
$(document).mouseup(function (e) {
e.preventDefault();
view.events.mouseUp.notify({event: e});
});
table.mouseover(function (e) {
if (e.target.nodeName != "TD") return;
e.preventDefault();
var cellData = $(e.target).data();
view.events.mouseEntersCell.notify(cellData);
});
table.mouseout(function (e) {
if (e.target.nodeName != "TD") return;
e.preventDefault();
var cellData = $(e.target).data();
view.events.mouseLeavesCell.notify(cellData);
});
},
// Private methods
_idOfCell: function (x, y) {
return this._id + "_x_" + x + "_y_" + y;
},
_idOfRowDefinition: function (row) {
return this._id + "_row_" + row + "_definition";
},
_idOfColumnDefinition: function (col) {
return this._id + "_column_" + col + "_definition";
},
_rowDefinitionToHTML: function (sequences) {
var html = "<nobr>";
for (var index = 0; index < sequences.length; index++) {
if (index) html += "&nbsp;";
html += "<span class='nonogram_sequence";
if (sequences[index].solved) {
html += " nonogram_solved_sequence";
}
html += "'>" + sequences[index].length + "</span>";
}
html += "</nobr>";
return html;
},
_columnDefinitionToHTML: function (sequences) {
var html = "";
for (var index = 0; index < sequences.length; index++) {
if (index) html += "<br>";
html += "<nobr><span class='nonogram_sequence";
if (sequences[index].solved) {
html += " nonogram_solved_sequence";
}
html += "'>" + sequences[index].length + "</span></nobr>";
}
return html;
},
_CSSClassesForCell: function (x, y) {
var cellGuess = this._model.getGuessAt(x, y);
var actualCell = this._model.getCellAt(x, y);
var classes = [];
classes.push("nonogram_cell");
classes.push("nonogram_column_" + x + "_cell");
classes.push(this._guessToCSSClass(cellGuess));
if (cellGuess === actualCell) {
classes.push("nonogram_correct_guess");
}
return classes.join(" ");
},
_guessToCSSClass: function (guess) {
return "nonogram_" + guess + "_cell";
}
};
/*
_____ _ _ _
/ ____| | | | | |
| | ___ _ __ | |_ _ __ ___ | | | ___ _ __
| | / _ \| '_ \| __| '__/ _ \| | |/ _ \ '__|
| |___| (_) | | | | |_| | | (_) | | | __/ |
\_____\___/|_| |_|\__|_| \___/|_|_|\___|_|
*/
koala.nonograms.Controller = function (model, view) {
this._dragHelper = new koala.nonograms.dragHelper();
this._model = model;
this._view = view;
var controller = this;
// Application Logic
model.events.nonogramChanged.attach(function () {
view.rebuildNonogram();
});
model.events.guessChanged.attach(function (model, opts) {
view.setGuessAt(opts.x, opts.y, opts.newGuess);
});
model.events.nonogramSolved.attach(function () {
view.setSolved();
});
model.events.nonogramUnsolved.attach(function () {
view.setUnsolved();
});
view.events.mouseDownOnCell.attach(function (view, cell) {
controller._dragHelper.start(cell.x, cell.y, controller._nextGuess(model.getGuessAt(cell.x, cell.y)));
controller._previewDragging();
});
view.events.mouseUp.attach(function () {
if (!controller._dragHelper.isDragging())
return;
controller._dragHelper.stop();
controller._cancelDraggingPreview();
controller._applyDragging();
});
view.events.mouseEntersCell.attach(function (view, cell) {
view.highlightColumn(cell.x);
if (!controller._dragHelper.isDragging()) return;
controller._cancelDraggingPreview();
controller._dragHelper.to(cell.x, cell.y);
controller._previewDragging();
});
view.events.mouseLeavesCell.attach(function (view, cell) {
view.unhighlightColumn(cell.x);
});
}
koala.nonograms.Controller.prototype = {
// Private methods
// cycles in [unknown, filled, empty]
_nextGuess: function (guess) {
if (guess === "unknown") {
return "filled";
} else if (guess === "filled") {
return "empty";
}
return "unknown";
},
_previewDragging: function () {
var view = this._view;
this._dragHelper.iterateOverDraggedCells(function (x, y, guess) {
view.setGuessAt(x, y, guess);
});
},
_applyDragging: function () {
var model = this._model;
this._dragHelper.iterateOverDraggedCells(function (x, y, guess) {
model.setGuessAt(x, y, guess);
});
},
_cancelDraggingPreview: function () {
var model = this._model;
var view = this._view;
this._dragHelper.iterateOverDraggedCells(function (x, y, guess) {
view.setGuessAt(x, y, model.getGuessAt(x, y));
});
}
};
/*****************************************************/
koala.nonograms.dragHelper = function () {
this._dragging = false;
};
koala.nonograms.dragHelper.prototype = {
start: function (x, y, guess) {
this._x1 = this._x2 = x;
this._y1 = this._y2 = y;
this._guess = guess;
this._dragging = true;
},
to: function (x, y) {
this._x2 = x;
this._y2 = y;
},
stop: function () {
this._dragging = false;
},
isDragging: function () {
return this._dragging;
},
iterateOverDraggedCells: function (fn) {
var x1 = this._x1;
var y1 = this._y1;
var x2 = this._x2;
var y2 = this._y2;
var fromX, toX, stepX, fromY, toY, stepY;
if (Math.abs(x1-x2) > Math.abs(y1-y2)) {
// Horizontal Line
stepX = 1;
stepY = 0;
fromY = toY = y1;
if (x1 < x2) {
fromX = x1;
toX = x2;
} else {
fromX = x2;
toX = x1;
}
} else {
// Vertical line
stepX = 0;
stepY = 1;
fromX = toX = x1;
if (y1 < y2) {
fromY = y1;
toY = y2;
} else {
fromY = y2;
toY = y1;
}
}
for (var x = fromX, y = fromY; x <= toX && y <= toY; x += stepX, y += stepY) {
fn(x, y, this._guess);
}
}
};
/*****************************************************/
/* The main Nonogram object */
/*****************************************************/
koala.nonograms.Nonogram = function (container, opts) {
this._container = container;
opts = opts || {};
this._opts = {
width: opts.width || 10,
height: opts.height || 10,
theme: opts.theme || "default"
};
this._model = new koala.nonograms.Model({
width: this._opts.width,
height: this._opts.height
});
this._view = new koala.nonograms.View(this._model, this._container);
this._view.setTheme(this._opts.theme);
this._controller = new koala.nonograms.Controller(this._model, this._view);
}
koala.nonograms.Nonogram.prototype = {
show: function () {
this._view.show();
},
randomize: function (opts) {
var density = 0.60;
if (opts && opts.density) {
density = opts.density;
}
this._model.randomize(density);
},
setTheme: function (theme) {
this._opts.theme = theme;
this._view.setTheme(theme);
}
};
</code></pre>
<p>If you want to try it in action I uploaded it <a href="http://freenonograms.altervista.org" rel="nofollow">here</a>.</p>
|
[] |
[
{
"body": "<p>In general, it looks good to me.</p>\n\n<p>My 2 cents:</p>\n\n<ul>\n<li><p>I am not sure why you have event related things in your model</p></li>\n<li><p><code>iterateOverDraggedCells</code> looked like it could use some refactoring.</p>\n\n<ul>\n<li>Whenever you start with x1,y1,x2,y2, I think it is better to have a point object with x and y.</li>\n<li>You can use Math.min() and Math.max() to find which value is the lowest/highest</li>\n<li>It looks like you went too far with DRY in that last for() loop</li>\n</ul></li>\n</ul>\n\n<blockquote>\n<pre><code> iterateOverDraggedCells: function ( fn )\n {\n var p1 = { x : this._x1 , y : this._y1 },\n p2 = { x : this._x2 , y : this._y2 },\n from, to;\n\n if( Math.abs( p1.x - p2.x ) > Math.abs( p1.y - p2.y ) ) \n {\n from = { x : Math.min( p1.x ,p2.x ) , y : p1.y };\n to = { x : Math.max( p1.x ,p2.x ) };\n for( var x = from.x, y = from.y ; x <= to.x , x++ )\n fn(x, y, this._guess); \n }\n else\n {\n from = { y : Math.min( p1.y , p2.y ) , x : p1.x };\n to = { y : Math.max( p1.y , p2.y ) };\n for( var x = from.x, y = from.y ; y <= to.y , y++ )\n fn(x, y, this._guess);\n }\n\n }\n</code></pre>\n</blockquote>\n\n<p>Taking that into account, you could try something like the above.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-04T19:17:37.873",
"Id": "30789",
"ParentId": "27689",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "30789",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T10:47:16.950",
"Id": "27689",
"Score": "10",
"Tags": [
"javascript",
"jquery",
"html",
"css",
"game"
],
"Title": "Nonogram game in JavaScript"
}
|
27689
|
<p>I'm taking a sentence and determining whether or not it is a palindrome. I'm doing this while learning about stacks.</p>
<ol>
<li><p>Is there a way I can use pointers instead of <code>char</code> array 'sent' so that the number of input characters need not be constrained to 20 in the following code?</p></li>
<li><p>The code is working fine, but should there be any improvements in terms of performance or anything else?</p></li>
<li><p>Is there anything important about pointers I should remember while using stacks, like initializing it to <code>NULL</code>?</p></li>
</ol>
<p></p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct node
{
char data;
struct node *link;
}StackNode;
void insertData(StackNode **);
void push(StackNode **, char);
void checkData(StackNode **);
bool pop(StackNode **,char *);
char sent[20] = "";
void main()
{
StackNode *stackTop;
stackTop = NULL;
insertData(&stackTop);
checkData(&stackTop);
printf("\n");
return;
}
void insertData(StackNode **stackTop)
{
char c;
int len;
printf("Enter the Sentence\n");
while( ( ( c = getchar() ) != '\n'))
{
if( ( ( c>='a' &&c<='z') || (c>='A' && c<='Z')))
{
if((c>='A' && c<='Z'))
{
int rem;
rem = c-'A';
c='a' + rem;
}
push(stackTop,c);
len = strlen(sent);
sent[len++]=c;
sent[len]='\0';
}
}
printf("Letters are %s\n\n",sent);
}
void push(StackNode **stackTop,char c)
{
StackNode *pNew;
pNew = (StackNode*) malloc(sizeof(StackNode));
if(!pNew)
{
printf("Error 100:Out of memory\n");
exit(100);
}
pNew->data = c;
pNew->link = *stackTop;
*stackTop = pNew;
}
void checkData(StackNode **stackTop)
{
char c;
int i=0;
while(pop(stackTop,&c))
{
if( c !=sent[i++])
{
printf("Not palindrome");
return;
}
}
printf("Palindrome");
}
bool pop(StackNode **stackTop,char *c)
{
StackNode *pNew;
pNew = *stackTop;
if(pNew == NULL)
return false;
*c = pNew->data;
*stackTop = pNew->link;
printf("char poped %c\n",*c);
free(pNew);
return true;
}
</code></pre>
|
[] |
[
{
"body": "<p>Where to start ;) Some hints:</p>\n\n<ol>\n<li>Was is part of the task to use a stack for this? You could easily check for the palindrome just on the char array by looping over it from left to right.</li>\n<li>Why using two different data structures for the same content: an char array for data entered and a stack for the reverse string? Try to be consistent.</li>\n<li>Why having the char array as a global variable but passing the stack as function parameter? Try to be consistent.</li>\n<li>If you return the stack pointer, you don't have to pass it as pointer to pointer - just change in the function and return the new one.</li>\n<li>Same for the char in pop_stack() - pass back as return value, '\\0' is a perfectly valid in bounds value here.</li>\n<li>I'd try to define and init a variable in one statement, e.g. <code>StackNode *stackTop = NULL;</code>. Avoids missing initialization, saves screen real estate, and sometimes even allows declaration as <code>const</code> - something admittedly not liked by all C programmers.</li>\n<li>Wrt NULLs - no quick answer here, you can find books filled with that. What I do: avoid where possible, use asserts, and even name variables/parameters, so that I easily see whether they can be NULL; e.g. opt_ptr, if ptr might be NULL.</li>\n<li>Good things last: you really think hard to have consistent naming, formatting, and structure - being self-driven here will keep you making progress, all those little things I mentioned above will just come with experience ;)</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T18:01:06.347",
"Id": "43164",
"Score": "0",
"body": "The advantage of `push(&stack,c);` is that the compiler makes sure that it is correctly called. Over `stack = push(stack, c)` here the caller needs to remember to assign the result to variable or loose track. So the first version is preferred as there is less chance of user error (it only needs to be done correctly once by the creator of the function rather than being done correctly every time by the user of the function)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T14:21:17.370",
"Id": "27696",
"ParentId": "27690",
"Score": "2"
}
},
{
"body": "<p>One <strong>MAJOR</strong> problems here.</p>\n\n<pre><code>char sent[20] = \"\";\n</code></pre>\n\n<p>Don't use global variables. Globally mutable state makes your code hard to debug/test and generally behave correctly. You not only need to know what a function does but also what external state the function depends on. Pass all state into functions via the parameters (that way you know exactly what it depends on).</p>\n\n<p>Note: Global <strong>constants</strong> are fine.</p>\n\n<p>This is not a valid declaration of main() <a href=\"https://stackoverflow.com/q/2108192/14065\">even in C</a></p>\n\n<pre><code>void main()\n\n/* TRY */\n\nint main(void)\n/* OR */\nint main(int argc, char* argv[])\n</code></pre>\n\n<p>Lets declare and initialize variables on the same line: </p>\n\n<pre><code> StackNode *stackTop;\n stackTop = NULL;\n\n /* Try */\n StackNode *stackTop = NULL;\n</code></pre>\n\n<p>Note if you correct main you will also need to correct the return statement so it returns a value.</p>\n\n<pre><code> return;\n</code></pre>\n\n<p>But when the function is void there seems little point in putting a return statement.</p>\n\n<p>OK. This reads a line.</p>\n\n<pre><code>void insertData(StackNode **stackTop)\n</code></pre>\n\n<p>But there are already functions that do that.<br>\nYou can use the <code>scanf</code> series of commands. Your code drops any non alphabetic characters (but you could read a line then post processes to remove and invalid characters).</p>\n\n<p>You should read up on the functions for handling characters.</p>\n\n<pre><code>isalpha() /* Note it is locale aware and thus will return true\n for characters other than a-z A-Z if your locale is\n not set to the default (which is C)\n */\n\ntolower() /* Lowercases letters. No affect on anything else */\n</code></pre>\n\n<p>I would have done:</p>\n\n<pre><code>char data[50]; /* You wanted a max of 20 letters.\n But if the user types a space between every word\n it can get longer and we post processes to remove\n space so. So we will cut off at 50.\n */\n\nfscanf(stdin, \"%50[^\\n]\", data); /* read upto 50 characters\n that are not '\\n'\n into data\n */\nfscanf(stdin, \"%*[^\\n]\"); /* Read the rest of the line if\n the user types more than 50 and\n throw it away\n */\nfscanf(stdin, \"\\n\"); /* Read the '\\n' off the input */\n\n/* Now remove any non letter characters and lowercase at the same time */\nint removed = 0;\nfor(int loop = 0; data[loop]; ++loop)\n{\n if (!isalpha(data[loop]))\n {\n removed++;\n continue; // starts next iteration.\n }\n data[loop-removed] = tolower(data[loop]);\n}\ndata[loop-removed] = '\\0'; /* Add string terminator */\n</code></pre>\n\n<p>Back to reviewing your version.</p>\n\n<p>This is going to enter an infinite loop if you hit an error or end of file before you hit '\\n'.</p>\n\n<pre><code> while( ( ( c = getchar() ) != '\\n'))\n</code></pre>\n\n<p>Then end of file is a real possibility if somebody pipes a file into your command from the command line.</p>\n\n<pre><code> cat file | ./palindromeCommand\n</code></pre>\n\n<p>This check:</p>\n\n<pre><code> if( ( ( c>='a' &&c<='z') || (c>='A' && c<='Z')))\n</code></pre>\n\n<p>Is really covered by: <code>isalpha()</code></p>\n\n<p>This check:</p>\n\n<pre><code> if((c>='A' && c<='Z'))\n {\n int rem;\n rem = c-'A';\n c='a' + rem;\n }\n</code></pre>\n\n<p>Is the same as: <code>c = tolower(c);</code> </p>\n\n<p>This string append:</p>\n\n<pre><code> len = strlen(sent);\n sent[len++]=c;\n sent[len]='\\0';\n</code></pre>\n\n<p>Can be achieved with: <code>strncat(sent, &c, 1);</code></p>\n\n<p>Normally I don't want checking functions to mutate the state of any objects. The name \"check\" implies I am looking not modifying.</p>\n\n<pre><code>void checkData(StackNode **stackTop)\n</code></pre>\n\n<p>Also you are mixing business logic and presentation logic into a single function. Make this function check to see if it a palindrome and return an appropriate value (0 for false and non zero for true (for example)). The code can then use this function to check for a palindrome and take appropriate action (like display text) in the display logic:</p>\n\n<p>Initialize and declare in the same line:</p>\n\n<pre><code> StackNode *pNew;\n pNew = *stackTop;\n\n /* Easier to read as */\n StackNode *pNew = *stackTop;\n</code></pre>\n\n<p>Overall I think you overcomplicated the processes with your <code>StackNode</code> concept. But it works. It would have been much simpler to use pointers to either end of the sent array and work towards the middle checking letters.</p>\n\n<pre><code>int checkForPalindrome(char* sent, int length)\n{\n char* st = sent;\n char* ed = sent + length - 1;\n\n int result = true;\n\n while(st < ed && result)\n {\n if (*st != *ed) { result = false;}\n ++st;\n --ed;\n }\n return result;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T17:46:02.737",
"Id": "27703",
"ParentId": "27690",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T11:03:56.730",
"Id": "27690",
"Score": "2",
"Tags": [
"c",
"stack",
"palindrome"
],
"Title": "Using pointers for string manipulation"
}
|
27690
|
<p>I present a bunch of grids of data to the user, and want to sum certain columns in some of the grids.</p>
<pre><code>// for one such grid:
rows = [{id: 0, name: "Alice", age: "23"},
{id: 1, name: "Bob", age: "25"} /* ... */]
sum_aggregator = {
init: function() { return 0 },
step: function(l, r) { return l + parse(r) },
stop: function(x) { return x }
}
columns = [{field: 'age', aggregator: sum_aggregator, filter: /* ... */}, /* ... */]
function reduce() { /* pseudocode */
for each column c: totals[c] = columns[c].aggregator.init()
for each row r: for each column c:
totals[c] = columns[c].aggregator.step(totals[c], get_field(r, c))
for each column c: totals[c] = columns[c].aggregator.stop(totals[c])
return totals[c]
}
</code></pre>
<p>Using <a href="http://en.wikipedia.org/wiki/Virtual_method_tablehttp://en.wikipedia.org/wiki/Virtual_method_table" rel="nofollow">vtables</a>---objects containing only functions---such as <code>sum_aggregator</code> seems unidiomatic javascript to me. I should note that I have several other vtable'y things dealing with the rows (SQL'ish <code>WHERE</code> clauses in <code>filter</code>, etc.), and I'm sorta' jerry-rigging a sum-of-vtables class-like thingy in the <code>columns</code> array.</p>
<p>Is this good design? Are there benefits to factoring it otherwise? Gluing the vtable together using smaller building blocks seems like it does something good for concern separation, but using objects with methods seems more javascripty to me. What are some good ways of thinking in this design space?</p>
|
[] |
[
{
"body": "<p>This is the first time I have heard \"vtabels\", the more known term is <a href=\"http://en.wikipedia.org/wiki/Decision_table\" rel=\"nofollow\">decision table</a>. Also, on the contrary, using decision tables is <em>very</em> idiomatic JavaScript and is used often, just rarely with lambdas and more often with named functions.</p>\n\n<p>Also, your <code>rows</code> array (is this a global intentionally?) uses rows implying it's a row where every element is a single object.</p>\n\n<p>That said, JavaScript has functional methods like <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow\"><code>Array.prototype.map</code></a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Filter\" rel=\"nofollow\"><code>Array.prototype.filter</code></a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce\" rel=\"nofollow\"><code>Array.prototype.reduce</code></a>. </p>\n\n<p>You can use those to map, filter and reduce things.</p>\n\n<p>For example, your code (assuming it sums ages) could be written as:</p>\n\n<pre><code>var rows = [{id: 0, name: \"Alice\", age: \"23\"},\n {id: 1, name: \"Bob\", age: \"25\"} /* ... */];\n\nvar ageSum = rows.reduce(function(accum,next){return (+next.age)+accum},0);\nageSum; //48\n</code></pre>\n\n<p>Given the more functional style, your SQL <code>WHERE</code> becomes <code>.filter</code></p>\n\n<pre><code>rows WHERE name = 'Bob'\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>rows.filter(function(name){\n return name===\"Bob\";\n})\n</code></pre>\n\n<p>Similarly, aggregators become <code>.reduce</code> and mappings (and joins) become <code>.map</code>. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T12:58:46.870",
"Id": "43157",
"Score": "0",
"body": "Also worth mentioning, you can use closure for iterators - that makes very nice, co-routinish style."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T14:13:36.747",
"Id": "43160",
"Score": "0",
"body": "I added a wikipedia link to vtables in my post; it may be of interest."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T14:16:56.383",
"Id": "43161",
"Score": "0",
"body": "Reading about decision tables, they seem to indicate that the action is chosen based on data which could be user-input or in other ways dynamic. In contrast, the entries of a vtable which are accessed are baked into the program. [modulo most-of-the-time, can-be-abused, etc.]"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T12:55:33.273",
"Id": "27694",
"ParentId": "27693",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T12:42:11.787",
"Id": "27693",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Data and vtables vs. objects and methods"
}
|
27693
|
<p>I have solved one <a href="http://codeforces.com/problemset/problem/317/B" rel="nofollow">problem</a> on Codeforces and I guess the output is quite correct. However, it is slow for input in range of thousands. Since, I am learning Python now, it would be great help if one could help me optimise this code. Any notes, tips or suggestions on the sidelines are always welcome.</p>
<p>The question is a practice question and hence does not violate any contest rules.</p>
<pre class="lang-py prettyprint-override"><code>import sys
import time
_no_of_ants, _no_of_queries = (input().split())
no_of_ants = int(_no_of_ants)
no_of_queries = int(_no_of_queries)
class ants_cord():
def __init__(self,point,no_of_ants):
self.co_ant = {point:no_of_ants}
def ants_at_point(self,point):
return self.co_ant[point]
def move_ants(self,point):
x1,y1 = point
if (x1+1,y1) in self.co_ant.keys():
self.co_ant[((x1+1),y1)] += 1
else:
self.co_ant[((x1+1),y1)] = 1
if (x1,y1+1) in self.co_ant.keys():
self.co_ant[((x1),y1+1)] += 1
else:
self.co_ant[((x1),y1+1)] = 1
if (x1,y1-1) in self.co_ant.keys():
self.co_ant[((x1),y1-1)] += 1
else:
self.co_ant[((x1),y1-1)] = 1
if (x1-1,y1) in self.co_ant.keys():
self.co_ant[((x1-1),y1)] += 1
else:
self.co_ant[((x1-1),y1)] = 1
self.co_ant[point] -= 4
def check_status(self):
for key in self.co_ant.keys():
if k.co_ant[key] >= 4:
return key
else: return False
start = time.time()
k = ants_cord((0,0),no_of_ants)
point = k.check_status()
while point:
k.move_ants(point)
point = k.check_status()
end = time.time()
print("Sec:{}".format(end-start))
while no_of_queries:
_x,_y = input().split()
x = int(_x)
y = int(_y)
if (x,y) in k.co_ant:
print(k.co_ant[(x,y)])
else:
print('0')
no_of_queries -= 1
</code></pre>
<p><strong>EDIT</strong>: I updated the code according to suggestion. But I still get a TLE error in test case 4. Should I employ other algorithm then?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T14:51:53.307",
"Id": "43207",
"Score": "0",
"body": "I've added an answer. I don't have the right version of python handy but it should again make your script orders of magnitude faster. I'd be interested in the results if you were to perform performances tests with a high number of ants."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T15:29:08.193",
"Id": "126809",
"Score": "0",
"body": "I'm not sure that the task is solvable using python or any interpreted language at all. As you [can see there aren't any python/ruby/..](http://codeforces.com/contest/317/status/B/page/12?order=BY_CONSUMED_TIME_ASC) solution and the fastest c++ solution time is 100 ms, so it's just impossible to run faster than may be ~2-5 seconds for a python solution. There is the list of failed (due to time limit) solutions - just apply the status filter (Python 2 or Python 3 and the Verdict like the 'Time limit...')."
}
] |
[
{
"body": "<p>A few things:</p>\n\n<ul>\n<li><p>You should probably put the <code>start = time.time()</code> as early as possible if you want it to make sense.</p></li>\n<li><p>As your class consists on a simple dict, there is no or little value in defining it. (In a \"real life\" scenario, it would be considered as a good practice).</p></li>\n</ul>\n\n<p>Things got 25% quicker on average starting with 1000 ants.</p>\n\n<ul>\n<li>You could make your code more concise by using structure to isolate the parts that change.</li>\n</ul>\n\n<p><code>move_ants()</code> would look like this :</p>\n\n<pre><code>def move_ants(g,point):\n x,y = point\n for a,b in [(x+1,y),(x,y+1),(x,y-1),(x-1,y)]: # or you could define x generxtor\n if (a,b) in g.keys():\n g[a,b] += 1\n else:\n g[a,b] = 1\n g[point] -= 4\n</code></pre>\n\n<p>(Not performance impact)</p>\n\n<ul>\n<li>In <code>check_status()</code>, instead of iterating on keys and then retrieve the corresponding value, you could use <code>iteritems()</code> :</li>\n</ul>\n\n<p><code>check_status()</code> would be like this :</p>\n\n<pre><code>def check_status(g):\n for k,v in g.iteritems():\n if v >= 4:\n return k\n else: return False\n</code></pre>\n\n<p>(This does improve performances)</p>\n\n<ul>\n<li>To get the values from your dict with default values, you could use <code>get()</code>. You'd have something like <code>print(g.get((x,y),0))</code> and <code>g[a,b] = 1 + g.get((a,b),0)</code>. (I really didn't expect so but this made the script more than twice faster).</li>\n</ul>\n\n<p>At the end, my script is like this (I've changed other details but it's mostly personal preferences) :</p>\n\n<pre><code>#!/usr/bin/python\n\nimport sys\nimport time\n\nstart = time.time()\n\n##_no_of_ants, _no_of_queries = (input().split())\n##no_of_ants = int(_no_of_ants)\n##no_of_queries = int(_no_of_queries)\n\nno_of_ants = 1000\nno_of_queries = 1\n\ndef move_ants(g,point):\n x,y = point\n for a,b in [(x+1,y),(x,y+1),(x,y-1),(x-1,y)]: # or you could define x generxtor\n g[a,b] = 1 + g.get((a,b),0)\n g[point] -= 4\n\ndef check_status(g):\n for k,v in g.iteritems():\n if v >= 4:\n return k\n else: return False\n\ng = {(0,0) : no_of_ants} # or you could use default dict\npoint = check_status(g)\nwhile point:\n move_ants(g,point)\n point = check_status(g)\nprint(\"Sec:{}\".format(time.time()-start))\nfor q in xrange(no_of_queries):\n ###_x,_y = input().split()\n ###x = int(_x)\n ###y = int(_y)\n x,y=1,1\n print(g.get((x,y),0))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T19:49:25.860",
"Id": "43165",
"Score": "0",
"body": "It would worthy to mention that your code is in Python 2.x. Thanks for response :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T04:53:08.137",
"Id": "43173",
"Score": "0",
"body": "The `g[a,b] = 1 + g.get((a,b),0)` is already nice, but still a double dict access. The prototypical tip here is to benchmark also using either `setdefault()` or `collections.defaultdict()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T07:11:59.343",
"Id": "43180",
"Score": "0",
"body": "user2512319 : setdefault is what I wanted to do as well but I couldn't make it work with integers. As for defaultdict i considered it as an option (cf comment in the code) and then forgot about it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T18:18:16.880",
"Id": "27705",
"ParentId": "27699",
"Score": "1"
}
},
{
"body": "<p>First answer was about micro-optimisation.</p>\n\n<p>Here are a few improvements you could perform on the algorithm itself :</p>\n\n<ul>\n<li>You could simulate many iterations in one go.</li>\n</ul>\n\n<p>In order to do so, </p>\n\n<pre><code>def move_ants(g,point):\n x,y = point\n for a,b in [(x+1,y),(x,y+1),(x,y-1),(x-1,y)]: # or you could define x generxtor\n g[a,b] = 1 + g.get((a,b),0)\n g[point] -= 4\n</code></pre>\n\n<p>could be changed for :</p>\n\n<pre><code>def move_ants(g,point):\n x,y = point\n nb_ants = g[point]\n nb_ants_per_dir = nb_ants/4\n for a,b in [(x+1,y),(x,y+1),(x,y-1),(x-1,y)]: # or you could define x generxtor\n g[a,b] = nb_ants_per_dir + g.get((a,b),0)\n g[point] = nb_ants - 4 * nb_ants_per_dir\n</code></pre>\n\n<ul>\n<li><code>check_status</code> could return a set of points to be handled</li>\n</ul>\n\n<p>You'd just need to do something like :</p>\n\n<pre><code>def check_status(g):\n return [k for k,v in g.iteritems() if v >= 4]\n</code></pre>\n\n<ul>\n<li><p>Also, you might want to keep track of the cells you've updated in order no to loop over the all dict but only the candidates. This would need quite a lot of rewritting.</p></li>\n<li><p>Also, you could take into account the fact that the problem offer many axis of symetry : obviously the x and y axis but also the y=x and the y=-x. Thus you could restrict yourself to 1/8 of the plan corresponding to 0 < x < y</p></li>\n</ul>\n\n<p><strong>Edit</strong></p>\n\n<p>After testing, this code on 5555 ants:</p>\n\n<pre><code> def move_ants(g,points):\n cand=set()\n for point in points:\n x,y = point\n nb_ants = g[point]\n nb_ants_per_dir = nb_ants/4\n for a,b in [(x+1,y),(x,y+1),(x,y-1),(x-1,y)]: # or you could define x generxtor\n new_nb = g.get((a,b),0) + nb_ants_per_dir\n g[a,b] = new_nb\n if new_nb >= 4:\n cand.add((a,b))\n g[point] = nb_ants - 4*nb_ants_per_dir\n return cand\n\n g = {(0,0) : no_of_ants} # or you could use default dict\n points = [(0,0)]\n while points:\n points = move_ants(g,points)\n print(\"Sec:{}\".format(time.time()-start))\n for q in xrange(no_of_queries):\n x,y=1,1\n print(g.get((x,y),0))\n</code></pre>\n\n<p>appears to be 21 times faster than the solution provided in my other answer and 141 times faster than yours.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T14:47:06.287",
"Id": "27731",
"ParentId": "27699",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27731",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T15:50:17.277",
"Id": "27699",
"Score": "2",
"Tags": [
"python",
"optimization",
"algorithm"
],
"Title": "Codeforces problem python code optimization"
}
|
27699
|
<p>I've written a simple program to test out the capabilities of <a href="http://hackage.haskell.org/package/netwire" rel="nofollow">netwire</a> (or rather, how to write programs using netwire). The goal is to have an application that shows a window, starting out as completely filled with red. Pressing space should switch from red to blue and vice versa. Pressing escape or closing the window should terminate the program. I've been able to write something that works (using Allegro, but that doesn't matter too much - the Allegro part can't be simplified, at least not by much), but it's gotten a bit lengthy for something that sounds so simple.</p>
<pre><code>{-# LANGUAGE OverloadedStrings #-}
module Main(main) where
import Control.Wire hiding (when)
import Prelude hiding ((.),id)
import qualified Graphics.UI.Allegro.Raw as Al
import Data.Monoid
import Control.Monad.Reader
import qualified Data.Set as S
import Data.Set (Set)
iff True a _ = a
iff False _ b = b
data Game = Game {
keyState :: Set Al.Key,
isClosed :: Bool
}
data Result = GameColor Al.Color | Quit
colRed = Al.Color {Al.colorR = 1.0, Al.colorG = 0.0, Al.colorB = 0.0, Al.colorA = 1.0}
colBlue = Al.Color {Al.colorR = 0.0, Al.colorG = 0.0, Al.colorB = 1.0, Al.colorA = 1.0}
initG = Game { keyState = S.empty, isClosed = False }
addKey (g@ Game {keyState = s}) k = g {keyState = S.insert k s}
-- Produce when event occurs, inhibit otherwise
gameEvent :: Monoid e => (Game -> Bool) -> Event e (ReaderT Game IO) a
gameEvent f = mkFixM $ \_ a ->
iff <$> asks f <*> (return $ Right a) <*> (return $ Left mempty)
windowClosed = gameEvent isClosed
keyPressed k = gameEvent (S.member k . keyState)
doQuit = pure Quit . (keyPressed Al.KeyEscape <|> windowClosed)
color = doColorRed
-- The once prevents infinite recursion in case space was pressed
doColorRed = pure (GameColor colRed) . (once <|> notE (keyPressed Al.KeySpace)) -->
doColorBlue
doColorBlue = pure (GameColor colBlue) . (once <|> notE (keyPressed Al.KeySpace)) -->
doColorRed
colorApp :: Wire () (ReaderT Game IO) a Result
colorApp = doQuit <|>
color
main = do
Al.initialize
Al.installKeyboard
Just window <- Al.createDisplay 800 600
Al.setTargetBackbuffer window
Just q <- Al.createEventQueue
t <- Al.createTimer $ 1/60
Al.registerEventSource q =<< Al.getKeyboardEventSource
Al.registerEventSource q =<< Al.getDisplayEventSource window
Al.registerEventSource q =<< Al.getTimerEventSource t
Al.startTimer t
loop colorApp clockSession q
Al.destroyEventQueue q
Al.destroyDisplay window where
loop w session q = do
game <- handleEvents initG q
(mx, w', session') <- runReaderT (stepSession w session ()) game
case mx of
Left ex -> putStrLn $ "Inhibited: " ++ show ex -- this should never happen
Right (GameColor c) -> do
Al.clearToColor c
Al.flipDisplay
loop w' session' q
Right Quit -> return ()
handleEvents g q = do
ev <- Al.waitForEvent q
case ev of
Al.KeyDownEvent{Al.eventKeycode = k} -> handleEvents (addKey g k) q
Al.Timer{} -> return g
Al.DisplayClose{} -> return g{isClosed = True}
_ -> handleEvents g q
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T04:36:48.463",
"Id": "43250",
"Score": "0",
"body": "Wow, that does really look like a heck of a lot of haskell for what it does, and it's also kind of hard to penetrate... Normally I find haskell a bit more readable, I wonder if this Allegro API might not be the best quality if it causes consumer code to do this much... Alternatively it may be that I'm unfamiliar with Allegro's API that makes this a bit tricky appearing to me"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T05:16:01.237",
"Id": "43253",
"Score": "0",
"body": "I think filling out some type signatures on what you have and designing some for what you want, then filling in the implementation based on the signatures you *want* to work with as a consumer will benefit you a lot and find you breaking these up and modeling this stuff a little more concisely"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T09:25:51.397",
"Id": "43260",
"Score": "0",
"body": "@JimmyHoffa It's a raw binding to a C API - there's a bit of setup code involved, but after that it's pretty straight forward."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T17:00:11.277",
"Id": "43274",
"Score": "0",
"body": "I understand that, I'm just not altogether clear that you're getting a nice clean API from it in that to consume it each step you perform requires so much code; though I've not worked with any library's like it so perhaps this is par for the course on API's to accomplish such functionality. Either way try some of the clean up I talked about data modeling your system, and then I'm curious what it looks like; I don't think I can mentally penetrate any further until it's had some of that clean up."
}
] |
[
{
"body": "<p>Your iff function would be better expressed with <code><|></code> or <code>msum</code>. They're for making a choice, so one of them ought be used in place of <code>iff</code>, I'm not sure where the <code>True</code>/<code>False</code> values are feeding out into <code>iff</code>, but I would maybe change them to feed out something that's a <code>Monoid</code> type or <code>MonadPlus</code> instead of <code>Bool</code> then use the appropriate choice technique.</p>\n\n<p>You named a data type which appears to be the purpose of being a state <code>Result</code>, was this supposed to be a <code>Command</code>, <code>Instruction</code>, <code>NextState</code>, or <code>Update</code> instead perhaps? <code>Result</code> seems like a confusing name to me for what I (think?) that is.</p>\n\n<pre><code>data Update = Color (Float, Float, Float) | Quit | Reset | etc | etc | whatever\ntype Command = (Game -> Update -> IO Game) -- Presuming those functions which execute changes like doColorRed return an IO monad\n</code></pre>\n\n<p>I think you're missing a cohesive set of data models to present your system and it's possible states for which you could write functions to alter... When working with any UI presentation, it's usually best to create a model of your system and a separate view which responds to your model.</p>\n\n<p>I would change:</p>\n\n<pre><code> case mx of\n Left ex -> putStrLn $ \"Inhibited: \" ++ show ex -- this should never happen\n Right (GameColor c) -> do\n Al.clearToColor c\n Al.flipDisplay\n loop w' session' q\n Right Quit -> return ()\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>toColor (r,g,b) = Al.Color {Al.colorR = r, Al.colorG = g, Al.colorB = b, Al.colorA = 1.0}\nProcessCommand g (Color c) = Al.clearToColor (toColor c) >> Al.flipDisplay >> (gameLoop g)\nProcessCommand g Quit = return ()\n</code></pre>\n\n<p>then where you do your case, make sure your <code>Game</code> data type (represented as <code>g</code> above) has those <code>w'</code>, <code>session'</code>, and <code>q</code> variables as a part of your <code>Game</code> data type so the <code>gameLoop</code> function can execute that loop given any <code>Game</code></p>\n\n<p>and your case can take advantage of the exception monad instead of doing a case...</p>\n\n<pre><code>fmap (processCommand g) (mx <|> Right $ someFunctionThatTakesMxAndCreatesACommandToPrintTheError mx)\n</code></pre>\n\n<p>Give some of these techniques a try and see how it cleans up for ya. After that perhaps you'll see a higher level design appear that will make the domain a little easier to model and approach.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T07:26:18.723",
"Id": "43256",
"Score": "0",
"body": "Could you expand your idea of `iff` expressed as `<|>` for `(Bool,a)`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T16:41:21.127",
"Id": "43273",
"Score": "0",
"body": "@PetrPudlák perhaps that's a dumb idea, I'm just thinking either `<|>` or `msum` are for making a choice, so one of them ought be used in place of iff, I'm not sure where the True/False values are feeding out into iff, but I would maybe change them to feed out something that's a Monoid type or MonadPlus instead of Bool then use the appropriate choice technique"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T04:30:51.797",
"Id": "27757",
"ParentId": "27701",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T16:24:37.533",
"Id": "27701",
"Score": "3",
"Tags": [
"haskell"
],
"Title": "Simple netwire program"
}
|
27701
|
<p>I am trying to solve <a href="http://www.spoj.com/problems/PRIME1/" rel="nofollow">this</a> problem on Sphere Online Judge. I keep getting a timeout error. Any comments or suggestions are welcome and appreciated.</p>
<pre><code>package info.danforbes.sphere;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.MalformedInputException;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
public class PrimeNumberGenerator {
private static BufferedReader inStream;
private static BufferedWriter outStream;
private static List<Entry<Integer, Integer>> pairs = new ArrayList<Entry<Integer, Integer>>();
private static HashSet<Integer> primes = new HashSet<Integer>();
private static void getPairs(int numCases) throws MalformedInputException {
String line;
int spaceNdx;
int num1, num2;
try {
for (int pairNdx = 0; pairNdx < numCases; ++pairNdx) {
line = inStream.readLine();
spaceNdx = line.indexOf(' ');
num1 = Integer.parseInt(line.substring(0, spaceNdx));
num2 = Integer.parseInt(line.substring(spaceNdx + 1));
if (num1 < 1) throw new MalformedInputException(num1);
if (num1 > num2) throw new MalformedInputException(num2 - num1);
if (num2 > 1000000000) throw new MalformedInputException(num2);
if (num2 - num1 > 100000) throw new MalformedInputException(num2 - num1);
pairs.add(new SimpleEntry<Integer, Integer>(num1, num2));
}
inStream.close();
} catch (IOException e) {
System.out.println("IOException encounterd!");
e.printStackTrace();
System.exit(-1);
}
}
private static boolean isPrime(int num) {
boolean isPrime = true;
if (num < 2) isPrime = false;
else if (num > 3) {
if (num % 2 == 0 || num % 3 == 0) isPrime = false;
else if (!primes.contains(num)){
int sqrRoot = (int)Math.sqrt(num);
for (int factorNdx = 1; 6 * factorNdx - 1 <= sqrRoot; ++factorNdx) {
if (num % (6 * factorNdx + 1) == 0 || num % (6 * factorNdx - 1) == 0) {
isPrime = false;
break;
}
}
}
}
if (isPrime) primes.add(num);
return isPrime;
}
public static void main(String[] args) {
if (args.length == 0) {
inStream = new BufferedReader(new InputStreamReader(System.in));
outStream = new BufferedWriter(new OutputStreamWriter(System.out));
}
StringBuilder resultBuilder = new StringBuilder();
try {
if (inStream == null && outStream == null) {
inStream = new BufferedReader(new FileReader(args[0]));
outStream = new BufferedWriter(new FileWriter(args[1]));
}
int numCases = Integer.parseInt(inStream.readLine());
if (numCases > 10) throw new MalformedInputException(numCases);
getPairs(numCases);
int beg, end;
for (Entry<Integer, Integer> anEntry : pairs) {
beg = anEntry.getKey();
end = anEntry.getValue();
for (int rangeNdx = beg; rangeNdx <= end; ++rangeNdx) {
if (isPrime(rangeNdx)) resultBuilder.append(Integer.toString(rangeNdx) + "\n");
}
resultBuilder.append("\n");
}
resultBuilder.delete(resultBuilder.length() - 2, resultBuilder.length());
outStream.write(resultBuilder.toString());
outStream.close();
} catch (IOException e) {
System.out.println("IOException encountered!");
e.printStackTrace();
System.exit(-1);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I'll make general statements not addressing (or not limited to) performance.</p>\n\n<hr>\n\n<p>Your overall design is not very Object-Oriented. Usage of static/global variables is discouraged for a reason, it is very hard to follow the flow the program. Consider rewriting it with proper classes/encapsulation.</p>\n\n<p>You could extract reading into one function, which then returns the list of pairs which another function can work on. Some pseudo code:</p>\n\n<pre><code>main()\n List pairs\n if args provided\n pairs = pairsFromFile(args[0])\n else\n pairs = pairsFromStdIn()\n\n foreach pair in pairs\n processpair(pair)\n</code></pre>\n\n<hr>\n\n<p>Your usage of one-line <code>if</code>s is partly confusing, consider to expand those to at least two lines for readability:</p>\n\n<pre><code>if(test)\n return true;\n</code></pre>\n\n<hr>\n\n<p>You're declaring and actively throwing exceptions which never get caught, that means that your application will exit with a thrown exception, that's a bad thing. Applications should handle exceptions at least in the main loop and exit gracefully.</p>\n\n<hr>\n\n<p>Consider writing directly to the output-stream instead of buffering everything in a StringBuilder. While it might hurt performance if you're doing <em>a lot</em> of writing, it will remove some of the complexity.</p>\n\n<hr>\n\n<pre><code>System.out.println(\"IOException encounterd!\");\n</code></pre>\n\n<p>Exceptions and errors should traditionally go to <code>System.err</code>.</p>\n\n<hr>\n\n<p>You're using <code>System.exit()</code> at some places, it might be more desirable to let the main loop handle the application flow instead of \"exiting\" from any or some functions. I also now realize that you're using some sort of template to handle exceptions (write to out, print stacktrace, exit(-1)), please don't just slap an \"error-handling-template\" on it and be done with it. Handle exceptions <em>in a context-sensitive way</em>.</p>\n\n<hr>\n\n<p><code>isPrime()</code> does use a temporary variable <code>isPrime</code> when returning at the appropriate places would be more then enough.</p>\n\n<pre><code>private static boolean isPrime(int num) {\n if (num < 2)\n return false;\n else if (num > 3) {\n // Loop here\n if (num % (6 * factorNdx + 1) == 0 || num % (6 * factorNdx - 1) == 0) {\n return false;\n }\n }\n\n if (isPrime) primes.add(num);\n return true;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T03:06:00.230",
"Id": "43247",
"Score": "0",
"body": "Thanks for your suggestions, Bobby. Unfortunately, they didn't seem to have an impact on the performance of my code, and it's still failing Sphere with a timeout error."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T09:15:14.920",
"Id": "27721",
"ParentId": "27702",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T17:45:23.233",
"Id": "27702",
"Score": "1",
"Tags": [
"java",
"optimization",
"primes"
],
"Title": "Sphere Online Judge, Problem 2: Prime Number Generator"
}
|
27702
|
<p>I made an android app which utilizes SSDP for automatic device discovery.</p>
<p>Because I didn't need the whole UPnP functionality, I wrote my own independent SSDP component.</p>
<p>It works well, but I feel like I might've made the implementation way more complex than it needs to by adding too much indirection/abstraction. </p>
<p>I can't articulate the problem well enough, but it just seems too hard to understand overall.</p>
<p>InitSSDPComponent - called upon application being launched</p>
<pre><code>private void InitSSDPComponent() {
try {
// Acquire multicast lock to broadcast udp packets to SSDP address
WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiManager.MulticastLock multicastLock = wm
.createMulticastLock("multicastLock");
multicastLock.acquire();
ssdpComponent = new SSDPMainComponent(getApplicationContext());
// Start receiving M-SEARCH and NOTIFY messages sent by other
// devices
ssdpComponent.StartReceivingSSDPMessages();
// Start receiving device information sent directly from other
// devices
// upon sending M-SEARCH messages from this device
ssdpComponent.StartReceivingSSDPDeviceInfo();
// Start sending M-SEARCH messages to SSDP broadcasting address
// periodically
ssdpComponent.StartPeriodicMSearch();
// Start sending NOTIFY messages to SSDP broadcasting address
// periodically
ssdpComponent.StartPeriodicNotify();
} catch (IOException e) {
Log.e("MainActivity", "onCreate IOException", e);
}
}
</code></pre>
<p>Basically two separate UDP sockets are created: A socket called ListenerSocket is bound to the multicast address of 239.255.255.250:1900, which listens for M-SEARCH messages sent from other SSDP compliant devices. Upon ListenerSocket receiving an M-SEARCH message, a response containing this device's information is sent back to the requested device. Another one called MulticastSocket creates a UDP socket on any random available port, then sends out M-SEARCH messages to the broadcasting address so that other devices listening for M-SEARCH messages can respond with the listener's device information (Basically what ListenerSocket does). </p>
<p>In short, ListenerSocket is for other devices to discover this device and MulticastSocket is for this device to discover other devices.</p>
<p>So my SSDPMainComponent.java looks something like this</p>
<pre><code>public class SSDPMainComponent {
private SSDPMulticastSocket multicastSocket;
private SSDPListenerSocket listenerSocket;
private boolean isMulticastSocketEnabled = false;
private static final long M_SEARCH_BROADCASTING_INTERVAL = 60000; // In milliseconds, every 60 seconds
private static final long NOTIFY_BROADCASTING_INTERVAL = 850000; // In milliseconds, every 850 seconds
private static final String ROOT_DEVICE_XML_URL_PATH = "/localService/xml/rootdevice.xml";
private static URL ROOT_DEVICE_URL;
Thread socketInitThread;
public SSDPMainComponent(Context context) throws IOException {
ROOT_DEVICE_URL = new URL("http://" + NetworkUtils.getLocalIpAddress(context)
+ ":" + RestfulWebServerConstants.WEB_SERVER_PORT
+ ROOT_DEVICE_XML_URL_PATH);
socketInitThread = new Thread(new Runnable() {
@Override
public void run() {
try {
//Socket need to be created on a separate thread.
multicastSocket = new SSDPMulticastSocket();
listenerSocket = new SSDPListenerSocket();
} catch (IOException e) {
Log.e("SSDPMainComponent", "SSDPMainComponent IOException", e);
}
}
});
socketInitThread.start();
try {
socketInitThread.join();
} catch (InterruptedException e) {
Log.e("SSDPMainComponent", "SSDPMainComponent InterruptedException", e);
}
ctx = context;
}
public void StartPeriodicMSearch() {
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
SendMSearchMessage();
}
}, 0, M_SEARCH_BROADCASTING_INTERVAL);
}
public void StartReceivingSSDPDeviceInfo() {
new Thread(new Runnable() {
@Override
public void run() {
ReceiveSSDPDeviceInfo();
}
}).start();
}
public void StartReceivingSSDPMessages() {
new Thread(new Runnable() {
@Override
public void run() {
ReceiveSSDPMessages();
}
}).start();
}
public void SendMSearchMessage() {
SSDPSearchMsg searchRootDevice = new SSDPSearchMsg(
SSDPConstants.ST_RootDevice);
try {
multicastSocket.send(searchRootDevice.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("SSDPMainComponent", "SendMSearchMessage IOException", e);
}
}
private void ReceiveSSDPMessages() {
while (true) {
DatagramPacket dp;
try {
dp = listenerSocket.receive();
String packetData = new String(dp.getData());
Log.i("ReceiveSSDPMessages", packetData.toString());
SSDPDiscoveryPacketParser packetParser = new SSDPDiscoveryPacketParser(packetData);
if (!packetParser.isValidDiscoveryPacket())
continue;
if (packetParser.isNotifyMessage()) {
//TODO: Add received device information to DB
}
else {
//Respond with this device's information back to the requested device
SendMSearchResponseMsg(packetParser.getMX(),dp.getAddress(),dp.getPort());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void SendMSearchResponseMsg(final int mx, final InetAddress destAddr, final int port) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(mx * 1000);
SSDPSearchResponseMsg responseMsg = new SSDPSearchResponseMsg(ROOT_DEVICE_URL);
Log.i("MSearchResponse","DEST ADDR: " + destAddr.getHostAddress() + ":" + Integer.toString(port));
listenerSocket.send(responseMsg.getRootResponseMsg(), destAddr, port);
} catch (InterruptedException e) {
Log.e("SSDPMainComponent", "SendMSearchResponseMsg InterruptedException",e);
} catch (IOException e) {
Log.e("SSDPMainComponent", "SendMSearchResponseMsg IOException",e);
}
}
}).start();
}
private void ReceiveSSDPDeviceInfo() {
if (multicastSocket == null || isMulticastSocketEnabled) {
return;
}
isMulticastSocketEnabled = true;
while (true) {
try {
DatagramPacket dp;
dp = multicastSocket.receive();
String packetData = new String(dp.getData());
Log.v("SSDP PACKET DATA", packetData.toString());
SSDPDevicePacketParser packetParser = new SSDPDevicePacketParser(packetData);
if (!packetParser.requestXML())
continue;
DeviceDbAdapter deviceDbAdapter = DeviceDbAdapter.getInstance();
ServiceApiDbAdapter serviceApiDbAdapter = ServiceApiDbAdapter.getInstance();
try {
deviceDbAdapter.open();
DeviceInfoStruct deviceStruct = packetParser.getDeviceInfo();
//If Invalid XML Info (with respect to LG protocol including Port/Device ID in location xml), go to next loop
if (deviceStruct == null || TextUtils.isEmpty(deviceStruct.getServerPort()) || TextUtils.isEmpty(deviceStruct.getDeviceID()) ||
TextUtils.isEmpty(deviceStruct.getDeviceID()) || TextUtils.isEmpty(deviceStruct.getManufacturer()))
continue;
serviceApiDbAdapter.open();
ServiceStruct serviceStruct = packetParser.getServiceAPI();
//Invalid XML Info for services, go to next loop
if (serviceStruct == null || TextUtils.isEmpty(serviceStruct.getDeviceID()) || serviceStruct.getAPICount() <= 0)
continue;
if (deviceDbAdapter.hasDevice(deviceStruct.getDeviceID())) {
deviceDbAdapter.updateDevice(deviceStruct);
Log.i("ReceiveSSDPDeviceInfo", "Updated Device: " + deviceStruct.getServerIP() + ":" + deviceStruct.getServerPort());
}
else {
deviceDbAdapter.insertDevice(deviceStruct);
Log.i("ReceiveSSDPDeviceInfo", "Inserted Device: " + deviceStruct.getServerIP() + ":" + deviceStruct.getServerPort());
}
ArrayList<APIStruct> apiList = serviceStruct.getAPIStructList();
String deviceID = serviceStruct.getDeviceID();
for (int i = 0; i < apiList.size(); i++) {
String apiType = apiList.get(i).getApiType();
ArrayList<String> apiNameList = apiList.get(i).getApiNameList();
for (int j = 0; j < apiNameList.size(); j++) {
String apiName = apiNameList.get(j);
if (!serviceApiDbAdapter.hasServiceAPI(deviceID, apiType, apiName))
serviceApiDbAdapter.insertServiceAPI(deviceID,apiType,apiName);
}
}
} catch (SAXException e) {
Log.e("SSDPMainComponent", "ReceiveSSDPDeviceInfo SAXException", e);
} catch (ParserConfigurationException e) {
Log.e("SSDPMainComponent", "ReceiveSSDPDeviceInfo ParserConfigurationException", e);
}
finally {
if (deviceDbAdapter.isOpen())
deviceDbAdapter.close();
if (serviceApiDbAdapter.isOpen())
serviceApiDbAdapter.close();
}
} catch (IOException e) {
Log.e("SSDPMainComponent", "ReceiveSSDPDeviceInfo IOException", e);
}
}
}
}
</code></pre>
<p>Already at this point, I've made things too complicated. Although I'm not 100% sure, I believe here are some things I'm doing wrong:</p>
<ul>
<li>SSDPMainComponent is doing too many things. It's supposed to be the class that starts up all the adjunct components, but it's also parsing the XML data received as part of the other devices' M-SEARCH response.</li>
<li>The way I'm starting the threads seem awkward. Since android needs you to do any socket related work on a separate thread, perhaps it can't be avoided to a degree.</li>
<li>Just by looking at the private methods being called to initialize certain components (SendNotifyMessage, SendMSearchMessage, ReceiveSSDPDeviceInfo, ReceiveSSDPMessages), I can't quite tell which socket it will use (Listener/Multicast). </li>
<li>The namings in general seem very awkward. At a cursory glance, you can't quite tell what "MulticastSocket" or "ListenerSocket" is supposed to do in this application's context.</li>
<li>I think I'm violating quite a bit of KISS in many places too. </li>
</ul>
<p>I guess I dragged on the question for too long but all I really want is some sort of guideline to make this code more elegant and understandable.</p>
|
[] |
[
{
"body": "<p>The <code>SSDPMainComponent</code> is doing <em>four</em> different jobs (the code for <code>StartPeriodicNotify()</code> seems to be missing though). Yet on closer inspection those jobs have very little in common. Some share the same socket, but that's it.</p>\n\n<p>We can simply refactor SSDMainComponent into delegating these jobs to 4 helper classes. I've also used FutureTasks instead of joining on one Socket creating thread. (this postpones waiting for the thread, until we actually need one of the sockets, with any luck it'll be ready by the time we need it)</p>\n\n<pre><code>public class SSDPMainComponent {\n private FutureTask<SSDPMulticastSocket> multicastSocket;\n private FutureTask<SSDPListenerSocket> listenerSocket;\n private static final String ROOT_DEVICE_XML_URL_PATH = \"/localService/xml/rootdevice.xml\";\n private static URL ROOT_DEVICE_URL;\n\n public SSDPMainComponent(Context context) throws IOException {\n ROOT_DEVICE_URL = new URL(\"http://\" + NetworkUtils.getLocalIpAddress(context)\n + \":\" + RestfulWebServerConstants.WEB_SERVER_PORT\n + ROOT_DEVICE_XML_URL_PATH);\n multicastSocket = new FutureTask<>(new Callable<SSDPMulticastSocket>() {\n @Override\n public SSDPMulticastSocket call() throws Exception {\n return new SSDPMulticastSocket();\n }\n });\n new Thread(multicastSocket).start();\n listenerSocket = new FutureTask<>(new Callable<SSDPListenerSocket>() {\n @Override\n public SSDPListenerSocket call() throws Exception {\n return new SSDPListenerSocket();\n }\n });\n new Thread(listenerSocket).start();\n }\n\n public void StartPeriodicMSearch() throws InterruptedException {\n new SSDPPeriodicSearcher(getMulticastSocket()).startPeriodicMSearch();\n }\n\n public void StartReceivingSSDPDeviceInfo() throws InterruptedException {\n new SSDPInfoReceiver(getMulticastSocket()).startReceivingSSDPDeviceInfo();\n }\n\n public void StartReceivingSSDPMessages() throws InterruptedException {\n new SSDPReceiver(getListenerSocket(), ROOT_DEVICE_URL).StartReceivingSSDPMessages();\n }\n\n private SSDPMulticastSocket getMulticastSocket() throws InterruptedException {\n try {\n return multicastSocket.get();\n } catch (ExecutionException e) {\n throw new RuntimeException(e.getCause());\n }\n }\n\n private SSDPListenerSocket getListenerSocket() throws InterruptedException {\n try {\n return listenerSocket.get();\n } catch (ExecutionException e) {\n throw new RuntimeException(e.getCause());\n }\n }\n\n}\n</code></pre>\n\n<p>In fact, it is now little more than a component to start creating the sockets. If we expose the getters for the sockets, we could simply move the content of the <code>start...()</code> methods to <code>initSSDPComponent()</code>.</p>\n\n<p>Of the helper classes, only <code>SSDPInfoReceiver</code> is doing too much. As you yourself already point out, it is doing the parsing and processing of the received datagram. But delegating this to a Parser and a Processor component will dramatically simplify <code>SSDPInfoReceiver</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T19:40:31.710",
"Id": "27775",
"ParentId": "27704",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "27775",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T18:07:49.647",
"Id": "27704",
"Score": "4",
"Tags": [
"java",
"android",
"networking"
],
"Title": "Using SSDP for automatic device discovery"
}
|
27704
|
<p>Right now I'm creating a community. You can register and create your own profile and post on a forum etc. I'm just doing this for fun and learning. I'm not planning on becoming a professional programmer this is just a hobby of mine.</p>
<p>Anyway, I want do it right though. Please review my script and tell me if it seems OK and safe. And please if you have a suggestion or anything go ahead. </p>
<p>This is the login (I use sessions):</p>
<pre><code>// Trim values sent from form
$username = trim($_POST['username']);
$password = trim($_POST['password']);
// Get user info and their rights matching login attempt
$stmt = $db->prepare("SELECT id, username, g_can_delete_users, g_can_edit_post, g_can_handle_reports FROM users LEFT JOIN groups ON groups.g_id = users.group_id WHERE users.username = ? AND SHA1(CONCAT(users.salt, ?)) = users.password");
$stmt->execute(array($username, $password));
$row = $stmt->fetch();
// Did we find a match?
if ($row) {
$_SESSION['user'] = $row;
header("Location: index.php");
exit;
} else {
header("Location: index.php");
exit;
}
</code></pre>
<p>And the registration part:</p>
<pre><code>// Example of a generated salt: &O93Wrl`x#iY
$username = trim($_POST['username']);
$email = strtolower(trim($_POST['email']));
$password1 = trim($_POST['password1']);
$password2 = trim($_POST['password2']);
// Validate the username
if (strlen($username) < 4)
$errors[] = "Username must be at least 4 characters.";
// ... and the password
else if (strlen($password1) < 4)
$errors[] = "Password too short";
else if ($password1 != $password2)
$errors[] = "Passwords do not match";
else
$stmt = $db->prepare("INSERT INTO users (username, password, email, salt, registered, registration_ip) VALUES (:username, :password, :email, :salt, :registered, :registration_ip)");
$stmt->execute(array(':username'=>$username, ':password'=>sha1($salt.$password1), ':email'=>$email, ':salt'=>$gen_salt, ':registered'=>time(), ':registration_ip'=>$_SERVER['REMOTE_ADDR']));
</code></pre>
|
[] |
[
{
"body": "<p>I can't say it is plain wrong, but the <code>LEFT JOIN</code> against groups makes me twitch when I read it, because it is so crucial that this password check works. I'd split it off into a separate query that you run after the user has been authorized.</p>\n\n<p>Then, in <code>$_SESSION['user'] = $row</code> it seems that the code ignores any following rows (i.e. if the user is a member of more than one group). Otherwise the database hasn't been normalized.</p>\n\n<p>Another thing is that this requires the user submits the password in plain text. Using HTTPS should solve that problem, but another solution is using a challenge response-scheme. If you have neither, well then there is a security issue to address.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T20:51:07.073",
"Id": "27708",
"ParentId": "27707",
"Score": "1"
}
},
{
"body": "<p>A few things to add to Michael Zedeler's review:</p>\n\n<hr>\n\n<p>Your formatting is a little odd. Pick an indenting scheme and stick with it. (This seems to be part of a bigger script though, so maybe it's just copy/paste gone wrong?)</p>\n\n<hr>\n\n<p>Don't assume array indexes exist (read the first section of <a href=\"https://codereview.stackexchange.com/questions/12757/basic-user-registration-code-in-php/12769#12769\">this</a>).</p>\n\n<hr>\n\n<p>You assume username's are available?</p>\n\n<hr>\n\n<p>By the HTTP <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30\" rel=\"nofollow noreferrer\">standard</a>, <code>Location</code> headers must have a full URL.</p>\n\n<hr>\n\n<p>I would pull the hashed password into PHP land and do the comparison there. This has multiple advantages:</p>\n\n<p>1) You can know whether the error is because the user doesn't exist or because the password is wrong\n2) The MySQL query log is guaranteed to not contain the password in plain text</p>\n\n<hr>\n\n<p>Your last if clause is a perfect example of why you should always use braces with if/else. It comes down to a stylistic choice whether or not to actually always use them, but in this situation, your code is wrong without them on the last clause:</p>\n\n<pre><code> else \n $stmt = $db->prepare(\"INSERT INTO users (username, password, email, salt, registered, registration_ip) VALUES (:username, :password, :email, :salt, :registered, :registration_ip)\");\n $stmt->execute(array(':username'=>$username, ':password'=>sha1($salt.$password1), ':email'=>$email, ':salt'=>$gen_salt, ':registered'=>time(), ':registration_ip'=>$_SERVER['REMOTE_ADDR']));\n</code></pre>\n\n<p>Is the same thing as:</p>\n\n<pre><code> else {\n $stmt = $db->prepare(\"INSERT INTO users (username, password, email, salt, registered, registration_ip) VALUES (:username, :password, :email, :salt, :registered, :registration_ip)\");\n }\n $stmt->execute(array(':username'=>$username, ':password'=>sha1($salt.$password1), ':email'=>$email, ':salt'=>$gen_salt, ':registered'=>time(), ':registration_ip'=>$_SERVER['REMOTE_ADDR']));\n</code></pre>\n\n<p>This means if that if any of the other branches are followed, you'll get an invalid object fatal error since you'll be trying to call <code>execute</code> on <code>null</code>.</p>\n\n<hr>\n\n<p>What is the data type of <code>registered</code>? I'm a little concerned that it might be an <code>int</code>. It should be either a <code>timestamp</code> or a <code>datetime</code> (likely a <code>timestamp</code> in this situation).</p>\n\n<hr>\n\n<p>While you've made good steps using sha1 and a salt, you might should consider using a better scheme for hashing. There's a lot of good information <a href=\"https://stackoverflow.com/questions/401656/secure-hash-and-salt-for-php-passwords\">here</a>.</p>\n\n<hr>\n\n<p>I'd use a different flow to handle the errors. In particular, there's no reason that a username error and a password error can't happen at the same time:</p>\n\n<pre><code>$errors = array();\n\nif (strlen($username) < 4) {\n $errors[] = \"Username must be at least 4 characters.\";\n}\n\nif (strlen($password1) < 4) {\n $errors[] = \"Password too short\";\n} else if ($password1 != $password2) {\n $errors[] = \"Passwords do not match\";\n}\n\nif (!$errors) {\n //Create the user\n} \n</code></pre>\n\n<hr>\n\n<p>You should declare <code>$errors</code> ahead of appending to it. <code>$errors[]</code> will create the variable fine without complaining, but it's much easier to read code if you know where all of the variables come into play. And, from a technical perspective, reading a non-existent <code>$errors</code> <em>will</em> complain (and error reporting should be cranked all the way up! especially in development).</p>\n\n<hr>\n\n<p>I don't like the g_ prefix for the groups table. What happens when you run out of letters? What happens if you have another g table? It seems odd. I would just name the columns naturally, and then when you join on it, alias the columns when necessary.</p>\n\n<p>(I agree with Michael though: your authentication and access code should be separate. Authenticate first and then worry about permissions.)</p>\n\n<hr>\n\n<p>I don't know how I feel about <code>trim</code>ing a password. That could be confusing for someone who legitimately wants a space on the end of a password (and I'm a huge fan of not restricting what characters are allowed in passwords). Then again, it's a rather questionable choice to end a password with white space anyway.</p>\n\n<hr>\n\n<p>I like to always use named parameters in prepared statements. It's easier to read, and it can save you from a \"Wtf?\" later if you rearrange or add clauses.</p>\n\n<hr>\n\n<p>I don't see a <code>session_start()</code> anywhere? But I guess this is just a snippet of a bigger script?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T23:46:30.757",
"Id": "27713",
"ParentId": "27707",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T20:01:51.920",
"Id": "27707",
"Score": "5",
"Tags": [
"php",
"pdo",
"authentication"
],
"Title": "Registration and login"
}
|
27707
|
<p>It's a standalone HTML file on <a href="https://github.com/mike-joyce/Mastermind/blob/master/Mastermind.html" rel="nofollow">GitHub</a></p>
<p>I included the CSS and JavaScript with the HTML so it would be easier to e-mail the game.</p>
<p>I'm most interested in comments about the solution-checking functions. This is the main function:</p>
<pre><code>var evaluateSolution = function () {
//"In play" is the default state for the game.
var state = stateGame;
//Look for exact matches.
checkColorPositionMatches();
//If every peg matches exactly, the game was won
if (colorPositionMatches == codeLength) {
state = stateWin;
} else {
//Look for color matches among the unmatched pegs.
checkColorMatches();
state = stateLose;
}
//Reset the match state of each codePeg
unmatchCodePegs();
return state;
}
</code></pre>
<p>This one checks for exact matches.</p>
<pre><code>var checkColorPositionMatches = function() {
colorPositionMatches = 0;
codePegLoop:
for (var codePegIdx=0;codePegIdx<codePegs.length;codePegIdx++) {
var codePeg = codePegs[codePegIdx];
//evaluate each gamePeg, stopping if we hit an exact match.
gamePegLoop:
for (var gamePegIdx=0;gamePegIdx<gamePegs.length;gamePegIdx++) {
var gamePeg = gamePegs[gamePegIdx];
if ((gamePeg.color == codePeg.color) &&
(gamePeg.position == codePeg.position)) {
gamePeg.colorPositionMatched = true;
codePeg.colorPositionMatched = true;
colorPositionMatches++;
break gamePegLoop;
}
}
}
}
</code></pre>
<p>This one checks for color-only matches.</p>
<pre><code>var checkColorMatches = function() {
colorMatches = 0;
codePegLoop:
for (var codePegIdx=0;codePegIdx<codePegs.length;codePegIdx++) {
var codePeg = codePegs[codePegIdx];
//evaluate each unmatched game peg, recording matches as they occur
gamePegLoop:
for (var gamePegIdx=0;gamePegIdx<gamePegs.length;gamePegIdx++) {
var gamePeg = gamePegs[gamePegIdx];
if (gamePeg.color == codePeg.color &&
(gamePeg.colorMatched == false) &&
(codePeg.colorMatched == false) &&
(gamePeg.colorPositionMatched == false) &&
(codePeg.colorPositionMatched == false)) {
gamePeg.colorMatched=true;
codePeg.colorMatched=true;
colorMatches++;
break gamePegLoop;
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The first thing I notice is that you're \"manually\" handling both color and position. This isn't actually necessary if you set everything up using simple arrays.</p>\n\n<p>An array is, by definition, an indexed list of values. So if you use a simple array for your code and the pegs, then positions are the array's indices and colors are its values. This simplifies things considerably.</p>\n\n<p>For instance, to find exact (color and position) matches, you only need to check if <code>code[i] === pegs[i]</code>. And to check if a peg matches anywhere in the code, you only need to check <code>code.indexOf(peg[i]) !== -1</code>. So if you can get something like this:</p>\n\n<pre><code>var code = [\"white\",\"black\",\"red\",\"blue\",\"green\"]; // the code\nvar pegs = [\"white\",\"black\",\"blue\",\"red\",\"orange\"]; // the player's selections\n</code></pre>\n\n<p>it'll make the checking a lot easier.</p>\n\n<p>Now, along the way you'll need to do some extra work to keep track of the number of matches, and make sure you're not double-matching stuff. I.e. you need to pare down your arrays as you go, so they only contain the remaining unmatched values.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>function evaluateSolution(code, pegs) {\n var i, l,\n foundIndex,\n exactMatches = 0,\n valueMatches = 0;\n\n // copy the arrays, so we don't ruin the orignals\n code = code.slice(0);\n pegs = pegs.slice(0);\n\n // First pass: Look for value & position matches\n // We're looping \"backwards\", so we can safely remove items\n // \"behind us\"\n for( i = pegs.length - 1 ; i >= 0 ; i-- ) {\n // If there's a match, remove the matched index from both\n // the code and the pegs so it isn't matched again later.\n if(pegs[i] === code[i]) {\n exactMatches++;\n pegs.splice(i, 1);\n code.splice(i, 1);\n }\n }\n\n // Now, pegs and code only contain unmatched values\n\n // Second pass: Look for value matches anywhere in the code\n for( i = 0 , l = pegs.length ; i < l ; i++ ) {\n // attempt to find the peg in the remaining code\n foundIndex = code.indexOf(pegs[i]);\n if( foundIndex !== -1 ) {\n valueMatches++;\n // remove the matched code peg, since it's been matched\n code.splice(foundIndex, 1);\n }\n }\n\n // Now, return the number of exact and inexact matches\n // as an object, so it's easy to use\n return {\n exactMatches: exactMatches,\n valueMatches: valueMatches,\n totalMatches: exactMatches + valueMatches\n };\n}\n</code></pre>\n\n<p>If you feed the arrays above to <code>evaluateSolution()</code> you'll get this back:</p>\n\n<pre><code>{\n exactMatches: 2,\n valueMatches: 2,\n totalMatches: 4\n}\n</code></pre>\n\n<p>If <code>exactMatches === code.length</code>, then congrats, you've won! Otherwise, use the numbers to render the hint.</p>\n\n<hr>\n\n<p>Other observations:</p>\n\n<ul>\n<li>You leave a lot of blank lines in your code, but the non-blank lines are pretty crammed (e.g. your whitespace-less <code>for</code>-loop declarations). Give you code (and the reader) some space to breathe. </li>\n<li>I looked briefly at the code on GitHub, and there's <em>a lot</em> going on. Too much really. But here's a hint: You can build most of HTML using JavaScript. Copy/pasting the HTML for each \"turn\" and giving it a new ID is a nightmare to deal with. Just loop and create elements in code.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T01:03:11.777",
"Id": "37456",
"ParentId": "27710",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37456",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T21:42:55.007",
"Id": "27710",
"Score": "4",
"Tags": [
"javascript",
"game"
],
"Title": "How can I improve this version of the board game Mastermind?"
}
|
27710
|
<p>I'm currently doing my first internship and had to create an application that will check through the first row of a CSV for valid or invalid input. Is there a more elegant way to code or to refactor my FileValidator class? This is my first time programming in a professional environment, so I'm still trying to learn how to "clean code". If you see any bad practices, please say so.</p>
<pre><code>package util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import org.apache.log4j.Logger;
import au.com.bytecode.opencsv.CSVReader;
public class FileValidator {
private CSVReader reader;
List<String[]> row;
private File file;
private String date;
private String[] header;
private final static Logger log = Logger.getLogger(FileValidator.class);
private static final int HEADER_MAX_COLUMNS = 4;
private static String[] BUSINESS = { "SAFC", "FLDB", "RGSP", "JKAA",
"FAKJ", "SFDK" };
public boolean readFile(File newFile, String date) // receive File object
// and date provided by
// user
{
try {
this.file = newFile;
reader = new CSVReader(new FileReader(file));
row = reader.readAll();
header = row.get(0); // assign first row of CSV to a List<String[]>
// (list of Strings(cells))
this.date = date;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
public boolean validateFile() {
boolean[] checkHeader = { checkNumColumns(), checkIfEmpty(),
checkDate(), checkFileName(), checkBusiness() };
for (int i = 0; i < checkHeader.length; i++) {
if (checkHeader[i] == false)
return false;
}
return true;
}
public boolean checkNumColumns() // check if number of header columns are
// correct
{
if (!(row.get(0).length <= HEADER_MAX_COLUMNS)) {
return false;
} else
return true;
}
public boolean checkIfEmpty() // check if any cells are empty
{
for (int i = 0; i < HEADER_MAX_COLUMNS; i++) {
if (!header[i].trim().equals(header[i]) || header[i] == null
|| header[i] == "" || header[i].length() == 0)
return false;
}
return true;
}
public boolean checkDate() // check if user-given date matches header:
// cell[0]
{
if (!header[0].equals(date)) {
return false;
} else
return true;
}
public boolean checkFileName() // check if file name equals cell[1]
{
if (!header[1].equals(file.getName())) {
return false;
} else
return true;
}
public boolean checkBusiness() // check if business name (cell[2]) matches
// any from static string list
{
for (int i = 0; i < BUSINESS.length; i++) {
if (header[3].equals(BUSINESS[i]))
return true;
}
return false;
}
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>Declare your <code>BUSINESS</code> constant as final</li>\n<li><code>readFile</code> will currently always return 'true', barring some unforeseen exception. Seems like you could make it a void method as well.</li>\n<li><code>validateFile</code> is a bit bad method name. Imagine it being used elsewhere: <code>if( x.validateFile() ) { /* do something */ }</code>. That looks like you're asking whether to validate a file or not. If you want to call the method that, make it return void and make it throw an exception if the validation fails. Otherwise call it something like <code>isFileValid()</code>.</li>\n<li>All the methods in your class are defined as public, which makes little sense. You could make them all but one private and enter the File and date in a constructor. Or you could just make one static method there which would call the other methods. As far as I can see there's no need for a FileValidator object to actually have a state.</li>\n<li><p><code>validateFile()</code> makes a fancy but redundant boolean array of all the validation results. In reality you do not need to call all the validators if the first one of them fails. Try this instead:</p>\n\n<pre><code>private boolean validateFile() {\n return checkNumColumns() && checkIfEmpty() && checkDate() && checkFileName() && checkBusiness();\n}\n</code></pre></li>\n<li>Your checkIfEmpty() method has a possible NullPointerException: it first trims <code>header[i]</code>, and only afterwards checks for null, at which point it's too late. Also, String comparisons with \"==\"s is just wrong, as that checks that the memory locations of the two strings are the same, saying nothing about their contents. <code>string == \"\"</code> would anyway be the same as <code>string.length() == 0</code> if it worked. Besides, nowadays the correct way to check for an empty string is `string.isEmpty()\".</li>\n<li><code>checkDate()</code> does not need an if-else block: just do <code>return header[0].equals(date);</code>. (A completely other thing is that representing dates with Strings isn't necessarily the best idea ever when java.util.Date exists as well.)</li>\n<li>The previous point also applies for <code>checkFileName()</code>. Those <code>header[1]</code> names are not readable anyway, you will want to pass the \"header[1]\" as an argument to the method (which should be static and private) and then call the argument \"filename\".</li>\n<li><code>checkBusiness()</code> is pretty good as it stands, just have it take the business as an argument instead of using \"header[3]\", just like I noted about the previous method.</li>\n<li>Don't forget to write unit tests for your class.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T23:00:30.063",
"Id": "43168",
"Score": "0",
"body": "That's excellent advice, just the constructive criticism I was hoping for. Thanks, will take all into consideration."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T05:54:11.530",
"Id": "43176",
"Score": "1",
"body": "@stevendao Happy to help. :) Please consider accepting my answer by finding the checkmark below the voting arrows on the left side of my post. That's the Stack Exchange way of saying the same thing you just said. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T22:41:26.453",
"Id": "27712",
"ParentId": "27711",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "27712",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T21:56:56.513",
"Id": "27711",
"Score": "3",
"Tags": [
"java",
"csv",
"excel"
],
"Title": "Is there a better or more elegant way to code this CSV cell-parser (using CSVReader)?"
}
|
27711
|
<p>I wrote <a href="https://github.com/jrenner/libgdx-updater/blob/master/libgdx_update.py" rel="nofollow">a script</a> that updates some library files for the game framework libgdx by grabbing the latest nightly build .zip file from a server and extracting the contents to the appropriate locations.</p>
<pre><code>#!/usr/bin/python
__appname__ = 'libgdx_library_updater'
__version__ = "0.1"
__author__ = "Jon Renner <rennerjc@gmail.com>"
__url__ = "http://github.com/jrenner/libgdx-updater"
__licence__ = "MIT"
import os, time, sys, urllib2, re, datetime, tempfile, zipfile, argparse
# error handling functions and utils
def fatal_error(msg):
print "ERROR: %s" % msg
sys.exit(1)
def warning_error(msg):
print "WARNING: %s" % msg
if not FORCE:
answer = confirm("abort? (Y/n): ")
if answer in YES:
fatal_error("USER QUIT")
def confirm(msg):
answer = raw_input(msg)
return answer.lower()
def human_time(t):
minutes = t / 60
seconds = t % 60
return "%.0fm %.1fs" % (minutes, seconds)
# constants
YES = ['y', 'ye', 'yes', '']
# for finding the time of the latest nightly build from the web page html
DATE_RE = r"[0-9]{1,2}-[A-Za-z]{3,4}-[0-9]{4}\s[0-9]+:[0-9]+"
REMOTE_DATE_FORMAT = "%d-%b-%Y %H:%M"
SUPPORTED_PLATFORMS = ['android', 'desktop', 'gwt']
CORE_LIBS = ["gdx.jar",
"gdx-sources.jar"]
DESKTOP_LIBS = ["gdx-backend-lwjgl.jar",
"gdx-backend-lwjgl-natives.jar",
"gdx-natives.jar"]
ANDROID_LIBS = ["gdx-backend-android.jar",
"armeabi/libgdx.so",
"armeabi/libandroidgl20.so",
"armeabi-v7a/libgdx.so",
"armeabi-v7a/libandroidgl20.so"]
GWT_LIBS = ["gdx-backend-gwt.jar"]
# parse arguments
EPILOGUE_TEXT = "%s\n%s" % (__author__, __url__) + "\nUSE AT YOUR OWN RISK!"
parser = argparse.ArgumentParser(description='LibGDX Library Updater %s' % __version__, epilog=EPILOGUE_TEXT)
parser.add_argument('-d', '--directory', help='set the libgdx project/workspace directory', default=os.getcwd())
parser.add_argument('-i', '--interactive', action='store_true', help='ask for confirmation for every file', default=False)
parser.add_argument('-f', '--force-update', action='store_true', help='no confirmations, just update without checking nightly\'s datetime', default=False)
parser.add_argument('-a', '--archive', help='specify libgdx zip file to use for update', default=None)
args = parser.parse_args()
PROJECT_DIR = args.directory
INTERACTIVE = args.interactive
FORCE = args.force_update
ARCHIVE = args.archive
# mutually exclusive
if FORCE:
INTERACTIVE = False
# check the time of the latest archive on the nightlies server
def get_remote_archive_mtime():
index_page = urllib2.urlopen("http://libgdx.badlogicgames.com/nightlies/")
contents = index_page.read()
print "-- OK --"
# regex for filename
regex = r"libgdx-nightly-latest\.zip"
# add regex for anything followed by the nighlty html time format
regex += r".*%s" % DATE_RE
try:
result = re.findall(regex, contents)[0]
except IndexError as e:
print "REGEX ERROR: failed to find '%s' in:\n%s" % (regex, contents)
fatal_error("regex failure to match")
try:
mtime = re.findall(DATE_RE, result)[0]
except IndexError as e:
print "REGEX ERROR: failed to find datetime in: %s" % result
fatal_error("regex failure to match")
dtime = datetime.datetime.strptime(mtime, REMOTE_DATE_FORMAT)
return dtime
# downloads and returns a temporary file contained the latest nightly archive
def download_libgdx_zip():
libgdx = tempfile.TemporaryFile()
url = "http://libgdx.badlogicgames.com/nightlies/libgdx-nightly-latest.zip"
# testing url - don't hammer badlogic server, host the file on localhost instead
# url = "http://localhost/libgdx-nightly-latest.zip"
resp = urllib2.urlopen(url)
print "downloading file: %s" % url
total_size = resp.info().getheader('Content-Length').strip()
total_size = int(total_size)
# base 10 SI units - following Ubuntu policy because it makes sense - https://wiki.ubuntu.com/UnitsPolicy
total_size_megabytes = total_size / 1000000.0
bytes_read = 0
chunk_size = 10000 # 10kB per chunk
while True:
chunk = resp.read(chunk_size)
libgdx.write(chunk)
bytes_read += len(chunk)
bytes_read_megabytes = bytes_read / 1000000.0
percent = (bytes_read / float(total_size)) * 100
sys.stdout.write("\rprogress: {:>8}{:.2f} / {:.2f} mB ({:.0f}% complete)".format(
"", bytes_read_megabytes, total_size_megabytes, percent))
sys.stdout.flush()
if bytes_read >= total_size:
print "finished download"
break
return libgdx
def update_files(libs, locations, archive):
for lib in libs:
if lib in archive.namelist():
if INTERACTIVE:
answer = confirm("overwrite %s? (Y/n): " % lib)
if answer not in YES:
print "skipped: %s" % lib
continue
with archive.open(lib, "r") as fin:
filename = os.path.basename(lib)
final_path = os.path.join(locations[lib], filename)
with open(final_path, "w") as fout:
fout.write(fin.read())
print "extracted to %s" % final_path
def run_core(locations, archive):
title("CORE")
update_files(CORE_LIBS, locations, archive)
def run_android(locations, archive):
title("ANDROID")
update_files(ANDROID_LIBS, locations, archive)
def run_desktop(locations, archive):
title("DESKTOP")
update_files(DESKTOP_LIBS, locations, archive)
def run_gwt(locations, archive):
title("GWT")
update_files(GWT_LIBS, locations, archive)
def search_for_lib_locations(directory):
platforms = []
search_list = CORE_LIBS + DESKTOP_LIBS + ANDROID_LIBS
locations = {}
for element in search_list:
locations[element] = None
for (this_dir, dirs, files) in os.walk(directory):
for element in search_list:
split_path = os.path.split(element)
path = os.path.split(split_path[0])[-1]
filename = split_path[1]
for f in files:
match = False
if filename == f:
f_dir = os.path.split(this_dir)[-1]
if path == "":
match = True
else:
if path == f_dir:
match = True
if match:
if locations[element] != None:
print "WARNING: found %s in more than one place!" % element
if not FORCE:
answer = confirm("continue? (Y/n): ")
if answer not in YES:
fatal_error("USER ABORT")
locations[element] = this_dir
for lib, loc in locations.items():
if loc == None:
print "WARNING: did not find library %s in directory tree of: %s" % (lib, directory)
found_libraries = [lib for lib, loc in locations.items() if locations[lib] != None]
if found_all_in_set(CORE_LIBS, found_libraries):
platforms.append("core")
if found_all_in_set(ANDROID_LIBS, found_libraries):
platforms.append("android")
if found_all_in_set(DESKTOP_LIBS, found_libraries):
platforms.append("desktop")
if found_all_in_set(GWT_LIBS, found_libraries):
platforms.append("gwt")
return platforms, locations
def found_all_in_set(lib_set, found_list):
for lib in lib_set:
if lib not in found_list:
return False
return True
def main():
start_time = time.time()
print "finding local libraries in %s" % PROJECT_DIR
platforms, locations = search_for_lib_locations(PROJECT_DIR)
if "core" not in platforms:
fatal_error("did not find CORE libraries %s in project directory tree" % str(CORE_LIBS))
else:
print "found CORE libraries"
for supported in SUPPORTED_PLATFORMS:
if supported in platforms:
print "found libraries for platform: %s" % supported.upper()
else:
print "WARNING: did not find libraries for platform: %s - WILL NOT UPDATE" % supported.upper()
if ARCHIVE == None:
print "checking latest nightly..."
mtime = get_remote_archive_mtime()
print "lastest nightly from server: %s" % mtime
if not FORCE:
answer = confirm("replace local libraries with files from latest nightly?(Y/n): ")
if answer not in YES:
fatal_error("USER QUIT")
libgdx = download_libgdx_zip()
else:
if not os.path.exists(ARCHIVE):
fatal_error("archive file not found: %s" % ARCHIVE)
if not FORCE:
answer = confirm("replace local libraries with files from '%s'?(Y/n): " % os.path.basename(ARCHIVE))
if answer not in YES:
fatal_error("USER QUIT")
libgdx = open(ARCHIVE, "r")
with zipfile.ZipFile(libgdx) as archive:
if "core" in platforms:
run_core(locations, archive)
if "desktop" in platforms:
run_desktop(locations, archive)
if "android" in platforms:
run_android(locations, archive)
if "gwt" in platforms:
run_gwt(locations, archive)
duration = time.time() - start_time
print "finished updates in %s" % human_time(duration)
libgdx.close()
def title(text):
dashes = "-" * 10
print dashes + " %s " % text + dashes
if __name__ == "__main__":
main()
</code></pre>
|
[] |
[
{
"body": "<p>Your code looks pretty good. Some notes:</p>\n\n<ul>\n<li><p>According to <a href=\"http://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow\">PEP8</a>, imports should be written in separate lines.</p></li>\n<li><p><code>fatal_error</code>: I'd probably write the signature this way: <code>fatal_error(msg, code=1)</code>.</p></li>\n<li><p><code>INTERACTIVE</code> -> <code>interactive</code>. According to <a href=\"http://www.python.org/dev/peps/pep-0008/#global-variable-names\" rel=\"nofollow\">PEP8</a>, global variables should be written lower-case.</p></li>\n<li><p>That's an opinion: I prefer to write multi-line lists/dictionaries in JSON style. You save indentation space and the reordering of elements is straightforward (all at the meager cost of two lines):</p>\n\n<pre><code>DESKTOP_LIBS = [\n \"gdx-backend-lwjgl.jar\",\n \"gdx-backend-lwjgl-natives.jar\",\n \"gdx-natives.jar\",\n] \n</code></pre></li>\n<li><p>Functions <code>download_libgdx_zip</code> and <code>search_for_lib_locations</code> are written (unnecessarily IMO) in a very imperative fashion. I'd probably refactor it with a functional approach in mind. At least don't reuse the same variable name to hold different values (i.e. <code>total_size</code>), as that takes away the sacred mathematical meaning of <code>=</code>.</p></li>\n<li><p>Those functions <code>run_xyz(locations, archive)</code> look very similar, why not a unique <code>run(platform, locations, archive)</code>.</p></li>\n<li><p>Function <code>found_all_in_set</code> can be written:</p>\n\n<pre><code>def found_all_in_set(lib_set, found_list):\n return all(lib in found_list for lib in lib_set)\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>def found_all_in_set(lib_set, found_list):\n return set(lib_list).issubset(set(found_list))\n</code></pre></li>\n<li><p><code>if ARCHIVE == None:</code> -> <code>if ARCHIVE is None:</code> although I prefer the (almost) equivalent, more declarative <code>if not ARCHIVE:</code>.</p></li>\n<li><p>There are a lot of imperative snippets that could be written functionally, for example this simple list-comprehension replaces a dozen lines from your code:</p>\n\n<pre><code>platforms = [platform for (platform, libs) in zip(platforms, libs_list)\n if found_all_in_set(libs, found_libraries)]\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T09:15:51.647",
"Id": "43190",
"Score": "0",
"body": "From PEP8, the proper way to write `if ARCHIVE == None:` is `if ARCHIVE is None`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T09:24:34.497",
"Id": "43193",
"Score": "0",
"body": "@Josay: Sorry, I forgot a `not`, updated. I would write `if ARCHIVE is None:` only if I needed to specifically check that ARCHIVE is exactly `None` and not other falsy value (`\"\"` for example). It does not seem the case here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T15:00:24.177",
"Id": "43209",
"Score": "0",
"body": "Thanks for the great feedback! I can see Java making my Python very imperative as well. regarding \"According to PEP8, global variables should be written lower-case.\" PEP8 also says constants should be all caps"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T15:27:36.843",
"Id": "43211",
"Score": "0",
"body": "@talloaktrees: A constant and a global variable are not the same. One is constant while the other is, well, variable :-) (either because it's different on each execution or because it's updated in-place). So `YES` is ok, but `INTERACTIVE` is not."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T08:38:23.090",
"Id": "27719",
"ParentId": "27715",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27719",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T04:14:25.943",
"Id": "27715",
"Score": "3",
"Tags": [
"python",
"library",
"libgdx"
],
"Title": "Updating libgdx game framework library files"
}
|
27715
|
<p>You can place the script where you want the content to be checked and loaded in your design.</p>
<ul>
<li><p><code>urlCheck</code> is the name given to the function. You can change it, and if you do, change all <code>urlCheck</code> references within the code.</p></li>
<li><p><code>window.location.href</code> returns the current address as <em>http://...</em>. Use this to identify certain pages on which you want the content to be loaded. Make as many <code>if</code>/<code>else</code> combinations as necessary.</p></li>
<li><p><code>document.write</code> builds the content to be loaded first. Type with later in one unique line or create multiple <code>document.write</code>s for each line of your content.</p></li>
</ul>
<p></p>
<pre><code><script language="JavaScript">
<!--
function urlCheck() {
if(
window.location.href=="address to check"
)
{
/* some code to load */
}else{
document.write('<div>testing my super loaded div code sample</div>')
}
}
urlCheck() /* autoLoadFunction */
//-->
</script>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T07:58:27.920",
"Id": "43183",
"Score": "6",
"body": "I'd probably fix the indentation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T08:11:18.713",
"Id": "43185",
"Score": "0",
"body": "Add `//` at the beginning of the line with `<!--` or remove it from the line `//-->`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T08:31:17.023",
"Id": "43188",
"Score": "4",
"body": "What is your question? What is the first paragraph supposed to mean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T13:55:57.747",
"Id": "43202",
"Score": "1",
"body": "Basic English lessons? Flaming aside, you do realize that we're here to do code review, and we do not accept anything that can't be answered? Because it seems like you want to use us as a blog, but we're not your personal blog. ... So, do you now have code which we can review?"
}
] |
[
{
"body": "<pre><code><script language=\"JavaScript\">\n</code></pre>\n\n<p>The <a href=\"http://www.w3.org/TR/html401/interact/scripts.html\" rel=\"nofollow noreferrer\"><code>script</code> tag</a> does not have a property <code>language</code> anymore, that property is deprecated. You should use the property <code>type</code> instead. Also the correct value for that property would be <code>text/javascript</code>.</p>\n\n<hr>\n\n<pre><code><!--\n</code></pre>\n\n<p>This is a relic from somewhere before all browsers could do JavaScript, please don't do it anymore.</p>\n\n<hr>\n\n<pre><code>function urlCheck() {\n</code></pre>\n\n<p>Nothing to say here. Except you should think about making it a habit to activate <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode\" rel=\"nofollow noreferrer\">strict mode</a> by default.</p>\n\n<hr>\n\n<pre><code>if(\nwindow.location.href==\"address to check\"\n)\n{\n/* some code to load */\n}else{\ndocument.write('<div>testing my super loaded div code sample</div>')\n}\n}\n</code></pre>\n\n<ul>\n<li>Your indentation and use of whitespace is completely broken, fix it.</li>\n<li>I've never seen a single if which was split over three lines, fix it.</li>\n<li>You should not use <code>==</code> unless you know what it is doing. <code>==</code> performs casting as necessary to compare two values, while <code>===</code> compares their type <em>and</em> value.</li>\n<li>I'm not a fan of creating HTML-elements in a string (<code>document.createElement()</code>), but for sure the opinions differ on this one vividly.</li>\n</ul>\n\n<hr>\n\n<pre><code>urlCheck() /* autoLoadFunction */\n</code></pre>\n\n<p>I suggest you either write your code <em>directly</em> and don't wrap it in a function (because that does nothing if you're going to directly run it after declaring) like this:</p>\n\n<pre><code><script type=\"text/javascript\">\n if(window.location.href === \"address to check\") {\n // some code to load\n } else {\n document.write('<div>testing my super loaded div code sample</div>')\n }\n</script>\n</code></pre>\n\n<p>Or run your code when the document is ready, by putting it at the end of the page (or use a framework which supports something like <code>$(document).ready()</code>):</p>\n\n<pre><code><script type=\"text/javascript\">\n urlCheck();\n</script>\n</code></pre>\n\n<hr>\n\n<pre><code>//-->\n</code></pre>\n\n<p>As I already said, that's a relic, stop doing it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T14:05:56.440",
"Id": "27728",
"ParentId": "27717",
"Score": "5"
}
},
{
"body": "<p>I use:</p>\n\n<pre><code>if(window.location.pathname === '/about'){\n //this is JavaScript for the about page\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-31T22:05:39.280",
"Id": "159491",
"ParentId": "27717",
"Score": "1"
}
},
{
"body": "<p>All above answers works, but we can also use Regular expressions</p>\n<pre><code>if (/StringtoCheck/.test(window.location.href))\n{\n //yes it contains\n}\n</code></pre>\n<p>Regex might help when conditions are a little bit tricky. Source: <a href=\"https://qawithexperts.com/questions/159/how-to-check\" rel=\"nofollow noreferrer\">How to check if url contains a sub-string using jQuery or javascript?</a></p>\n<p>OR you can simply use</p>\n<pre><code>if(window.location.href.indexOf("YourStringToCheck") != -1){\n //string found code here\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-17T15:12:29.470",
"Id": "260853",
"ParentId": "27717",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T07:44:47.787",
"Id": "27717",
"Score": "0",
"Tags": [
"javascript",
"url"
],
"Title": "Using if/else by checking page URL"
}
|
27717
|
<p>Is there any way I can refactor this expression tree?</p>
<pre><code> public static IOrderedQueryable<T_PO> SortedPO(this IQueryable<T_PO> query, ExtjsGridPagingParameter.SortingParameter sortingParameter)
{
IOrderedQueryable<T_PO> result = null;
if (String.IsNullOrEmpty(sortingParameter.property) == false)
{
Expression<Func<T_PO, string>> orderField = null;
Expression<Func<T_PO, DateTime?>> orderFieldDate = null;
Expression<Func<T_PO, decimal>> orderFieldDecimal = null;
switch (sortingParameter.property)
{
case "po_code":
orderField = (item => item.po_code);
break;
case "proj_name":
orderField = (item => item.T_PROJECT.proj_name);
break;
case "po_supplier_contact":
orderField = (item => item.po_supplier_contact);
break;
case "po_grandtotal":
orderFieldDecimal = (item => item.po_grandtotal);
break;
case "po_docdate":
orderFieldDate = (item => item.po_docdate);
break;
default:
break;
}
if (orderField != null)
{
if (sortingParameter.direction == "ASC")
{
result = query.OrderBy(orderField);
}
else
{
result = query.OrderByDescending(orderField);
}
}
else if (orderFieldDate != null)
{
if (sortingParameter.direction == "ASC")
{
result = query.OrderBy(orderFieldDate);
}
else
{
result = query.OrderByDescending(orderFieldDate);
}
}
else if (orderFieldDecimal != null)
{
if (sortingParameter.direction == "ASC")
{
result = query.OrderBy(orderFieldDecimal);
}
else
{
result = query.OrderByDescending(orderFieldDecimal);
}
}
}
return result;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-05T13:32:55.800",
"Id": "195370",
"Score": "1",
"body": "As we all want to make our code more efficient or improve it in one way or another, try to write a title that summarizes what your code does, not what you want to get out of a review. For examples of good titles, check out [Best of Code Review 2014 - Best Question Title Category](http://meta.codereview.stackexchange.com/q/3883/23788) You may also want to read [How to get the best value out of Code Review - Asking Questions](http://meta.codereview.stackexchange.com/a/2438/41243)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-16T12:23:31.933",
"Id": "217449",
"Score": "0",
"body": "Okay. It's got something to do with expression trees. Got it, *but what is this code supposed to do?* You've not given us enough context to properly review this code. What is its purpose? What are the expected inputs & outputs? Do you have any particular concerns about the code? If so, what are they?"
}
] |
[
{
"body": "<p>Note that your code will return <code>null</code> in case if the sort order is not defined. I've preserved this logic, but you may want to change it to return original query (and thus change return type to <code>IQueryable<T_PO></code>).</p>\n\n<p>You are doing 2 separate actions in this method, so if you split it into 2 parts you can get more compact and readable code:</p>\n\n<pre><code>public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, bool isAscending)\n{\n return isAscending\n ? source.OrderBy(keySelector)\n : source.OrderByDescending(keySelector);\n}\n\npublic static IOrderedQueryable<T_PO> SortedPO(this IQueryable<T_PO> query, ExtjsGridPagingParameter.SortingParameter sortingParameter)\n{\n bool isAscending = sortingParameter.direction == \"ASC\";\n\n switch (sortingParameter.property)\n {\n case \"po_code\":\n return query.OrderBy(item => item.po_code, isAscending);\n case \"proj_name\":\n return query.OrderBy(item => item.T_PROJECT.proj_name, isAscending);\n case \"po_supplier_contact\":\n return query.OrderBy(item => item.po_supplier_contact, isAscending);\n case \"po_grandtotal\":\n return query.OrderBy(item => item.po_grandtotal, isAscending);\n case \"po_docdate\":\n return query.OrderBy(item => item.po_docdate, isAscending);\n default:\n return null;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T14:39:33.723",
"Id": "43206",
"Score": "0",
"body": "Salute you (-/\\-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T18:46:25.213",
"Id": "43223",
"Score": "1",
"body": "I was thinking about using manually constructed `Expression`s for this, but: 1. It would be messier than this code 2. the special case for `proj_name` would be hard to do."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T07:48:01.623",
"Id": "43257",
"Score": "0",
"body": "@svick it was my first thought as well, but I went this way due to reasons exactly as you described"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T13:42:06.730",
"Id": "27726",
"ParentId": "27723",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "27726",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T11:09:15.827",
"Id": "27723",
"Score": "-1",
"Tags": [
"c#",
"linq",
"expression-trees"
],
"Title": "Refactor Linq Expression"
}
|
27723
|
<p>Let's say I have a List contains numbers: </p>
<p>1,2,3,4,5,6,7,8,9</p>
<p>and I would like to split this to two lists:</p>
<ul>
<li>odd numbers</li>
<li>even numbers</li>
</ul>
<p>So I can do this two ways: </p>
<p><strong>Solution 1:</strong></p>
<p>Create two methods:</p>
<pre><code>List<Integer> filterOdd(List<Integer> numbers){
List<Integer> result = new ArrayList<Integer>();
for(Integer n : numbers){
if(n % 2 != 0){
result.add(n);
}
}
return result;
}
List<Integer> filterEven(List<Integer> numbers){
List<Integer> result = new ArrayList<Integer>();
for(Integer n : numbers){
if(n % 2 == 0){
result.add(n);
}
}
return result;
}
</code></pre>
<p>and in the code I will call: </p>
<pre><code>List<Integer> numbers = Arrays.asList(new Integer[] { 1,2,3,4,5,6,7,8,9 });
List<Integer> oddNumbers = filterOdd(numbers);
List<Integer> evenNumbers = filterEven(numbers);
</code></pre>
<p>and do something with these lists.</p>
<p>Disadvantage: </p>
<p>I do two loops over one collection.</p>
<p><strong>Solution 2:</strong> </p>
<p>Create one method:</p>
<pre><code>public void filter(List<Integer> numbers, List<Integer> oddNumbers, List<Integer> evenNumbers){
for(Integer n : numbers){
if(n % 2 != 0){
oddNumbers.add(n);
}else{
evenNumbers.add(n);
}
}
}
</code></pre>
<p>and in the code I will call: </p>
<pre><code>List<Integer> numbers = Arrays.asList(new Integer[] { 1,2,3,4,5,6,7,8,9 });
List<Integer> oddNumbers = new ArrayList<Integer>();
List<Integer> evenNumbers = new ArrayList<Integer>();
filter(numbers, oddNumbers, evenNumbers);
</code></pre>
<p>Disadvantage:</p>
<p>I hear that assigning results for parameters is bad practice. </p>
<p>Which solution is better?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T12:51:35.580",
"Id": "43199",
"Score": "2",
"body": "\"Disadvantage: I hear that assign results for parameters is a bad practice.\" <-- where did you read that? If it is the most practical for you, just use it..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T15:43:30.430",
"Id": "43212",
"Score": "0",
"body": "I think the first one is better. Not only because it is most reusable, but because the second one can be created also by making calls to the 2 methods of the first solution"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T13:02:28.567",
"Id": "43266",
"Score": "1",
"body": "Assigning to parameters is definitely an abomination. But it is not what the OP does here. So that principle, however true, just do not apply here. Calling a method on a parameter is not an assignment."
}
] |
[
{
"body": "<p>Here is a solution which replicates Guava's <code>Predicate</code> interface. Since this interface is really easy, here is how it is done:</p>\n\n<pre><code>public interface Predicate<T>\n{\n // returns true if input obeys the predicate\n boolean apply(T input);\n}\n</code></pre>\n\n<p>Given this interface, implement it for your types; and then do a method like this:</p>\n\n<pre><code>public static <T> List<List<T>> filteredLists(final List<T> list,\n final List<Predicate<T>> predicates)\n{\n final int size = predicates.size();\n final List<List<T>> ret = new ArrayList<List<T>>(size);\n\n // Fill ret with initial lists\n for (int i = 0; i < size; i++)\n ret.add(new ArrayList<T>());\n\n // Now walk the predicates and add to the necessary lists\n\n for (final T element: list)\n for (int i = 0; i < size; i++)\n if (predicates.get(i).apply(element))\n ret.get(i).add(element);\n\n // Done! Return...\n return ret;\n}\n</code></pre>\n\n<p>Now, if you had a utility class, say <code>MyPredicates</code>, with two methods <code>even()</code> and <code>odd()</code>, you could write:</p>\n\n<pre><code>final List<List<Integer>> filtered = filteredList(inputList,\n Arrays.asList(MyPredicates.even(), MyPredicates.odd()));\n</code></pre>\n\n<p>The \"drawback\" here is that it is up to the caller to remind what predicates where in what order in the calling lists, of course.</p>\n\n<p>As to your <code>MyPredicates</code> hypothetical class:</p>\n\n<pre><code>public static final class MyPredicates\n{\n // No instansiation\n private MyPredicates()\n {\n }\n\n public static Predicate<Integer> even()\n {\n return new Predicate<Integer>()\n {\n @Override\n public boolean apply(final Integer input)\n {\n return input.intValue() % 2 == 0;\n }\n }\n }\n\n public static Predicate<Integer> odd()\n {\n return new Predicate<Integer>()\n {\n @Override\n public boolean apply(final Integer input)\n {\n return input.intValue() % 2 == 1;\n }\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T13:02:11.077",
"Id": "27725",
"ParentId": "27724",
"Score": "8"
}
},
{
"body": "<p>Go for two methods :</p>\n\n<ul>\n<li>the methods will lead to code that is more readable</li>\n<li>the signatures make more sense, and you don't need to use parameters as return values</li>\n<li>while this is probably slightly slower, we should remember that <a href=\"http://en.wikiquote.org/wiki/Donald_Knuth\" rel=\"noreferrer\">\"Premature optimization is the root of all evil\" (Knuth)</a>; unless you can show that having two loops is a performance bottle neck in your code : don't optimize.</li>\n<li>this will be easier to refactor to using the Predicate approach that @fge suggests. Even though at this point that would, in my opinion, be overkill. Nevertheless, a valid option once lambdas are available in 8.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T10:18:04.040",
"Id": "43261",
"Score": "1",
"body": "In fact, Java 8 _will_ have `Predicate`... They have salvaged quite a few interfaces from Guava for that matter. Hurray!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T05:25:10.913",
"Id": "27759",
"ParentId": "27724",
"Score": "7"
}
},
{
"body": "<p>As already mentioned in the other answers, in Java 8 you can use lambdas and the stream API to remove a lot of boilerplate. </p>\n\n<p>Both your solutions can be converted to use streams.</p>\n\n<p>Solution 1 - two methods:</p>\n\n<pre><code>public List<Integer> oddNumbers(List<Integer> numbers) {\n return numbers.stream().filter(n -> (n % 2) != 0).collect(Collectors.toList());\n}\n\npublic List<Integer> evenNumbers(List<Integer> numbers) {\n return numbers.stream().filter(n -> (n % 2) == 0).collect(Collectors.toList());\n}\n</code></pre>\n\n<p>Solution 2 - as single method:</p>\n\n<pre><code>public void filter(List<Integer> numbers, List<Integer> oddNumbers, List<Integer> evenNumbers) {\n Map<Boolean, List<Integer>> partitions = numbers.stream().collect(Collectors.partitioningBy(n -> (n % 2) == 0));\n evenNumbers.addAll(partitions.get(true));\n oddNumbers.addAll(partitions.get(false));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-17T04:57:31.230",
"Id": "378772",
"Score": "2",
"body": "For solution 1, you can even pass the predicate as a parameter, and then just one method will be enough."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2017-04-24T12:05:01.480",
"Id": "161652",
"ParentId": "27724",
"Score": "8"
}
},
{
"body": "<p>If you only need to split collection into 2 pieces by a certain criterion, then there's a built-in collector to achieve this:</p>\n\n<pre><code> final List<Integer> numbers = asList(1, 2, 3, 4, 5);\n final Map<Boolean, List<Integer>> lists = numbers.stream().collect(Collectors.partitioningBy(n -> n % 2 == 0));\n System.out.println(lists.get(true));\n System.out.println(lists.get(false));\n</code></pre>\n\n<p>This will print:</p>\n\n<pre><code> [2, 4]\n [1, 3, 5]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-01T14:47:12.173",
"Id": "463554",
"Score": "0",
"body": "Indeed the solution I would go with. Also, in case of more than two options (so not a Boolean), there's also various `groupingBy` functions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-31T12:11:49.097",
"Id": "236468",
"ParentId": "27724",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-06-24T12:49:49.607",
"Id": "27724",
"Score": "14",
"Tags": [
"java",
"comparative-review"
],
"Title": "Split Collection to two list depend on criteria"
}
|
27724
|
<p>I'm trying to determine whether an element which has been clicked has a specific tagname. The trick is, that sometimes when you click an element you want any parent to be that specific tag.</p>
<p>My approach:</p>
<pre><code>var ignore = 'a input textarea body'.split(' ');
var isClickable = function(elem) {
var cancel = false;
for (i in ignore) {
if (elem.nodeName.toLowerCase() !== ignore[i]) {
if (elem.parentNode.nodeName.toLowerCase() !== 'body')
isClickable(elem.parentNode);
}
else {
cancel = true;
return cancel;
}
}
return cancel;
};
document.onclick = function(evt) {
isClickable(evt.target);
}
</code></pre>
<p>Is that code right or did I forget something?</p>
<p><strong>SOLUTION</strong>: I came up to that tiny script based on Guffas solution (thanks!)
I've optimized the code to a shorter and faster version:</p>
<pre><code>var isClickable = function(elem) {
for (i in ignore)
if (elem.nodeName.toLowerCase() === ignore[i])
return true;
return (elem.parentNode.nodeName.toLowerCase() !== 'body') && isClickable(elem.parentNode);
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T13:29:04.727",
"Id": "45917",
"Score": "0",
"body": "You shouldn't use `for ... in` on arrays. It loops over all properties, including `length`."
}
] |
[
{
"body": "<p>I see two big problems with the code:</p>\n\n<ul>\n<li><p>You are doing the recursive call inside the loop, so you will do each level four times. That will quickly escalade to a lot of calls. You should do the call after the loop, where you have determined that the node is not one in the array.</p></li>\n<li><p>You are ignoring the result of the recursive call.</p></li>\n</ul>\n\n<p>So:</p>\n\n<pre><code>function isClickable(elem) {\n for (i in ignore) {\n if (elem.nodeName.toLowerCase() === ignore[i]) {\n return true;\n }\n }\n if (elem.parentNode.nodeName.toLowerCase() !== 'body') {\n return isClickable(elem.parentNode);\n }\n return false;\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T14:54:09.973",
"Id": "43208",
"Score": "0",
"body": "for your first advice: how can i optimize that then?\n\nand for the second one: can i avoid this by doing `return isClickable(elem.parentNode)` ??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T15:09:20.043",
"Id": "43210",
"Score": "0",
"body": "@DavidFariña: That's not really optimising, but rather keeping it from doing the same thing an awful lot of times for no reason... Simply put the call after the loop. Yes, using return works for taking care of the result from the recursion. I added some code above."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T15:47:07.157",
"Id": "43213",
"Score": "0",
"body": "Thank you very much, weve optimized your code that its very short!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T14:36:08.550",
"Id": "27730",
"ParentId": "27729",
"Score": "2"
}
},
{
"body": "<p>As mentioned for (var in obj) shouldn't be used for arrays. Instead, and since you've got the tags in a string, I'd use following method:</p>\n\n<pre><code>var tags = [\"a\", \"input\", \"textarea\", \"body\"],\n isClickable = function (elem) {\n return ((tags.join(\" \") + \" \").indexOf(elem.nodeName.toLowerCase() + \" \") !== -1) ||\n ((elem.parentNode.nodeName.toLowerCase() !== 'body') && isClickable(elem.parentNode));\n };\n</code></pre>\n\n<p>If support for IE8 and earlier isn't required (or with use of polyfills) following would also work:</p>\n\n<pre><code>// Alternatively use \"a input textarea body\".split(\" \")\nvar tags = [\"a\", \"input\", \"textarea\", \"body\"],\n isClickable = function (elem) {\n return (tags.indexOf(elem.nodeName.toLowerCase()) !== -1) ||\n ((elem.parentNode.nodeName.toLowerCase() !== 'body') && isClickable(elem.parentNode));\n };\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T16:49:37.647",
"Id": "59094",
"Score": "0",
"body": "This would incorrectly return true for `b` and `i` tags."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T11:21:30.633",
"Id": "59238",
"Score": "0",
"body": "True. Hacked the solution a bit to work with partial tag-names, e.g. i and b. It's not elegant anymore though."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T09:02:44.873",
"Id": "36114",
"ParentId": "27729",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T14:17:13.337",
"Id": "27729",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Check if clicked element has specific tagname"
}
|
27729
|
<p>I have some custom tables in a Wordpress database that I need to export to CSV. I created a dashboard widget to help with this based on some assistance given to me on on one of my SO questions. It basically consists of a single button that posts back and does some output buffering to render the CSV.</p>
<p>I've had it working correctly for a few weeks now, but when I went to push it live on our launch date, I ran into some odd behavior. The gist is that when I export locally on my dev box (Windows 7/Xampp) or on my personal hosted site (Linux) everything exports fine, but when I export on the client's server (Linux) the data is exported, but the CSV also contains the markup for the rest of the wp-admin dashboard page that follows after the widget is rendered. For example:</p>
<pre><code>joe, blow
john, smith
<div><strong>Last entry: </strong>Hank Jones</div>
<div><strong>Total submissions: </strong> 7</div>
.. remaining markup removed for brevity
</code></pre>
<p>You can see that the CSV contains the <code><div><strong>Last entry:</code> markup (and a whole lot more). I have no idea why this would be different based on different servers, but I wanted to post my plugin code in hopes that someone can see what's going on (and tips for improvement if applicable).</p>
<pre><code><?php
/*
Plugin Name: My Plugin
Description: Exporting Stuff
Author: tjans
Version: 1.0
Author URI: http://example.com
*/
add_action('init', 'myplugin_export_buffer_start');
add_action('in_admin_footer', 'myplugin_export_buffer_end');
function myplugin_export_ob_callback($buffer) {
return $buffer;
}
function myplugin_export_buffer_start()
{
ob_start("myplugin_export_ob_callback");
}
function myplugin_export_buffer_end()
{
ob_end_flush();
}
function myplugin_display_mydata_export_widget_process()
{
$errors = array();
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && isset ( $_POST['myplugin_export_button'] ))
{
ob_clean(); // erase the output buffer...blow away all the code up to this point
global $wpdb;
$tablePrefix = $wpdb->prefix;
$qry = "QUERY TO PULL EXPORT DATA";
$result = $wpdb->get_results($qry, ARRAY_A);
if ($wpdb->num_rows)
{
$date = new DateTime();
$ts = $date->format("Y-m-d-G-i-s");
$filename = "mydata-export-$ts.csv";
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);
$fp = fopen('php://output', 'w');
// show a header
$headRow = $result[0];
fputcsv($fp, array_keys($headRow));
foreach ($result as $data)
{
foreach($data as $field=>$value)
{
$data[$field] = stripslashes($value);
}
fputcsv($fp, $data);
}
fclose($fp);
$contLength = ob_get_length();
header( 'Content-Length: '.$contLength);
}
}
return myplugin_display_mydata_export_form_widget();
}
function myplugin_display_mydata_export_form_widget()
{
global $wpdb;
$tableName = $wpdb->prefix . "myplugin_mydata";
$submissionCount = $wpdb->get_var("select count(Id) from $tableName");
$lastUser = $wpdb->get_row("QUERY TO RETRIEVE LAST RECORD", ARRAY_A);
?>
<?php if($lastUser) { ?><div><strong>Last entry: </strong><?php echo $lastUser['FirstName'] ?> <?php echo $lastUser['LastName'] ?> (<?php echo date('F jS, Y - g:i a', $lastUser['DateStamp']) ?>)</div><?php } ?>
<div><strong>Total submissions: </strong> <?php echo $submissionCount ?></div>
<form id="myplugin_mydata_export_widget" method="post" action="">
<input type="submit" name="myplugin_export_button" value="Export All" />
</form>
<?php
}
function myplugin_add_mydata_export_dashboard_widgets()
{
// widget_id, widget_name, callback, control_callback
wp_add_dashboard_widget(
'myplugin-mydata-export-form-widget',
'Form Submissions',
'myplugin_display_mydata_export_widget_process'
);
}
add_action('wp_dashboard_setup', 'myplugin_add_mydata_export_dashboard_widgets' );
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T18:46:02.370",
"Id": "43222",
"Score": "0",
"body": "I suspect is has something to do with the content-length header being ignored..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T18:50:47.033",
"Id": "43224",
"Score": "0",
"body": "I think I fixed it by adding \"exit();\" to the end of the myplugin_display_mydata_export_widget_process function"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T19:01:52.597",
"Id": "43226",
"Score": "0",
"body": "Seems you fixed it already, i'v also added the exit in mu SO answer, that was a mistake. All the best."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T12:28:47.220",
"Id": "43264",
"Score": "0",
"body": "Yes I did, thank you. Though I'm really curious to know why the \"exit\" wasn't needed locally or on my personal live web server but not on my client's...some kind of buffering setting or something on their server that wasn't playing nice?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T18:35:53.430",
"Id": "43277",
"Score": "0",
"body": "Same question has arose on my mind too, because even in my local environment it's working without exit, I'll let you know if can find it out."
}
] |
[
{
"body": "<p>Normally, Output Buffer functions are not needed in a WordPress context, here neither. We'll just hook on <code>admin_init</code> to intercept our <code>$_POST</code> action, output the export file and <code>exit</code>. The browser doesn't even reloads the page.</p>\n\n<p>The form needs a security field, with <a href=\"http://codex.wordpress.org/Function_Reference/wp_nonce_field\" rel=\"nofollow\"><code>wp_nonce_field()</code></a>, and a hidden one with our control action <code><input type=\"hidden\" name=\"my_action\" value=\"my_export\" /></code>.</p>\n\n<p>The <a href=\"https://github.com/pippinsplugins/Settings-Import-and-Export-Example-Plugin/blob/master/settings-import-export-example.php#L112\" rel=\"nofollow\">export code</a> is based on a Pippin Plugins <a href=\"http://pippinsplugins.com/building-settings-import-export-feature/\" rel=\"nofollow\">tutorial</a>. He uses two functions I didn't know, <a href=\"http://www.php.net/manual/en/function.ignore-user-abort.php\" rel=\"nofollow\"><code>ignore_user_abort()</code></a> (PHP) and <a href=\"https://core.trac.wordpress.org/browser/tags/3.9/src/wp-includes/functions.php#L991\" rel=\"nofollow\"><code>nocache_headers()</code></a> (WP).</p>\n\n<p>You're using <code>myplugin</code> as prefix, but it's better to personalize that, like <code>tjs_</code> for example. But here I'll use a suffix, _CODEREVIEW-SE_QUESTION-ID (<code>_crse_27734</code>). Anyway, it's better to <a href=\"https://gist.github.com/3804204\" rel=\"nofollow\">go OOP</a> and drop this <em>pre-suf-fixing</em>.</p>\n\n<p>I prefer to declare all actions first and then write the functions. I've stripped your data and replaced with simple/dummy info for replication purposes.</p>\n\n<pre><code><?php\n/**\n * Plugin Name: (CR) Export DB as CSV\n * Description: Exporting a database Query as CSV\n * Plugin URI: http://codereview.stackexchange.com/a/52051/14985\n * Author: brasofilo\n * Version: 1.0\n */\n\nadd_action( 'wp_dashboard_setup', 'add_widgets_crse_27734' );\nadd_action( 'admin_init', 'csv_export_crse_27734' );\n\n\n/**\n * Create Dashboard Widget\n *\n * @return void\n **/\nfunction add_widgets_crse_27734()\n{\n wp_add_dashboard_widget(\n 'export-form-widget', \n 'Form Submissions', \n 'display_widget_crse_27734'\n ); \n}\n\n/**\n * Print Dashboard Widget\n *\n * @return void\n **/\nfunction display_widget_crse_27734()\n{\n # Dummy data\n $submissionCount = 10;\n $lastUser = array('FirstName' => 'John', 'LastName' => 'Smith', 'DateStamp' => '12569537329' );\n ?>\n <?php if($lastUser) { \n ?><div><strong>Last entry: </strong>\n <?php echo $lastUser['FirstName'] ?> \n <?php echo $lastUser['LastName'] ?> \n (<?php echo date('F jS, Y - g:i a', $lastUser['DateStamp']) ?>)</div>\n <?php } ?>\n <div><strong>Total submissions: </strong> <?php echo $submissionCount ?></div>\n <form method=\"post\">\n <?php wp_nonce_field( 'export_nonce_crse_27734', 'export_nonce_crse_27734' ); ?>\n <input type=\"hidden\" name=\"action_crse_27734\" value=\"export_csv\" />\n <input type=\"submit\" name=\"myplugin_export_button_crse_27734\" value=\"Export All\" />\n </form>\n <?php\n}\n\n\n/**\n * Export CSV File\n *\n * @return void\n **/\nfunction csv_export_crse_27734() \n{\n if( !isset( $_POST['action_crse_27734'] ) || 'export_csv' != $_POST['action_crse_27734'] )\n return;\n\n if( ! wp_verify_nonce( $_POST['export_nonce_crse_27734'], 'export_nonce_crse_27734' ) )\n return;\n\n if( ! current_user_can( 'manage_options' ) )\n return;\n\n $output = db_data_crse_27734();\n if( empty( $output ) )\n return;\n\n ignore_user_abort( true );\n nocache_headers();\n header( 'Content-Type: text/csv; charset=utf-8' );\n header( 'Content-Disposition: attachment; filename=code-review-export-' . date( 'Y-m-d-G-i-s' ) . '.csv' );\n header( \"Expires: 0\" );\n echo $output;\n exit;\n}\n\n/**\n * Query DB and build CSV string\n *\n * @return string\n **/\nfunction db_data_crse_27734()\n{\n global $wpdb;\n\n # Dummy query\n $args = array( 'ID', 'post_title', 'post_date', 'post_type' );\n $sql_select = implode( ', ', $args );\n $result = $wpdb->get_results(\"\n SELECT $sql_select\n FROM $wpdb->posts\n WHERE post_status = 'publish' \n \");\n\n $output = '';\n if( $result )\n {\n foreach ( $result as $data ) \n {\n $out_data = array();\n foreach( $data as $field => $value ) \n {\n $out_data[$field] = stripslashes( $value );\n }\n $output .= implode( '|', $out_data ) . \"\\r\\n\";\n }\n }\n return $output;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T21:59:15.477",
"Id": "52051",
"ParentId": "27734",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T16:06:47.947",
"Id": "27734",
"Score": "3",
"Tags": [
"php",
"wordpress"
],
"Title": "Exporting data in a WordPress widget"
}
|
27734
|
<p>I created my first jQuery plugin over this weekend. I would like a code review so that I can improve my code in the future and learn from any mistakes I make. Any tips for Github would also be greatly appreciated since I am also new to GitHub :). </p>
<p>Demo: <a href="https://rawgithub.com/Shivambh28/ezToggle/master/demo.html" rel="nofollow">https://rawgithub.com/Shivambh28/ezToggle/master/demo.html</a></p>
<p>GitHub: <a href="https://github.com/Shivambh28/ezToggle" rel="nofollow">https://github.com/Shivambh28/ezToggle</a></p>
<p>Plugin code:</p>
<pre><code>(function($){
$.fn.ezToggle = function(options) {
var defaults = {
selector: '.selector',
speed : 200
}
defaults.minHeight = $(defaults.selector).outerHeight(true);
var options = $.extend(defaults, options);
return this.each(function() {
var o = options,
yDiv = $(this),
oHei = $(yDiv).height();
$(yDiv).not('.opened').addClass('closed');
$('.closed').height(defaults.minHeight);
$('.opened').height(oHei);
$(defaults.selector).click(function() {
if ($(this).closest(yDiv).hasClass('closed') ) {
$('.opened').removeClass('opened').addClass('closed').animate({height:defaults.minHeight}, defaults.speed);
$(this).closest(yDiv).removeClass('closed').addClass('opened').animate({height:oHei}, defaults.speed);
} else if ( $('.opened').length == 1 ) {
$(this).closest(yDiv).removeClass('opened').addClass('closed').animate({height:defaults.minHeight}, defaults.speed);
}
});
});
};
})(jQuery);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T17:12:59.990",
"Id": "43215",
"Score": "0",
"body": "\"Uncaught ReferenceError: jQuery is not defined \" <- on your Demopage. Reason: \"[blocked] The page at https://rawgithub.com/Shivambh28/ezToggle/master/demo.html ran insecure content from http://code.jquery.com/jquery-1.10.1.min.js.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T18:42:20.073",
"Id": "43221",
"Score": "0",
"body": "Thanks, I fixed the issue. I notice a strange issue related to the border-radius on chrome. It appears as if when I click on a div, the border-radius-top turns to 0. I wonder why this might be occurring.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T19:04:18.703",
"Id": "43227",
"Score": "0",
"body": "Nevermind, fixed border-radius issue as-well."
}
] |
[
{
"body": "<p>Props to you on your first plugin! Well here are a few pointers in no particular order:</p>\n\n<p><strong>- Double Wrapping:</strong> When you cache <code>yDiv=$(this);</code>, you're wrapping the element with the jQuery object. And then you do: <code>$(yDiv).not(...</code> What this does is wrap that object twice. You've already wrapped it so you don't need to do so again. Just do this <code>yDiv.not(...</code> after you cache.</p>\n\n<p>So this is how you should do it:</p>\n\n<pre><code>//Don't\nyDiv = $(this);\n$(yDiv).not('.opened').addClass('closed');\n\n//Instead do:\nyDiv = $(this);\nyDiv.not('.opened').addClass('closed');\n</code></pre>\n\n<p><strong>- Variable Names:</strong> If you want anyone else to provide you input on your code, they have to be able to understand it. You should use variable names that will make sense to anyone reading your code. Yes, in this simple example one can deduce the what and why you named the variables the way you did and we can sort of follow along. But when you start working on large scale projects, things can get out of hand real quick. Take for example your <code>yDiv</code> variable. The keyword <code>this</code> can refer to any element that goes through the <code>.each()</code> which might not be a <code>div</code> in the first place. What if it was a <code>ul</code> or any other element. In that case, the name <code>yDiv</code> would no longer represent what is actually stored in there. Anyways, try to use meaningful and descriptive variable names and stay away from names that might not exactly represent what is stored in said variable.</p>\n\n<p><strong>- Cache your selectors:</strong> As a rule of thumb, if you use a selection more than once, you should cache it. What happens when you use <code>$(\"someElem\")</code> is jQuery has to jump into the DOM and look through all elements that would match that selection. So you should really do a search only once, and save your results for future use. This way you can look and play with them whenever you want without having to try and find them again.</p>\n\n<p>Ex:</p>\n\n<pre><code>var closestElem = $(this).closest(yDiv); //Cache it\nif (closestElem.hasClass('closed')){ //Now use it\n //...\n}\n</code></pre>\n\n<p><strong>- Save a function calls:</strong> If you read the jQuery source code you'll see that shortcut methods like <code>.click()</code>, <code>.scroll()</code>, and etc. all reference the <code>.on()</code> method. All they do is basically call the <code>.on()</code> method with some parameters. Well why not just go straight to the meat and potatoes?</p>\n\n<p>Check this out:</p>\n\n<pre><code>$(\"#foo\").click(function() {\n //Do your awesomeness\n});\n\n//That does the same thing as this:\n$(\"foo\").on(\"click\", function() {\n //Do your awesomeness even awesomener.\n});\n\n//You can also use that to set up your own custom events\n$(\"foo\").on(\"myEvent\", function() {\n //bar\n});\n</code></pre>\n\n<p>That just makes the syntax so easy to remember as well as provide you with enormous control over your events. If you're going to use jQuery on a regular basis, I recommend that you take some time and read through the source code of the methods you're using. To find them quickly just use <code>CTRL+F</code> and type <code>methodName:</code>. That should jump you straight to what you want to know. This way you can understand what and how they are doing things, and even find better ways to do them on your own. Also if you see something you think should be done better or differently, you understand how it works and you can contribute to jQuery.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-04T01:24:40.390",
"Id": "43857",
"Score": "0",
"body": "Thanks so much for the in-depth review of the code and tips, I really took everything you told me into consideration and redid the entire plugin from scratch. It is much more flexible now and more clean and easier to read. Thanks again for your help!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-05T15:06:24.297",
"Id": "43980",
"Score": "0",
"body": "Open another question with your updated code and link back to this one so we can see your improvements. Other people might have more to add, and you might still have more to learn."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-06T13:55:37.867",
"Id": "44035",
"Score": "0",
"body": "Sure, I just re-posted the question: http://codereview.stackexchange.com/questions/28195/first-jquery-plugin-request-code-review"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T22:28:46.047",
"Id": "27749",
"ParentId": "27735",
"Score": "3"
}
},
{
"body": "<p>+1 for Jonny Sooter.</p>\n\n<p>I just linted your code plus followed Jonny Sooter's advice. I didn't renamed any variables as such, but made huge changes to formatting and readability. Gurus feel free to edit this code if there is any stupidity.</p>\n\n<pre><code>(function($){\n 'use strict';\n $.fn.ezToggle = function(opts) {\n var \n defaults = {\n selector: '.selector',\n speed : 200\n },\n options\n ;\n\n defaults.minHeight = $( defaults.selector ).outerHeight( true );\n options = $.extend( defaults, opts );\n\n return this.each( function() {\n var \n yDiv = $(this),\n oHei = yDiv.height();\n\n yDiv\n .not( '.opened' )\n .addClass( 'closed' );\n\n $( '.closed' ).height( defaults.minHeight );\n $( '.opened' ).height( oHei );\n\n $( defaults.selector ).on( 'click', function() {\n if ( $(this).closest( yDiv ).hasClass( 'closed' ) ) {\n $('.opened')\n .removeClass('opened')\n .addClass('closed')\n .animate({\n height: defaults.minHeight\n }, \n defaults.speed\n );\n $(this)\n .closest(yDiv)\n .removeClass('closed')\n .addClass('opened')\n .animate({\n height: oHei\n }, \n defaults.speed\n );\n } else if ( $('.opened').length === 1 ) {\n $(this)\n .closest(yDiv)\n .removeClass('opened')\n .addClass('closed')\n .animate({\n height: defaults.minHeight\n }, \n defaults.speed\n );\n }\n });\n });\n };\n}(jQuery));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T08:58:45.723",
"Id": "27795",
"ParentId": "27735",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27749",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T16:10:32.683",
"Id": "27735",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"plugin"
],
"Title": "First jQuery Plugin, Would like a code review"
}
|
27735
|
<p>I have some duplicate code using LINQ & XML. I'm sure there is a way to refactor it, but I'm not sure how to go about doing it. Would someone help, please?</p>
<pre><code>var fileInfo = dataXL.Worksheet("data")
.Where(t => t["F2"].Equals(company))
.Select(t => new
{
Price = t["F5"],
EPS10Q1 = t["F12"], EPS10Q2 = t["F13"], EPS10Q3 = t["F14"], EPS10Q4 = t["F15"],
EPS11Q1 = t["F19"], EPS11Q2 = t["F20"], EPS11Q3 = t["F21"], EPS11Q4 = t["F22"],
EPS12Q1 = t["F26"], EPS12Q2 = t["F27"], EPS12Q3 = t["F28"], EPS12Q4 = t["F29"],
EPS13Q1 = t["F33"], EPS13Q2 = t["F34"], EPS13Q3 = t["F35"], EPS13Q4 = t["F36"],
EPS14Q1 = t["F40"], EPS14Q2 = t["F41"], EPS14Q3 = t["F42"], EPS14Q4 = t["F43"]
});
xdoc.Element("company")
.Add(new XElement("eps",
new XElement("year2010",
new XElement("EPS1", resAnGreyInfo.Select(x => x.EPS10Q1)),
new XElement("EPS2", resAnGreyInfo.Select(x => x.EPS10Q2)),
new XElement("EPS3", resAnGreyInfo.Select(x => x.EPS10Q3)),
new XElement("EPS4", resAnGreyInfo.Select(x => x.EPS10Q4))),
new XElement("year2011",
new XElement("EPS1", resAnGreyInfo.Select(x => x.EPS11Q1)),
new XElement("EPS2", resAnGreyInfo.Select(x => x.EPS11Q2)),
new XElement("EPS3", resAnGreyInfo.Select(x => x.EPS11Q3)),
new XElement("EPS4", resAnGreyInfo.Select(x => x.EPS11Q4))),
new XElement("year2012",
new XElement("EPS1", resAnGreyInfo.Select(x => x.EPS12Q1)),
new XElement("EPS2", resAnGreyInfo.Select(x => x.EPS12Q2)),
new XElement("EPS3", resAnGreyInfo.Select(x => x.EPS12Q3)),
new XElement("EPS4", resAnGreyInfo.Select(x => x.EPS12Q4))));
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T18:37:05.810",
"Id": "43219",
"Score": "0",
"body": "Both of those XML schemas seem to be badly designed. Is there any possibility of changing them?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T18:40:32.140",
"Id": "43220",
"Score": "0",
"body": "Also, can there be more than one element where `t[\"F2\"] == company`? If yes, you're going to get weird results. If not, `fileInfo` should be a single object, not a collection."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T19:00:33.480",
"Id": "43225",
"Score": "0",
"body": "@svick how do you suggest that I do that? Do you have any examples to get a single object rather than a collection? Also, regarding the XML, i need ideas on how to remodel them. This was the line of business requires but I don't want to repeat code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T19:16:24.440",
"Id": "43230",
"Score": "1",
"body": "The simplest solution would be to just call `.Single()` after your `Select()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-05T13:33:51.540",
"Id": "195375",
"Score": "1",
"body": "As we all want to make our code more efficient or improve it in one way or another, try to write a title that summarizes what your code does, not what you want to get out of a review. For examples of good titles, check out [Best of Code Review 2014 - Best Question Title Category](http://meta.codereview.stackexchange.com/q/3883/23788) You may also want to read [How to get the best value out of Code Review - Asking Questions](http://meta.codereview.stackexchange.com/a/2438/41243)."
}
] |
[
{
"body": "<p>This is what you could do:</p>\n\n<ul>\n<li>Try to bring order to the chaos of field numbers. For instance, associate 'F12' to 'Year 2010, Quarter 1'. This is essential to reduce code duplication.</li>\n<li>Fortunately, the field names of each year are sequential (that is, F12 is 2010Q1, F13 is 2010Q2, etc.)</li>\n<li>Once you have that figured out, you can rewrite the <code>fileInfo</code> retrieval code to reduce duplication.</li>\n<li>With fileInfo corrected, you can move to xdoc.</li>\n<li>Assuming <code>resAnGreyInfo</code> is the same as <code>fileInfo</code>, the main obstacle to reduce duplication were the many different fields. With the new fileInfo layout, you should be able to get the fields with <code>fileInfo[year][quarter]</code>, which is much better than <code>fileInfo.EPSYEARQUARTER</code>.</li>\n<li>If changing the layout of <code>fileInfo</code> is not possible for some reason, you could try messing with reflection or dynamic typing to work around this mess.</li>\n<li>Once that's done, the <code>xdoc</code> could be much simpler, since each year element has essentially the same format.</li>\n</ul>\n\n<p>So here's a rough sketch of what the final code would look like (it does not have the equivalent of the <code>Select</code> for resAnGreyInfo`, but even if you add that the result should be similar):</p>\n\n<pre><code>var years = new List<int>(2010, 2011, 2012, 2013, 2014);\nvar yearToFieldNumber = new Dictionary<int, int>();\nyearToFieldNumber[2010] = 12; //2010 starts at F12\nyearToFieldNumber[2011] = 19; //2011 starts at F19\nyearToFieldNumber[2012] = 26;\nyearToFieldNumber[2013] = 33;\nyearToFieldNumber[2014] = 40;\n\nvar fileInfo = dataXL.Worksheet(\"data\")\n .Where(t => t[\"F2\"].Equals(company))\n .Select(t => new\n {\n Price = t[\"F5\"],\n Years = years.Select(year => Enumerable.Range(1, 4)\n .ToDictionary(quarter => quarter, quarter => t[\"F\" + (yearToFieldNumber[year] + quarter - 1)]).ToList()\n });\n\n//Now, fileInfo.Years[year][quarter] gives us the data for that quarter\n\nvar yearElements = Enumerable.Range(2010, 3) //Take 3 years starting from 2010\n .Select(year => new XElement(\"year\" + year,\n Enumerable.Range(1, 4).Select(quarter => new XElement(\"EPS\" + quarter, fileInfo[year][quarter])).ToArray()\n )).ToArray();\n\nxdoc.Element(\"company\").Add(new XElement(\"eps\", yearElements));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T20:03:28.010",
"Id": "27744",
"ParentId": "27736",
"Score": "1"
}
},
{
"body": "<p>Let's start by indenting it:</p>\n\n<pre><code>var fileInfo = dataXL.Worksheet(\"data\")\n .Where(t => t[\"F2\"].Equals(company))\n .Select(t =>\n new\n {\n Price = t[\"F5\"], \n EPS10Q1 = t[\"F12\"], EPS10Q2 = t[\"F13\"], EPS10Q3 = t[\"F14\"], EPS10Q4 = t[\"F15\"],\n EPS11Q1 = t[\"F19\"], EPS11Q2 = t[\"F20\"], EPS11Q3 = t[\"F21\"], EPS11Q4 = t[\"F22\"],\n EPS12Q1 = t[\"F26\"], EPS12Q2 = t[\"F27\"], EPS12Q3 = t[\"F28\"], EPS12Q4 = t[\"F29\"],\n EPS13Q1 = t[\"F33\"], EPS13Q2 = t[\"F34\"], EPS13Q3 = t[\"F35\"], EPS13Q4 = t[\"F36\"],\n EPS14Q1 = t[\"F40\"], EPS14Q2 = t[\"F41\"], EPS14Q3 = t[\"F42\"], EPS14Q4 = t[\"F43\"]\n });\n\nxdoc.Element(\"company\")\n .Add(new XElement(\"eps\",\n new XElement(\"year2010\",\n new XElement(\"EPS1\", resAnGreyInfo.Select(x => x.EPS10Q1)),\n new XElement(\"EPS2\", resAnGreyInfo.Select(x => x.EPS10Q2)),\n new XElement(\"EPS3\", resAnGreyInfo.Select(x => x.EPS10Q3)),\n new XElement(\"EPS4\", resAnGreyInfo.Select(x => x.EPS10Q4))),\n new XElement(\"year2011\",\n new XElement(\"EPS1\", resAnGreyInfo.Select(x => x.EPS11Q1)),\n new XElement(\"EPS2\", resAnGreyInfo.Select(x => x.EPS11Q2)),\n new XElement(\"EPS3\", resAnGreyInfo.Select(x => x.EPS11Q3)),\n new XElement(\"EPS4\", resAnGreyInfo.Select(x => x.EPS11Q4))),\n new XElement(\"year2012\",\n new XElement(\"EPS1\", resAnGreyInfo.Select(x => x.EPS12Q1)),\n new XElement(\"EPS2\", resAnGreyInfo.Select(x => x.EPS12Q2)),\n new XElement(\"EPS3\", resAnGreyInfo.Select(x => x.EPS12Q3)),\n new XElement(\"EPS4\", resAnGreyInfo.Select(x => x.EPS12Q4))));\n</code></pre>\n\n<p>Let's remove unused code and replace the repetitive lines by arrays and a few anonymous types. Note that your original code won't compile, so the modified version doesn't exactly correspond to the original one.</p>\n\n<pre><code>var fileInfo = dataXL.Worksheet(\"data\")\n .Where(t => t[\"F2\"].Equals(company))\n .Select(\n t => new []\n {\n new { Year = 2010, Data = new [] { t[\"F12\"], t[\"F13\"], t[\"F14\"], t[\"F15\"] } },\n new { Year = 2011, Data = new [] { t[\"F19\"], t[\"F20\"], t[\"F21\"], t[\"F22\"] } },\n new { Year = 2012, Data = new [] { t[\"F26\"], t[\"F27\"], t[\"F28\"], t[\"F29\"] } },\n new { Year = 2013, Data = new [] { t[\"F33\"], t[\"F34\"], t[\"F35\"], t[\"F36\"] } },\n new { Year = 2014, Data = new [] { t[\"F40\"], t[\"F41\"], t[\"F42\"], t[\"F43\"] } },\n });\n\nxdoc.Element(\"company\")\n .Add(new XElement(\"eps\",\n fileInfo\n .Take(3)\n .Select(\n year => new XElement(\n \"year\" + year.Year,\n year.Data.Select((d, i) => new XElement(\"EPS\" + (i + 1), d))))));\n</code></pre>\n\n<p>Let's refactor:</p>\n\n<pre><code>var fileInfo = dataXL.Worksheet(\"data\")\n .Where(t => t[\"F2\"].Equals(company))\n .Select(\n t => new []\n {\n new { Year = 2010, Data = new [] { t[\"F12\"], t[\"F13\"], t[\"F14\"], t[\"F15\"] } },\n new { Year = 2011, Data = new [] { t[\"F19\"], t[\"F20\"], t[\"F21\"], t[\"F22\"] } },\n new { Year = 2012, Data = new [] { t[\"F26\"], t[\"F27\"], t[\"F28\"], t[\"F29\"] } },\n new { Year = 2013, Data = new [] { t[\"F33\"], t[\"F34\"], t[\"F35\"], t[\"F36\"] } },\n new { Year = 2014, Data = new [] { t[\"F40\"], t[\"F41\"], t[\"F42\"], t[\"F43\"] } },\n });\n</code></pre>\n\n<p>into:</p>\n\n<pre><code>var fileInfo = from t in dataXL.Worksheet(\"data\")\n where t[\"F2\"].Equals(company)\n select this.LoadYears(t);\n\nprivate Dictionary<int, IEnumerable<dynamic>> LoadYears(dynamic t)\n{\n return new Dictionary<int, IEnumerable<dynamic>>\n {\n { 2010, new [] { t[\"F12\"], t[\"F13\"], t[\"F14\"], t[\"F15\"] } },\n { 2011, new [] { t[\"F19\"], t[\"F20\"], t[\"F21\"], t[\"F22\"] } },\n { 2012, new [] { t[\"F26\"], t[\"F27\"], t[\"F28\"], t[\"F29\"] } },\n { 2013, new [] { t[\"F33\"], t[\"F34\"], t[\"F35\"], t[\"F36\"] } },\n { 2014, new [] { t[\"F40\"], t[\"F41\"], t[\"F42\"], t[\"F43\"] } },\n }\n}\n</code></pre>\n\n<p>This is slightly more readable, isn't it? But what about those repetitive lines? What if, with a simple extension method, we could slice an array?</p>\n\n<pre><code>private IEnumerable<dynamic> LoadYears(dynamic t)\n{\n return Enumerable\n .Range(12, 43)\n .Select(i => t[\"F\" + i])\n .Slice(4)\n .Select(\n (groupValues, groupIndex) =>\n new\n {\n Year = 2010 + groupIndex,\n Data = groupValues\n });\n}\n</code></pre>\n\n<p>The whole code is:</p>\n\n<pre><code>var fileInfo = from t in dataXL.Worksheet(\"data\")\n where t[\"F2\"].Equals(company)\n select this.LoadYears(t);\n\nprivate IEnumerable<dynamic> LoadYears(dynamic t)\n{\n return Enumerable\n .Range(12, 43)\n .Select(i => t[\"F\" + i])\n .Slice(4)\n .Select((groupValues, groupIndex) => new { Year = 2010 + groupIndex, Data = groupValues });\n}\n\nxdoc.Element(\"company\")\n .Add(new XElement(\"eps\",\n fileInfo\n .Take(3)\n .Select(\n year => new XElement(\n \"year\" + year.Year,\n year.Data.Select((d, i) => new XElement(\"EPS\" + (i + 1), d))))));\n</code></pre>\n\n<p>We don't repeat code here, but the solution is slightly unreadable. Maintaining such code is difficult as hell. Variable names are poorly chosen, too short and too cryptic. Debugging would be difficult as well.</p>\n\n<p>Let's refactor it into:</p>\n\n<pre><code>var fileInfo = from dataSet in dataXL.Worksheet(\"data\")\n where dataSet[\"F2\"].Equals(company)\n select this.LoadYears(dataSet);\n\nprivate IEnumerable<dynamic> LoadYears(dynamic dataSet)\n{\n return Enumerable\n .Range(12, 43)\n .Select(dataIndex => t[\"F\" + dataIndex])\n .Slice(4)\n .Select(\n (groupValues, groupIndex) =>\n new\n {\n Year = 2010 + groupIndex,\n Data = groupValues\n });\n}\n\nprivate dynamic SerializeYear(dynamic year)\n{\n var quarters = year.Data.Select((quarter, index) => new XElement(\"EPS\" + (index + 1), quarter));\n return new XElement(\"year\" + year.Year, quarters);\n}\n\ndocument.Element(\n \"company\"\n new XElement(\n \"eps\",\n fileInfo.Take(3).Select(year => this.SerializeYear(year)))));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T20:06:29.773",
"Id": "27745",
"ParentId": "27736",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T17:39:58.420",
"Id": "27736",
"Score": "-1",
"Tags": [
"c#",
"linq"
],
"Title": "Refactor LINQ & XML code"
}
|
27736
|
<p>I have created a personal password storage program that takes the user's username, password, and for what account it is for, and stores it in a text file and can also read from them (assuming you type the right name in). What I'm looking to do, is either trim it down (take out none needed code) or finding more effective ways to go about this.</p>
<pre><code>import java.io.*;
import java.util.*;
public class testing_file
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Access or create?");
String select = input.nextLine();
switch(select)
{
case "Create":
String name, user, password;
FileOutputStream fop = null;
File file;
System.out.println("What account is this for?");
name = input.nextLine();
System.out.println("Enter the Username");
user = input.nextLine();
try
{
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("c:/"+name+".dnx")));
file = new File("c:/"+name+".dnx");
fop = new FileOutputStream(file);
if (!file.exists())
{
file.createNewFile();
}
System.out.println("You may now input your password");
password = input.nextLine();
pw.write("Account: " + name);
pw.println();
pw.write("Username: " + user);
pw.println();
pw.write("Password: " + password);
pw.flush();
pw.close();
System.out.println("Operation Complete");
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (fop != null)
{
fop.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
break;
case "Access":
String string="";
System.out.println("Enter the account you wish to view");
name = input.nextLine();
String file1 = "c:/"+name+".dnx";
//reading
try{
InputStream ips=new FileInputStream("C:/"+name+".dnx");
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);
String line;
while ((line=br.readLine())!=null)
{
System.out.println(line);
string+=line+"\n";
}
br.close();
}
catch (Exception e){
System.out.println(e.toString());
}
break;
default:
System.out.println("Invalid method, terminating program");
break;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T19:37:21.080",
"Id": "43231",
"Score": "0",
"body": "is this java 7 your targeting?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T12:42:11.637",
"Id": "43265",
"Score": "0",
"body": "If all you do is write a text file to console, as in `\"Access\"` case in your program, you needn't write your own program for that. You can use your operating systems standard tools for that; `type` command in Windows or `cat` in Linux etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T19:29:27.047",
"Id": "62849",
"Score": "0",
"body": "Simplest way to do this would be to store a List of Password objects as a Serializable object vs having to parse a text file."
}
] |
[
{
"body": "<p>Couple of Points.</p>\n\n<p><strong>Most Important:</strong> If your looking for secure password storage do not write your own library. Password storage is a very complex at best pratice. So I you care about the contents of the plain text password file being accessed don't do this. </p>\n\n<p>If this is a <strong>learning exercise</strong> or not that critical <strong>go ahead</strong>, just keep that in mind.</p>\n\n<p><strong>Now for the actual review.</strong></p>\n\n<ul>\n<li>First thing that grabs me is if you are using Java 7 then you should\nlook at using try with resources. <a href=\"http://www.mkyong.com/java/try-with-resources-example-in-jdk-7/\" rel=\"nofollow\">Try with resources</a> has two\nadvantages for your code. First it always closes the streams (Under\nnormal jvm operation) secondly it is a little less verbose to write.</li>\n</ul>\n\n<p>Basic syntax would be :</p>\n\n<pre><code> try (PrintWriter pw = new PrintWriter(new BufferedWriter(\n new FileWriter(\"c:/\" + name + \".dnx\")));)\n {\n //Rest of code here.\n catch (IOException e)\n {\n e.printStackTrace();\n }\n</code></pre>\n\n<p>This eliminates the need for a lot of the closing resources. </p>\n\n<ul>\n<li>Second problem you open a File reference that is never used. Remove all occurences of fop and file.</li>\n<li>Consider moving the two \"cases\" to seperate methods. They are seperate things and don't need to share blocks.</li>\n<li>I'm not convinced as your printing the stack trace anyway if there is any need to catch the exceptions. Let the method just throw them (Note this is only because this is a self contained program I'm suggesting this.</li>\n</ul>\n\n<p><strong>EDIT:</strong></p>\n\n<p>This is a first stab at refactoring. I've followed my advise above then further more there are three places where your writing a key and value into a stream followed by a blank line. I've moved that to a seperate method. I've also added in your pattern for user input to a method. Hopefully you find this shorter and not too hard to read. </p>\n\n<p>There are a few other points that came up when I was doing this but their not so important.</p>\n\n<ul>\n<li><strong>Class Name</strong>: Your class doesn't follow java naming conventions.</li>\n<li><strong>All in Main</strong>: If the objective is to practice with java please note that this isn't very object orientated. The standard java idiom would be to create a class (possibly an instance of itself) and set the values you want on this for example no need to pass scanner and pw arround as I have done in my refactor.</li>\n<li><p><strong>Naming</strong> no huge deal but you should consider more meaningful names for variables \"string\" I'm looking at you.</p>\n\n<pre><code>import java.io.*;\nimport java.util.*;\n\npublic class testing_file {\n public static void main(String args[]) throws IOException {\n\n Scanner input = new Scanner(System.in);\n String select = prompt(input, \"Access or create?\");\n\n switch (select) {\n case \"Create\":\n createPasswordEntry(input);\n break;\n\n case \"Access\":\n readPasswordFile(input);\n break;\n\n default:\n System.out.println(\"Invalid method, terminating program\");\n break;\n }\n }\n\n private static String prompt(Scanner input, String question) {\n System.out.println(question);\n return input.nextLine();\n }\n\n private static void readPasswordFile(Scanner input) throws IOException {\n String name = prompt(input, \"Enter the account you wish to view\");\n\n //reading\n try (\n InputStream ips = new FileInputStream(\"C:/\" + name + \".dnx\");\n InputStreamReader ipsr = new InputStreamReader(ips);\n BufferedReader br = new BufferedReader(ipsr);\n ) {\n String line, string = \"\";\n while ((line = br.readLine()) != null) {\n System.out.println(line);\n string += line + \"\\n\";\n }\n }\n }\n\n private static void createPasswordEntry(Scanner input) throws IOException {\n String name, user, password;\n name = prompt(input, \"What account is this for?\");\n user = prompt(input, \"Enter the Username\");\n\n try (\n PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(\"c:/\" + name + \".dnx\")));\n ) {\n password = prompt(input, \"You may now input your password\");\n writeKeyValue(pw, \"Account\", name);\n writeKeyValue(pw, \"Username: \", user);\n writeKeyValue(pw, \"Password\", password);\n pw.flush();\n pw.close();\n System.out.println(\"Operation Complete\");\n }\n }\n\n private static void writeKeyValue(PrintWriter pw, String key, String name) {\n pw.write(key + \": \" + name);\n pw.println();\n }\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T18:57:52.390",
"Id": "43278",
"Score": "0",
"body": "To answer your question I am using Java 7, as for the program itself, it's more for practice purposes, more/less this program primarily was a test to write and read data from a file. I just wanted to store my info on my desktop at home to make it easier on me, but i digress. I tried removing the instances of fop and it gave me errors.. maybe i removed the wrong ones? would you be able to point out the ones you're referring to?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T22:22:16.277",
"Id": "43292",
"Score": "0",
"body": "See latest edit @DaNinjaSmurf"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T21:19:56.053",
"Id": "27747",
"ParentId": "27738",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27747",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T18:51:29.203",
"Id": "27738",
"Score": "5",
"Tags": [
"java",
"authentication"
],
"Title": "Password storage slim/trim it down?"
}
|
27738
|
<p>I've been teaching myself Python - my first programming language - for about two years now.</p>
<p>I recently discovered the <code>concurrent.futures</code> module and wanted to do something with it. What do you think about this script?</p>
<pre><code>import re
import shutil
import string
from collections import Counter
from concurrent.futures import ProcessPoolExecutor
from itertools import chain, islice, zip_longest
from urllib.request import urlopen
# Regex to use for splitting text into words, dropping everything but
# alphabetic characters.
REGEX = re.compile(r"[{}{}{}]+".format(
string.whitespace, string.digits, string.punctuation))
# http://docs.python.org/3/library/itertools.html#itertools-recipes
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
def split_and_clean(line):
"""Returns an iterator of the words in line.
Example:
>>> list(split_and_clean("3, Four, five'"))
['four', 'five']
Args:
line: A string.
Returns:
A filter of the alphabetic words in the line.
Raises:
TypeError: Your input was of type <>. Must be a string.
"""
try:
return filter(None, re.split(REGEX, line.lower()))
except AttributeError:
input_type_str = str(type(line))[8:-2]
error_message = "Your input was of type {}. Must be a string.".format(
input_type_str)
raise TypeError(error_message)
def wc_some_lines(lines):
"""Return a Counter containing the word count of several lines.
Excludes any digital numbers or punctuation.
Example:
>>> wc_some_lines(["Line 1.", "Another line."])
Counter({'line': 2, 'another': 1})
Args:
lines: An iterable of strings.
Returns:
A collections.Counter mapping words to their word counts.
Raises:
TypeError
"""
return Counter(chain(*map(split_and_clean, lines)))
def main(num_processes=5):
"""Fetch Shakespeare's complete works and perform a concurrent word count.
"""
url = "http://www.gutenberg.org/files/100/100.txt"
filename = "shakespeare_complete_works.txt"
try:
text = open(filename)
except IOError:
with open(filename, "wb") as f:
r = urlopen(url)
shutil.copyfileobj(r, f) # write r to f
text = open(filename)
# exclude the small print at the beginning and the end
relevant_part = islice(text, 181, 124379)
# group text into blocks of 5000 lines
blocks = grouper(relevant_part, 5000, "")
# perform actual word count in concurrent processes
result = Counter()
with ProcessPoolExecutor(num_processes) as pool:
for part in pool.map(wc_some_lines, blocks):
result.update(part)
# output results
for word, count in result.most_common(20):
print("{}: {}".format(word, count))
if __name__ == "__main__":
main()
</code></pre>
|
[] |
[
{
"body": "<p>PEP8 mentions that top-level constructs like functions should be separated by two lines. Hanging indents should have only one level of indentation (lines 43 and 61). Be careful about trailing whitespaces (lines 61 and 89).</p>\n\n<p>I love functional style myself but it is often frowned upon in Python, and <code>Counter(chain(*map(split_and_clean, lines)))</code> or <code>filter(None, re.split(REGEX, line.lower()))</code> will be considered unreadable by some, and elegant by others.</p>\n\n<p>Otherwise your code is awesome, well-written with beautiful docstrings and clever (<code>filter()</code> to drop empty strings, <code>AttributeError</code> and to the call to <code>lower()</code>). Thanks for sharing!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-11T10:00:04.833",
"Id": "31092",
"ParentId": "27739",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T19:03:58.827",
"Id": "27739",
"Score": "4",
"Tags": [
"python",
"concurrency"
],
"Title": "Self-taught Pythonista: Any criticism welcome for this concurrent word count script!"
}
|
27739
|
<pre><code>def alist(x):
if x == 1:
return 1
return [alist(x - 1), x, alist(x - 1)]
l = '%r' % alist(int(raw_input('Maximum Number Of Asterisks: ')))
f = l.replace("[", "").replace("]", "").replace(",", "").replace(" ", "")
for i in f:
print "*" * int(i)
</code></pre>
<p>So, basically, I just formatted the list into a string, removed all unwanted characters (left bracket, right brakcer, comma, and space), and for every number in that string, printed the appropriate amount of asterisks. If there is anything you don't understand, sorry because I had to type this up in under 2 minutes, so please just post a comment and I'll try to answer as soon as I can.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T20:14:03.873",
"Id": "43232",
"Score": "0",
"body": "You should clarify what exactly you want.Give us an example of the multidimensional list."
}
] |
[
{
"body": "<p>Without many details, maybe the following can help you:</p>\n\n<pre><code>>>> import itertools\n>>> list_of_lists = [['item_1'], ['item_2', 'item_3'], ['item_4', 'item_5', 'item_6']]\n>>> chain = list(itertools.chain(*list_of_lists))\n>>> print chain\n['item_1', 'item_2', 'item_3', 'item_4', 'item_5', 'item_6']\n</code></pre>\n\n<p>Take a look at this <a href=\"https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python\">question</a>, there are some answers that might help you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T22:04:25.190",
"Id": "43233",
"Score": "0",
"body": "Thanks for the effort, evil_inside, but that would only flatten out a 2-dimensional list, not anything higher. In my solution, I could easily use the split() method and not remove the spaces in the string to separate the string by the spaces (that sounds confusing) and make a 1-dimensional list from any multidimensional list."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T20:33:14.030",
"Id": "27746",
"ParentId": "27740",
"Score": "1"
}
},
{
"body": "<p>Go to this link from the <a href=\"http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow\">python tutorials</a>. Read this completely or just search for flat. That is an easy way to flatten lists.</p>\n\n<p>Now you may say that it is not good for multidimensional lists. Then I would say that you can use recursion to solve the problem. Think about that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T10:16:56.130",
"Id": "27799",
"ParentId": "27740",
"Score": "0"
}
},
{
"body": "<p>Instead of replacing stuff in the <code>repr(li)</code>, flatten the list with a recursive function..</p>\n\n<pre><code>def alist(x):\n if x in (0,1): return x\n return [alist(x - 1), x, alist(x - 1)]\n\n# the magic function\ndef flatten(list_to_flatten):\n for elem in list_to_flatten:\n if isinstance(elem,(list, tuple)):\n for x in flatten(elem):\n yield x\n else:\n yield elem\n\nl = alist(int(raw_input('Maximum Number Of Asterisks: ')))\nf = flatten(l)\n\nfor i in f:\n print \"*\" * int(i)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-29T07:56:01.133",
"Id": "27944",
"ParentId": "27740",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27944",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T19:08:02.273",
"Id": "27740",
"Score": "1",
"Tags": [
"python"
],
"Title": "Is there a better way to flatten out a multidimensional list?"
}
|
27740
|
<p>As suggested on my <a href="https://codereview.stackexchange.com/questions/27573/c-simple-matrix-class-improve-coding">previous question</a>, I am posting my revised code for feedback.</p>
<p>One thing that caught my attention is that my program actually runs slower after adding the modifications. It was previously running near 128 iterations per second on a single core machine and 382 in a 4-core machine. It now runs at 125 in the single core and 360 in the 4-core machine. I am not sure the way I was managing memory in my first version is faster or if I implemented it wrong.</p>
<p>Grid3d.h:</p>
<pre><code>#ifndef _GRID3D_
#define _GRID3D_
#include <iostream>
class Grid3d
{
private:
size_t M, N, L;
double* buffer;
size_t compute_index(size_t, size_t, size_t) const;
public:
//Constructores
Grid3d(size_t,size_t,size_t);
Grid3d();
Grid3d(const Grid3d&);
~Grid3d();
//Operadores
double& operator()(size_t, size_t, size_t);
double operator()(size_t, size_t, size_t) const;
Grid3d& operator=(Grid3d);
//Acceso
int get_L();
int get_M();
int get_N();
double get(size_t,size_t,size_t) const;
void reset();
};
std::ostream & operator<< (std::ostream &,Grid3d);
#endif
</code></pre>
<p>Grid3d.cc:</p>
<pre><code>#include "Grid3d.h"
#include <cmath>
#include <iomanip>
#include <cassert>
using namespace std;
//------------------------------------------------------------------
// Constructores
//------------------------------------------------------------------
//Constructor
Grid3d::Grid3d(size_t M, size_t N, size_t L)
: M(M), N(N), L(L), buffer(new double[M * N * L])
{
for (size_t l=0;l<M*N*L;l++){
buffer[l] = NAN;
}
}
//Constructor vacío
Grid3d::Grid3d()
:M(0), N(0), L(0)
{
buffer = NULL;
}
//Constructor copia
Grid3d::Grid3d(const Grid3d &other)
:M(other.M), N(other.N), L(other.L)
{
buffer = new double[M * N * L];
for (size_t l=0;l<M*N*L;l++){
buffer[l] = other.buffer[l];
}
}
//Destructor
Grid3d::~Grid3d() { delete [] buffer; }
//------------------------------------------------------------------
// Operadores
//------------------------------------------------------------------
//Access operator ():
double& Grid3d::operator()(size_t i, size_t j, size_t k)
{
assert(i >= 0 and i < M);
assert(j >= 0 and j < N);
assert(k >= 0 and k < L);
return buffer[compute_index(i, j, k)];
}
//Access operator () const:
double Grid3d::operator()(size_t i, size_t j, size_t k) const
{
assert(i >= 0 and i < M);
assert(j >= 0 and j < N);
assert(k >= 0 and k < L);
return buffer[compute_index(i, j, k)];
}
//Assignment operator
Grid3d& Grid3d::operator=(Grid3d other)
{
using std::swap;
swap(M, other.M);
swap(N, other.N);
swap(L, other.L);
swap(buffer, other.buffer);
return *this;
}
//------------------------------------------------------------------
// Acceso
//------------------------------------------------------------------
size_t Grid3d::compute_index(size_t i, size_t j, size_t k) const
{
return k * (M * N) + i * N + j;
}
int Grid3d::get_L()
{
return L;
}
int Grid3d::get_M()
{
return M;
}
int Grid3d::get_N()
{
return N;
}
double Grid3d::get(size_t i, size_t j, size_t k) const
{
assert(i >= 0 and i < M);
assert(j >= 0 and j < N);
assert(k >= 0 and k < L);
return buffer[compute_index(i, j, k)];
}
void Grid3d::reset()
{
for (size_t l=0;l<M*N*L;l++){
buffer[l] = NAN;
}
}
//------------------------------------------------------------------
// Others
//------------------------------------------------------------------
//cout
std::ostream & operator << (std::ostream & os , Grid3d g)
{
int M = g.get_M();
int N = g.get_N();
int L = g.get_L();
for (int k=0;k<L;k++){
cout << "k = " << k << endl;
for (int i=0;i<M;i++){
for (int j=0;j<N;j++){
cout.width(10);
os << setprecision(3) << g.get(i,j,k)<< " ";
}
os << endl;
}
os << endl;
}
return os;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T01:13:15.290",
"Id": "43236",
"Score": "0",
"body": "Are you compiling with optimization on? This is probably important, as with optimization off, compute_index will not be inlined (for example)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T01:16:40.227",
"Id": "43237",
"Score": "2",
"body": "As another note, using NANs may slow down your code considerably. Floating point operations with NaNs are slower than those without."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T03:38:53.790",
"Id": "43248",
"Score": "4",
"body": "I won't post this as an answer since it's been covered in detail on your previous post, but I'd like to again strongly urge you to use a single dimensional vector. With optimizations, it will be as fast as a raw array. It will provide much cleaner and smaller code at literally 0 cost. I consider a bare array the wrong choice here unless performance actually does be one a concern and a bare array is faster (and it wouldn't be)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T05:38:58.107",
"Id": "43254",
"Score": "1",
"body": "I would strongly recommend you to use English in your comments as well. Not only is it good practice, but it also helps in case you ever need to, say, post your code to an English-language online Q&A or code review site."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T03:00:22.570",
"Id": "43308",
"Score": "0",
"body": "@ruds I am compiling using gcc 4.7 with -O2.\nI initialize the grid points as NAN, then i change each point to its propper value(which is generally not 0). That way, if I forget to define the value of a grid point I notice imediatley, so i am not doing float operation with nans."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T04:44:01.753",
"Id": "43317",
"Score": "0",
"body": "Please show us the test harness you're using -- it's hard to evaluate what's slower if we don't know what's actually running."
}
] |
[
{
"body": "<p>Most likely the performance degradation is caused because in your previous version, <code>operator<<</code> took a <code>Grid3d&</code>, and in this version it takes a <code>Grid3d</code>. Your <code>operator<<</code> signature should be</p>\n\n<pre><code>std::ostream& operator<<(std::ostream&, const Grid3d&);\n</code></pre>\n\n<p>As another code improvement, you should change your copy constructor:</p>\n\n<pre><code>Grid3d::Grid3d(const Grid3d &other)\n : L(other.L), M(other.M), N(other.N)\n{\n buffer = new double[L * M * N];\n std::memcpy(buffer, other.buffer, M * N * L * sizeof(double));\n}\n</code></pre>\n\n<p><code>memcpy</code> may give you better performance than the <code>for</code> loop you wrote.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T02:41:47.927",
"Id": "43246",
"Score": "2",
"body": "A small note, but the order of `delete` and `new` in your copy constructor should be the other way around. This ensures strong exception safety in the case that `new` throws."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T05:05:20.413",
"Id": "43251",
"Score": "1",
"body": "Well, it can't be quite in the opposite order, but I'll edit the code to take your comment into account."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T18:16:44.087",
"Id": "43276",
"Score": "1",
"body": "Will M, N and L of the object be left containing the wrong values if `new` throws?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T20:17:14.150",
"Id": "43283",
"Score": "2",
"body": "Err... on further thought, this is a constructor, so if `new` throws, the object get cleaned up and no longer exists, so the state of L, M and N is irrelevant. Sorry to confuse :-("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T23:39:58.890",
"Id": "43298",
"Score": "0",
"body": "**BANG** you are dead the shuttle just blew up. You are deleting an initialized member `Buffer`. It is not leaked . This is a **CONSTRUCTOR** so it has not previously been initialized."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T23:41:29.177",
"Id": "43299",
"Score": "0",
"body": "prefer `std::copy()` worst case it has the same performance as `std::memcpy`. Best case there is some cool optimization in the standard that makes it faster (unlikely but you never know)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T03:02:25.657",
"Id": "43309",
"Score": "0",
"body": "@Loki Astari, yes actually that line was generating a \"core\" so i commented it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T03:07:30.127",
"Id": "43311",
"Score": "0",
"body": "@ruds I is not likely that the performance degradation is caused by that. I used that function for testing purposes only. The only functions that are used intensively are \"operator()\" and \"get()\", mostly \"operator()\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T04:38:17.620",
"Id": "43316",
"Score": "0",
"body": "@LokiAstari ugh, oops. I had assignment operator in my head. I should get more sleep before answering these..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T04:47:26.607",
"Id": "43318",
"Score": "0",
"body": "@ruds: No problem. Downvote removed."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T01:22:05.893",
"Id": "27753",
"ParentId": "27752",
"Score": "4"
}
},
{
"body": "<p>I will expand on this when I have more time, but a few things jumped out:</p>\n\n<hr>\n\n<p><code>get_M</code>/<code>get_L</code>/<code>get_N</code> should return a <code>std::size_t</code>, not an <code>int</code>.</p>\n\n<hr>\n\n<p><code>get_M</code>/<code>get_L</code>/<code>get_N</code> should be const.</p>\n\n<hr>\n\n<p>It might make sense in your field of study, but to me, NAN is weird for the initial value. I would expect the initial values to be either undefined or 0. Whatever works best for you though. Initializing to NAN would, after all, provide a few convenient properties.</p>\n\n<hr>\n\n<p>All of the <code>size_t</code> in the header should be <a href=\"https://stackoverflow.com/questions/237370/does-stdsize-t-make-sense-in-c\"><code>std::size_t</code></a>.</p>\n\n<hr>\n\n<p>Rather than duplicate the exact same code, the constructor should use <code>reset</code>. </p>\n\n<hr>\n\n<p>Be careful with <code>using namespace std;</code>, even in implementation files. If you want to read way more than you ever wanted to on it, see <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">this</a>. The \"tl;dr\" of it is that a potentially application breaking bug might happen years down the road do to a change a dozen files away, but that can all be avoided with 5 extra characters (<code>std::</code>). </p>\n\n<hr>\n\n<p>When outputting potentially huge chunks of data, try not to flush until you either need to or the end (in single threaded applications, that's almost always going to be the end).</p>\n\n<p>In particular, std::endl is <em>not</em> equivalent to <code>\"\\n\"</code>. <code>std::cout << \"\\n\";</code> pushes a new line into <code>std::cout</code>s buffer. <code>std::cout << std::endl;</code> pushes a newline into <code>std::cout</code>'s buffer and then flushes the buffer. This means that your <code>operator<<</code> isn't really using buffered IO since it flushes after every output. </p>\n\n<p>Simple fix: use \"\\n\" and then just do <code>std::flush(std::cout);</code> (or <code>std::cout << std::flush</code>) at the end.</p>\n\n<hr>\n\n<p><code>cout.width(10);</code> in your <code>operator<<</code> should be <code>os.width(10)</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T22:25:10.507",
"Id": "43293",
"Score": "1",
"body": "+1; instead of creating a separate answer, I'll just add a comment: in addition, I'd also replace all uses of `int` with `std::size_t` in `operator <<` (which should also preferably take `Grid3d` by const-ref, 4 x 64-bit + alignment may be a bit too much for pass-by-value). Also, regardless of whether the OP adopts `std::vector`, I'd probably also use `std::copy` in the copy constructor."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T05:16:44.623",
"Id": "27758",
"ParentId": "27752",
"Score": "7"
}
},
{
"body": "<p>So you do not have to handle NULL created a zero sized array here (and use the initializer list):</p>\n\n<pre><code>//Constructor vacío\nGrid3d::Grid3d()\n :M(0), N(0), L(0)\n{\n buffer = NULL;\n}\n\n// Prefer\nGrid3d::Grid3d()\n :M(0), N(0), L(0), buffer(new double[N*M*L])\n{}\n</code></pre>\n\n<p>By creating the array like this, the rest of you code does not need to have a special case for NULL buffer. The code just looks the same.</p>\n\n<p>Now that looks very similar to your other constructor.<br>\nYou could potentially just combine the two.</p>\n\n<p>Prefer to use the initializer liest (even in the copy constructor)</p>\n\n<pre><code>Grid3d::Grid3d(const Grid3d &other)\n :M(other.M), N(other.N), L(other.L)\n ,buffer(new double[M * N * L])\n{\n for (size_t l=0;l<M*N*L;l++){\n buffer[l] = other.buffer[l];\n }\n}\n</code></pre>\n\n<p>For the const version of your access operator. Just make it call the non const version. (We know that neither version actually mutate the object so there is no harm in casting away constness). The const version returns a value so it is not exposing any data for modification:</p>\n\n<pre><code>double Grid3d::operator()(size_t i, size_t j, size_t k) const\n{\n return const_cast<Grid3d>(*this)(i,j,k);\n}\n</code></pre>\n\n<p>All the following should be const:</p>\n\n<pre><code>int Grid3d::get_L()\nint Grid3d::get_M()\nint Grid3d::get_N()\n</code></pre>\n\n<p>Pass by const reference when you can to prevent an expensive copy.</p>\n\n<pre><code>std::ostream & operator << (std::ostream & os , Grid3d const& g)\n // ^^^^^^\n</code></pre>\n\n<p>Prefer not to use <code>\\n</code> instead of <code>std::endl</code>. It has no major benefits and can slow code down dramatically. If you want to guarantee a flush print the whole structure first then use <code>std::endl</code> instad of the last '\\n'.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T23:54:13.787",
"Id": "27786",
"ParentId": "27752",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T00:43:50.413",
"Id": "27752",
"Score": "3",
"Tags": [
"c++",
"performance",
"matrix"
],
"Title": "Simple matrix class - version 2"
}
|
27752
|
<p>I'm using a payment gateway and am trying to implement the post and response handling with CURL so that it all happens on one page.</p>
<p>The following is tested and works but I want to double check it's secure. I'm not storing the card details but I'm essentially posting them to myself (via AJAX) and then curling that through to the gateway. I can't AJAX post it directly to the gateway because of cross domain restrictions.</p>
<p>So, this all happens in <a href="https://mysite.com/payment.php" rel="nofollow">https://mysite.com/payment.php</a>:</p>
<p><strong>HTML</strong></p>
<pre><code><form method="post" action="https://mysite.com/payment.php">
<input type="hidden" name="Amount" value="1.00">
<!-- fingerprint is a hash of my gateway passwords and fields on this form -->
<input type="hidden" name="Gateway_Fingerprint" value="<?php echo $fingerprint ?>">
<input type="hidden" name="Gateway_ReturnURL" value="https://mysite.com/payment.php">
<input type="hidden" name="Card_Number" value="">
</form>
</code></pre>
<p><br />
<strong>PHP</strong></p>
<pre><code>// when payment form is submitted
if(isset($_POST['Card_Number'])){
// CURL the data to payment gateway
foreach($data as $key => $value){
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$post = curl_init();
curl_setopt($post, CURLOPT_VERBOSE, true);
curl_setopt($post, CURLOPT_URL, 'https://gatewayurlhere');
curl_setopt($post, CURLOPT_POST, count($data));
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($post);
// output result from gateway as JSON
header('Content-Type: application/json');
echo $result;
curl_close($post);
exit();
}
// result returned from gateway, this will be the CURL result data
if(isset($_POST['restext']))
{
echo json_encode($_POST);
exit();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T13:53:34.237",
"Id": "43267",
"Score": "0",
"body": "Is the Gateway_Fingerprint unique? or is it the same over all requests?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T22:00:22.423",
"Id": "43290",
"Score": "0",
"body": "It's a hash of the gateway password, amount ($), timestamp and our merchant ref. That said I should probably add it to the post data before curling instead of putting in the form."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T22:29:09.410",
"Id": "43294",
"Score": "0",
"body": "You simply should. You are sending data to the client it shouldn't know about in the first place."
}
] |
[
{
"body": "<p>Well, security from what type of threat? You need to figure out what you want to protect against before you can protect against it! Since I'm unsure of what you're protecting against, I'll point out relevant <code>setopt</code> flags.</p>\n\n<ul>\n<li><code>CURLOPT_VERBOSE</code> - This is fine for a developer, but make sure the client doesn't see this returned information. It could lead to a possible exploit. More on the output later on.</li>\n<li><code>CURLOPT_POST</code> - You're using this incorrectly. The value should be true or an alternate HTTP POST.</li>\n<li><code>CURLOPT_RETURNTRANSFER</code> - Using <code>1</code> does result in <code>TRUE</code>, but it's easier to read if the explicit boolean is used.</li>\n</ul>\n\n<p>Here are some flags you may way to consider in order to help secure this connection even more. Each can be <a href=\"http://php.net/manual/en/function.curl-setopt.php\">found in the docs</a>.</p>\n\n<ul>\n<li><code>bool CURLOPT_FAILONERROR</code> - Just in case the page you fetch is \"out of order\".</li>\n<li><code>bool CURLOPT_FORBID_REUSE</code> - Force the connection to close on finish, and prevent the reuse of a connection. Also see <code>bool CURLOPT_FRESH_CONNECT</code>.</li>\n<li>Make sure you keep <code>bool CURLOPT_SSL_VERIFYPEER</code> set to <code>TRUE</code>.</li>\n<li><code>int CURLOPT_TIMEOUT</code> - Timeout if the connection takes too long.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-21T17:49:59.627",
"Id": "57594",
"ParentId": "27755",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T02:56:07.510",
"Id": "27755",
"Score": "5",
"Tags": [
"php",
"security",
"curl",
"ssl"
],
"Title": "Secure CURL to & handle response from Payment Gateway"
}
|
27755
|
<p>This method takes a string and parses the syllables. I've broken much of the logic into helper methods. Without getting into the helper methods, it's pretty easy to tell what this is doing. But there are a lot of conditionals. I tried handling the conditions that handle adding to the <code>syllables</code> variable and those that subtract as two separate methods, but <code>syllables</code> kept changing value out from under me.</p>
<pre><code>def count_syllables
exceptions = YAML::load_file(File.join(__dir__, 'exceptions.yml'))['exceptions']
return exceptions[word.to_s] if exceptions.keys.include?(word)
syllables = count_vowels
syllables += count_ys_in_vowel_role if contains_non_initial_y?
syllables += 1 if contains_le_vowel_sound?
syllables += 1 if begins_with_re_vowel?
syllables += 1 if ends_in_sm?
syllables -= 1 if ends_in_silent_e?
syllables -= count_diphthongs if contains_diphthongs?
syllables <= 1 ? 1 : syllables
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T10:49:01.120",
"Id": "43262",
"Score": "0",
"body": "> This method takes a string and parses the syllables. Well, the method takes no arguments, you mean you are storing it in the class with a reader?"
}
] |
[
{
"body": "<p>Not really elegant, but you could merge the lines by using the <a href=\"http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Control_Structures#short-if_expression_.28aka_ternary_operator.29\" rel=\"nofollow\"><code>?:</code> operator</a>:</p>\n\n<pre><code>syllables = count_vowels + (count_ys_in_vowel_role if contains_non_initial_y?) + (contains_le_vowel_sound? ? 1 : 0) + ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T15:30:56.230",
"Id": "43269",
"Score": "0",
"body": "You'd need also a `?:` for the second expression or you might try to sum a `nil`. But that's the way to go, expressions are definitely better than a parade of in-place updates."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T17:32:36.550",
"Id": "43275",
"Score": "1",
"body": "this is way shorter, but hard to refactor or debug in the future. I personally feel like more than one conditional per line is a code smell"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T14:31:19.217",
"Id": "27765",
"ParentId": "27756",
"Score": "2"
}
},
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li><p><code>YAML::load_file</code>. Loading a file each time a method is called is dubious. I'd load it in the <code>initialize</code> of the class so it's only done once.</p></li>\n<li><p><code>return exceptions[word.to_s] if exceptions.keys.include?(word)</code> Inline conditionals are ok as guards (in a fact here it's kind of a guard), but as a general rule indented conditionals are more declarative (granted, at the cost of an indentation level and some lines).</p></li>\n<li><p><code>+=</code>, <code>-=</code>. Imperative programming. As always, I'd advise against in-place updates, try to avoid statements in favor of expressions (functional programming).</p></li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>def count_syllables\n if @exceptions.has_key?(word)\n @exceptions[word]\n else\n counts = [\n count_vowels,\n (count_ys_in_vowel_role if contains_non_initial_y?)\n (+1 if contains_le_vowel_sound?),\n (+1 if begins_with_re_vowel?) \n (+1 if ends_in_sm?),\n (-1 if ends_in_silent_e?),\n (-count_diphthongs if contains_diphthongs?),\n ]\n [counts.compact.reduce(0, :+), 1].max\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T02:56:14.630",
"Id": "43307",
"Score": "0",
"body": "I like this approach a lot. But I don't love that the majority of it falls in an `else` statement. Do you think you would lose a lot by an early `return` with an inline conditional here?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T06:50:57.500",
"Id": "43321",
"Score": "0",
"body": "@nickcoxdotme: it's orthogonal, you can leave the guard and still write the second part of the method similar to this."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T17:04:51.157",
"Id": "27770",
"ParentId": "27756",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T03:56:25.800",
"Id": "27756",
"Score": "2",
"Tags": [
"strings",
"ruby"
],
"Title": "Parsing syllables from a string"
}
|
27756
|
<p>I've done a LOT of reading about creating a Unit Of Work and Repository based implementation for my Entity Framework based application. I have come up with the following - what problems can you find?</p>
<p>The theory of making the actual SQL Server unit of work, context, and repository coupled to entity framework is that these three implementations will not be used independently. I can create a fake unit Unit of work and Repository for unit testing without worrying about the context as the Unit of Work is responsible for instantiating the concrete repository.</p>
<p>p.s. Do I need to implement IDisposable on the repository?</p>
<p><strong>Dgc.CriminalJustice.Model</strong></p>
<p>Repository Interface</p>
<pre><code>public interface IRepository<T> : IDisposable
where T : class
{
void Add(T entity);
void Delete(T entity);
void Update(T entity);
T GetById(int id);
IEnumerable<T> All();
IEnumerable<T> Find(Expression<Func<T, bool>> filter = null, string includeProperties = "");
}
</code></pre>
<p>Unit of work interface</p>
<pre><code>public interface IUnitOfWork : IDisposable
{
IRepository<Person> PersonRepository { get; }
void Save();
}
</code></pre>
<p><strong>Dgc.CriminalJustice.Data.SqlServer</strong></p>
<p>Entity Framework Context</p>
<pre><code>public class CriminalJusticeContext : DbContext
{
static CriminalJusticeContext()
{
Database.SetInitializer<CriminalJusticeContext>(null);
}
public CriminalJusticeContext()
: base("Name=CriminalJusticeContext")
{
}
public DbSet<Address> Addresses { get; set; }
public DbSet<Person> People { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new Mapping.AddressMap());
modelBuilder.Configurations.Add(new Mapping.PersonMap());
modelBuilder.Configurations.Add(new Mapping.AliasMap());
modelBuilder.Configurations.Add(new Mapping.CaseNoteMap());
}
}
</code></pre>
<p>Entity framework based Repository</p>
<pre><code>public class Repository<T> : IRepository<T>
where T : class
{
private CriminalJusticeContext context;
private IDbSet<T> dbSet;
internal Repository(CriminalJusticeContext criminalJusticeContext)
{
this.context = criminalJusticeContext;
this.dbSet = criminalJusticeContext.Set<T>();
}
public void Add(T entity)
{
dbSet.Add(entity);
}
public void Delete(T entity)
{
dbSet.Remove(entity);
}
public void Update(T entity)
{
dbSet.Attach(entity);
context.Entry(entity).State = EntityState.Modified;
}
public T GetById(int id)
{
return dbSet.Find(id);
}
public IEnumerable<T> All()
{
return dbSet.ToList();
}
public IEnumerable<T> Find(Expression<Func<T, bool>> filter = null, string includeProperties = "")
{
IQueryable<T> query = dbSet;
if (filter != null)
{
query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
return query.ToList();
}
public void Dispose()
{
throw new NotImplementedException();
}
}
</code></pre>
<p>Entity Framework based Unit Of Work</p>
<pre><code>public class UnitOfWork : IUnitOfWork
{
private CriminalJusticeContext context = new CriminalJusticeContext();
private Repository<Model.Person> personRepository;
public IRepository<Model.Person> PersonRepository
{
get
{
if (personRepository == null)
{
personRepository = new Repository<Model.Person>();
}
return personRepository;
}
}
public void Save()
{
context.SaveChanges();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
</code></pre>
<p><strong>Dgc.CriminalJustice.Model</strong></p>
<pre><code>public class Person
{
public Person()
{
this.Aliases = new List<Alias>();
this.CaseNotes = new List<CaseNote>();
}
public int PersonRef { get; private set; }
public string Title { get; private set; }
public string FirstName { get; private set; }
public string PreferredForename { get; private set; }
public string Surname { get; private set; }
public string NameSuffix { get; private set; }
public string Gender { get; private set; }
public Nullable<System.DateTime> DateBirth { get; private set; }
public bool EstimatedDateOfBirth { get; private set; }
public string AddressRef { get; private set; }
public Nullable<System.DateTime> DateofDeath { get; private set; }
public string URN { get; private set; }
public string SwissRef { get; private set; }
public string CJSwissRef { get; private set; }
public Address ContactAddress { get; set; }
public ICollection<Alias> Aliases { get; set; }
public ICollection<CaseNote> CaseNotes { get; set; }
}
public class Address
{
public string AddressRef { get; private set; }
public string Address1 { get; private set; }
public string Address2 { get; private set; }
public string Address3 { get; private set; }
public string Address4 { get; private set; }
public string Postcode { get; private set; }
}
public class Alias
{
public int PersonRef { get; private set; }
public string Forename { get; private set; }
public string Surname { get; private set; }
}
public class CaseNote
{
public int CaseNoteRef { get; private set; }
public int PersonRef { get; private set; }
public System.DateTime ContactDate { get; private set; }
public int WhoWithId { get; private set; }
public int ContactTypeId { get; private set; }
public int VenueId { get; private set; }
public int AuthorId { get; private set; }
public int PurposeId { get; private set; }
public string NoteText { get; private set; }
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-03T19:07:28.773",
"Id": "43836",
"Score": "0",
"body": "This may be of interest to you: [MSDN: The Unit Of Work Pattern And Persistence Ignorance](http://msdn.microsoft.com/en-us/magazine/dd882510.aspx)"
}
] |
[
{
"body": "<p>In your <code>Repository<T></code>, you might want to check the <code>EntityState</code> of your <code>entity</code> before manipulating them in your <code>DbSet</code> like this:</p>\n\n<pre><code> public void Add(T entity)\n {\n DbEntityEntry dbEntityEntry = DbContext.Entry(entity);\n if (dbEntityEntry.State != EntityState.Detached)\n {\n dbEntityEntry.State = EntityState.Added;\n }\n else\n {\n DbSet.Add(entity);\n }\n }\n\n public void Update(T entity)\n {\n DbEntityEntry dbEntityEntry = DbContext.Entry(entity);\n if (dbEntityEntry.State == EntityState.Detached)\n {\n DbSet.Attach(entity);\n }\n dbEntityEntry.State = EntityState.Modified;\n }\n\n public void Delete(T entity)\n {\n DbEntityEntry dbEntityEntry = DbContext.Entry(entity);\n if (dbEntityEntry.State != EntityState.Deleted)\n {\n dbEntityEntry.State = EntityState.Deleted;\n }\n else\n {\n DbSet.Attach(entity);\n DbSet.Remove(entity);\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-04T09:57:20.777",
"Id": "30760",
"ParentId": "27766",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T15:01:41.227",
"Id": "27766",
"Score": "3",
"Tags": [
"c#",
"design-patterns",
"entity-framework"
],
"Title": "Review Repository and UnitOfWork implementation"
}
|
27766
|
<p>I've worked hard on this code and it functions exactly as I wanted, but I've been told it is a little bit unreadable. My focus is to get the code as clean as possible, and have things as efficient as possible.</p>
<p>This is the code I am working with:
<a href="http://jsfiddle.net/xT5X5/6/" rel="nofollow">http://jsfiddle.net/xT5X5/6/</a></p>
<pre><code>//latest
var maxFields = 10;
$('.form').on('click', '.add', function () {
var value_src = $(this).prev();
var container = $(this).parent().prev();
if ($.trim(value_src.val()) !== '') {
if (container.children().length < maxFields) {
var value = value_src.val();
var html = '<div class="line">' +
'<input class="accepted" type="text" value="' + value + '" />' +
'<input type="button" value="X" class="remove" />' +
'</div>';
$(html).appendTo(container);
value_src.val('');
} else {
alert("You tried to add a field when there are already " + maxFields);
}
} else {
alert("You didn't enter anything");
}
})
.on('click', '.remove', function () {
$(this).parents('.line').remove();
});
$(".current").keyup(function(e) {
if (e.which == 13) {
$(this).next("input").trigger("click");
}
});
$(document).on("keyup",".accepted",function(e) {
if (e.which == 13) {
$(this).closest('.copies').next().find(".current").focus();
}
});
</code></pre>
<p>Can anyone give me any pointers on how I've done, and if there are any improvements that you can spot. Any feedback would be much appreciated!</p>
<p>Thank you.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T15:22:42.510",
"Id": "43268",
"Score": "1",
"body": "You are storing your application state in the HTML instead of keeping a JavaScript object and separating concerns (\"requirements\" for example is conceptually an array, not a list of DOM elements). This approach will make it very hard for your code to scale in terms of maintenance (Even atm, it's not very readable). Also, please post the code here as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T15:44:12.793",
"Id": "43271",
"Score": "1",
"body": "Posted the code. I am adding in fields (I'm guessing thats what dom elements are applying to in this case) because it seemed a lot easier to submit in a form that way"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T21:00:05.693",
"Id": "43285",
"Score": "1",
"body": "@BenjaminGruenbaum I disagree. I'd say state _should_ be stored in the DOM. That, I'd argue, is exactly how to separate concerns: JS controls behavior, the DOM contains the data, and CSS governs presentation. If the user is supposed to see what's going on, the data must necessarily be added to the DOM at some point, so I'd say keep it there to begin with. To get a \"clean\" JS array rather than a list of DOM elements, a simple jQuery `.map()` will suffice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T21:05:07.977",
"Id": "43286",
"Score": "1",
"body": "@Flambino I consider that a blunt _mistake_. You're developing a web application not a document. The state should be stored in JavaScript, in models like in any sensible GUI that does separation of concerns. This is exactly what the transition from static web pages to web applications is all about. Do you _honestly_ think querying your presentation is reasonable whenever you want to know your application's state? Storing HTML in JavaScript strings and having no separation of concerns? Storing application state in the DOM is dangerous and harmful. Separate the _right_ concerns."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T22:39:28.520",
"Id": "43296",
"Score": "0",
"body": "I'm a little confused. Are we talking about submitting the array via ajax so that the results don't have to be stored in actual DOM field elements? The advantage of using fields is that I can easily edit the contents of each field after they have been added, otherwise I would probably just have text in printed above with no way to edit"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T01:33:37.107",
"Id": "43301",
"Score": "0",
"body": "@JamesWillson A lot of libraries like AngularJS and KnockoutJS provide bi-directional data-binding, for example (which is very similar to what you're doing) see http://learn.knockoutjs.com"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T15:27:42.690",
"Id": "43356",
"Score": "0",
"body": "@BenjaminGruenbaum If we're talking about a full-on everything-is-ajax-and-js _application_, then sure, throw Angular or KnockoutJS or anything else at it. Would I want to keep all state data in the DOM for such a project? No, of course not. But for this I'd do it. The DOM is beast, yes, but it's still a data model (and jQuery tames it). Libs like Knockout & Angular are neat, but they're also more code and more abstractions, and overkill in this case. All we're talking about is a neater HTML form."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T15:42:31.187",
"Id": "43358",
"Score": "0",
"body": "@Flambino The DOM is not a beast. I think that the DOM is quite a nice abstraction to do presentation and it works which is why you see similar concepts for GUI like XAML in WPF or QML in QT. That's what it is though, presentation. Using data representing things - like JavaScript objects to represent well... data is not another abstraction - it's common sense. Storing application state in the presentation layer with all the markup is a bad technique that completely ignores how GUI is coded - it originates in an age where web pages were static. You don't need a framework to do it right!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T16:31:55.760",
"Id": "43360",
"Score": "0",
"body": "@BenjaminGruenbaum And I still hold that the DOM is about data, not _necessarily_ presentation. Markup of any kind provides structure and semantics for data, and the DOM is the API: It is - among other things - a database you can query. (If we were talking about a simple XML file, I think you'd agree that it's just structured data, since XML by itself has no GUI.) It's a beast because it's not the nicest/fastest API for manipulating structured data, but it is an API nontheless. It also has a GUI component, but that doesn't invalidate its data modelling abilities."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T16:36:19.913",
"Id": "43361",
"Score": "0",
"body": "@Flambino Right, and you can use XML for data all you want (although it's a data-exchange format for _documents_). However, HTML is _not_ just XML (or at all) and it's a specific mark up language for the presentation of web pages. Just because you can use something to store data doesn't mean that you should. You _can_ store data in custom attributes but it's a _horrible_ idea - just like you can create one giant string and slice it at specific places instead of using variables at all - doesn't mean it makes sense, it's simply not where it belongs. The DOM _is_ about data, presentation data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T17:15:47.157",
"Id": "43363",
"Score": "0",
"body": "@BenjaminGruenbaum And I still disagree. If HTML was only about presentation, we'd still be using `<font>` tags, or `<i>` when we mean `<em>`. If anything HTML is _less_ about presentation nowadays, although you can treat it as merely that. Yes, you can do everything in JS, keep state there, and make sure the DOM reflects that state. Or you can consider the JS itself (in this simple case) practically stateless and wholly event-driven. The goal is DOM manipulation (adding/removing elements) so why complicate it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T17:22:41.760",
"Id": "43364",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/9407/discussion-between-benjamin-gruenbaum-and-flambino)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T19:02:21.377",
"Id": "43376",
"Score": "0",
"body": "For the record, Benjamin and I kept arguing in the chat for a bit (we agreed to disagree), and ended up with these two fiddles: [His, using KnockoutJS](http://jsfiddle.net/kZZ5L/) and [mine, which is not too different from yours](http://jsfiddle.net/72BMm/). I used CoffeeScript for mine, but [here it is as JS](http://jsfiddle.net/e3FJB/1/)"
}
] |
[
{
"body": "<p>First of all there is a great article on <a href=\"http://javascriptplayground.com/blog/2013/06/refactoring-js/?utm_source=javascriptweekly&utm_medium=email\" rel=\"nofollow\">refactoring jQuery</a> by Jack Franklin.</p>\n\n<p>Second is my solution that i came up with in last 2 hours(ocd kicked in). My solution is probably not right, because i still have a ton to learn and would appreciate any feedback !!</p>\n\n<p><a href=\"http://jsfiddle.net/Rusln/CsKzh/\" rel=\"nofollow\">Here fiddle with implementation</a>. Here is a short version of what is going on inside, as you can see i tried to refactor each action in it's own method: </p>\n\n<pre><code>// detail object that handles our form\nvar details = {\n maxFields: 10,\n form: \"\",\n init: function(el) {},\n bindEvents: function() {},\n appendCopy: function(event) {},\n removeCopy: function(event) {},\n createCopy: function(value) {},\n focusOnEnter: function(event) {},\n addCopyOnEnter: function(event) {},\n _isValueEmpty: function(val) {},\n _isMaxReached: function(copyContainer) {},\n _getParent: function(event){},\n _getCurrent: function(event){}\n _getCopyContainer: function(event){},\n _getValue: function(event){}, \n};\n\n// initialize our details object\n details.init(\".form\");\n</code></pre>\n\n<p>I think this could also be rewritten using <code>$.deferred</code> where each <code>deferred</code> would be responsible for tracking it's own progress (requirements,benefits,qualifications). </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T15:30:26.187",
"Id": "27851",
"ParentId": "27767",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T15:08:53.113",
"Id": "27767",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"performance"
],
"Title": "Jquery field add code - Improvements in readability, compactness or efficiency"
}
|
27767
|
<p>I'm working on my site, and need help knowing what I need to do to improve the security of my login system.</p>
<p>If you feel so inclined, I would love some help to tell me what the exact changes that I need to make, but if you could just tell me what other security measures I need to add, that would be amazing.</p>
<p>This is a login system.</p>
<p>Specifically, I need help using MySQLi prepared statements.</p>
<p>I'm very confused about that, but any other things I should add to secure user data would be great.</p>
<p><a href="http://pastebin.com/vC7c4dPU" rel="nofollow" title="Login.php"><strong>Register.php</strong></a></p>
<pre><code>//Get all POST data from user trying to register
$username = $_POST['username'];
$password = $_POST['password'];
$name = $_POST['name'];
$email = $_POST['email'];
$lat = $_POST['lat'];
$lon = $_POST['lon'];
//Choose wether the user will be "it" or "not it"
$choose_it = array('it', 'not it');
$key = array_rand($choose_it);
$it = $choose_it[$key];
$message = "";
$allEmails = "";
$allUnames = "";
function strong_crypt($input, $rounds = 81)
{
$salt = "";
$salt_chars = array_merge(range('A','Z'), range('a','z'), range(0,9));
for($i=0; $i < 22; $i++)
{
$salt .= $salt_chars[array_rand($salt_chars)];
}
return crypt($input, sprintf('$2a$%02d$', $rounds) . $salt);
}
//Get emails from registered users and check if it has already been used
$AllPeople = "SELECT email, uname FROM login WHERE email = '$email'";
$query = mysqli_query($conn,$AllPeople);
while($row = mysqli_fetch_array($query))
{
$allEmails = $row['email'];
$allUnames = $row['uname'];
}
if($allEmails != "")
{
$message = "That email already exists. You can only have one account per email address.";
}
if($allUnames != "")
{
$message = "That username has already been taken. Please choose a different one.";
}
if($allEmails === "" && $allUnames === "")
{
$hash = strong_crypt($password);
mysqli_query($conn, "INSERT INTO login (name, uname, pword, email, lat, lon, it) VALUES ('$name', '$username', '$hash', '$email', '$lat', '$lon', '$it')");
$message = "goodtogo";
}
echo json_encode(array("message" => $message, "name" => $name, "it" => $it));
mysqli_close($conn);
</code></pre>
<p><a href="http://pastebin.com/PHVv679L" rel="nofollow" title="Register.php"><strong>Login.php</strong></a></p>
<pre><code>$username = $_POST['username'];
$inPword = $_POST['password'];
$lat = $_POST['lat'];
$lon = $_POST['lon'];
$returnmessage = "";
$loggedin = "";
$password_hash = "";
$loggedinstatus = "";
$sel = mysqli_query($conn,"SELECT pword, loggedin FROM login WHERE uname = '$username'");
if(mysqli_num_rows($sel) < 1)
{
$returnmessage = "BadLogin";
}
while($fetch = mysqli_fetch_array($sel,MYSQLI_ASSOC))
{
$password_hash = $fetch['pword'];
$loggedinstatus = $fetch['loggedin'];
}
if(crypt($inPword, $password_hash) == $password_hash)
{
switch($loggedinstatus)
{
case "no":
$returnmessage = "AllGood";
$sel = mysqli_query($conn,"UPDATE login SET loggedin='yes' WHERE uname = '$username'");
break;
defaut:
$returnmessage = "alreadyin";
break;
}
}
else
{
$returnmessage = "error";
}
echo json_encode(array("message" => $returnmessage, "uname" => $username));
mysqli_close($conn);
</code></pre>
|
[] |
[
{
"body": "<p>The first thing I will tell you to do is to look into SQL injections. Your scripts are providing a pretty easy way of potentially exposing security holes. using <code>mysqli_real_escape_string</code> to escape any data going into your database is one of the better sanity checks. </p>\n\n<p>In your registration, you want to check that the specified email or username does not exist within the login table. You are not currently checking for the username - only the email. </p>\n\n<p>Personally, I would split them email and username data off, gathered from the query, into separate arrays, then perform a count on the array to ascertain whether the information exists or not - others may do this differently. </p>\n\n<p>With your login script, again, parameters need to be escaped before being placed in the SQL query. </p>\n\n<p>When comparing the number of available login users we have, you are doing: <code>mysqli_num_rows($sel) < 1</code>, it might be prudent to check that we have 0 - since we aren't going to have anything less than 0: <code>0 == mysqli_num_rows($sel)</code>.</p>\n\n<p>I would advise adding a <code>LIMIT 1</code> to the SQL, simply because, if for some reason we end up with two users from the search query, we are going to be overwriting the variables used to test the supplied credentials.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-03T20:30:28.047",
"Id": "43846",
"Score": "0",
"body": "Thank you so much for the help. You were very detailed with what I need to do and are helped give me directions about how to do it. Thank you again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-03T22:27:21.877",
"Id": "43851",
"Score": "0",
"body": "No worries - I like to see people fulfill their potential"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-02T23:09:49.250",
"Id": "28062",
"ParentId": "27768",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "28062",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T15:55:03.643",
"Id": "27768",
"Score": "3",
"Tags": [
"php",
"security",
"mysqli",
"authentication"
],
"Title": "User Data Security"
}
|
27768
|
<p>I am trying to turn this function:</p>
<pre><code>collection = ['hey', 5, 'd']
for x in collection:
print(x)
</code></pre>
<p>Into this one:</p>
<pre><code>def printElement(inputlist):
newlist=inputlist
if len(newlist)==0:
Element=newlist[:]
return Element
else:
removedElement=newlist[len(inputlist)-1]
newlist=newlist[:len(inputlist)-1]
Element=printElement(newlist)
print(removedElement)
collection = ['hey', 5, 'd']
printElement(collection)
</code></pre>
<p>It works, but I wonder if it's okay there's no "return" line under "else:"
Is this as "clean" as I can make it?
Is it better code with or without the newlist?</p>
|
[] |
[
{
"body": "<blockquote>\n <p>but I wonder if it's okay there's no \"return\" line under \"else:\"</p>\n</blockquote>\n\n<p>Yes, that's OK. You don't need to return anything from your function if you don't want to. In fact, in the interest of consistency, you may as well remove the thing returned in the if block too:</p>\n\n<pre><code>def printElement(inputlist):\n newlist=inputlist\n if len(newlist)==0:\n return\n else:\n removedElement=newlist[len(inputlist)-1]\n newlist=newlist[:len(inputlist)-1]\n Element=printElement(newlist)\n print(removedElement)\n\n\ncollection = ['hey', 5, 'd']\n\nprintElement(collection)\n</code></pre>\n\n<blockquote>\n <p>Is it better code with or without the newlist?</p>\n</blockquote>\n\n<p>Assigning new things to <code>inputlist</code> won't modify it outside of the function, so there's no harm in doing so. May as well get rid of newlist.</p>\n\n<pre><code>def printElement(inputlist):\n if len(inputlist)==0:\n return\n else:\n removedElement=inputlist[len(inputlist)-1]\n inputlist=inputlist[:len(inputlist)-1]\n Element=printElement(inputlist)\n print(removedElement)\n\n\ncollection = ['hey', 5, 'd']\n\nprintElement(collection)\n</code></pre>\n\n<p>you don't use <code>Element</code> after assigning it, so you may as well not assign it at all.</p>\n\n<pre><code>def printElement(inputlist):\n if len(inputlist)==0:\n return\n else:\n removedElement=inputlist[len(inputlist)-1]\n inputlist=inputlist[:len(inputlist)-1]\n printElement(inputlist)\n print(removedElement)\n\n\ncollection = ['hey', 5, 'd']\n\nprintElement(collection)\n</code></pre>\n\n<p>You don't really need to modify <code>inputlist</code>, since you only use it once after modifying it. Just stick that expression straight into the <code>printElement</code> call. And now that <code>inputlist</code> is never modified, you can get rid of <code>removedElement</code> too, and just inline its expression in the <code>print</code> function.</p>\n\n<pre><code>def printElement(inputlist):\n if len(inputlist)==0:\n return\n else:\n printElement(inputlist[:len(inputlist)-1])\n print(inputlist[len(inputlist)-1])\n\n\ncollection = ['hey', 5, 'd']\n\nprintElement(collection)\n</code></pre>\n\n<p>Fun fact: for any list <code>x</code>, <code>x[len(x)-1]</code> can be shortened to <code>x[-1]</code>. Same with <code>x[:len(x)-1]</code> to <code>x[:-1]</code>.</p>\n\n<pre><code>def printElement(inputlist):\n if len(inputlist)==0:\n return\n else:\n printElement(inputlist[:-1])\n print(inputlist[-1])\n\n\ncollection = ['hey', 5, 'd']\n\nprintElement(collection)\n</code></pre>\n\n<p>Since the first block unconditionally returns, you could remove the <code>else</code> and just put that code at the function level, without changing the code's behavior. Some people find this less easy to read. Personally, I like my code to have the least amount of indentation possible.</p>\n\n<pre><code>def printElement(inputlist):\n if len(inputlist)==0:\n return\n printElement(inputlist[:-1])\n print(inputlist[-1])\n\n\ncollection = ['hey', 5, 'd']\n\nprintElement(collection)\n</code></pre>\n\n<p>That's about as compact as you can get, with a recursive solution. You should probably just stick with the iterative version, for a few reasons:</p>\n\n<ul>\n<li>Fewer lines</li>\n<li>More easily understood</li>\n<li>Doesn't raise a \"maximum recursion depth exceeded\" exception on lists with 200+ elements</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T19:55:36.597",
"Id": "27777",
"ParentId": "27773",
"Score": "1"
}
},
{
"body": "<p>Your function is needlessly complicated. The return value is never used. You also print from the end of the list, which is a bit odd: tail recursion is a more usual style. For example:</p>\n\n<pre><code>def printCollection(c):\n if c:\n print c[0]\n printCollection(c[1:])\n</code></pre>\n\n<p>This still has the flaw that it copies the list for every element in the list, making it an O(n^2) function. It's also limited to data structures that use slices and indices. Here's a recursive version that prints any iterable:</p>\n\n<pre><code>def printCollection(c):\n it = iter(c)\n try:\n el = it.next()\n print el\n printCollection(it)\n except StopIteration:\n pass\n</code></pre>\n\n<p>It's still a bit odd to recurse here as this is a naturally iterative problem.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T03:03:11.533",
"Id": "43310",
"Score": "0",
"body": "You're right. I was thinking I could get a better grip on recursion by doing some programs that were easier to understand. While that helped a little, I see I need to step it up."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T19:55:53.630",
"Id": "27778",
"ParentId": "27773",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27777",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T19:27:19.883",
"Id": "27773",
"Score": "2",
"Tags": [
"python",
"recursion"
],
"Title": "I'm practicing turning for loops into recursive functions. what do you think?"
}
|
27773
|
<p>I wrote this tiny script to pull the JSON feed from the <a href="http://citibikenyc.com/stations/json" rel="nofollow">CitiBike website</a>:</p>
<pre><code>import requests
import time
def executeCiti():
r = requests.get("http://citibikenyc.com/stations/json")
print r.json()
time.sleep(62)
while True:
executeCiti()
exit()
</code></pre>
<p>Then I just run the script in terminal and output it to a .txt file like so: python citi_bike.py > output.txt</p>
<p>The end goal of what I would like by the end of this exercise is well formatted JSON data (with only select few of the pairs from each request), separated by each request. I want it to be manageable so I can create visualizations from it.</p>
<ol>
<li><p>Is this an okay way to start what I'm trying to accomplish?</p></li>
<li><p>Is there a better way to begin, so that the data came out like I want it as my end goal? In regards to this question, I feel like I have already started taking a very roundabout way to getting to a cleaned up data set, even though this is only the first step.</p></li>
</ol>
|
[] |
[
{
"body": "<p>While this is a good start, there are several things that should be noted.</p>\n\n<blockquote>\n <p>r = requests.get(\"<a href=\"http://citibikenyc.com/stations/json\">http://citibikenyc.com/stations/json</a>\")</p>\n</blockquote>\n\n<p>This is code snippet is network-based, and so errors may occur. You will want to handle these errors in some way, with a <code>try-except</code> block like so:</p>\n\n<pre><code>try:\n r = requests.get(\"http://citibikenyc.com/stations/json\")\nexcept ConnectionError:\n pass # handle the error\nexcept TimeoutError:\n pass # handle the error\n</code></pre>\n\n<p>and so on, as per <a href=\"http://docs.python-requests.org/en/latest/user/quickstart/#timeouts\">the requests documentation</a>.</p>\n\n<p>Additionally, do not sleep and do in the same function. These are two responsibilities and so should be separated as per the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\">Single Responsibility Principle</a>.</p>\n\n<p>I would suggest adding the <code>sleep(62)</code> to the <code>while True:</code> block.</p>\n\n<p>Also, there is no point to this:</p>\n\n<blockquote>\n <p>exit()</p>\n</blockquote>\n\n<p>as it will never be executed. This leads me to my next point, you should probably do the file writing in Python instead of the command line, so you can open the file, append some data, and then close it to make sure it is safe between network errors and power outages. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-21T21:41:51.647",
"Id": "60757",
"ParentId": "27774",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T19:38:57.170",
"Id": "27774",
"Score": "8",
"Tags": [
"python",
"json",
"timer"
],
"Title": "Timed requests and parsing JSON in Python"
}
|
27774
|
<p>I am doing interview studies and can't find a simple DFS for a cycle-finding algorithm. I want someone to tell me if my DFS algorithm works and how it can be improved.</p>
<p>Where can you get a typical DFS cycle finding algorthm for Java? I assume you have to "mark" the nodes and edges in order to find a cycle? Can you simplify / improve it? <em>e.g. A-->B-->A , shouldn't be a cycle!</em></p>
<pre><code>boolean isCycled(Node root){
return isCycled(root, -1);
}
boolean isCycled(Node n, int edgeNum){
//base case
if(n==null) return false;
//base case: if an unexplored edge that lead to a node that is visited.
if(edgeNum>=0){//make sure it is not the first node
if(n.visted==true && edge[edgeNum]!=true ) {
return true; //found cycle
}
}
n.visited=true;
edge[edgeNum]==true; // already explored edge wont' lead to cycle.
List nodes = getAllNeigbors(n); //visited or unvisited
boolean isCycle = false;
for(Node node : nodes){
isCycle = isCycle || isCycled(node, getEdgeNum(n,node));
}
return isCycle;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-18T07:44:58.337",
"Id": "44971",
"Score": "1",
"body": "Why would `A -> B -> A` not be a cycle? Can different nodes have the same name? If so, how do you distinguish nodes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T10:54:44.350",
"Id": "59427",
"Score": "0",
"body": "`edge[edgeNum]==true;` compilation error. I think it's a copy-paste typo."
}
] |
[
{
"body": "<p>There are a couple of suggestions I have here.</p>\n\n<p>The first is a major performance one... you have the code:</p>\n\n<pre><code>boolean isCycle = false;\nfor(Node node : nodes){ \n isCycle = isCycle || isCycled(node, getEdgeNum(n,node)); \n}\nreturn isCycle;\n</code></pre>\n\n<p>This should be 'short-circuited' for true conditions, and should simply be:</p>\n\n<pre><code>for(Node node : nodes){ \n if (isCycled(node, getEdgeNum(n,node))) {\n return true;\n } \n}\nreturn false;\n</code></pre>\n\n<p>There is no need to continue to walk the entire tree and find every cycle after yu have found one already!</p>\n\n<p>The second item is more minor, and just something I would 'try'....</p>\n\n<p>Instead of using the edge management, and <code>visited</code> tate on the nodes, I would consider using an IdentityHashMap to track what has been seen or not. Treat it like a 'stack' using <code>put()</code> and <code>remove()</code> like push and pop. That way yon can do something like:</p>\n\n<pre><code>//base case: if an unexplored edge that lead to a node that is visited.\n// if(edgeNum>=0){//make sure it is not the first node\n if(seenmap.contains(node)) {\n return true; //found cycle\n }\n// }\n\nfor(Node node : nodes){\n seenmap.put(node, null); \n isCycle = isCycle || isCycled(node, getEdgeNum(n,node)); \n seenmap.remove(node); \n}\n</code></pre>\n\n<p>If your comment about the <code>A-->B-->A</code> not being a cycle means that if a node points back to where it came from , it's not a cycle, then I recommend passing in the 'source' when you walk the graph... for example:</p>\n\n<pre><code>boolean isCycled(Node n, Node from, int edgeNum){\n</code></pre>\n\n<p>and then, your logic will look like:</p>\n\n<pre><code>for(Node node : nodes){\n if (node == from) {\n // this is a point-back to where we just came from in the graph)\n return false;\n }\n seenmap.put(node, null); \n isCycle = isCycle || isCycled(node, n, getEdgeNum(n,node)); \n seenmap.remove(node); \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T05:13:58.280",
"Id": "36267",
"ParentId": "27776",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T19:55:14.687",
"Id": "27776",
"Score": "4",
"Tags": [
"java",
"depth-first-search"
],
"Title": "Java cycle detection using DFS in an undirected graph"
}
|
27776
|
<p>I figure that someone here probably knows a much better way to do this. I'm still figuring out AJAX and jQuery, so I consider that I still need to master quite a bit of knowledge. </p>
<p>My function extends Foundation 4 Reveal's functionality in a few ways:</p>
<ul>
<li>Uses WordPress AJAX to dynamically pull in content to populate a modal div.</li>
<li>Centers the modal div and allows it to be variable width.</li>
<li>Adds paging navigation from the modal window that when triggered will close the open modal window, then open the previous/next modal content.</li>
</ul>
<p>While I feel like I've managed to figure out a lot on my own, my code isn't optimal; I would greatly appreciate any feedback or insights on ways to improve it, or things that I should avoid.</p>
<pre><code>(function($) {
$.fn.displayPost = function() {
event.preventDefault();
var post_id = $(this).data("id");
var id = "#" + post_id;
// Check if the reveal modal for the specific post id doesn't already exist by checking for it's length
if($(id).length == 0 ) {
// We'll add an ID to the new reveal modal; we'll use that same ID to check if it exists in the future.
var modal = $('<div>').attr('id', post_id ).addClass('reveal-modal').appendTo('body');
var ajaxURL = MyAjax.ajaxurl;
$.ajax({
type: 'POST',
url: ajaxURL,
data: {"action": "load-content", post_id: post_id },
success: function(response) {
modal.empty().html(response).append('<a class="close-reveal-modal">&#215;</a>').foundation('reveal', 'open');
modal.bind('opened', function() {
// Reset visibility to hidden and set display: none on closed reveal-modal divs, for some reason not working by default when reveal close is triggered on .secondary links
$(".reveal-modal:not('.reveal-modal.open')").css({'visibility': 'hidden', 'display' : 'none'})
// Trigger resize
$(window).trigger('resize');
return false;
});
}
});
}
//If the div with the ID already exists just open it.
else {
$(id).foundation('reveal', 'open');
}
// Recalculate left margin on window resize to allow for absolute centering of variable width elements
$(window).resize(function(){
var left;
left = Math.max($(window).width() - $(id).outerWidth(), 0) / 2;
$(id).css({
left:left + $(window).scrollLeft()
});
});
}
})(jQuery);
// Apply the function when we click on the .reveal link
// (document).ready won't work on any reveal-modal divs added subsequently
// after page load via AJAX so use .on instead.
jQuery(document).on("click", ".reveal,.secondary", function() {
jQuery(this).displayPost();
});
// Close open modal via secondary paging links; target parent div id.
jQuery(document).on("click", ".secondary", function() {
var id = jQuery(this).closest("div").attr("id");
jQuery(id).foundation('reveal', 'close');
});
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p><strong>L15</strong>, <strong>L26</strong>, <strong>L31-60</strong>: Inconsistent indentation levels.</p></li>\n<li><p><strong>L4-43</strong>: Consider indenting this block.</p></li>\n<li><p><strong>L04</strong>: I don't see the point in storing the ID rather than the jQuery object itself. Instead of <code>var id = \"#\" + post_id;</code>, go ahead and store the object: <code>var $id = $(\"#\" + post_id);</code>. Modify the references as appropriate on <strong>L11</strong> and <strong>L33</strong>.</p></li>\n<li><p><strong>L13</strong>: Your code for appending the modal is nice in terms of the builder pattern, but it might be better just as:</p>\n\n<pre><code>var modal = $(\"<div class='reveal-modal' id='\" + post_id + \"'></div>\").appendTo(\"body\")\n</code></pre></li>\n<li><p><strong>L14</strong>: There's no point in declaring the <code>ajaxURL</code> variable. Instead, just go ahead and use <code>{ ... url: MyAjax.ajaxurl, ... }</code> on <strong>L17</strong>,</p></li>\n<li><p><strong>L20</strong>: The jQuery API documentation on <code>.html()</code> <a href=\"http://api.jquery.com/html/#html2\" rel=\"nofollow\">notes a specific case</a> in which it's important to use <code>.empty().html()</code>. I don't believe this applies in your case; you don't need the call to <code>.empty()</code> since <code>.html()</code> will effectively empty the container first.</p></li>\n<li><p><strong>L21</strong>: Since jQuery 1.7, <a href=\"http://api.jquery.com/bind/\" rel=\"nofollow\"><code>.on()</code> is preferred</a>.</p></li>\n<li><p><strong>L58-59</strong>: This part is at best senseless and wrong, and at worst unintuitive and potentially deceptive. By extracting the ID attribute and using it as a selector, you're effectively matching against the ID without the <code>#</code>. This either means that it doesn't do what you think it does, in which case you should use:</p>\n\n<pre><code>jQuery(this).closest(\"div\").foundation(\"reveal\", \"close\");\n</code></pre>\n\n<p>or you for some reason have a construct like <code><div id='span'></code> and you really mean to match all <code>span</code> elements instead of <code>#span</code>. In that case, I strongly suggest you restructure your HTML to be more semantically sensible, and to leave a comment explicitly detailing that that's your intention.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-08T05:03:47.247",
"Id": "56402",
"ParentId": "27779",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T20:07:39.037",
"Id": "27779",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"ajax",
"plugin",
"wordpress"
],
"Title": "Plugin for WordPress and Foundation Reveal"
}
|
27779
|
<p>This little program is self-explanatory. I count letters in a string (can be any string), using a <code>for</code> loop to iterate through each letter. The problem is that this method is very slow and I want to avoid loops.</p>
<p>Any ideas? I thought that maybe if I remove checked letters from the string after each loop, then in some cases, where many letters repeat, that would make a difference.</p>
<pre><code>def count_dict(mystring):
d = {}
# count occurances of character
for w in mystring:
d[w] = mystring.count(w)
# print the result
for k in sorted(d):
print (k + ': ' + str(d[k]))
mystring='qwertyqweryyyy'
count_dict(mystring)
</code></pre>
<p>The output:</p>
<pre><code>e: 2
q: 2
r: 2
t: 1
w: 2
y: 5
</code></pre>
|
[] |
[
{
"body": "<p>Use the built in <code>Counter</code> in the <code>collections</code> module:</p>\n\n<pre><code>>>> from collections import Counter\n>>> Counter('qwertyqweryyyy')\nCounter({'y': 5, 'e': 2, 'q': 2, 'r': 2, 'w': 2, 't': 1})\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T22:53:21.943",
"Id": "27784",
"ParentId": "27781",
"Score": "15"
}
},
{
"body": "<p>Counter is definitely the way to go (and I've upvoted Jaime's answer).</p>\n\n<p>If you want to do it yourself and iterate only once, this should work :</p>\n\n<pre><code>d={}\nfor l in s:\n d[l] = d.get(l,0) + 1\n</code></pre>\n\n<p>There might be a short/more pythonic way to do so but it works...</p>\n\n<p><strong>Edit</strong> : \nI must confess that Jaime's comment to this answer surprised me but I've just tested this code :</p>\n\n<pre><code>from profilehooks import profile\n\ns=\"qwertyuiopasdfghjklzxcvbnm\"\n\n@profile\ndef function1(s):\n d={}\n for l in s:\n d[l] = d.get(l,0)+1\n return d\n\n@profile\ndef function2(s):\n return dict((char_, s.count(char_)) for char_ in set(s))\n\nfor i in xrange(0,200):\n function1(s*i)\n function2(s*i)\n</code></pre>\n\n<p>And the results can hardly be contested :</p>\n\n<pre><code>*** PROFILER RESULTS ***\nfunction2 (./fsdhfsdhjk.py:13)\nfunction called 200 times\n\n 10948 function calls in 0.161 seconds\n\n Ordered by: cumulative time, internal time, call count\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 200 0.083 0.000 0.161 0.001 fsdhfsdhjk.py:13(function2)\n 5374 0.033 0.000 0.077 0.000 fsdhfsdhjk.py:15(<genexpr>)\n 5174 0.044 0.000 0.044 0.000 {method 'count' of 'str' objects}\n 200 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n 0 0.000 0.000 profile:0(profiler)\n\n\n\n*** PROFILER RESULTS ***\nfunction1 (./fsdhfsdhjk.py:6)\nfunction called 200 times\n\n 517800 function calls in 2.891 seconds\n\n Ordered by: cumulative time, internal time, call count\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 200 1.711 0.009 2.891 0.014 fsdhfsdhjk.py:6(function1)\n 517400 1.179 0.000 1.179 0.000 {method 'get' of 'dict' objects}\n 200 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n 0 0.000 0.000 profile:0(profiler)\n</code></pre>\n\n<p><strong>TL;DR</strong>\nJaime's solution (<code>function2</code>) is 18 times faster than mine (<code>function1</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T23:12:48.610",
"Id": "43383",
"Score": "4",
"body": "This would be the right way of doing things in a language such as C. Because Python loops have so much overhead, it actually may turn out to be faster to do something like: `char_counts = dict((char_, test_string.count(char_)) for char_ in set(test_string))` It does run multiple times over the string, but because the loops run in C, not in Python, it is faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T23:32:28.317",
"Id": "43385",
"Score": "0",
"body": "I am really really impressed. I've updated my answer accordingly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T03:38:15.833",
"Id": "43389",
"Score": "3",
"body": "I tested it on a 10**6 character string and there it was only 4x faster. It's one of the few things I don't like about Python, that sometimes optimizing code is not about writing the most efficient algorithm, but about figuring out which built-in functions run faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T06:31:05.757",
"Id": "43393",
"Score": "0",
"body": "Yes, as function2 loops roughly (x+1) times on the string (x being the number of different characters), I can imagine that the performance gain, compared to function 1 looping only once, gets smaller as x and the string get bigger. Still, this is a damn long string :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T20:37:05.523",
"Id": "43537",
"Score": "0",
"body": "This is my first experience with python profiler. I ran cProfile on several methods and surprisingly, my original method took less function calls than suggested Counter, even though all methods take exactly the same amount of time (I had a relatively short string).\n\nI am running profiler with \n\n`$ python -m cProfile -s time test.py`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T21:43:45.900",
"Id": "27820",
"ParentId": "27781",
"Score": "6"
}
},
{
"body": "<p>This is the shortest answer I can think of:</p>\n\n<pre><code>{i:str.count(i) for i in str}\n</code></pre>\n\n<p>This is called Dictionary comprehension, which is an efficient way to get the count of each alphabet in the string as a letter(key):count(value) pair.</p>\n\n<p>Example:</p>\n\n<pre><code>str = \"StackExchange\" \n{i:str.count(i) for i in str} \n{'a': 2, 'c': 2, 'E': 1, 'g': 1, 'h': 1, 'k': 1, 'n': 1, 'S': 1, 't': 1, 'x': 1, 'e': 1}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-29T03:25:17.660",
"Id": "85278",
"ParentId": "27781",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27784",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-06-25T21:43:08.603",
"Id": "27781",
"Score": "11",
"Tags": [
"python",
"strings"
],
"Title": "Counting letters in a string"
}
|
27781
|
<p>I'm working on a communications layer for a system that reads data from a TCPIP client that is formatted as fixed-width ASCII (yeah, old school). I was quite surprised that there seemed to be no built in way to do this, and ended up using the following simple StreamReader subclass:</p>
<pre><code>/// <summary>
/// A Stream reader that reads values as fixed width fields from a stream
/// </summary>
class FixedWidthFieldStreamReader : StreamReader
{
#region Private/Protected fields
private char[] buffer; // Local buffer used to copy data before conversion
#endregion
#region Methods
/// <summary>
/// Instantiates a new FixedWidthFieldStreamReader for a stream
/// </summary>
/// <param name="stream">Stream to read from</param>
/// <param name="initialBufferSize">Initial size of the buffer used to copy data before formatting</param>
/// <param name="encoding">Encoding to use when reading from the stream</param>
public FixedWidthFieldStreamReader(Stream stream, int initialBufferSize, Encoding encoding)
: base(stream, encoding)
{
buffer = new char[initialBufferSize];
}
/// <summary>
/// Checks if the buffer exists and is large enough,
/// and allocates or grows it if necessary.
/// </summary>
/// <param name="length">The required buffer length</param>
private void EnsureBufferLength(int length)
{
if (null == buffer ||
buffer.Length < length)
{
buffer = new char[length];
}
}
/// <summary>
/// Reads a number of bytes into the buffer
/// </summary>
/// <param name="length">The number of bytes to read</param>
/// <returns>True if the required number of bytes was read, false otherwise</returns>
private bool ReadToBuffer(int length)
{
EnsureBufferLength(length);
// Read from the stream
int read = Read(buffer, 0, length);
return read == length;
}
/// <summary>
/// Reads a specified number of bytes from the stream and
/// converts and returns the read value.
/// </summary>
/// <typeparam name="T">Type of the object to read and return</typeparam>
/// <param name="length">Number of bytes in the field to read from the stream.</param>
/// <returns>The read object if successful, or the default value for the type otherwise.</returns>
public T Read<T>(int length) where T : IConvertible
{
if (ReadToBuffer(length))
{
return (T)Convert.ChangeType(new string(buffer, 0, length), typeof(T));
}
return default(T);
}
/// <summary>
/// Skips a specified number of bytes in the stream
/// </summary>
/// <param name="length">The number of bytes to skip</param>
public void Skip(int length)
{
// Ideally we should be able to just seek on the current stream,
// but that seems to seek to an incorrect location?
//this.BaseStream.Seek(length, SeekOrigin.Current);
ReadToBuffer(length);
}
#endregion
}
</code></pre>
<p>This would be used something like this:</p>
<pre><code>using (MemoryStream stream = new MemoryStream(buffer))
{
stream.Seek((int)FieldOffsets.DATA, SeekOrigin.Begin);
using (FixedWidthFieldStreamReader reader = new FixedWidthFieldStreamReader(stream, 15, Encoding.ASCII))
{
intVal = reader.Read<int>(3);
stringVal = reader.Read<string>(15);
floatVal= reader.Read<float>(5);
}
}
</code></pre>
<p>I have two questions based on this:</p>
<ol>
<li>Am I just missing some completely obvious existing utility to do this? It really does seem like a common problem that would have been solved by the framework team ages ago.</li>
<li>Aside from the obvious optimization of having some type specific versions of Read that don't do the conversion, are there any suggestions to improve this approach?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T08:03:46.760",
"Id": "43287",
"Score": "0",
"body": "I considered posting there as well, but thought since the primary question was really \"is there a better way to do this?\" here would be more appropriate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-29T11:52:43.977",
"Id": "117307",
"Score": "0",
"body": "There is an example of implementation of Mika Kolari's suggestion here: http://stackoverflow.com/questions/26060441/reading-data-from-fixed-length-file-into-class-objects/26099038#26099038"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-31T20:38:34.070",
"Id": "273728",
"Score": "0",
"body": "An alternative approach is to use [C# CSV Reader](http://www.csharpcsvreader.com/). More info: [http://csvreader.readthedocs.io/en/latest/FixedWidthFileReader/](http://csvreader.readthedocs.io/en/latest/FixedWidthFileReader/)"
}
] |
[
{
"body": "<p>I don't know if something does that already, but you could mimic <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute.aspx\" rel=\"nofollow\">StructLayout</a> if you need to read multiple types of 'objects' or need reusability.</p>\n\n<p>Basically just set starting point/offset and length for each property and read them.</p>\n\n<pre><code>public class Item\n{\n // 3 chars starting from 0\n [Layout(0, 3)]\n public int Number { get; set; }\n\n // 15 chars starting from 3\n [Layout(3, 15)]\n public string Text { get; set; } \n\n // 5 chars starting from 18\n [Layout(18, 5)]\n public float Number2 { get; set; } \n}\n\nreader.Read<Item>()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T08:22:44.230",
"Id": "43328",
"Score": "0",
"body": "+1 this is the way to go. In addition to explicit struct layout you could also look at [fixed size buffers](http://msdn.microsoft.com/en-us/library/zycewsya.aspx)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T07:59:17.280",
"Id": "43403",
"Score": "0",
"body": "That is much more readable, good suggestion, thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-19T20:26:25.310",
"Id": "115833",
"Score": "0",
"body": "@FlintZA, just curious, feel like updating your post to you final version of the class using attributes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-24T12:03:50.420",
"Id": "116506",
"Score": "0",
"body": "@Terry unfortunately I haven't been able to justify refactoring with the attribute version. The original is working really well. It's on the todo list, but really, really low down below higher priority stuff :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-01T19:05:45.657",
"Id": "117837",
"Score": "1",
"body": "@FlintZA - I'm not sure what protocol here is, but given I just wrote up a slightly more generic version of the answer above (and posted by Giuseppe at SO) with Generics, LayoutAttribute, Compiled Expression Trees and Convert.ChangeType, I didn't post a new answer or code here. You can, however, read my blog post on this and see the sample code at http://terryaney.wordpress.com/2014/10/01/fixedwidthstreamreader-conceived-from-death/. Should I have posted new answer/code here or? Just following http://www.hanselman.com/blog/YourWordsAreWasted.aspx :)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-14T12:08:11.273",
"Id": "121334",
"Score": "0",
"body": "Thanks @Terry. Philosophical discussions about Hansel's view aside, if I did have to implement this I'd also need to take into account that in some cases the object layout does change. Most notably there are contained objects of which one of the fields specifies the count."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T07:31:09.890",
"Id": "27793",
"ParentId": "27782",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "27793",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T09:25:22.707",
"Id": "27782",
"Score": "3",
"Tags": [
"c#",
"stream"
],
"Title": "Reading fixed-width data fields in .NET"
}
|
27782
|
<p>We have a lot of phone numbers that contain dashes and start with a zero which are from another country.</p>
<p>I am trying to strip the dashes and the one leading zero and select the country code from a drop-down box.</p>
<p>I'm using "raw" JS with DOM here (for the sake of not having to pull in a framework):</p>
<pre><code><html>
<head><title>Dash Remover</title></head>
<body>
<form method="POST">
<select id="countryCallingCode">
<option value="0043">+43</option>
<option value="0044">+44</option>
<option value="0049">+49</option>
<option value="">Other</option>
</select>
<input id="numbertodial" type="text" size="16"
oninput="prepareTelNo()" />
<button name="callBtn" onclick="callTelNo();">Call!</button>
</form>
<script>
function getCCC() { return document.getElementById('countryCallingCode').value; }
function prepareTelNo() {
var wd = document.getElementById('numbertodial');
wd.value = wd.value.replace(/-/g, ''); // strip - from the tel. no.
// Cut off leading zeros
if(wd.value.charAt(0) === '0' & getCCC() != "")
wd.value = wd.value.substring(1);
}
function callTelNo() {
var telNo = document.getElementById('numbertodial').value;
window.alert('Calling '+getCCC()+telNo);
}
</script>
</body>
</html>
</code></pre>
<p>Any room for improvement? I know that <code>oninput</code> <a href="https://stackoverflow.com/questions/574941/best-way-to-track-onchange-as-you-type-in-input-type-text/574971#574971">is only supported in some browsers</a>. </p>
<p>That's ok, it's for an intranet app that is usually used with IE 10.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T01:35:19.567",
"Id": "43302",
"Score": "0",
"body": "You're only cutting off 'a' leading zero (and not all of them), (all that needs fixing is changing that if to a while). You're also not caching your selectors (not a big deal if that's all your JS). Maybe use addEventListener in favor of inlining onclick or oninput. Other than that your code looks fine :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T01:57:35.273",
"Id": "43303",
"Score": "0",
"body": "Thanks. We only happen to have numbers with one leading zero, so that's ok. I'll try addEventListener instead. Thanks!"
}
] |
[
{
"body": "<p>Just a few points</p>\n\n<ul>\n<li><p>You're missing a <code>&</code> in your <code>if</code> conditional. Right now you're doing a bitwise AND, rather than a logical AND (which would be <code>&&</code>).</p></li>\n<li><p>I'd say you should always use curly braces, even for one-liners. JS accepts one-liners just fine, but as a code-hygiene thing it's better to have braces there, I think.</p></li>\n<li><p>You could rewrite the reg exp to remove <em>everything</em> that isn't a numerical digit (instead of only removing dashes). I don't know if that's what you need, but if it is</p>\n\n<pre><code>wd.value = wd.value.replace(/[^\\d]/g, \"\"); // remove all non-digit characters\n</code></pre></li>\n<li><p>You also could use a little more reg exp to make sure you remove all leading zeros (even if you say there's only going to be 1). Incidentally, this allows you to skip the \"starts with zero\" check, and only have the <code>getCCC() != \"\"</code> check. Point is, you can do a replace for leading zeros specifically, rather than \"blindly\" chopping something off of the string.</p></li>\n</ul>\n\n<hr>\n\n<pre><code>function prepareTelNo() {\n var wd = document.getElementById('numbertodial');\n wd.value = wd.value.replace(/-/g, ''); // strip - from the tel. no.\n\n // Cut off leading zeros if a country code is set\n if(getCCC() != \"\") {\n wd.value = wd.value.replace(/^0+/, \"\"); // cuts off all leading zeros\n }\n}\n</code></pre>\n\n<p>If you really, truly only want to remove 1 leading zero rather than all of them, use <code>/^0/</code> (without the plus sign) as the reg exp pattern.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T20:08:30.937",
"Id": "43432",
"Score": "0",
"body": "Nice suggestion! I see again: I really need to improve my regexp knowledge :). Thanks again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T19:22:18.133",
"Id": "27815",
"ParentId": "27787",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27815",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T01:07:26.613",
"Id": "27787",
"Score": "3",
"Tags": [
"javascript",
"strings",
"dom"
],
"Title": "String processing in JavaScript"
}
|
27787
|
<p>I have this ExpressJS route for saving and listing <code>Category</code> model.</p>
<pre><code>exports.save = function(req, res, next){
//validate here>>>
var name = req.body.name;
var description = req.body.description;
new Category({
name: name,
description: description,
}).save(function(err, docs){
if ( err ) {
console.log('error: saving category');
next(error);
}else{
console.log('category saved.');
res.redirect('categories');
}
});
}
exports.list = function(req, res, next){
Category.find(function ( err, categories, count ){
if (err) {
console.log('error: listing categories');
next(error);
}
res.render( 'categories/list', {
categories : categories
});
});
}
</code></pre>
<p>Is having <code>console.log</code> and <code>next(error)</code> OK? How could I improve the above code in terms of conventions in NodeJS / ExpressJS?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T17:23:00.240",
"Id": "127954",
"Score": "0",
"body": "Instead of the [`console.log`](http://nodejs.org/api/stdio.html#stdio_console_error_data) you could use `console.error` to print errors. It's the same as `console.log` but it prints to stderr. I bet you've seen [this](http://expressjs.com/guide.html#error-handling) in the documentation of express.js."
}
] |
[
{
"body": "<p>I assume you have a typo there, <code>error</code> is nowhere defined but you do have <code>err</code>.</p>\n\n<p>To jackdbernier's point, you should read the docs:\n<a href=\"http://expressjs.com/guide.html#users-online\" rel=\"nofollow\">http://expressjs.com/guide.html#users-online</a></p>\n\n<p>In there it is clear that you should call <code>next</code> regardless whether you have an error or not, otherwise not all middlewares will be processed.</p>\n\n<p>If you insist on logging before call next, you could.</p>\n\n<pre><code>function handleError( message , err , next )\n{\n console.error( message );\n return next( err );\n}\n\nnew Category({\n name: name,\n description: description,\n}).save(function(err, docs){\n if ( err ){\n return handleError( 'error: saving category' , err, next );\n } \n console.log('category saved.');\n res.redirect('categories');\n next(); // <- this!\n});\n}\n</code></pre>\n\n<p>Though I would personally drop the curly braces from that <code>if( err )</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T17:57:43.720",
"Id": "40983",
"ParentId": "27788",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T02:03:01.103",
"Id": "27788",
"Score": "2",
"Tags": [
"javascript",
"error-handling",
"mongodb",
"express.js"
],
"Title": "Saving and listing Category model"
}
|
27788
|
<p>This code doesn't look too good. Could anyone help me format it?</p>
<pre><code>private void initComparisonDatatable() {
List<BrandProfitAndLoss> brandProfitAndLossComparisonDatatable = new ArrayList<BrandProfitAndLoss>();
BrandProfitAndLoss brandProfitAndLossCurrentYear = new BrandProfitAndLoss();
BrandProfitAndLoss brandProfitAndLossPreviousYear = new BrandProfitAndLoss();
// if the selected year is null and the previous year is not null
if(brandActionForm.getBrandProfitLossList().size() <= 0 && brandActionForm.getBrandProfitLossComparisonList().size() > 0){
for(int i = 0; i < brandActionForm.getBrandProfitLossComparisonList().size(); i++){
brandProfitAndLossPreviousYear = brandActionForm.getBrandProfitLossComparisonList().get(i);
brandProfitAndLossCurrentYear = new BrandProfitAndLoss(brandActionForm.getBrandProfitLossComparisonList().get(i).getDate(), brandActionForm.getDateMode(), Consts.CURRENT_YEAR);
brandProfitAndLossComparisonDatatable.add(brandProfitAndLossCurrentYear);
brandProfitAndLossComparisonDatatable.add(brandProfitAndLossPreviousYear);
brandProfitAndLossComparisonDatatable.add(new BrandProfitAndLoss().getAllRateComparisonRecords(brandProfitAndLossCurrentYear
, brandProfitAndLossPreviousYear));
}
}
// the selected year is not null
else {
for(int i = 0; i < brandActionForm.getBrandProfitLossList().size(); i++){
brandProfitAndLossCurrentYear = brandActionForm.getBrandProfitLossList().get(i);
brandProfitAndLossComparisonDatatable.add(brandProfitAndLossCurrentYear);
if(brandActionForm.getBrandProfitLossComparisonList().size() > 0){
brandProfitAndLossPreviousYear = brandActionForm.getBrandProfitLossComparisonList().get(i);
brandProfitAndLossComparisonDatatable.add(brandProfitAndLossPreviousYear);
brandProfitAndLossComparisonDatatable.add(new BrandProfitAndLoss().getAllRateComparisonRecords(brandProfitAndLossCurrentYear
, brandProfitAndLossPreviousYear));
}
else {
brandProfitAndLossPreviousYear = new BrandProfitAndLoss(brandActionForm.getBrandProfitLossList().get(i).getDate(), brandActionForm.getDateMode(), Consts.CURRENT_YEAR);
brandProfitAndLossComparisonDatatable.add(brandProfitAndLossPreviousYear);
brandProfitAndLossComparisonDatatable.add(new BrandProfitAndLoss().getAllRateComparisonRecords(brandActionForm.getBrandProfitLossList().get(i)
, brandProfitAndLossPreviousYear));
}
}
}
brandActionForm.setBrandProfitLossComparisonListForDatatable(brandProfitAndLossComparisonDatatable);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T07:41:15.270",
"Id": "43325",
"Score": "2",
"body": "What is this method supposed to do in plain English? Method name doesn't help."
}
] |
[
{
"body": "<p>Some problems that could be seen without actually understanding code:</p>\n\n<ul>\n<li>Unhelpful and possibly misleading comments: <code>// the selected year is not null</code></li>\n<li>Repeating type in variable name : <code>brandProfitAndLossCurrentYear</code></li>\n<li>Using ad hoc code instead of using appropriate library methods: <code>list.size() <= 0</code> instead of <code>list.isEmpty()</code> and <code>list.size() > 0</code> instead of <code>!list.isEmpty()</code></li>\n<li><p>Long method doing more than one thing: <code>initComparisonDatatable</code> retrieve data from form, calculate something based using said data, modify form using calculated data</p></li>\n<li><p>Feature Envy: Since <code>initComparisonDatatable</code> acts on <code>brandActionForm</code> and uses only data from <code>brandActionForm</code> it belongs to <code>brandActionForm</code>.</p></li>\n<li><p>Repetitive code: body of the three loops are repeated with minor variations.</p></li>\n</ul>\n\n<p>There are probable design issues, but those cannot be addressed properly without further clarification. For example <code>new BrandProfitAndLoss().getAllRateComparisonRecords</code> suggests <code>BrandProfitAndLoss</code> has some data access code in it, therefore should be moved elsewhere; it probably is a class method instead of an instance method; and since it is a class method it probably has dependency issues, I can smell an evil singleton from here.</p>\n\n<p>How refactored code could look like, (since loops and conditional statements have been changed these will definitely break something, so <strong><em>do not try to use it in production</em></strong> without proper unit testing):</p>\n\n<pre><code> private void initComparisonDatatable() {\n List<BrandProfitAndLoss> comparisonDatatable = listForDatatable(\n brandActionForm.getBrandProfitLossComparisonList(), \n brandActionForm.getBrandProfitLossList(), \n brandActionForm.getDateMode());\n\n brandActionForm.setBrandProfitLossComparisonListForDatatable(comparisonDatatable);\n }\n\n private static List<BrandProfitAndLoss> listForDatatable(\n List<BrandProfitAndLoss> brandProfitLossComparisonList,\n List<BrandProfitAndLoss> brandProfitLossList, Object dateMode) {\n List<BrandProfitAndLoss> comparisonDatatable = new ArrayList<BrandProfitAndLoss>();\n\n int prevYearSize = brandProfitLossComparisonList.size();\n int currentYearSize = brandProfitLossList.size();\n int size = Math.max(prevYearSize, currentYearSize);\n\n for (int i = 0; i < size; i++) {\n BrandProfitAndLoss ofPreviousYear = (i < prevYearSize) \n ? brandProfitLossComparisonList.get(i) \n : null;\n\n BrandProfitAndLoss ofCurrentYear = (i < currentYearSize) \n ? brandProfitLossList.get(i) \n : null;\n\n if (ofPreviousYear == null) {\n ofPreviousYear = new BrandProfitAndLoss(\n ofCurrentYear.getDate(), dateMode, Consts.CURRENT_YEAR);\n }\n\n if (ofCurrentYear == null) {\n ofCurrentYear = new BrandProfitAndLoss(\n ofPreviousYear.getDate(), dateMode, Consts.CURRENT_YEAR);\n }\n\n comparisonDatatable.add(ofCurrentYear);\n comparisonDatatable.add(ofPreviousYear);\n comparisonDatatable\n .add(new BrandProfitAndLoss().getAllRateComparisonRecords(\n ofCurrentYear, ofPreviousYear));\n }\n\n return comparisonDatatable;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T08:32:56.033",
"Id": "27794",
"ParentId": "27791",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "27794",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T06:41:52.227",
"Id": "27791",
"Score": "1",
"Tags": [
"java"
],
"Title": "Initialize comparison datatable"
}
|
27791
|
<p>I finally got my upload form and code that uploads to db. I used tutorial from <a href="http://www.icraftzone.com/2012/06/file-upload-and-download-script-using.html" rel="nofollow">this site</a>.</p>
<p>As I am php newbie, I want to know how secure this code is and if it is not secure at all (which I am almost sure of...) could someone tell me how to make it secure. This upload should be only for pdf, jpeg, jpg, doc files. Also this upload will be available to public.</p>
<pre><code><form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1"
cellspacing="1" class="box">
<tr>
<td>please select a file</td></tr>
<tr>
<td>
<input type="hidden" name="MAX_FILE_SIZE"
value="16000000">
<input name="userfile" type="file" id="userfile">
</td>
<td width="80"><input name="upload"
type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table>
</form>
</body>
</html>
<?php
if(isset($_POST['upload'])&&$_FILES['userfile']['size']>0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fileType=(get_magic_quotes_gpc()==0 ? mysql_real_escape_string(
$_FILES['userfile']['type']) : mysql_real_escape_string(
stripslashes ($_FILES['userfile'])));
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$con = mysql_connect('localhost', 'root', 'root') or die(mysql_error());
$db = mysql_select_db('olearyinternational', $con);
if($db){
$query = "INSERT INTO upload (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
mysql_close();
echo "<br>File $fileName uploaded<br>";
}else { echo "file upload failed"; }
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T05:05:35.747",
"Id": "43391",
"Score": "1",
"body": "You haven't validated the file type. That seems to be most important thing to do."
}
] |
[
{
"body": "<ol>\n<li><p><strong>Restrict file types</strong>:\nAs your concern is security, you should make sure that the file type is one of those you allow.\nFor that you must implement a file type checker, that validates file type is allowed, then you let the user upload the file. Learn how to do that <a href=\"http://php.net/manual/en/function.filetype.php\" rel=\"nofollow noreferrer\">here</a> or at <a href=\"https://stackoverflow.com/questions/6654351/check-file-uploaded-is-in-csv-format\">stackOverflow</a>.</p></li>\n<li><p><strong>Upload Size</strong> You may like to have max upload size, so users do not upload too large files. Find how to do that at <a href=\"http://phpmaster.com/file-uploads-with-php/\" rel=\"nofollow noreferrer\">phpmaster</a>.</p></li>\n<li><p><strong>Check the referrer</strong>: Check to make sure that the information being sent to your script is from your website and not an outside source. While this information can be faked, it's still a good idea to check.</p></li>\n<li><p><strong>Rename files</strong>: You can rename the files that are uploaded. In doing so, check for double-barreld extensions like yourfile.php.gif and eliminate extensions you don't allow, or remove the file completely.</p></li>\n<li><p><strong>Change permissions:</strong> Change the permissions on the upload folder so that files within it are not executable. Your FTP program probably allows you to chmod right from it.</p></li>\n<li><p><strong>Login and Moderate:</strong> Making your users login might deter some deviant behavior. You can also take the time to moderate all file uploads before allowing them to become live on the web.</p></li>\n<li><p><strong>Keep away from root</strong>: If your document root is /var/www/html, create a directory /var/www/uploads and use it to store uploaded files. That way, an attacker will not be able to retrieve the file directly. This will allow you to provide fine grained access control. The file will not be parsed by the server's application language module but the source of the file will be streamed.</p></li>\n<li><p><strong>Malware Scan</strong>:\nThe extension is right, and you checked that the file is actually a valid JPEG file per it's header. However, it could still be a malicious JPEG using one of the many image parser bugs to exploit clients downloading the file. There is no great defense against this as far as I am aware. One possible work around is to \"rebuild\" the file. Convert the JPEG to a GIF and back to a JPEG. This will likely strip out any malicious feature. But this technique could expose your servers to just the same image parser bugs.</p></li>\n</ol>\n\n<p>Here are some links to help,</p>\n\n<p><a href=\"http://software-security.sans.org/blog/2009/12/28/8-basic-rules-to-implement-secure-file-uploads/\" rel=\"nofollow noreferrer\">http://software-security.sans.org/blog/2009/12/28/8-basic-rules-to-implement-secure-file-uploads/</a></p>\n\n<p><a href=\"http://webcheatsheet.com/PHP/file_upload.php\" rel=\"nofollow noreferrer\">http://webcheatsheet.com/PHP/file_upload.php</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T05:18:21.663",
"Id": "27828",
"ParentId": "27796",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T09:01:31.657",
"Id": "27796",
"Score": "1",
"Tags": [
"php",
"mysql"
],
"Title": "PHP upload to database"
}
|
27796
|
<p>The function <code>arg_to_uint64</code> takes a 0-terminated string and returns an <code>unsigned int</code>. The <code>unsigned int</code> is the integer presentation of <code>arg</code> in decimal or in hex (if prefixed with 0x) as defined in the C language standard.</p>
<pre><code>constexpr char hexprefix[]="0x";
inline std::uint64_t
arg_to_uint64(const char* arg)
{
constexpr std::size_t hexprefix_len=sizeof(hexprefix)-1;
bool is_hex=std::strncmp(arg,hexprefix,hexprefix_len)==0;
int base;
if(is_hex)
{
arg+=hexprefix_len;
base=16;
}
else
base=10;
std::size_t idx;
std::uint64_t r=std::stoull(arg,&idx,base);
if(idx!=std::strlen(arg))
throw std::runtime_error("garbage at the end of input");
return r;
}
</code></pre>
<p>Is there a better/shorter way to do this? My platform is Linux.</p>
<hr>
<p>This is my improved code as described in the answer from William Morris:</p>
<pre><code>inline std::uint64_t
arg_to_uint64(const char* arg)
{
std::size_t idx;
std::uint64_t r=std::stoull(arg,&idx,0);
if(arg[idx]!='\x0')
throw std::runtime_error("garbage at the end of input");
return r;
}
</code></pre>
|
[] |
[
{
"body": "<p>Just use <code>strtoll</code> with a base of 0 </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T16:05:57.473",
"Id": "27810",
"ParentId": "27797",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "27810",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T09:16:36.573",
"Id": "27797",
"Score": "3",
"Tags": [
"c++",
"parsing",
"c++11",
"linux"
],
"Title": "Parsing hex and decimal numbers in C++11"
}
|
27797
|
<p>I am currently working on a project which uses the MVVM pattern. I have a POCO which I want to present in an editor and, because the object is composed from a number of smaller, reusable POCOs, I thought it would be appropriate to show it in a <code>TabControl</code>.</p>
<p>The result looks like this:</p>
<p><img src="https://i.stack.imgur.com/6ix3z.jpg" alt="Picture=1k words"></p>
<p>On the left is a collection of <code>ProductViewModel</code> and on the right is an instance of <code>ProductEditorViewModel</code>.</p>
<p>The editor splits the <code>Product</code> properties into groups - all of which have one or more View/ViewModel pairs. Each ViewModel has an <code>IsDirty</code> property to indicate its' edited status and an <code>IsEditable</code> property which defines whether the content can be edited or not.</p>
<p>What I am finding that it is tricky to get all the ViewModels properly linked together so that the <code>IsEditable</code> status gets passed down into nested ViewModels and that the <code>IsDirty</code> property gets passed up so that, for example, the <code>Save</code> button can be enabled.</p>
<p>I'm trying to keep it all as loose as possible. In the right of the picture is a list of Events with associated Actions. The selected MessageAction (see screen-shot) can itself define lists of Actions which are editable (in a separate dialog window). It can get quite complicated!</p>
<p>Any suggestions appreciated.</p>
<p>Here are some snippets:</p>
<p><strong>At top level</strong></p>
<pre><code> #region COMMAND - EditProductCommand
private ICommand _EditProductCommand;
public ICommand EditProductCommand
{
get
{
if (this._EditProductCommand == null)
{
this._EditProductCommand = new RelayCommand(parm => DoEditProductCommand(), parm => CanDoEditProductCommand());
}
return this._EditProductCommand;
}
}
private bool CanDoEditProductCommand()
{
// can only edit if editor, owner of product and editor not already in use
return (app.CurrentUser.HasRole(Role.ProductEditor))
&& SelectedProduct != null
&& ProductEditorVM.IsDirty == false
&& (SelectedProduct.Product.CheckedOutBy == null // not checked out
|| SelectedProduct.Product.CheckedOutBy.UserGuid == app.CurrentUser.UserGuid); // or owner
}
private void DoEditProductCommand()
{
if (SelectedProduct != null && SelectedProduct.IsCheckedOut == false)
{
CheckoutCommand.Execute(null);
}
ProductEditorVM.EditProduct = SelectedProduct.Product;
ProductEditorVM.IsEditable = true;
}
#endregion
</code></pre>
<p><strong>ProductEditorView</strong></p>
<pre><code> <TabControl Grid.Row="0">
<TabItem Header="{x:Static me:Messages.Tab_Product_Core}">
<ContentControl Content="{Binding CoreEditorVM}" IsEnabled="{Binding IsEditable}"/>
</TabItem>
<TabItem Header="{x:Static me:Messages.Tab_Product_Events}">
<ContentControl Content="{Binding EventTreeVM}"
IsEnabled="{Binding IsEditable}"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</TabItem>
</code></pre>
<p><strong>ProductEditorViewModel</strong></p>
<pre><code>public class ProductEditorViewModel : ViewModelBase
{
private IApplicationManager app;
private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#region PROPERTIES - SELECTED PRODUCT
private IProduct _EditProduct;
public IProduct EditProduct
{
get { return _EditProduct; }
set
{
if (value != _EditProduct)
{
_EditProduct = value;
OnPropertyChanged("EditProduct");
InitialiseProduct(_EditProduct);
}
}
}
#endregion
#region PROPERTIES - CORE
private ProductCoreEditorViewModel _CoreEditorVM;
public ProductCoreEditorViewModel CoreEditorVM
{
get { return _CoreEditorVM; }
set
{
if (value != _CoreEditorVM)
{
_CoreEditorVM = value;
OnPropertyChanged("CoreEditorVM");
}
}
}
#endregion
[... and more ...]
#region CONSTRUCTOR
public ProductEditorViewModel(IApplicationManager app)
{
this.app = app;
CoreEditorVM = new ProductCoreEditorViewModel();
EventTreeVM = new ActionTreeViewModel(app);
HistoryVM = new HistoryViewModel(app);
CoreEditorVM.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(VM_PropertyChanged);
EventTreeVM.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(VM_PropertyChanged);
}
private void InitialiseProduct(IProduct product)
{
CoreEditorVM.Initialise(product);
EventTreeVM.Initialise(product.Events.EventList);
HistoryVM.ItemsList = product == null ? null : app.PersistenceManager.GetProducts(
new ProductCriteria(app.CurrentUser, false).Add(ProductCriteria.HasId(product.ProductGuid)),
false);
IsDirty = false;
}
void VM_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsDirty")
{
UpdateDirty();
}
}
private void UpdateDirty()
{
IsDirty = CoreEditorVM.IsDirty || EventTreeVM.IsDirty;
}
#endregion
</code></pre>
<p><strong>ViewModelBase</strong></p>
<pre><code>public abstract class ViewModelBase : INotifyPropertyChanged, IDisposable
{
bool _isDirty;
public bool IsDirty
{
get { return _isDirty; }
set
{
if (value != IsDirty)
{
_isDirty = value;
OnPropertyChanged("IsDirty");
}
}
}
private bool _IsEditable;
public bool IsEditable
{
get { return _IsEditable; }
set
{
if (value != _IsEditable)
{
_IsEditable = value;
OnPropertyChanged("IsEditable");
}
}
}
private bool _result;
public bool DialogResult
{
get { return _result; }
set
{
_result = value;
OnPropertyChanged("DialogResult");
}
}
[...and more]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T10:24:04.140",
"Id": "43333",
"Score": "0",
"body": "I guess you're going to have to show a bit of code how your ViewModels or POCOs are structured."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T12:17:14.310",
"Id": "43344",
"Score": "0",
"body": "@Abbas - code snippets ready for you ;-)"
}
] |
[
{
"body": "<p>Looks pretty good. Just a few little things:</p>\n\n<ul>\n<li>Command-related methods <code>CanDoXXXX</code> and <code>DoXXXX</code> would be better off named <code>CanExecuteXXXX</code> and <code>ExecuteXXXX</code> or <code>OnExecuteXXXX</code>.</li>\n<li>I would put the ViewModel properties <code>IsEditable</code> and <code>IsDirty</code> in some <code>IEditable</code> interface that applicable <em>ViewModels</em> implement. Looks like reusable stuff.</li>\n<li>Your VM is <em>tightly coupled</em> with your log provider - I'd wrap it with some <code>ILogger</code> interface which would be constructor-injected as needed.</li>\n<li>You're not always consistent with access modifiers: sometimes you <em>do</em> specify the default (<code>private void InitialiseProduct</code>), other times you leave it (<code>void VM_PropertyChanged</code>). I'd specify it everywhere (be <em>explicit</em>).</li>\n<li><code>IApplicationManager</code> is dangerous. You're passing it as a dependency which is good, but its name (<code>xxxxManager</code>) suggests that it might, over time, become a <em>shove-it-all-in-there</em> helper class with <em>low cohesion</em>. You don't show much code, but if all it's used for in the VM is to get the <code>app.CurrentUser</code>, maybe the VM's dependencies are more with some <code>ICurrentUser</code> than the whole <code>IApplicationManager</code>.</li>\n<li>Your <code>ViewModelBase</code> doesn't show its <code>INotifyPropertyChanged</code> implementation, I'd do <a href=\"https://codereview.stackexchange.com/questions/30769/converting-between-data-and-presentation-types\">something like this</a> so instead of <code>OnPropertyChanged(\"CoreEditorVM\")</code> you could do <code>OnPropertyChanged(() => CoreEditorVM)</code> and have a strongly-typed way of referring to your property names.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T20:17:52.847",
"Id": "36014",
"ParentId": "27798",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "36014",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T10:10:52.503",
"Id": "27798",
"Score": "2",
"Tags": [
"c#",
"wpf",
"mvvm"
],
"Title": "Implementing a POCO editor split over a number of TabItems"
}
|
27798
|
<p>I wrote something that has probably done thousands of times:
a function that takes a parsed http query as input and return a linq query. </p>
<p>Any input is appreciated.</p>
<pre><code>public IList<Lead> GetLeads(NameValueCollection nvc)
{
IQueryable<MyContext> queryBase = QueryBase();
foreach (string key in nvc)
{
const string format = "dd-MM-yyyy";
if (nvc[key] == "all")
continue;
//case where an array of possible values is sent
const string regex = "\\[.*\\]";
Expression<Func<MyContext, bool>> predicate = c => false;
string[] values = nvc[key].Split(',');
foreach (string value in values)
{
Expression<Func<MyContext, bool>> predicateTemp;
DateTime date;
switch (Regex.Replace(key, regex, ""))
{
case "nature":
string value1 = value;
predicateTemp =
c => c.Typologies.NatureDemande == value1;
break;
case "departementCode":
string value2 = value;
predicateTemp = c => c.Geographies.DepartementCode == value2;
break;
case "start":
String start = value;
date = DateTime.ParseExact(start, format, null);
DateTime date1 = date;
predicateTemp = c => c.Temps.Date >= date1;
break;
case "end":
String end = value;
date = DateTime.ParseExact(end, format, null);
DateTime date2 = date;
predicateTemp = c => c.Temps.Date <= date2;
break;
default:
predicateTemp =
c => true;
break;
}
predicate = OrElse(predicate, predicateTemp);
}
queryBase = queryBase.Where(predicate);
}
//query all leads
IQueryable<Lead> query = (from x in queryBase
select new Lead
{
id = Convert.ToInt32(x.Leads.DemandeWeb_FK),
lng = Convert.ToDouble(x.Leads.longitudeClient.Replace(",", ".")),
lat = Convert.ToDouble(x.Leads.latitudeClient.Replace(",", ".")),
temps = Convert.ToInt32(x.Leads.GeolocDureeTrajetDistrib),
distance = Convert.ToInt32(x.Leads.GeolocDistanceRouteDistrib),
nature = x.Typologies.NatureDemande,
type = x.Distributeurs.DistribType,
reseau = x.Distributeurs.ReseauDistributeur,
instance = x.Demands.IdInstance,
distribution = Convert.ToInt32(x.Distributeurs.DistribIdPointDeVente),
});
return query.ToList();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T12:10:03.593",
"Id": "43336",
"Score": "2",
"body": "Why is your DB returning everything as `string`s? This is especially problematic for the `double`s, since the `Replace()` indicates there is some culture mismatch."
}
] |
[
{
"body": "<p>Here's a stab at making it a tad more performant while simplifying the syntax a bit:</p>\n\n<pre><code>//case where an array of possible values is sent\nprivate const string MyRegex = \"\\\\[.*\\\\]\";\n\nprivate static readonly Regex replacer = new Regex(MyRegex, RegexOptions.Compiled);\n\npublic IList<Lead> GetLeads(NameValueCollection nvc)\n{\n var queryBase = QueryBase();\n\n foreach (var key in nvc.Cast<string>().Where(key => nvc[key] != \"all\"))\n {\n // case where an array of possible values is sent\n Expression<Func<MyContext, bool>> predicate = c => false;\n\n foreach (var value in nvc[key].Split(','))\n {\n const string Format = \"dd-MM-yyyy\";\n Expression<Func<MyContext, bool>> predicateTemp;\n var localValue = value;\n\n switch (replacer.Replace(key, string.Empty))\n {\n case \"nature\":\n predicateTemp = c => c.Typologies.NatureDemande == localValue;\n break;\n case \"departementCode\":\n predicateTemp = c => c.Geographies.DepartementCode == localValue;\n break;\n case \"start\":\n predicateTemp = c => c.Temps.Date >= DateTime.ParseExact(localValue, Format, null);\n break;\n case \"end\":\n predicateTemp = c => c.Temps.Date <= DateTime.ParseExact(localValue, Format, null);\n break;\n default:\n predicateTemp = c => true;\n break;\n }\n\n predicate = this.OrElse(predicate, predicateTemp);\n }\n\n queryBase = queryBase.Where(predicate);\n }\n\n // query all leads\n return queryBase.Select(x => new Lead\n {\n id = Convert.ToInt32(x.Leads.DemandeWeb_FK),\n lng = Convert.ToDouble(x.Leads.longitudeClient.Replace(\",\", \".\")),\n lat = Convert.ToDouble(x.Leads.latitudeClient.Replace(\",\", \".\")),\n temps = Convert.ToInt32(x.Leads.GeolocDureeTrajetDistrib),\n distance = Convert.ToInt32(x.Leads.GeolocDistanceRouteDistrib),\n nature = x.Typologies.NatureDemande,\n type = x.Distributeurs.DistribType,\n reseau = x.Distributeurs.ReseauDistributeur,\n instance = x.Demands.IdInstance,\n distribution = Convert.ToInt32(x.Distributeurs.DistribIdPointDeVente),\n }).ToList();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T14:14:28.253",
"Id": "27805",
"ParentId": "27800",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27805",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T11:37:07.697",
"Id": "27800",
"Score": "3",
"Tags": [
"c#",
".net",
"linq"
],
"Title": "Transforming http request into linq query"
}
|
27800
|
<p>I am trying to make a text-based RPG in Python and Pygame. I need a way to manage my inventory slots. Currently, I have no way to find out what is currently equipped. I can only overwrite it, even though I can display the current armor value and what it would be.</p>
<p>Here is the code for the only item I have "finished," a leather tunic:</p>
<pre><code>leatherTunicItem = False
if leatherTunicItem == True and itemSlotArmorChest == False:
itemSlotArmorChest = True
chestArmorValue = 2
print("The leather tunic is now equipped")
elif leatherTunicItem == True and itemSlotArmorChest == True:
print("Your armor value is currently: ", totalArmorValue, "Equipping a Leather Tunic will make this value: ", totalArmorValue - chestArmorValue + 2)
print("Would you still like to equip this item? (Yes or No)")
lti = input("")
if lti == "y" or lti == "Y" or lti == "yes" or lti == "Yes":
itemSlotArmorChest = True
chestArmorValue = 2
print("Your armor value is now ", totalArmorValue)
else:
print("This Leather Tunic will be discarded.")
leatherTunicItem = False
</code></pre>
<p>I have the whole Pastebin code <a href="http://www.pastebin.com/3Hh2uftE" rel="nofollow noreferrer">here</a>.</p>
<p><strong>Note:</strong> the inventory is all that I am working on for now.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-15T01:20:25.917",
"Id": "400917",
"Score": "2",
"body": "The code that you have posted makes no sense. If `leatherTunicItem = False`, then none of the rest of the code can possibly have any effect, because both the `if` and the `elif` blocks require it to be `True`. So what code is there to review?"
}
] |
[
{
"body": "<p>Some considerations on your current code:</p>\n\n<ol>\n<li>Don't use <code>== True</code>. You either want to check the truth value of the object, in which case simply drop the <code>== True</code>, or you want to check for identity, in which case you should use <code>is True</code>(even though it's really rare to see <code>is True/False</code>. You usually check for <code>is None</code>).</li>\n<li>Instead of <code>lti == \"y\" or lti == \"Y\" or ...</code> you can simply convert <code>lti</code> to lowercase and check for <code>y</code>. Something like <code>lti.lower()[:1] == \"y\"</code>. This will include also things like <code>yabbadu</code>. An other option is to use <code>in</code>: <code>lti.lower() in {\"y\", \"yes\"}</code> accepts <code>y</code> and <code>yes</code> in any case(so also <code>yEs</code> is accepted.</li>\n<li>You should follow the <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a> when writing. It's the <em>standard</em> coding-style for python. Using it will allow all python programmers to read your code more easily. To follow this style you should use <code>lower_case_with_underscore</code> for functions/variables, <code>FullCamelCase</code> for classes.</li>\n<li>Regarding the full code from pastebin: it is not well organized. Things like equipping an armor should be managed by a function or by some class and they shouldn't depend on the armor kind. It's probably a good example where using classes make sense. You should have an <code>Armor</code> class that provides the basic implementation of an armor and the various subclasses <code>TunicArmor</code> etc. that provide different armor points etc. Note that inheritance is not the only way to do it.</li>\n</ol>\n\n<p>In the end the code would look like:</p>\n\n<pre><code>leather_tunic_item = False\nif leather_tunic_item and not item_slot_armor_chest:\n item_slot_armor_chest = True\n chest_armor_value = 2\n print(\"The leather tunic is now equipped\")\nelif leather_tunic_item: #no need: and item_slot_armor_chest.\n print(\"Your armor value is currently: \", total_armor_value, \"Equipping a Leather Tunic will make this value: \", total_armor_value - chest_armor_value + 2)\n print(\"Would you still like to equip this item? (Yes or No)\")\n lti = input(\"\")\n if lti.lower() in {\"y\", \"yes\"}:\n item_slot_armor_chest = True\n chest_armor_value = 2\n print(\"Your armor value is now \", total_armor_value)\n else:\n print(\"This Leather Tunic will be discarded.\")\n leather_tunic_item = False\n</code></pre>\n\n<hr>\n\n<p>A sample implementation of what I meant in the last point might be this:</p>\n\n<pre><code>class ArmorPiece:\n def __init__(self, name, points):\n self.name = name\n self.points = points\n\n\nclass NullPiece:\n \"\"\"An armor piece that is used to represent a missing armor piece.\"\"\"\n def __init__(self):\n super(NullPiece, self).__init__(\"\", 0)\n\n\nclass Armor:\n def __init__(self, head=None, chest=None, legs=None):\n self.head = head if head is not None else NullPiece()\n self.chest = chest if chest is not None else NullPiece()\n self.legs = legs if legs is not None else NullPiece()\n\n def defense_points(self):\n return self.head.points + self.chest.points + self.legs.points\n\n\nclass Tunic(ArmorPiece):\n def __init__(self):\n super(Tunic, self).__init__(\"tunic\", 2)\n</code></pre>\n\n<p>After this, if you want to replace the chest piece you could do:</p>\n\n<pre><code>def change_chest(armor, new_chest):\n if isinstance(armor.chest, NullPiece):\n # The player is not wearing a chest armor piece\n armor.chest = new_chest\n print(\"The {.name} is now equipped.\".format(new_chest))\n else:\n # The player is wearing something else.\n print(\"Your armor value is currently: \", armor.defense_points(), \"Equipping a {.name} will make this value: \".format(new_chest), armor.defense_points() - armor.chest.points + new_chest.points)\n print(\"Would you still like to equip this item? (Yes or No)\")\n lti = input(\"\")\n if lti.lower() in {\"y\", \"yes\"}:\n armor.chest = new_chest\n print(\"Your armor value is now: \", armor.defense_points())\n else:\n print(\"This {.name} will be discarded\".format(new_chest))\n</code></pre>\n\n<p>You could make this function a method of <code>Armor</code> if you want, even though I like to separate the logic of the program from the input/output code. Your code will be more flexible.</p>\n\n<p>Note that in the formatting strings the <code>{.name}</code> parts are replaced with the attribute <code>name</code> of the object passed to <code>format</code>. Doing <code>\"{.name}\".format(new_chest)</code> is the same as <code>\"{}\".format(new_chest.name)</code>.</p>\n\n<p>You should probably read a bit of the documentation about <a href=\"http://docs.python.org/2/library/stdtypes.html#string-formatting\" rel=\"nofollow\">string formatting</a>.</p>\n\n<hr>\n\n<p>If you are not comfortable with classes you can simplify the code using some dictionaries. something like:</p>\n\n<pre><code>armor = {\n \"head\": {\"name\": \"\", \"points\": 0},\n \"chest\": {\"name\": \"\", \"points\": 0},\n \"legs\": {\"name\": \"\", \"points\": 0},\n}\n\ndef defense_points(armor):\n return sum(value[\"points\"] for key, value in armor.items())\n</code></pre>\n\n<p>To change the <code>head</code> armor simply do:</p>\n\n<pre><code>armor[\"head\"] = {\"name\": \"tunic\", \"points\": 2}\n</code></pre>\n\n<p>The code to handle this would be pretty similar to the above, but replacing attribute access with item access(e.g. <code>new_chest.name -> new_chest[\"name\"]</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T15:19:53.010",
"Id": "43349",
"Score": "0",
"body": "Thanks @Bakuriu, that helps a lot! what i was looking for, though, was how to detect what was currently equipped, print that, so \"You will replace \"THIS\" with a Leather Tunic, your armor walue will be x\". If you add that, i will accept this answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T15:24:22.193",
"Id": "43354",
"Score": "0",
"body": "@PythonInProgress Well, by what I see you don't keep track of the name of the items. In your code there's only a `leather_tunic_item` which is either `True` or `False`. You probably want to keep track of the names of the items too. I'll update my answer(soon) with an example on how you could do this using classes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T17:54:10.660",
"Id": "43368",
"Score": "0",
"body": "Is is ok to use this code? If you say yes I will note you in the credits. :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T18:07:18.353",
"Id": "43369",
"Score": "0",
"body": "@PythonInProgress Sure, but before using it be sure to understand it, otherwise it may hinder you later, when you have to modify it to implement new things in your game."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T18:11:39.943",
"Id": "43371",
"Score": "0",
"body": "Want to join me in chat?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T18:17:18.403",
"Id": "43372",
"Score": "0",
"body": "@PythonInProgress Sorry but I have other things to do now. Anyway there's plenty of people that could help you(in chat, or on the SE sites), so feel free to asks for other help too if you need."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T18:17:52.533",
"Id": "43373",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/9409/discussion-between-pythoninprogress-and-bakuriu)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T15:16:12.710",
"Id": "27807",
"ParentId": "27806",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "27807",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T14:57:06.330",
"Id": "27806",
"Score": "3",
"Tags": [
"python",
"pygame"
],
"Title": "Text-based adventure RPG inventory code"
}
|
27806
|
<p>I have been working on improving my javascript skills, mainly "namespacing" and the best practices used by js developers. I would like to know how I can improve this code and any tips that may help me along the way. Below is the specific code I am working with and there is a working fiddler also. </p>
<p>Just to note, I only want to use straight javascript and not jQuery for this.</p>
<pre><code>var quiz = window.quiz || {};
(function(ns) {
var currentIndex = 0;
var parent, back, next;
var selectedChoices = [];
ns.version = '1.0.0';
ns.author = 'Anonymous Hands';
ns.parentId = function(id) { parent = document.getElementById(id); };
ns.nextButtonId = function(id) { next = document.getElementById(id); next.onclick = moveNext; };
ns.backButtonId = function(id) { back = document.getElementById(id); back.onclick = moveBack; };
ns.questions = [];
ns.render =
function() {
renderQuestion(0);
};
//Pass results and missed questions?
ns.onComplete = function(results){};
function moveNext(){
saveState();
if (!atEnd()){
currentIndex++;
renderQuestion(currentIndex);
restoreState();
return;
}
renderComplete();
}
function moveBack(){
saveState();
if(!atBeginning()){
currentIndex--;
renderQuestion(currentIndex);
restoreState();
}
}
function renderQuestion(index){
clearParent();
var questionNum = index + 1;
var node = ns.questions[index];
var questionNumDiv = makeElement({type: "div", class: "question-number" ,html: questionNum});
var questionText = makeElement({type: "div", class: "question-text" ,html: node.question});
var choicesDiv = makeElement({type: "div", class: "choices"});
var l = node.choices.length;
for(var i = 0; i < l; i++){
var choiceRadio = makeElement({
type: "input",
subtype: "radio",
name: "choices",
id: "choice-" + i
});
var choiceLabel = makeElement({type: "label", class: "choice", html: node.choices[i], for: "choice-" + i});
choicesDiv.appendChild(choiceRadio);
choicesDiv.appendChild(choiceLabel);
}
parent.appendChild(questionNumDiv);
parent.appendChild(questionText);
parent.appendChild(choicesDiv);
}
function renderComplete(){
clearParent();
var n = getTotalCorrect();
var d = ns.questions.length;
var p = Math.round(((n / d) * 100))
var totalDiv = makeElement({type: "div", id: "score-total", html: "Your score: " + n + "/" + d});
var percentDiv = makeElement({type: "div", id: "score-percentage", html: p + "%"});
parent.appendChild(totalDiv);
parent.appendChild(percentDiv);
back.style.display = "none";
next.style.display = "none";
//onComplete();
}
function saveState(){
var anwser = selectedChoices[currentIndex];
var userChoice = getUserChoice();
if(anwser){
anwser.choice = userChoice;
return;
}
selectedChoices.push({questionId: currentIndex, choice: userChoice});
}
function restoreState(){
var anwser = selectedChoices[currentIndex];
if(anwser && anwser.choice != null){
var choices = document.getElementsByName("choices");
choices[anwser.choice].checked = true;
}
}
function clearParent(){
parent.innerHTML = "";
}
function atBeginning(){
return (currentIndex <= 0) ? true : false;
}
function atEnd(){
return (currentIndex >= ns.questions.length - 1) ? true : false;
}
function getTotalCorrect(){
var correct = 0;
var l = ns.questions.length;
for(var i = 0; i < l; i++){
if (ns.questions[i].anwser === selectedChoices[i].choice) correct++;
}
return correct;
}
function makeElement(p){
var e = document.createElement(p.type);
if (p.id) e.id = p.id;
if (p.class) e.className = p.class;
if (p.name) e.name = p.name;
if (p.html) e.innerHTML = p.html;
if (p.for) e.setAttribute("for", p.for);
if (e.type) e.type = p.subtype;
return e;
}
function getUserChoice(){
var choices = document.getElementsByName("choices");
var l = choices.length;
var index = null;
for(var i = 0; i < l; i++){
var node = choices[i];
if (node.checked) index = i;
}
return index;
}
})(quiz);
</code></pre>
<p>The <a href="http://jsfiddle.net/JThomas/3C66R/10/" rel="nofollow">jsfiddle</a>, as promised.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T16:47:12.433",
"Id": "43362",
"Score": "1",
"body": "Just a little comment on the UX. When you are at the first or last question, you should disable the back/next button. It looks weird that the button has an hover and can be clicked but doesn't do anything. Also, make the labels clickable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T17:49:49.397",
"Id": "43367",
"Score": "0",
"body": "@HugoDozois I agree on the buttons in addition next should turn to \"Finish\" when the user is on the last question. I am really looking for guidance on the structure of the code and ways to improve the overall code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T18:55:36.380",
"Id": "43375",
"Score": "1",
"body": "a small point: `return (currentIndex <= 0) ? true : false;` can simply be replaced by `return currentIndex <= 0;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T21:38:05.690",
"Id": "43378",
"Score": "2",
"body": "It might not seem useful to you but the rules on CR is to post your full code here and not a link to it. (I can't find a link to the explanation if required)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T02:01:50.197",
"Id": "43386",
"Score": "0",
"body": "You must post your code in your question, otherwise I'll be forced to close your question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T02:17:37.427",
"Id": "43387",
"Score": "0",
"body": "@Josay I never said, nor thought, it wasn't useful, but I was updating if fairly often and didn't want to have them fall out of sync because of typos or things I forgot."
}
] |
[
{
"body": "<p>I tend to use a lot of Java best practices in my JavaScript code. The biggest issue I see is the lack of extensible classes/methods. The methods are procedural and only seem to be broken into new methods because they are repeatable. The class as a whole violates the single responsibility principle because it has to handle the entire widget from modifying input (also bad practice), parsing the input, managing the question state, and appending the view. By following SRP your code will become much easier to read, maintain, and extend. I'm not going to comment on your grammatical issues but you should definitely set up <a href=\"http://www.sonarqube.org/\" rel=\"nofollow\">Sonar</a> to scan your code if you haven't already.</p>\n\n<p>So how it could be improved?</p>\n\n<p>I would start be making a new class called <em>Question</em> that could take a single question model and display it on the page. Then create a <em>Questionnaire</em> class that can take a questionnaire model (metadata & list of questions) and handle the state transitions until all questions have been answered. <em>Questionnaire</em> will have to instantiate a new <em>Question</em> object inside a div.</p>\n\n<p>I create the classes this way which allows the class to maintain scope.</p>\n\n<pre><code>function Question(divId, question) {\n\n // private variables\n var myVar;\n\n // this is a public method\n this.getAnswer = function() {\n }\n\n // this is a private method\n function renderChoice() {\n }\n\n function init() {\n // build the view\n }\n\n // this method call initializes the class like a constructor\n // so the caller doesn't have to initialize\n init();\n}\n</code></pre>\n\n<p>There are then two ways the state transitions could be handled. POST the answer after every question and store the values at the server or store each question result in the <em>Questionnaire</em> and POST at the end. Don't store the answers in the code because anyone that knows how to access and read the code could cheat. Either way you choose make sure that each class knows as little about each other as possible. <em>Question</em> should know nothing about <em>Questionnaire</em> and <em>Questionnaire</em> should only know that is has a list of questions to loop through and use accessor methods to get the value from.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T14:29:48.823",
"Id": "44259",
"Score": "0",
"body": "I accepted your answer as you are the only one to actually provide feedback, which I appreciate greatly. Have you ever had any issues with this approach? I ask because since js isn't strongly typed, I don't see a really good way to enforce the use of the `Question` \"class\". I rarely see the usage of the `new` keyword in js these days which seems to hint that it is fluff and makes the user have to type more to accomplish the same thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T19:17:26.467",
"Id": "44288",
"Score": "0",
"body": "I agree that new is not used much. I would attribute that to most frameworks becoming more like utilities that can register types for DOM parsing and attaching events. The \"classes\" remove functions from the global namespace so there is no collision/overwriting and allow a MVP pattern. Data models are still in JSON. Usually I don't use more than one presenter class because reusable components of a page can become a JSP tag or custom widget. The classes are defined in a .js while the variable is defined in the .html script tag."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T17:13:11.560",
"Id": "28257",
"ParentId": "27808",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "28257",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T14:38:21.320",
"Id": "27808",
"Score": "5",
"Tags": [
"javascript",
"quiz"
],
"Title": "Multiple-choice quiz"
}
|
27808
|
<p>Is there a smarter way to write this code? I used to add all the elements in the collection constructor, something like this:</p>
<pre><code>new OrderWizardStateCollection([new OrderWizardState(..), new OrderWizardState(..)..])
</code></pre>
<p>but now, since I have this one conditional addition, I'm writing it this way:</p>
<pre><code>this.state_collection = new OrderWizardStateCollection();
this.state_collection.add(new OrderWizardState({ state: 'basket', phase: this.phase_collection.findWhere({ phase: 'basket' }) }));
this.state_collection.add(new OrderWizardState({ state: 'account', phase: this.phase_collection.findWhere({ phase: 'account' }) }));
if ( _.has(this.regions, "lp") ) this.state_collection.add(new OrderWizardState({ state: 'loyaltypoints', phase: this.phase_collection.findWhere({ phase: 'account' }) }));
this.state_collection.add(new OrderWizardState({ state: 'delivery', phase: this.phase_collection.findWhere({ phase: 'delivery' }) }));
this.state_collection.add(new OrderWizardState({ state: 'payment', phase: this.phase_collection.findWhere({ phase: 'payment' }) }));
this.state_collection.add(new OrderWizardState({ state: 'placeorder', phase: this.phase_collection.findWhere({ phase: 'placeorder' }) }));
</code></pre>
|
[] |
[
{
"body": "<p>You could do a loop over the elements that you are always adding:</p>\n\n<pre><code>for (var info in [\"basket\", \"account\", \"delivery\", \"payment\", \"placeorder\"] {\n this.state_collection.add (new OrderWizardState ({ state: info, phase: this.phase_collection.findWhere ({ phase: info }) }));\n}\n</code></pre>\n\n<p>And to add the special one, you use your <code>if</code> statement and <code>insert</code> it at a specific index:</p>\n\n<pre><code>if ( _.has (this.regions, \"lp\")) { \n var state = new OrderWizardState({ state: 'loyaltypoints', phase: this.phase_collection.findWhere({ phase: 'account' }) })\n this.state_collection.insert (2, state);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-13T10:49:19.840",
"Id": "210773",
"Score": "0",
"body": "Don't use `for..in` on arrays in javascript; it enumerates properties - not just the array's elements (also, that line is missing a `)`). Use a regular `for`, or maybe call `forEach`, or use `_.each` since underscore/lodash seems to be there."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T18:43:11.443",
"Id": "27814",
"ParentId": "27812",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T17:36:23.210",
"Id": "27812",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Add elements to collection conditionally"
}
|
27812
|
<p>Could it be written better?</p>
<pre><code>package main
import (
"code.google.com/p/go-tour/wc"
"fmt"
)
func WordCount(s string) map[string]int {
dict := make(map[string]int)
splited := Split(s)
for _, string := range splited {
_, present := dict[string]
if present {
dict[string]++
} else {
dict[string] = 1
}
}
return dict
}
func Split(s string) []string{
arraySize := 1
for i := 0; i < len(s); i++ {
if s[i] == ' ' {
arraySize++
}
}
array := make([]string, arraySize)
currentStrInd := 0
currentStr := ""
for i := 0; i < len(s); i++ {
if s[i] == ' ' {
array[currentStrInd] = currentStr
currentStrInd++
currentStr = ""
} else {
currentStr += string(s[i])
}
}
array[arraySize - 1] = currentStr
return array;
}
func main() {
fmt.Println(Split("I am learning Go!"))
wc.Test(WordCount)
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T18:54:47.083",
"Id": "43374",
"Score": "0",
"body": "\"for _, string := range splited {\"\nAre you using \"string\" as a variable Name?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T09:25:55.363",
"Id": "43408",
"Score": "0",
"body": "oh, my bad ;..("
}
] |
[
{
"body": "<p>For example,</p>\n\n<pre><code>package main\n\nimport (\n \"code.google.com/p/go-tour/wc\"\n \"strings\"\n)\n\n// WordCount returns a map of the counts of each “word” in the string s.\nfunc WordCount(s string) map[string]int {\n words := strings.Fields(s)\n counts := make(map[string]int, len(words))\n for _, word := range words {\n counts[word]++\n }\n return counts\n}\n\nfunc main() {\n wc.Test(WordCount)\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T17:25:42.307",
"Id": "67793",
"Score": "1",
"body": "Code-only answers do not constitute a review. Please explain how your changes improve the original code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T12:00:27.273",
"Id": "27845",
"ParentId": "27813",
"Score": "1"
}
},
{
"body": "<p>For simply counting word occurrencies, yes:</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"regexp\"\n)\n\nfunc get_words_from(text string) []string{\n words:= regexp.MustCompile(\"\\\\w+\")\n return words.FindAllString(text, -1)\n}\n\nfunc count_words (words []string) map[string]int{\n word_counts := make(map[string]int)\n for _, word :=range words{\n word_counts[word]++\n }\n return word_counts;\n}\n\nfunc console_out (word_counts map[string]int){\n for word, word_count :=range word_counts{\n fmt.Printf(\"%v %v\\n\",word, word_count)\n }\n}\n\nfunc main() {\n text := \"I am learning Go! Go is a nice language to learn.\"\n console_out(count_words(get_words_from(text)))\n}\n</code></pre>\n\n<p>Supposing, splitting by \\w+ gives in most cases, what you want.</p>\n\n<p>Another solution would be <code>(\\\\b[^\\\\s]+\\\\b)</code>. Depends on your demands.</p>\n\n<p><a href=\"http://play.golang.org/p/r_PFmGmGQN\" rel=\"nofollow\">Go play with it!</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-20T14:32:22.267",
"Id": "205236",
"Score": "1",
"body": "Have you considered the same word with different cases: say \"Book\", \"book\", \"BOOK\" should be treated as one word. Maybe convert all words to lower case before getting their counts is a good idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-20T16:44:57.867",
"Id": "205262",
"Score": "0",
"body": "Dependend on the result you want - this would be an improvement :]"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-15T22:56:19.217",
"Id": "229098",
"Score": "2",
"body": "Instead of regexp you can use strings.FieldsFunc, example https://play.golang.org/p/GrlgFyZAXB"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-26T00:24:28.597",
"Id": "33271",
"ParentId": "27813",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T17:38:18.803",
"Id": "27813",
"Score": "4",
"Tags": [
"strings",
"go"
],
"Title": "Split and word count in go"
}
|
27813
|
<p>I recently came across the <a href="https://en.wikipedia.org/wiki/Sleeping_barber_problem" rel="nofollow">Sleeping Barber</a> problem and found out that it is a good place to start learning how to use threads properly. </p>
<p>I don't have <em>too</em> much experience with threads and want to learn more, so I figured I'd give it a go.</p>
<p>I'm hoping to get some constructive criticism on the code and any heads up on the logic of the problem if I'm not implementing it correctly.</p>
<pre><code>import time
import random
import Queue
from threading import Thread
NAMES = ["Al", "Alex", "Anthony", "Bill", "Bob", "Brad", "Cam", "Cal",
"Chris", "Charlie", "Dave", "Dan", "Derek", "Devin", "Eric",
"Elijah", "Frank", "Fred", "Gary", "George", "Hal", "Harry",
"Isaac", "Ishmael", "Jared", "Jake", "Jeremy", "Kevin", "Kris",
"Larry", "Louie", "Mark", "Mort", "Nathan", "Norb", "Oscar",
"Orville", "Peter", "Paul", "Quinn", "Rob", "Rick", "Steve",
"Tim", "Trevor", "Ulysses", "Victor", "Walter", "Xavier",
"Yadier", "Zack"]
class Barber(Thread):
def __init__(self, waiting_customers):
super(Barber, self).__init__()
self.waiting_customers = waiting_customers # the Queue passed in
self.number_haircuts = 0
self.tips = 0
self.days_profit = 0
self.shop_open = True # Flag to end the main thread
self.sleeping = True # Flag to have the barber start at sleep until a customer arrives
def run(self):
'''
I check if the `shop_open` flag is True *and* there arent any customers in line.
I did this to make sure that if a customer thread is put in the queue but,
isnt called before the `shop_open` is false, the barber thread will continue
to get the last customers out but, no other customers will be put in the
waiting room(no customer threads left alive after barber exits).
'''
while self.shop_open or not self.waiting_customers.empty(): # continue until Queue is empty or shop is closed
if not self.waiting_customers.empty():
self.sleeping = False # if customers awake
customer = self.waiting_customers.get()
if customer.hair_type == 'short':
customer.in_barber_chair = True
print "The barber is cutting %s's hair." % customer.name
print "%s has %s hair, this should take 20 minutes." % (customer.name, customer.hair_type)
time.sleep(2)
elif customer.hair_type == 'medium':
customer.in_barber_chair = True
print "The barber is cutting %s's hair." % customer.name
print "%s has %s hair, this should take 40 minutes." % (customer.name, customer.hair_type)
time.sleep(4)
else:
customer.in_barber_chair = True
print "The barber is cutting %s's hair." % customer.name
print "%s has %s hair, this should take 60 minutes." % (customer.name , customer.hair_type)
time.sleep(6)
print "Done cutting %s's hair" % customer.name
self.number_haircuts += 1
self.tips += random.choice(range(6))
self.days_profit += 15
elif not self.sleeping: # elif no customers in line and not already sleeping go to sleep
self.sleeping = True
print "No one in the waiting room, the barber is going to nap in his chair"
print "The barber gave %d haircuts and made $%d." % (self.number_haircuts,
sum([self.tips, self.days_profit]))
class Customer(Thread):
def __init__(self, name, hair_type):
super(Customer, self).__init__()
self.name = name
self.hair_type = hair_type
self.in_barber_chair = False
def run(self):
while not self.in_barber_chair:
pass
if self.hair_type == 'short': # have the thread stay alive while getting haircut.
time.sleep(2)
elif self.hair_type == 'medium':
time.sleep(4)
else:
time.sleep(6)
if __name__ == '__main__':
hair_types = ['short', 'medium', 'long'] # additional variable for a haircut length to simulate time
waiting_room = Queue.Queue(3) # a queue for a waiting room with max 3 chairs
barber = Barber(waiting_room)
barber.start()
close_time = 48 # end thread after 48 seconds
shop_open = time.time()
current_time = shop_open
while (current_time - shop_open) < close_time: # check if barber thread has been running longer than open time
i_need_a_haircut = random.choice(NAMES) # pick a random name
if not waiting_room.full(): # if the Queue isn't full grab a seat
length = random.choice(hair_types)
customer = Customer(i_need_a_haircut, length)
waiting_room.put(customer)
print "%s sat down in the waiting room" % i_need_a_haircut
customer.start()
else: # else leave shop
print "Sorry, %s too full, try coming back when its not so busy" % i_need_a_haircut
stagger = random.choice([1, 5, 10, 20]) # stagger time each customer thread is created
time.sleep(stagger)
current_time = time.time()
barber.shop_open = False # close shop/barber will finish off remaining threads in queue.
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T21:17:23.220",
"Id": "43377",
"Score": "0",
"body": "Please add a description of the problem in your question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T21:47:46.230",
"Id": "43381",
"Score": "0",
"body": "@Josay I added a hyperlink on the \"sleeping barber\" text."
}
] |
[
{
"body": "<p>I have no idea what you are trying to achieve here so here are a full general comments :</p>\n\n<p>The pythonic way to check <code>not self.waiting_customers.empty()</code> is <code>self.waiting_customers</code> (if <code>waiting_customers</code> is known to be a container).</p>\n\n<p>Also</p>\n\n<pre><code> if customer.hair_type == 'short':\n customer.in_barber_chair = True\n print \"The barber is cutting %s's hair.\" % customer.name\n print \"%s has %s hair, this should take 20 minutes.\" % (customer.name, customer.hair_type)\n time.sleep(2)\n elif customer.hair_type == 'medium':\n customer.in_barber_chair = True\n print \"The barber is cutting %s's hair.\" % customer.name\n print \"%s has %s hair, this should take 40 minutes.\" % (customer.name, customer.hair_type)\n time.sleep(4)\n else:\n customer.in_barber_chair = True\n print \"%s has %s hair, this should take 60 minutes.\" % (customer.name , customer.hair_type)\n time.sleep(6)\n</code></pre>\n\n<p>could/should be written :</p>\n\n<pre><code> duration = 2 if customer.hair_type == 'short' else 4 if customer.hair_type == 'medium' else 6\n customer.in_barber_chair = True\n print \"The barber is cutting %s's hair.\" % customer.name\n print \"%s has %s hair, this should take %0 minutes.\" % (customer.name, duration, customer.hair_type)\n time.sleep(duration)\n</code></pre>\n\n<p>Also, as you do this operation twice, it might be worth defining a function to convert hair types to duration.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T21:45:22.967",
"Id": "43380",
"Score": "0",
"body": "I'll put in a link to the problem on wikipedia. Two good points, I had just starting using the `Queue` module and thought I would use the `.empty()` method. I did think at one point to make another method out of `hair_type` action too. Thanks for the response."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T21:24:59.407",
"Id": "27819",
"ParentId": "27817",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27819",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T20:50:07.707",
"Id": "27817",
"Score": "1",
"Tags": [
"python",
"algorithm",
"multithreading"
],
"Title": "Feedback on a Python 'sleeping barber' program"
}
|
27817
|
<p>As a follow-up to my previous <a href="https://codereview.stackexchange.com/questions/26071/computation-of-prefix-free-codes-with-many-repeated-weight-values-in-reduced-spa">question</a> about prefix free code, I learned about the module unittest and wrote the following set of functions, to be used in order to semi-automatically check the optimality of the output of any new algorithm to compute prefix free code.</p>
<p>The code works but I would like it to be as elegant (and compact) as possible in order to potentially include it in a research article, in a more formal and reproducible maneer than the traditional "algorithm". I am proud of how it looks, but I do expect you to still criticize it!!!</p>
<pre><code>import unittest, doctest, math
def codeIsPrefixFreeCodeMinimal(L,W):
"""Checks if the prefix free code described by an array $L$ of
pairs $(codeLenght_i,nbWeights_i)$ is minimal for weights $W$, by
1) checking if the code respects Kraft's inequality and
2) comparing the lenght of a code encoded with $L$ with the
entropy of $W$.
"""
assert respectsKraftInequality(L)
return compressedTextLenght(L,W) <= NTimesEntropy(W)+len(W)
def respectsKraftInequality(L):
"""Checks if the given array $L$ of pairs $(codeLenght_i,nbWeights_i)$
corresponds to a prefix free code by checking Kraft's inequality, i.e.
$\sum_i nbWeights_i 2^{-codelenght_i} \leq 1$.
"""
return KraftSum(L) <= 1 ;
def KraftSum(L):
"""Computes the Kraft sum of the prefix free code described by an
array $L$ of pairs $(codeLenght_i,nbWeights_i)$ i.e.
$\sum_i nbWeights_i 2^{-codelenght_i}$.
"""
if len(L)==0:
return 0
terms = map( lambda x: x[1] * math.pow(2,-x[0]), L)
return sum(terms)
class TestKraftSum(unittest.TestCase):
def test_empty(self):
"""Empty input."""
self.assertEqual(KraftSum([]),0)
def test_singleton(self):
"""Singleton with one single symbol."""
self.assertEqual(KraftSum([(0,1)]),1)
def test_simpleCode(self):
"""Simple Code with code lenghts [1,2,2]."""
self.assertEqual(KraftSum([(1,1),(2,2)]),1)
def test_fourEqual(self):
"""Four equal weights"""
self.assertEqual(KraftSum([(2,4)]),1)
def test_HuffmanExample(self):
"""Example from Huffman's article"""
self.assertEqual(KraftSum([(5,6),(4,3),(3,3),(2,1)]),1)
def test_MoffatTurpinExample(self):
"""Example from Moffat and Turpin's article"""
self.assertEqual(KraftSum([(5,4),(4,4),(3,3),(2,1)]),1)
def NTimesEntropy(W):
"""Returns N times the entropy, rounded to the next integer, as computed by
$\lceil \sum_{i=1}^N W[i]/\sum(W) \log (sum(W) / W[i]) \rceil$.
"""
if len(W)==0:
return 0
assert min(W)>0
sumWeights = sum(W)
terms = map( lambda x: x * math.log(x,2), W )
return math.ceil(sumWeights * math.log(sumWeights,2) - sum(terms))
class TestNTimesEntropy(unittest.TestCase):
def test_empty(self):
"""Empty input"""
self.assertEqual(NTimesEntropy([]),0)
def test_singleton(self):
"""Singleton"""
self.assertEqual(NTimesEntropy([1]),0)
def test_pair(self):
"""Pair"""
self.assertEqual(NTimesEntropy([1,1]),2)
def test_fourEqual(self):
"""Four equal weights"""
self.assertEqual(NTimesEntropy([1,1,1,1]),8)
def test_HuffmanExample(self):
"""Example from Huffman's article"""
self.assertEqual(NTimesEntropy([1,3,4,4,4,4,6,6,10,10,10,18,20]),336)
def test_MoffatTurpinExample(self):
"""Example from Moffat and Turpin's article"""
self.assertEqual(NTimesEntropy([1,1,1,1,1,2,2,2,2,3,3,6]),84)
def compressedTextLength(L,W):
"""Computes the lengths of a text which frequencies are given by
an array $W$, when it is compressed by a prefix free code
described by an array $L$ of pairs $(codeLenght_i,nbWeights_i)$.
"""
compressedTextLength = 0
Ls = sorted(L, reverse=True)
Ws = sorted(W)
for (l,n) in Ls:
compressedTextLength += l*sum(Ws[0:n])
Ws = Ws[n:]
return compressedTextLength
class TestcompressedTextLength(unittest.TestCase):
def test_empty(self):
"""Empty input"""
self.assertEqual(compressedTextLength([],[]),0)
def test_pair(self):
"""Pair of symbols, arbitrary text"""
self.assertEqual(compressedTextLength([(1,2)],[1,1]),2)
def test_fourEqual(self):
"""Four equal weights"""
self.assertEqual(compressedTextLength([(2,4)],[1,1,1,1]),8)
def test_HuffmanExample(self):
"""Example from Huffman's article (compares with value compared by hand)"""
self.assertEqual(compressedTextLength([(5,6),(4,3),(3,3),(2,1)],[1,3,4,4,4,4,6,6,10,10,10,18,20]),342)
def test_MoffatTurpinExample(self):
"""Example from Moffat and Turpin's article (compares with entropy value)"""
self.assertEqual(compressedTextLength([(5,4),(4,4),(3,3),(2,1)],[1,1,1,1,1,2,2,2,2,3,3,6]),84)
def main():
unittest.main()
if __name__ == '__main__':
doctest.testmod()
main()
</code></pre>
|
[] |
[
{
"body": "<p>Most Python I read these days prefers list comprehensions over <code>map</code> or <code>filter</code>. For example, I'd change</p>\n\n<pre><code>terms = map( lambda x: x[1] * math.pow(2,-x[0]), L)\nreturn sum(terms)\n</code></pre>\n\n<p>to</p>\n\n<pre><code>return sum(x[1] * math.pow(2, -x[0]) for x in L)\n</code></pre>\n\n<hr>\n\n<p>You consistently misspell \"length\" as \"lenght\".</p>\n\n<hr>\n\n<p>Your formatting is odd. Sometimes you have 3 blank lines between functions, sometimes 0. Likewise, sometimes you write <code>foo <= bar</code> and sometimes <code>foo=bar+baz</code>. Sometimes your functions begin with a lowercase letter (<code>compressedTextLength</code>, <code>respectsKraftInequality</code>) and sometimes with an uppercase (<code>KraftSum</code>). Look over <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a> for formatting recommendations.</p>\n\n<hr>\n\n<p>In <code>compressedTextLength</code>, you can rewrite</p>\n\n<pre><code>for (l,n) in Ls:\n compressedTextLength += l*sum(Ws[0:n])\n Ws = Ws[n:]\n</code></pre>\n\n<p>as</p>\n\n<pre><code>for i, (l, n) in enumerate(Ls):\n compressedTextLength += l * sum(Ws[i:i+n])\n</code></pre>\n\n<hr>\n\n<p>You call <code>doctest.testmod()</code> but it doesn't look like you have any doctests.</p>\n\n<hr>\n\n<p>As a generalized note, I would find it difficult to learn anything about this algorithm from reading your code. I also have no idea how to use this module. I would add a docstring to the beginning of the module telling the reader about the functions they should care about, and in each function's docstring I would document what the arguments should be and what the return values are (arrays of ints? floating point numbers? etc).</p>\n\n<p>It looks like this may be a test harness for code that actually computes minimal prefix free codes. If that's a case, document it in the module's docstring.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T05:05:39.987",
"Id": "27827",
"ParentId": "27821",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T21:45:48.927",
"Id": "27821",
"Score": "1",
"Tags": [
"python"
],
"Title": "Code to check for the optimality of a minimal prefix free code"
}
|
27821
|
<p>I applied for a job and they asked me to write code with the following requirements:</p>
<blockquote>
<p>Get a "toolbar offer" description from
http..update.utorrent.com/installoffer.php?offer=conduit. Parse the
bencoded (see <a href="http://en.wikipedia.org/wiki/Bencode">http://en.wikipedia.org/wiki/Bencode</a>) response and
extract the URL of the binary and its SHA1 hash. The hash is contained
in the value of the key 'offer_hash'. The binary is in list for the
key 'offer_urls' — please use the one prefixed with
"http..download.utorrent.com/".</p>
<p>Download the binary and calculate its hash</p>
<p>Verify that the calculated SHA1 hash is identical to the one provided
in the offer details. It is okay to use existing libraries for
bencoding, hashing, etc.</p>
</blockquote>
<p>What is wrong with my code? The recruiter said it didn't meet their bar.</p>
<pre><code># Script that verifies the correctness of a toolbar offers
import urllib, bencode , hashlib
from hashlib import sha1
url = "http://update.utorrent.com/installoffer.php?offer=conduit"
filename = "content.txt"
f= urllib.urlretrieve(url, filename)
#Bdecoding the response
with open (str(filename), 'rb') as myfile:
data=myfile.read()
decoded = bencode.bdecode(data)
# Returning the list for the key 'offer_urls'
list = decoded['offer_urls']
#print list
# Returning the URL of the binary that is prefixed with "http://download3.utorrent.com/"
length = len (list)
prefix = "http://download3.utorrent.com/"
i= -1
while i < length:
i = i + 1
if list[i].startswith(prefix) :
break
binary= list[i]
print "The URL of the the binary is: " , binary
# Returning the sha1 hash contained in the value of the key 'offer_hash'
encrypted_hash = decoded['offer_hash']
sha1_hash1 = encrypted_hash.encode('hex')
print "The sha1 hash contained in the value of the key 'offer_hash' is: " , sha1_hash1
# Downloading the binary and calculating its hash
urllib.urlretrieve ( binary , "utct2-en-conduit-20130523.exe")
file = "C:\Python27\utct2-en-conduit-20130523.exe"
with open (file, 'rb') as myfile:
downloaded=myfile.read()
k = hashlib.sha1()
k.update(downloaded)
sha1file = k.hexdigest()
print "The sha1 hash of the downloaded binary is: " , sha1file
# Verify that the calculated sha1 hash is identical to the one provided in the offer details
if (sha1file == sha1_hash1) :
print "Test result = Pass"
else :
print "Test result = Fail"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T17:25:54.403",
"Id": "43422",
"Score": "58",
"body": "A fairly simple problem with your code: Comments should explain why, not how."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T23:44:24.430",
"Id": "43441",
"Score": "2",
"body": "It does show your a pragmatist which is good when your working alone."
}
] |
[
{
"body": "<p>Run your code through <a href=\"https://pypi.python.org/pypi/pep8\">pep8</a> and possibly a more pedantic static analyzer like <a href=\"http://www.logilab.org/857#projectinfo_tab\">pylint</a>.</p>\n\n<p>You will find these tools don't like some of your formatting and variable names. They will likely complain there are too many variables, branches, etc. because the code is not broken up into modularized functions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T03:57:00.137",
"Id": "27825",
"ParentId": "27824",
"Score": "64"
}
},
{
"body": "<p>I'm going to tell you the things in your code that made me wonder.</p>\n\n<pre><code># Script that verifies the correctness of a toolbar offers\n\nimport urllib, bencode , hashlib\n</code></pre>\n\n<p>Extra space after <code>bencode</code> suggests lack of attention to detail.</p>\n\n<pre><code>from hashlib import sha1\n\nurl = \"http://update.utorrent.com/installoffer.php?offer=conduit\"\n\nfilename = \"content.txt\"\n\nf= urllib.urlretrieve(url, filename)\n</code></pre>\n\n<p>Use of single-letter variables suggests lack of attention to clean code.</p>\n\n<pre><code>#Bdecoding the response\n\nwith open (str(filename), 'rb') as myfile:\n</code></pre>\n\n<p><code>filename</code> is already a string. Converting it to a string again suggests confusion as to what is going on.</p>\n\n<pre><code> data=myfile.read()\n decoded = bencode.bdecode(data)\n</code></pre>\n\n<p>Massive indentation suggests disregard for consistent indentation style.</p>\n\n<p>Downloading the file to disk then reading it into memory is poor use of available APIs. You should download the file directly into memory.</p>\n\n<pre><code># Returning the list for the key 'offer_urls'\n</code></pre>\n\n<p>Excess whitespace suggests someone is enter-happy.</p>\n\n<pre><code>list = decoded['offer_urls']\n</code></pre>\n\n<p>\"Returning\" is technically incorrect here. You aren't in a function, so you aren't returning anything. Use of <code>list</code> is a bad name for a variable since it's a built-in Python type.</p>\n\n<pre><code>#print list\n\n\n# Returning the URL of the binary that is prefixed with \"http://download3.utorrent.com/\"\n\nlength = len (list)\n</code></pre>\n\n<p>Putting spaces after function calls is odd, and you don't do it consistently. There's also rarely a good reason to store the length of a <code>list</code>.</p>\n\n<pre><code>prefix = \"http://download3.utorrent.com/\"\n\ni= -1\n</code></pre>\n\n<p>No space before the <code>=</code>.</p>\n\n<pre><code>while i < length:\n i = i + 1\n if list[i].startswith(prefix) :\n break\nbinary= list[i]\n</code></pre>\n\n<p>You are using a <code>while</code> loop when you should be using a <code>for</code> loop. It is also going to cause an <code>IndexError</code>, rather than fail gracefully, if the prefix isn't found.</p>\n\n<pre><code>print \"The URL of the the binary is: \" , binary\n\n\n# Returning the sha1 hash contained in the value of the key 'offer_hash'\n\n\nencrypted_hash = decoded['offer_hash']\n</code></pre>\n\n<p>Is that hash really encrypted?</p>\n\n<pre><code>sha1_hash1 = encrypted_hash.encode('hex')\nprint \"The sha1 hash contained in the value of the key 'offer_hash' is: \" , sha1_hash1 \n\n\n# Downloading the binary and calculating its hash\n\nurllib.urlretrieve ( binary , \"utct2-en-conduit-20130523.exe\")\nfile = \"C:\\Python27\\utct2-en-conduit-20130523.exe\"\n</code></pre>\n\n<p>Hard-coded filename will be easy to break. You shouldn't even need to do it. The string also contains <code>\"\\\"</code> which should be escaped, or the whole string should be raw. i.e.</p>\n\n<pre><code>\"C:\\\\Python27\\\\utct2-en-conduit-20130425.exe\"\n</code></pre>\n\n<p>or</p>\n\n<pre><code>r\"C:\\Python27\\utct2-en-conduit-20130425.exe\"\n</code></pre>\n\n<p>or in most cases you can use the other slashes, even on Windows.</p>\n\n<pre><code>\"C:/Python27/utct2-en-conduit-20130425.exe\"\n</code></pre>\n\n<p>You got away with what you did, but that's mostly because you are lucky.</p>\n\n<pre><code>with open (file, 'rb') as myfile:\n downloaded=myfile.read()\n</code></pre>\n\n<p>This last piece of code did pretty much the same thing as a previous bit of code, but you didn't use a function.</p>\n\n<pre><code>k = hashlib.sha1()\nk.update(downloaded)\nsha1file = k.hexdigest()\nprint \"The sha1 hash of the downloaded binary is: \" , sha1file\n\n# Verify that the calculated sha1 hash is identical to the one provided in the offer details\n\nif (sha1file == sha1_hash1) :\n</code></pre>\n\n<p>You've put parentheses, which are not necessary.</p>\n\n<pre><code> print \"Test result = Pass\"\nelse :\n print \"Test result = Fail\"\n</code></pre>\n\n<p>Your basic problems:</p>\n\n<ol>\n<li>Your style is poor and inconsistent</li>\n<li>A few things suggest you don't quite understand what's going on</li>\n<li>You haven't taken care to make the code readable</li>\n</ol>\n\n<p>Here's my take on the problem:</p>\n\n<pre><code># Script that verifies the correctness of a toolbar offers\n\nimport urllib\nimport bencode\nimport hashlib\nimport contextlib\n\n# it's common practice to put input details like this\n# as global constants at the start of your script\nURL = \"http://update.utorrent.com/installoffer.php?offer=conduit\"\nPREFIX = \"http://download3.utorrent.com/\"\n\n# by breaking down your task into functions\n# you can make the code easier to follow\ndef read_bencoded_url(url):\n with contextlib.closing(urllib.urlopen(url)) as offer_file:\n return bencode.bdecode(offer_file.read())\n\ndef find_string_with_prefix(strings, prefix):\n for string in strings:\n if string.startswith(prefix):\n return string\n else:\n raise Exception(\"Did not find prefix: {}\".format(prefix))\n\n# this function is a bit more complicated\n# but it avoids saving the file to disk or loading it entirely into memory.\n# instead it hashes it 4096 bytes at a time\ndef hash_of_url(url):\n hasher = hashlib.sha1()\n with contextlib.closing(urllib.urlopen(url)) as binary_file:\n while True:\n data = binary_file.read(4096)\n if not data:\n break\n hasher.update(data)\n return hasher.hexdigest()\n\n# the actual high level logic just calls the functions\n# this avoid obscuring the logic with lower level details\ndef main():\n decoded = read_bencoded_url(URL)\n binary = find_string_with_prefix(decoded['offer_urls'], PREFIX)\n reported_hash = decoded['offer_hash'].encode('hex')\n actual_hash = hash_of_url(binary)\n print \"The sha1 hash contained in the value of the key 'offer_hash' is: \", reported_hash\n print \"The sha1 hash of the downloaded binary is: \" , actual_hash\n\n if reported_hash == actual_hash:\n print \"Test result = Pass\"\n else:\n print \"Test result = Fail\"\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T06:57:18.963",
"Id": "43397",
"Score": "3",
"body": "Still some things to do. Imports per line, or at least fix your first own comment. High level logic in a function called main please the check if its teh main module and run main this way its easier to reuse the code. PS I presume the comments are for the benefit of OP and most not to be included in the actual submission ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T13:06:53.473",
"Id": "43414",
"Score": "118",
"body": "Harsh... but very well done. Hopefully just what the doctor ordered."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T15:44:09.990",
"Id": "43420",
"Score": "0",
"body": "@joojaa, you are of course correct. I didn't address those because I'd wouldn't necessarily assume a poor coder on those alone. But i've gone ahead and done so now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T17:29:20.870",
"Id": "43423",
"Score": "0",
"body": "Actually, one of the comments shouldn't be there at all, the one directly before the part comparing the hashes. That comment does not contribute to making the code easier to understand."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T23:07:45.737",
"Id": "43440",
"Score": "45",
"body": "I was really confused by this answer until I realized I wasn't on StackOverflow anymore."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T00:02:08.967",
"Id": "43442",
"Score": "23",
"body": "I wouldn't ding him on the extra parens. When you're dealing with multiple languages it's good to be defensive with paren usage, extra ones do no harm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T00:06:16.610",
"Id": "43444",
"Score": "4",
"body": "@LorenPechtel, What? I need those two extra bytes of disk space! :P The parens aren't a serious issue, but they might indicative of confusion about the language."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T01:26:32.807",
"Id": "43445",
"Score": "109",
"body": "I don't think this is too harsh by any means. If you upload your code, you should be GRATEFUL for a critique this thorough. Well done!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T16:24:29.850",
"Id": "43510",
"Score": "0",
"body": "In your `hash_of_url` you can replace the ugly `while True` + `break` with a `for` + `iter(callable, sentinel)`: `for chunk in iter(lambda: binary_file.read(4096), ''): hasher.update(chunk)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-29T00:25:55.343",
"Id": "43551",
"Score": "0",
"body": "@Bakuriu, I'm not sure I like that better. I'll agree that `while True/break` is ugly. Regardless, probably more complexity than the OP needs right now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-29T18:34:09.157",
"Id": "43579",
"Score": "0",
"body": "Note that the requirements specified to download the file. I'd interpret that to mean it should reside on disk when the program exits, which this code avoids."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-29T22:24:09.587",
"Id": "43587",
"Score": "0",
"body": "@AlanShutko, hmm.. I wouldn't interpret the requirements that way. Furthermore, it doesn't really seem to make sense in the scope of the question to want the file left on disk. But that's why you should clarify in the face of ambiguity."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-01T17:30:39.780",
"Id": "43668",
"Score": "41",
"body": "@WinstonEwert: Thanks a lot for taking the time to provide me with such a detailed answer!! It really helped!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-04T00:53:37.923",
"Id": "43856",
"Score": "5",
"body": "Amazing answer. Well done @WinstonEwert"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T05:27:36.253",
"Id": "57363",
"Score": "2",
"body": "Made my day proves that there are good skilled people who can take time to read and answer your problem"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-21T22:51:17.660",
"Id": "426385",
"Score": "0",
"body": "*You did not just* `raise Exception()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T01:27:44.673",
"Id": "454977",
"Score": "0",
"body": "When you say “Downloading the file to disk then reading it into memory is poor use of available APIs. You should download the file directly into memory.” would that look like this: decoded = bencode.bdecode(myfile) ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T02:05:20.427",
"Id": "455053",
"Score": "0",
"body": "@RobertHoughton, that depends on where `myfile` came from. To see how I'd do it, see my version of the code at the end of the answer."
}
],
"meta_data": {
"CommentCount": "18",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T06:19:03.920",
"Id": "27831",
"ParentId": "27824",
"Score": "362"
}
},
{
"body": "<p>If I was to take your code then multiply it out 100 or a thousand times into other files (the size of a regular commercial/enterprise application then it would be a dog's breakfast and not maintainable at all.</p>\n\n<p>You need to take more care with your code and make it readable and consistent. Think of it as formatting your resume for a potential employer. Use consistent whitespace between characters, consistent comments above the code (not multiple line breaks between) and above all adopt one of the common style guides for the language. Winston posted an excellent example earlier.</p>\n\n<p>This shows you can at least write code that reads and presents well. If you're coding in a professional environment, other people have to read the code you wrote as well and they need to understand it quickly. If they're scanning through the code then suddenly there's a random comment floating in the page it's a real distraction.</p>\n\n<p>A good book to read is <a href=\"http://rads.stackoverflow.com/amzn/click/0132350882\">Clean Code by Robert Martin</a>. You must read this as if your life depended on it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-21T03:18:15.070",
"Id": "329038",
"Score": "5",
"body": "https://xkcd.com/859/ )"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T23:59:40.400",
"Id": "27870",
"ParentId": "27824",
"Score": "44"
}
},
{
"body": "<p>Problems:</p>\n\n<ol>\n<li><p>I would say that <code>import</code> should be an efficient way of reusing the libraries.</p>\n\n<pre><code>import urllib, bencode , hashlib\nfrom hashlib import sha1\n</code></pre>\n\n<p>In the above line of code you have imported <code>hashlib</code> and <code>sha1</code> from <code>hashlib</code> on the second line. There is nothing wrong in that, but when you just want to use only <code>sha1</code>, then no need to import the entire class. </p>\n\n<p>Same with other classes: how many members of the above mentioned libraries have you used in your code?</p></li>\n<li><p>All the constants should be predefined at the beginning of the script, not wherever required.</p></li>\n<li><p>What if the above file failed to open (in case file not present)? How do you deal with this exception?</p>\n\n<pre><code>with open (str(filename), 'rb') as myfile:\n downloaded=myfile.read()\n</code></pre>\n\n<p>Use try-except to catch exceptions.</p></li>\n<li><p>Filename is already a string.</p></li>\n<li><p>No need to use an extra variable to store the length of the list. Also there is a space in between the function <code>len</code> and its arg.</p>\n\n<pre><code>length = len (list)\n</code></pre></li>\n<li><p>Use a <code>for</code> loop for indexing, which is better than using a <code>while</code> loop.</p></li>\n<li><p>Meaningless variable names such as <code>i</code>, <code>f</code>, <code>k</code>.</p></li>\n<li><p>The tasks are not well-divided into different subroutines.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-05T11:42:33.130",
"Id": "60320",
"Score": "3",
"body": "Problem 8 is the biggest problem. His solution is a typical case of a `transactional script`. I hate transactional scripts, and others do too."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T10:06:01.127",
"Id": "27887",
"ParentId": "27824",
"Score": "30"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T03:55:04.517",
"Id": "27824",
"Score": "213",
"Tags": [
"python",
"algorithm",
"interview-questions"
],
"Title": "Calculate SHA1 hash from binary and verify with a provided hash"
}
|
27824
|
<p>This is Tic-Tac-Toe using negamax for AI. Help me make it better!</p>
<p>Some sore points are:</p>
<pre><code>def get_mark
good_mark = false
until good_mark
mark = gets.chomp
if mark =~ /x/i
chose_x
good_mark = true
elsif mark =~ /o/i
chose_y
good_mark = true
else
puts <<-EOS.gsub(/^ */, '')
What is this strange mark? please choose 'X' or 'O'!
EOS
end
end
end
</code></pre>
<p>and</p>
<pre><code>def game_won?
@solutions.clear
make_solutions
won = false
@solutions.each do |solution|
if solution[0] != ' ' &&
solution[0] == solution[1] && solution[1] == solution[2]
won = true
end
end
return won
end
</code></pre>
<p>The rest of this is <a href="https://github.com/dave-maldonado/tic-tac-doh/blob/master/tic-tac-doh.rb" rel="nofollow">here</a>.</p>
|
[] |
[
{
"body": "<p>Some suggestions:</p>\n\n<ol>\n<li>Avoid flags. Oftentimes there are a hint that you can structure your code better</li>\n<li>Learn the available language constructs and methods (e.g. <code>case/when</code> or <code>#any?</code>)</li>\n<li>Avoid methods with side effects when you can better use a functional style. (E.g. a implement <code>solutions</code> method returning the solutions instead of a <code>make_solutions</code> method which modifies an instance variable with even has to be initialized before the call.) Among other things this improves reusability. You can still cache results in instance variables if needed.</li>\n</ol>\n\n<p>Considering this you can write your provided code snippets a little neater: </p>\n\n<pre><code>def get_mark\n while (mark = gets.chomp)\n case mark\n when /x/i then chose_x\n when /o/i then chose_y\n else\n puts <<-EOS.gsub(/^ */, '')\n\n What is this strange mark? please choose 'X' or 'O'!\n EOS\n continue\n end\n break\n end\nend\n\ndef game_won?\n solutions.any? do |solution|\n solution[0] != ' ' && solution[0] == solution[1] && solution[1] == solution[2]\n end\nend\n</code></pre>\n\n<p>I didn't dig through your git repo though. If you have more specific questions you should ask them. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T21:32:41.540",
"Id": "35206",
"ParentId": "27826",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T04:56:21.927",
"Id": "27826",
"Score": "1",
"Tags": [
"beginner",
"ruby",
"game",
"tic-tac-toe",
"ai"
],
"Title": "Ruby Tic-Tac-Toe using classes"
}
|
27826
|
<p>I'm a JavaScript developer. I'm pretty sure that will be immediately apparent in the below code if for no other reason than the level/depth of chaining that I'm comfortable with. However, I'm learning Ruby, and so I'd love to write beautiful Ruby code too. My simple first project is a Craigslist search-across-regions script.</p>
<p>The full code is <a href="https://github.com/nathanhammond/carscanner/blob/master/index.rb" rel="nofollow">on GitHub</a>, but broken down into snippets with questions below.</p>
<hr>
<pre><code>def get_us_regions()
# Accumulator for building up the returned object.
results = {}
# Important URLs
sitelist = URI('http://www.craigslist.org/about/sites')
geospatial = URI('http://www.craigslist.org/about/areas.json')
# Get a collection of nodes for the US regions out of craigslist's site list.
usregions = Nokogiri::HTML(Net::HTTP.get(sitelist)).search("a[name=US]").first().parent().next_element().search('a')
# Parse out the information to build a usable representation.
usregions.each { |usregion|
hostname = usregion.attr('href').gsub('http://','').gsub('.craigslist.org','')
results[hostname] = { name: usregion.content, state: usregion.parent().parent().previous_element().content }
}
# Merge that information with craigslist's geographic information.
areas = JSON.parse(Net::HTTP.get(geospatial))
areas.each { |area|
if results[area["hostname"]]
results[area["hostname"]][:stateabbrev] = area["region"]
results[area["hostname"]][:latitude] = area["lat"]
results[area["hostname"]][:longitude] = area["lon"]
end
}
# This is a complete list of the US regions, keyed off of their hostname.
return results
end
</code></pre>
<p><strong>Bootstrapping</strong></p>
<ul>
<li>How should I get procedural information I need to get started?</li>
<li>Does this change if I were doing this on bootstrap for a long-running application and wanted to refresh, say, monthly?</li>
<li>Should I shove bootstrapping this into some really abstract class?</li>
</ul>
<p><strong>This Isn't JS</strong></p>
<ul>
<li>How should I chain calls to class methods?</li>
<li>Why hashes with string keys versus the weird named key thing?</li>
</ul>
<p><strong>Object-ions</strong></p>
<ul>
<li>Should I be creating an object for each region and feeding the pieces I parse out of the document into the constructor function?</li>
<li>If I did that, should that constructor function just take a DOM node and be clever with figuring out what I passed it?</li>
<li>And for reopening an object since I have to collate across two sources what's the "right" approach?</li>
</ul>
<hr>
<pre><code># Perform a search in a particular region.
def search_region(regionhostname, query)
# In case there are multiple pages of results from a search
pages = []
pagecount = false
# An accumulator for storing what we need to return.
result = []
# Make requests for every page.
while (pages.length != pagecount)
# End up with a start of "0" on the first time, 100 is craigslist's page length.
page = pages.length * 100
# Here is the URL we'll be making the request of.
url = URI("http://#{regionhostname}.craigslist.org/search/cto?query=#{query}&srchType=T&s=#{page}")
# Get the response and parse it.
pages << Nokogiri::HTML(Net::HTTP.get(url))
# If this is the first time through
if (pagecount == false)
#check to make sure there are results.
if pages.last().search('.resulttotal').length() != 0
# There are results, and we need to see if additional requests are necessary.
pagecount = (pages.last().search('.resulttotal').first().content().gsub(/[^0-9]/,'').to_i / 100.0).ceil
else
# There are no results, we're done here.
return []
end
end
end
# Go through each of the pages of results and process the listings
pages.each { |page|
# Go through all of the listings on each page
page.search('.row').each { |listing|
# Skip listings from other regions in case there are any ("FEW LOCAL RESULTS FOUND").
if listing.search('a[href^=http]').length() != 0
next
end
# Parse information out of the listing.
car = {}
car["id"] = listing["data-pid"]
car["date"] = listing.search(".date").length() == 1 ? Date.parse(listing.search(".date").first().content) : nil
# When Craigslist wraps at the end of the year it doesn't add a year field.
# Fortunately Craigslist has an approximately one month time limit that makes it easy to know which year is being referred to.
# Overshooting by incrementing the month to make sure that timezone differences between this and CL servers don't result in weirdness
if car["date"].month > Date.today.month + 1
car["date"] = car["date"].prev_year
end
car["link"] = "http://#{regionhostname}.craigslist.org/cto/#{car['id']}.html"
car["description"] = listing.search(".pl > a").length() == 1 ? listing.search(".pl > a").first().content : nil
car["price"] = listing.search("span.price").length() == 1 ? listing.search("span.price").first().content : nil
car["location"] = listing.search(".l2 small").length() == 1 ? listing.search(".l2 small").first().content.gsub(/[\(\)]/,'').strip : nil
car["longitude"] = listing["data-longitude"]
car["latitude"] = listing["data-latitude"]
# Pull car model year from description
# Can be wrong, but likely to be accurate.
if /(?:\b19[0-9]{2}\b|\b20[0-9]{2}\b|\b[0-9]{2}\b)/.match(car["description"]) { |result|
# Two digit year
if result[0].length == 2
# Not an arbitrary wrapping point like it is in MySQL, etc.
# Cars have known manufacture dates and can't be too far in the future.
if result[0].to_i <= Date.today.strftime("%y").to_i + 1
car["year"] = "20#{result[0]}"
else
car["year"] = "19#{result[0]}"
end
# Four digit year is easy.
elsif result[0].length == 4
car["year"] = result[0]
end
}
else
car["year"] = nil
end
# Store the region lookup key.
car["regionhostname"] = regionhostname
result << car
}
}
return result
end
</code></pre>
<p><strong>Car vs. Listing</strong></p>
<ul>
<li>Now I have two possible "competing" objects if I were to throw this into a class. The listing is describing a car, but I care about capturing information from both. Should I store both and link them? A listing "has-one" car?</li>
</ul>
<p><strong>Results Pages</strong></p>
<ul>
<li>Should each page be an object? The first little bit I go through is to figure out how many pages I need to request.</li>
<li>How should I prevent this from running in serial? Should I bubble these functions back out by returning functions? Is that really possible to do cleanly in Ruby?</li>
</ul>
<p><strong><em>If</em> the code has to look like <em>this</em>...</strong></p>
<ul>
<li>The if statements where I'm checking to see if something is there (and calling the method twice) are terrible. But it throws ugly errors if I try to access things that aren't present.</li>
<li>Ternary was the best I found, are there other tricks?</li>
</ul>
<p><strong>Misc.</strong></p>
<ul>
<li>Is "next" in good favor?</li>
<li>Are there idioms for pulling information out of Match objects?</li>
<li>What about building up strings? Am I doing that right?</li>
</ul>
<hr>
<pre><code>def search(query)
results = []
# Get a copy of the regions we're going to search.
regions = get_us_regions()
# Divide the requests to each region across the "right" number of threads.
iterations = 5
count = (regions.length/iterations.to_f).ceil
# Spin up the threads!
(0..(iterations-1)).each { |iteration|
threads = []
# Protect against source exhaustion
if iteration * count > regions.length()
next
end
# Split the requests by region.
regions.keys.slice(iteration*count,count).each { |regionhostname|
threads << Thread.new(regionhostname) { |activeregionhostname|
# New block for proper scoping of regionhostname
results << search_region(activeregionhostname, query)
}
}
# Wait until all threads are complete before kicking off the next set.
threads.each { |thread| thread.join }
}
# From search_region we return an array, which means we need to flatten(1) to pull everything up to the top level.
results = results.flatten(1)
# Sort the search results by date, descending.
results.sort! { |a,b|
if a["date"] == b["date"]
b["id"].to_i <=> a["id"].to_i
else
b["date"] <=> a["date"]
end
}
return results
end
puts search("TDI").to_json
</code></pre>
<p><strong><code>public static void main</code></strong></p>
<ul>
<li>Threading! Asynchronous code makes sense to me, but my (Ruby) threads blow up if I create too many at once. Is there an idiom for queuing activity for a set number of worker threads?</li>
<li>For statements? or (0..5).each { |index| }?</li>
<li>Globals for collections of objects? only in "main"?</li>
<li>Are there naming conventions I'm doing incredibly wrong?</li>
<li>Is there anything else I should have asked?</li>
</ul>
<hr>
<p><strong>Conclusion</strong></p>
<p>The code works, and you can use it to get results from every region for a car search on Craigslist. This is nice for rare/hard-to-find vehicles. I'd love for the threading to be better and include the multiple requests from pagination on different threads, but I'd need some sort of pool to handle that. Eventually I'm thinking of integrating Rack into this for a simplistic vehicle search API. Or maybe it gets smarter and stores the results in a DB to track pricing over time and create more educated sellers and consumers or to flag good deals.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T23:33:11.313",
"Id": "43550",
"Score": "0",
"body": "my goodness i had totally forgotten that ruby even had a `for` statement"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-29T01:22:53.417",
"Id": "43553",
"Score": "0",
"body": "So I think that answers the question about using \"for\" statements. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-29T04:02:45.337",
"Id": "43561",
"Score": "0",
"body": "`5.times { |i| }` is a little more expressive"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-29T04:06:43.523",
"Id": "43562",
"Score": "0",
"body": "also i'm sure you know this at this point, but when a block spans more than one line, you should almost always be using the `do |i| end` construct instead of the `{ |i| }` one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-08T21:23:46.953",
"Id": "44202",
"Score": "0",
"body": "Check out this [Ruby-Style-Guide](https://github.com/bbatsov/ruby-style-guide). It's a good reference for all the little questions you may have. Good luck"
}
] |
[
{
"body": "<p>Long, long question. I'll take your first snippet and leave others to tackle the rest. First some comments about your code:</p>\n\n<ul>\n<li><p><code>def get_us_regions()</code>: It's not idiomatic to puts those <code>()</code> on methods without arguments.</p></li>\n<li><p><code>first()</code>: It's not idiomatic to write them on calls without arguments either.</p></li>\n<li><p><code>results = {}</code>: I've already written a lot about this subject in CR, so I'll just give the link: <a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">functional programming with Ruby</a>.</p></li>\n<li><p><code># Important URLs</code>: Not sure if important enough to deserve a comment :-)</p></li>\n<li><p><code>Nokogiri::HTML(...) ... long expression</code>. Expressions can be chained without end, you must decide when to break and give meaningful names. I'd broke it down at least into two subexpressions.</p></li>\n<li><p><code>gsub('http://','').gsub('.craigslist.org','')</code>: Use module <a href=\"http://www.ruby-doc.org/stdlib-1.9.3/libdoc/uri/rdoc/URI.html\" rel=\"nofollow\">URI</a> instead of performing manual manipulation of URLs.</p></li>\n<li><p><code>results[area[\"hostname\"]][:stateabbrev]</code>: Again, a functional approach on this kind of expressions make them more concise and clear.</p></li>\n<li><p><code>return results</code>: Explicit <code>return</code>s are not idiomatic.</p></li>\n<li><p><code>def get_us_regions</code>. When a method is so trivial to make it configurable, do so, here give the country as argument -> <code>def get_regions(country_code)</code>.</p></li>\n</ul>\n\n<p>Now how I'd write the method. First I'd use <a href=\"http://ruby-doc.org/gems/docs/f/facets-2.9.3/\" rel=\"nofollow\">Facets</a>, an excellent library with lots of cool abstractions not present in the core:</p>\n\n<pre><code>require 'uri'\nrequire 'nokogiri'\nrequire 'net/http'\nrequire 'json'\nrequire 'facets'\n\nmodule CraigsList\n SitelistUrl = 'http://www.craigslist.org/about/sites'\n GeospatialUrl = 'http://www.craigslist.org/about/areas.json'\n\n # Return hash of pairs (hostname, {:name, :state, :stateabbr, :latitude, :longitude})\n # for US regions in craigslist.\n def self.get_regions(country_code)\n doc = Nokogiri::HTML(Net::HTTP.get(URI(SitelistUrl)))\n usregions = doc.search(\"a[name=#{country_code}]\").first.parent.next_element.search('a')\n state_info = usregions.mash do |usregion|\n hostname = URI.parse(usregion.attr('href')).host.split(\".\").first\n state = usregion.parent.parent.previous_element.content\n info = {name: usregion.content, state: state}\n [hostname, info] \n end\n\n areas = JSON.parse(Net::HTTP.get(URI(GeospatialUrl)))\n geo_info = areas.slice(*state_info.keys).mash do |area|\n info = {stateabbrev: area[\"region\"], latitude: area[\"lat\"], longitude: area[\"lon\"]}\n [area[\"hostname\"], info] \n end\n\n state_info.deep_merge(geo_info)\n end\nend\n</code></pre>\n\n<p>You mention that you write Javascript code. The good thing about a functional approach is that code is (syntactic differences aside) identical in any language (if it has minimal functional capabilities). In JS (although FP style is more friendly with Coffeescript) and <a href=\"http://underscorejs.org/\" rel=\"nofollow\">underscore</a> (+ custom abstractions as mixins) you could write the same code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-29T02:05:29.347",
"Id": "43555",
"Score": "0",
"body": "Okay, it looks like I need to learn how Ruby blocks work in depth, as well as all of their syntax. They appear to be wonderfully powerful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-29T04:00:50.577",
"Id": "43560",
"Score": "0",
"body": "in one way, blocks are just syntactic sugar for javascript's anonymous functions :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-29T04:08:21.107",
"Id": "43563",
"Score": "0",
"body": "although i guess javascript rarely encourages functional programming to the extent that ruby does"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-29T04:31:05.163",
"Id": "43564",
"Score": "0",
"body": "They're incredibly similar to anonymous functions in JS, but I saw a few use cases where you could pass blocks around into things that look like ES6 generators with their use of yield. I'm reading as much as I can on it for now. :) And, hello lexical scoping! My how I've missed you old friend!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-29T06:40:43.850",
"Id": "43567",
"Score": "0",
"body": "@JustinL. Personally I always use (try to use at least) JS with a purely functional approach except, of course, for external side-effects. But as I said I use Coffeescript because its light syntax makes it more bearable."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T20:55:48.227",
"Id": "27863",
"ParentId": "27832",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27863",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T06:35:18.253",
"Id": "27832",
"Score": "5",
"Tags": [
"object-oriented",
"ruby",
"multithreading",
"http",
"web-scraping"
],
"Title": "Craigslist search-across-regions script"
}
|
27832
|
<p>Background: I was making a chrome extension that injects movie ratings into theatres' showtimes pages. The problem I was duplicating a lot of code calling similar but just slightly different functions. Sometimes I wanted to do an <code>$(el).prepend</code>, sometimes <code>$(el).append</code>, or <code>$(el).after</code>, or <code>$(el).find('something').prepend</code>, or <code>$(el).closest('something').prepend/append/after</code>. </p>
<p>An example of an instance of a function I'm trying to generalize/abstract: </p>
<pre><code>$('.FFEC-Display').each(function(i, el){
var title = $(el).find('h3').text().replace(blacklistRegexp, '').trim();
/* can ignore the three lines below, they are always the same
var tomato = findTomato(title, tomatoes);
var classes = ["poster-width", "overlay"];
var templateData = tomato ? prepareData(tomato, classes) : { query: title, classes: namespaceClasses(classes) };
*/
$(el).find('.movie-link').prepend(Handlebars.templates.ratings(templateData)); //this is the line that gives me trouble
});
</code></pre>
<p>Another instance: </p>
<pre><code>$('.MovieItemsRotator .item').each(function(i, el){
var title = $(el).find('.Title').text().replace(blacklistRegexp, '').trim();
/* you can ignore the code in here
var tomato = findTomato(title, tomatoes);
var classes = ["overlay", "overlay-poster"];
var templateData = tomato ? prepareData(tomato, classes) : { query: title, classes: namespaceClasses(classes) };
*/
$(el).prepend(Handlebars.templates.ratings(templateData));
});
</code></pre>
<p>I have three more instances of very similar functions, and plan on adding more. Full code page <a href="https://github.com/cheapsteak/Chrome-Movie-Buddy/blob/master/moviebuddy.js" rel="nofollow noreferrer">here on GitHub</a></p>
<p>One of the <a href="https://stackoverflow.com/a/17335053/482053">half-joking answers</a> in my SO question inspired me to write a solution using strings of function names, iteratively called on <code>$(el)</code> to solve the problem. </p>
<p>It started out as an exercise just because it seemed like too fun a solution not to try and write, but now I'm feeling more tempted to actually use the code, as opposed to <a href="https://stackoverflow.com/a/17334826/482053">this other one</a>, which seems much more readable/maintainable. Hopefully people with more experience can give me some advice. </p>
<p>The code in question: </p>
<pre><code>json = [
{target: '.FFEC-Display', title : 'h3', actions : [{action: 'find', target: '.movie-link'}, 'prepend']},
{target: '.MovieItemsRotator .item', title: '.Title', actions: ['prepend']}
];
$.each(json, function(index, j){
$(j.target).each(function(i, el){
var title = $(el).find(j.title).text().replace(blacklistRegexp, '').trim();
/* you can ignore the code in here
var tomato = findTomato(title, tomatoes);
var classes = ["poster-width", "overlay"];
var templateData = tomato ? prepareData(tomato, classes) : { query: title, classes: namespaceClasses(classes) };
*/
var abomination = $(el);
$.each(j.actions, function(k, action){
if(typeof action === "string") {
abomination = abomination[action]();
} else {
abomination = abomination[action.action](action.target);
}
});
abomination(Handlebars.templates.ratings(templateData));
});
});
</code></pre>
|
[] |
[
{
"body": "<p>Firstly, I wouldn't say it's evil. From JS's point of view, <code>obj[\"foo\"]()</code> is identical to <code>obj.foo()</code>. The dot-syntax and bracket-syntax are completely interchangeable. Of course, if you call your variable \"abomination\" then, yeah, it's going to <em>sound</em> evil.</p>\n\n<p>Anyway, I think there's a bug or two in your code. When you loop through the <code>json</code> array and get to the <code>actions</code> property, you call the function on <code>$(el)</code> right away. This won't actually do anything, as far as I can tell.</p>\n\n<p>Here's your code, manually interpreted, so to speak:</p>\n\n<pre><code>// this line does nothing; abomination is still === $(el)\nabomination = abomination[action](); // same as: abomination = $(el)[\"prepend\"]();\n\n// ...\n\n// and this line fails with \"error: object is not a function\", because $(el) is indeed not a function\nabomination(Handlebars.templates.ratings(templateData)); // same as: $(el)(Handlebars.templates.ratings(templateData))\n</code></pre>\n\n<p>Also, I imagine the objects in the <code>json</code> array are meant to work on different sites. In that case, I'd key them to the site's domain, so you don't have to loop through everyone of the them on every site. This also eliminates the risk of \"false positives\" such as if a two different sites both use, say, \"movie\" as a class name.</p>\n\n<p>Here is what I'd probably do. I've changed names here and there to make 'em more descriptive, but the comments should make it fairly clear</p>\n\n<pre><code>var sites = { // slightly more descriptive name than \"json\"\n 'movietheatre.com': {\n container: '.FFEC-Display', // changed the name here too..\n title: 'h3',\n select: [\n { name: 'find', args: ['.movie-link'] } // note that args is an array\n ],\n action: 'prepend'\n },\n\n 'showtimes.randomcinema.com': { // note there's no `select` property here\n container: '.MovieItemsRotator .item',\n title: '.Title',\n action: 'prepend'\n }\n};\n\nvar domain = window.location.hostname.replace(/^www\\./, \"\"), // the domain (incl. subdomain unless it's \"www\")\n config = sites[domain]; // get the config\n\n// only do stuff if there's a configuration for the current domain\nif( config ) {\n $(config.container).each(function () {\n var container = $(this);\n\n // I'd put the blacklist-replace/trim stuff into a `getRatings()` function\n // that does all the stuff you say is the always the same anyway. It can also\n // do the template rendering, while it's at it\n var title = container.find(config.title).text();\n var ratings = getRatings(title); // get the rendered template\n\n // maybe throw in a check here, in case `getRatings` fails/refuses to return something\n if( !ratings ) { return; }\n\n // Now for the fun stuff\n var target = container;\n\n // if there's no sub-select-stuff, default to an empty array \n // (and use the built-in forEach instead of jQuery)\n (config.select || []).forEach(function (call) {\n // use `apply()` to call the requested function with the requested args (if any)\n target = target[call.name].apply(target, call.args || []);\n });\n\n // now `target` should be the right element\n // and we can call the required insert/append/prepend action\n target[config.action](ratings); // i.e. target.prepend(ratings)\n });\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T12:43:00.283",
"Id": "27894",
"ParentId": "27833",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T06:48:46.900",
"Id": "27833",
"Score": "4",
"Tags": [
"javascript"
],
"Title": "Is this use of an array of function names and bracket-notation function calling a hacky/evil solution?"
}
|
27833
|
<p>Thanks for the Reply. </p>
<p>Here is the actual Scenario
My application received the data from a backend in the form of a class object ie. </p>
<pre><code>public class FlowObject {
private String id;
private List<FlowStep> flowlSteps;
private List<String> audRefs;
}
</code></pre>
<p>Now FlowStep class as mentioned above is </p>
<pre><code>public class FlowStep {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
</code></pre>
<hr>
<p>Now since Backend code is NOT ready Im writing the dummy implementation of backend FlowObject Class at my Side whose data gets copied to my local Class FlowCopy
Thats why I need to write both FlowObject and FlowCopy Classes </p>
<p>Now My Backend Dummpy Implemetation of FlowObject is as below</p>
<pre><code>import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FlowObject {
private String id;
private List<FlowStep> flowlSteps;
private List<String> audRefs;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<FlowStep> getFlowSteps() {
return flowlSteps;
}
public void setFlowSteps(List<FlowStep> flowlSteps) {
this.flowlSteps= flowlSteps;
}
public List<String> getAudRefs() {
return audRefs;
}
public void setAudRefs(List<String> audRefs) {
this.audRefs = audRefs;
}
}
</code></pre>
<p>And public class FlowStep { </p>
<pre><code>private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
</code></pre>
<p>} </p>
<p>and my local FlowCopy Class is as below</p>
<pre><code>public class FlowCopy {
private String id;
private List<FlowStep> flowSteps;
private List<String> audRefs;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<FlowStep> getFlowSteps() {
return flowSteps;
}
public void setFlowlSteps(List<FlowStep> flowSteps) {
this.flowSteps= flowSteps;
}
public List<String> getAudRefs() {
return audRefs;
}
public void setAudRefs(List<String> audRefs) {
this.audRefs = audRefs;
}
}
</code></pre>
<p>Now my intention is to Copy the Custom FlowObject Class to a list of FlowCopy which will be used in application </p>
<pre><code>public List<FlowCopy> getFlow( List<FlowObject > obj ){
List<FlowCopy> flowRes = new ArrayList<FlowCopy>(obj.size());
for (FlowObject object:obj)
{
FlowCopy callFlow = new FlowCopy();
callFlow.setId(object.getId());
callFlow.setAudioRefs(object.getAudRefs());
callFlow.setCallSteps(object.getFlowSteps());
flowRes .add(callFlow);
}
return flowRes ;
}
</code></pre>
<p>Please review the above implemetation and suggest a suitable approach</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T09:18:49.937",
"Id": "43405",
"Score": "2",
"body": "The first problem I see is that your FlowStep is mutable; as such, if an element of a list in FlowObject is still referenced by another method and it modifies it, the list in FlowObject sees that change. Is that intended? Also, you set and get Lists directly; same problem: collections are mutable"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T09:23:55.083",
"Id": "43407",
"Score": "0",
"body": "Thanks , So what changes u suggest ? Please let me know"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T09:28:24.697",
"Id": "43409",
"Score": "0",
"body": "I can't really know unless I know the use case; for instance, are there potentially several threads accessing a same FlowObject? Are there potentially threads putting a FlowStep in a List but keeping a reference to it? I can only list the possibilities in an answer if you like, but proposing code to fit your model requires knowing the model ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-26T23:29:40.553",
"Id": "48104",
"Score": "0",
"body": "Copying objects is tedious, you could consider Dozer which does deep object copies with no configuration if the property names match: http://dozer.sourceforge.net/"
}
] |
[
{
"body": "<p>One thing I guess you can consider is to add a constructor for class FlowCopy that handles (or encapsulates) the copy task to release this burden from function getFlow():</p>\n\n<pre><code>public class FlowCopy {\n public FlowCopy(FlowObject obj) {\n setId(obj.getId()); \n setAudioRefs(obj.getAudRefs()); \n setCallSteps(obj.getFlowSteps());\n }\n ...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T10:13:24.200",
"Id": "27840",
"ParentId": "27837",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T09:06:16.383",
"Id": "27837",
"Score": "1",
"Tags": [
"java"
],
"Title": "Review the code to copy List of custom class to another list of Custom class"
}
|
27837
|
<p>T_PROJECT is the class that will be retrieve data from linq to sql and ProjectOwnerDataFields is the class that will be used to show data in view. in edit mode i have to get value from model and send it back like this. is there anyway to refactor this and remove the reverse duplication on ProjectOwnerDataFields and UpdateToModel ?</p>
<pre><code> public class ProjectOwnerDataFields
{
public int Id { get; set; }
public string CompanyName { get; set; }
public string ContactPerson { get; set; }
public string CountryIsoLetter { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string Fax { get; set; }
public string Location { get; set; }
public string Province { get; set; }
public string Remark { get; set; }
public string CountryFullName
{
get
{
if (String.IsNullOrEmpty(this.CountryIsoLetter) == false)
{
return new RegionInfo(this.CountryIsoLetter).EnglishName;
}
return "";
}
}
public ProjectOwnerDataFields()
{
}
public ProjectOwnerDataFields(T_PROJECT project)
{
this.Id = project.proj_owner_id ;
this.CompanyName = project.proj_owner ;
this.ContactPerson = project.proj_owner_contact ;
this.CountryIsoLetter = project.proj_owner_country ;
this.Phone = project.proj_owner_phone ;
this.Email = project.proj_owner_email ;
this.Fax = project.proj_owner_fax ;
this.Location = project.proj_owner_location ;
this.Province = project.proj_owner_province ;
this.Remark = project.proj_remark ;
}
public void UpdateToModel(T_PROJECT project)
{
project.proj_owner = this.CompanyName ;
project.proj_owner_contact = this.ContactPerson ;
project.proj_owner_country = this.CountryIsoLetter ;
project.proj_owner_phone = this.Phone ;
project.proj_owner_email = this.Email ;
project.proj_owner_fax = this.Fax ;
project.proj_owner_location = this.Location ;
project.proj_owner_province = this.Province ;
project.proj_remark = this.Remark ;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Anyone may correct me if I'm wrong but honestly: I don't think so. </p>\n\n<p>(Offtopic)</p>\n\n<p>This can be rewritten:</p>\n\n<pre><code>if (String.IsNullOrEmpty(this.CountryIsoLetter) == false)\n{\n return new RegionInfo(this.CountryIsoLetter).EnglishName;\n}\nreturn \"\";\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>return String.IsNullOrEmpty(CountryIsoLetter) ? \"\" : new RegionInfo(CountryIsoLetter).EnglishName;\n</code></pre>\n\n<p>Also you can ommit 'this' in your code as it is not qualifying a hidden member with a same name.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T13:16:15.790",
"Id": "43415",
"Score": "2",
"body": "BTW, I think the second part of your question is not off topic. It's okay to review the code in question in ways that weren't asked for."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T12:59:41.637",
"Id": "27846",
"ParentId": "27844",
"Score": "0"
}
},
{
"body": "<p>This is very close to what <a href=\"http://automapper.org/\" rel=\"nofollow\">AutoMapper</a> is for. Though it doesn't directly support bidirectional maps, so you'll have to write a simple class that builds two mappers at the same time:</p>\n\n<pre><code>public class TwoWayMapper<TSource, TDestination>\n{\n private readonly IMappingExpression<TSource, TDestination> m_sourceMapping =\n Mapper.CreateMap<TSource, TDestination>();\n private readonly IMappingExpression<TDestination, TSource> m_destinationMapping =\n Mapper.CreateMap<TDestination, TSource>();\n\n public TwoWayMapper<TSource, TDestination> ForMember(\n Expression<Func<TSource, object>> sourceMember,\n Expression<Func<TDestination, object>> destinationMember)\n {\n m_sourceMapping.ForMember(destinationMember, opt => opt.MapFrom(sourceMember));\n m_destinationMapping.ForMember(sourceMember, opt => opt.MapFrom(destinationMember));\n return this;\n }\n}\n</code></pre>\n\n<p>You can then set up your mapping like this (maybe in a static constructor of <code>ProjectOwnerDataFields</code>?):</p>\n\n<pre><code>new TwoWayMapper<ProjectOwnerDataFields, T_PROJECT>()\n .ForMember(f => f.Id, p => p.proj_owner_id)\n .ForMember(f => f.CompanyName, p => p.proj_owner)\n .ForMember(f => f.ContactPerson, p => p.proj_owner_contact)\n .ForMember(f => f.CountryIsoLetter, p => p.proj_owner_country);\n // etc.\n</code></pre>\n\n<p>With that, your methods simplify to:</p>\n\n<pre><code>public ProjectOwnerDataFields(T_PROJECT project)\n{\n Mapper.Map(project, this);\n}\n\npublic void UpdateToModel(T_PROJECT project)\n{\n Mapper.Map(this, project);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T14:08:53.127",
"Id": "27848",
"ParentId": "27844",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "27848",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T11:57:38.793",
"Id": "27844",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Refactor data tranfer object and model"
}
|
27844
|
<p>I should be able to figure this out on my own, but I can't seem to wrap my head around how to optimize this set of logic for interpreting the existence of URL parameters.</p>
<pre><code><cfif ParameterExists(start) and not ParameterExists(end) and not ParameterExists(after)>
<cfquery name="STUDENT" datasource="#STUD_DB#">
SELECT *
FROM student_profile
WHERE (Date_Modified BETWEEN '#token# #start#' AND '#token# 23:59:59')
</cfquery>
<cfelseif ParameterExists(end) and not ParameterExists(start) and not ParameterExists(after)>
<cfquery name="STUDENT" datasource="#STUD_DB#">
SELECT *
FROM student_profile
WHERE (Date_Modified BETWEEN '#token# 00:00:00' AND '#token# #end#')
</cfquery>
<cfelseif ParameterExists(start) and ParameterExists(end) and not ParameterExists(after)>
<cfquery name="STUDENT" datasource="#STUD_DB#">
SELECT *
FROM student_profile
WHERE (Date_Modified BETWEEN '#token# #start#' AND '#token# #end#')
</cfquery>
<cfelseif ParameterExists(after) and not ParameterExists(start) and not ParameterExists(end)>
<cfquery name="STUDENT" datasource="#STUD_DB#">
SELECT *
FROM student_profile
WHERE (Date_Modified BETWEEN '#token# #after#' AND '#today# 23:59:59')
</cfquery>
<cfelse>
<cfquery name="STUDENT" datasource="#STUD_DB#">
SELECT *
FROM student_profile
WHERE (Date_Modified BETWEEN '#token# 00:00:00' AND '#token# 23:59:59')
</cfquery>
</cfif>
</code></pre>
<p>It's a disgusting chunk of code, I know. Its operation is pretty simple, though: run a query with a set of parameters if they exist.</p>
<p>I would like to have some sort of short circuit logic so I can just say:</p>
<pre><code><cfif (logic to check parameters) >
<cfquery name="STUDENT" datasource="#STUD_DB#">
SELECT *
FROM student_profile
WHERE (Date_Modified BETWEEN '#startdate# #starttime#' AND '#enddate# #endtime#')
</cfquery>
</code></pre>
<p>This would most likely require me to set default values as well, but I am okay with that.</p>
|
[] |
[
{
"body": "<p>Yeah, you're not doing yourself any favours by having the elements of the IF conditions in differing orders. It took a bit for me to re-sort everything so I could understand what the heck was going on. I <em>think</em> it distills down to this:</p>\n\n<pre><code><cfscript>\n if (structKeyExists(URL, \"after\")){\n param name=\"URL.start\" default=URL.after type=\"time\";\n variables.endDate = today; // I am not sure what scope TODAY is in, but SCOPE IT. TODAY *must* be a valid, unambiguous date string, EG YYYY-MM-DD\n }else{\n param name=\"URL.start\" default=\"00:00:00\" type=\"time\";\n variables.endDate = token; // same as with TODAY: scope it and make sure it's a valid date\n }\n param name=\"URL.end\" default=\"23:59:59\" type=\"time\";\n\n variables.startDate = token;\n\n variables.start = parseDateTime(\"#startDate# #URL.start#\"); // this could error if the contributing values don't comprise a date/time\n variables.end = parseDateTime(\"#endDate# #URL.end#\"); // ditto\n</cfscript>\n\n<cfquery name=\"STUDENT\" datasource=\"#STUD_DB#\">\n SELECT * <!--- [LIST YOUR COLUMNS HERE, DO NOT USE SELECT *] --->\n FROM student_profile\n WHERE Date_Modified BETWEEN <cfqueryparam value=\"#variables.start#\" cfsqltype=\"CF_SQL_TIMESTAMP\">\n AND <cfqueryparam value=\"#variables.end#\" cfsqltype=\"CF_SQL_TIMESTAMP\">\n</cfquery>\n</code></pre>\n\n<p>Some notes on this solution:</p>\n\n<ol>\n<li>You probably want to do better validation than how I've just used a typed <code>param</code>, and <code>parseDateTime()</code> without first checking the thing actually parses as a date time!</li>\n<li>You want to check and recheck the <code>if</code> statement logic I've used. I did not 100% compare it to your initial <code>if</code> logic</li>\n</ol>\n\n<p>Some general notes:</p>\n\n<ol>\n<li>always scope your variables.</li>\n<li><code>parameterExists()</code> has been deprecated for over ten years. Do not use it.</li>\n<li>you seldom want to <code>SELECT *</code>. In general, specify the columns you want; do not return columns you don't actually need</li>\n<li>NEVER hard-code values into the SQL string. ALWAYS pass them as parameters.</li>\n<li>Don't use strings in place of date/times, when you are doing date operations.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T17:52:44.573",
"Id": "43425",
"Score": "0",
"body": "Great answer, I appreciate this. I am working with 10+ year old code so pardon some of the deprecated functions, this is definitely an improvement over what I had, will start using these practices in the future. Just to clarify, using sqlqueryparams help prevent sql injection if i recall?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T18:01:01.177",
"Id": "43426",
"Score": "0",
"body": "Protecting against SQL injection is a side effect of their purpose. Basically it enables the SQL parser / compile to separate out the SQL from the values, which means it can compile the SQL statement for later use. However it can only be reused if the SQL statement is the same. So if you include values... then it's a different compile for each value combination (if that makes sense). Also as the compiler knows what's SQL and what's value, a value containing SQL (ie: SQL injection) will still not be treated as SQL, it'll be treated as value, and not be executed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T18:03:50.563",
"Id": "43427",
"Score": "0",
"body": "Oh... compilation of SQL (which needs to be done before it can run) is quite resource intensive and slow, so there's quite a performance gain from passing queries that can be compiled for later. Equally, the number of compiled queries that will be held in memory is limited, so the fewer different ones you pass to the DB, the more likely a previously compiled one will still be in memory from last time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T19:37:37.200",
"Id": "43431",
"Score": "0",
"body": "Ahh this is very useful to know, thank you again for the info!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T17:41:15.713",
"Id": "27856",
"ParentId": "27852",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "27856",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T16:52:57.447",
"Id": "27852",
"Score": "0",
"Tags": [
"bitwise",
"coldfusion",
"cfml"
],
"Title": "Bitwise Logic optimization"
}
|
27852
|
<p>I'm working on some exercises Scala by Example and I've implemented an excl() method on sets which removes an element from a set, and a toString method that converts a set to a string.</p>
<p>I'm practicing use pattern matching here. A bit concerned about shadowing my instance variables on the line</p>
<p><code>case NonEmptySet(elem, left, right)</code></p>
<p>Is there anything obvious that could be improved?</p>
<pre><code>trait IntSet {
def incl(x: Int): IntSet
def excl(x: Int): IntSet
def contains(x: Int): Boolean
}
case object EmptySet extends IntSet {
def contains(x: Int): Boolean = false
def incl(x: Int): IntSet = new NonEmptySet(x, EmptySet, EmptySet)
def excl(x: Int) = this
override def toString = "{}"
}
case class NonEmptySet(elem: Int, left: IntSet, right: IntSet) extends IntSet {
def contains(x: Int): Boolean =
if (x < elem) left contains x
else if (x > elem) right contains x
else true
def incl(x: Int): IntSet =
if (x < elem) NonEmptySet(elem, left incl x, right)
else if (x > elem) NonEmptySet(elem, left, right incl x)
else this
def excl(x: Int): IntSet = {
def combine(left: IntSet, right: IntSet): IntSet = {
left match {
case EmptySet => right
case NonEmptySet(elem, ll, lr) => NonEmptySet(elem, combine(ll, lr), right)
}
}
if (x < elem) new NonEmptySet(elem, left excl x, right)
else if (x > elem) new NonEmptySet(elem, left, right excl x)
else combine(left, right)
}
override def toString(): String = {
def listElements(comma: Boolean, set: IntSet) : String = {
set match {
case EmptySet => ""
case NonEmptySet(elem, left, right) => {
val rightPart = elem + listElements(true, right)
val list = left match {
case EmptySet => rightPart
case NonEmptySet(le, ll, lr) => listElements(false, left) + ", " + rightPart
}
(if (comma) ", " else "") + list
}
}
}
'{' + listElements(false, this) + '}'
}
}
var subset = EmptySet incl 2
var set = subset incl 3 incl 4 incl 8 incl 9 incl 10 incl 11 excl 4
println(set contains 6)
println(set.contains(6))
println(set contains 2)
println(set incl 4 incl 6 excl 2)
</code></pre>
|
[] |
[
{
"body": "<p>Some ideas:</p>\n\n<ul>\n<li>Make the trait <code>sealed</code>.</li>\n<li><p><code>combine</code> doesn't need to be a nested function, this only makes it harder to read and causes problems with shadowed variables. Instead you could move it to an accompanying object, or make it a separate method such as:</p>\n\n<pre><code>sealed trait IntSet {\n ...\n private def combine(withRight: IntSet): IntSet;\n}\n</code></pre>\n\n<p>for <code>EmptySet</code> it will just return <code>withRight</code>, for a <code>NonEmptySet</code> it will be</p>\n\n<pre><code> def combine(withRight: IntSet): IntSet =\n NonEmptySet(elem, left.combine(right), withRight);\n</code></pre></li>\n<li><p><code>toString</code> is somewhat complicated, and can suffer from performance problems due to repeatedly concatenating strings together. Instead I'd suggest you to implement <a href=\"http://www.scala-lang.org/api/current/index.html#scala.collection.Traversable\" rel=\"nofollow\"><code>Traversable</code></a>. Not only this will make your class much more useful, it's implementation will be cleaner, because it won't be cluttered by operating with strings. And then you'll already have <code>mkString</code> which you can use as</p>\n\n<pre><code>override def toString: String = mkString(\"{\", \",\", \"}\")\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T11:32:36.767",
"Id": "28872",
"ParentId": "27853",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "28872",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T16:57:32.943",
"Id": "27853",
"Score": "3",
"Tags": [
"scala"
],
"Title": "Printing out a tree set using pattern matching in Scala"
}
|
27853
|
<p>I'd like some comments and any suggestions that you have for where to go next with this.</p>
<p>I've been working on developing a JavaScript library that allows for dynamic forms by simply adding some extra HTML tags and attributes to your form. It's brand new, so it doesn't have a lot of features, but it's based on the idea that you shouldn't need to write a bunch of JavaScript and have to deal with bugs and stuff just to get your form to have multiple pages or to add new fields when you click a button... stuff like that.</p>
<p>All you have to do to make it work is include jQuery and this JavaScript in the page after all the form HTML.</p>
<pre><code>...
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js'></script>
<script type='text/javascript' src='edomform.js'></script>
</body>
</code></pre>
<p>I've got the current JavaScript in a Fiddle with some example HTML and CSS, and some basic documentation/guide material in a Google doc that you can comment on if you like. Any comments and suggestions are welcome.</p>
<p>You're also welcome to use this for whatever you want as-is or with any modifications you or anyone comes up with.</p>
<p><a href="http://jsfiddle.net/Wp2Ue/1/" rel="nofollow">Fiddle</a></p>
<p><a href="https://docs.google.com/document/d/1T08AJr4OGR2ohXLeSK3WjKn8zG-sSLi3Vz1Ya5tLkQY/edit?usp=sharing" rel="nofollow">eDomForm</a></p>
<pre><code>//Configuration variables
var config = jQuery("edfconfig");
function getConfigBoolean(attr) {
if (config != null)
return jQuery(config).attr(attr) != undefined;
}
function getConfigValue(attr) {
if (config != null)
return jQuery(config).attr(attr);
}
var noasterisks = getConfigBoolean("noasterisks");
var addafter = getConfigBoolean("addafter");
var doactions = getConfigBoolean("doactions");
var noappend = getConfigBoolean("noappend");
var requiredmessage = getConfigValue("requiredmessage");
var requiredmessageid = getConfigValue("requiredmessageid");
//eDomForm variables
var attrs = jQuery("edfvars")[0];
var variables = {};
if (attrs != null)
for (i=0;i<attrs.attributes.length;i++) {
variables[attrs.attributes[i].nodeName] = attrs.attributes[i].nodeValue;
}
//Function because jQuery doesn't have a selector for the name attribute
function getByName(n) {
return document.getElementsByName(n);
}
//required fields have the class required_field
var required = jQuery(".required_field");
//message div to display global form messages
var message = jQuery("#message");
//reference to the entire form itself
var form = jQuery("#form");
//form data
jQuery(form).data("required_empty",required.length);
//Add next and back buttons
jQuery(".form_page").each(function(i){
jQuery(this).prepend('<button type="button" class="back">Back</button> <button type="button" class="next">Next</button>');
});
//Next and Back buttons
var pages = jQuery(".form_page");
var backButtons = jQuery(".back");
var nextButtons = jQuery(".next");
for (i=0;i<pages.length;i++) {
if (i != pages.length-1) {
nextButtons[i].onclick = function() {
jQuery(this).closest("div").fadeOut();
jQuery(this).closest("div").nextAll(":not(.disabled):first").fadeIn();
};
} else {
jQuery(nextButtons[i]).remove();
}
if (i != 0) {
backButtons[i].onclick = function(i) {
jQuery(this).closest("div").fadeOut();
jQuery(this).closest("div").prevAll(":not(.disabled):first").fadeIn();
};
} else {
jQuery(backButtons[i]).remove();
}
}
//Aliases
function getByAlias(a) {
return jQuery("[alias="+a+"]");
}
function hasClass(element, cls) {
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
var aliases = jQuery(".alias");
for (i=0;i<aliases.length;i++) {
var alias = jQuery(aliases[i]).attr("alias");
var original = jQuery("."+alias);
for (j=0;j<original.length;j++) {
if (hasClass(original[j],"required_field")) {
jQuery(aliases[i]).addClass("required_field");
}
original[j].onchange = aliasChange.bind(null,original[j],aliases[i]);
aliases[i].onchange = aliasChange.bind(null,aliases[i],original[j]);
}
}
function aliasChange(o,a) {
a.value = o.value;
a.onblur();
}
var radioGroupCounter = 1;
jQuery(document).ready(function() {
//Prevent form submission if required fields have not been filled in
if (form[0] != null)
form[0].onsubmit = function() {
var required_fields = document.getElementsByClassName("required_field");
for (i=0;i<required_fields.length;i++) {
if (required_fields[i].value == "") {
jQuery("#"+requiredmessageid).html(requiredmessage);
return false;
}
}
jQuery("#"+requiredmessageid).html("");
return true;
};
//Hidden pages
function handleHiddenPages() {
jQuery(".revealer").each(function(i){
var page = jQuery(this).attr("page");
jQuery(this).click(function(){
if (jQuery(this).is(":checked")) {
jQuery("."+page).removeClass("disabled");
} else {
jQuery("."+page).addClass("disabled");
}
});
});
}
handleHiddenPages();
//Switchers
function handleSwitchers() {
jQuery(".switcher").each(function(x){
var connections = jQuery(this).attr("connections");
connections = jQuery.parseJSON(connections);
var connectedSections = {};
for (var key in connections) {
//if something like a-b
if (connections[key].indexOf("-") > -1) {
var nums = connections[key].split("-");
var resultNums = [];
for (i=0;i<nums.length;i++) {
nums[i] = parseInt(nums[i]);
}
for (i=nums[0];i<=nums[nums.length-1];i++) {
resultNums.push(i+"");
connectedSections[i] = key;
}
} else {
if (connections.hasOwnProperty(key))
connectedSections[connections[key]] = key;
}
}
jQuery(this).change(function(){
for (var key in connectedSections) {
jQuery("."+connectedSections[key]).hide();
}
jQuery("."+connectedSections[jQuery(this).val()]).show();
});
});
}
handleSwitchers();
//Displayers/Hiders
function handleDisplayers() {
jQuery(".displayer").each(function(x){
var connected = jQuery(this).attr("display");
var special = "";
var connecteds = [];
if (connected.indexOf(" ") > -1) {
connecteds = connected.split(" ");
var special = connecteds[0];
connected = connecteds[1];
}
var name = jQuery(this).attr("name");
var group = getByName(name);
jQuery(group).each(function() {
jQuery(this).on("click",function() {
var button = this;
if (jQuery(this).attr("display") != null) {
if (special == "") {
jQuery("."+connected).each(function() {
jQuery(this).show();
});
}
else if (special == "next") {
jQuery("."+connected).each(function() {
if (button.compareDocumentPosition(this) == 4) {
jQuery(this).show();
return false;
}
});
}
else if (special == "prev") {
jQuery(jQuery("."+connected).get().reverse()).each(function(i) {
if (button.compareDocumentPosition(this) == 2) {
jQuery(this).show();
return false;
}
});
}
}else {
if (special == "") {
jQuery("."+connected).each(function() {
jQuery(this).hide();
});
}
else if (special == "next")
jQuery("."+connected).each(function() {
if (button.compareDocumentPosition(this) == 4) {
jQuery(this).hide();
return false;
}
});
else if (special == "prev")
jQuery(jQuery("."+connected).get().reverse()).each(function(i) {
if (button.compareDocumentPosition(this) == 2) {
jQuery(this).hide();
return false;
}
});
}
});
});
});
}
handleDisplayers();
//findNext function from stackoverflow
/**
* Find the next element matching a certain selector. Differs from next() in
* that it searches outside the current element's parent.
*
* @param selector The selector to search for
* @param steps (optional) The number of steps to search, the default is 1
* @param scope (optional) The scope to search in, the default is document wide
*/
$.fn.findNext = function(selector, steps, scope)
{
// Steps given? Then parse to int
if (steps)
{
steps = Math.floor(steps);
}
else if (steps === 0)
{
// Stupid case :)
return this;
}
else
{
// Else, try the easy way
var next = this.next(selector);
if (next.length)
return next;
// Easy way failed, try the hard way :)
steps = 1;
}
// Set scope to document or user-defined
scope = (scope) ? $(scope) : $(document);
// Find kids that match selector: used as exclusion filter
var kids = this.find(selector);
// Find in parent(s)
hay = $(this);
while(hay[0] != scope[0])
{
// Move up one level
hay = hay.parent();
// Select all kids of parent
// - excluding kids of current element (next != inside),
// - add current element (will be added in document order)
var rs = hay.find(selector).not(kids).add($(this));
// Move the desired number of steps
var id = rs.index(this) + steps;
// Result found? then return
if (id > -1 && id < rs.length)
return $(rs[id]);
}
// Return empty result
return $([]);
}
//Adding New Sections
function handleAdds() {
jQuery(".add").each(function(x){
var add = jQuery(this).attr("add");
if (add.indexOf(" ") > -1) {
add = add.split(" ");
}
var to = jQuery(this).attr("to");
var radiogroup = jQuery(this).attr("radiogroup");
if (radiogroup != null)
radiogroup = radiogroup.split(" ");
var cpy = jQuery("<div />").append(jQuery("."+add).clone()).html();
if (to == null) {
jQuery(this).click(function() {
var text = cpy;
var counter = radioGroupCounter++;
if (radiogroup != null)
for (i=0;i<radiogroup.length;i++) {
var re = new RegExp(radiogroup[i]+"\\[\\d\\]","g");
text = text.replace(re,radiogroup[i]+"["+(counter)+"]");
}
if (addafter)
jQuery(this).after(text);
else
jQuery(this).before(text);
handleHiddenPages();
handleDisplayers();
handleSwitchers();
});
} else {
if (to.indexOf(" ") > -1) {
to = to.split(" ");
}
jQuery(this).click(function() {
var text = cpy;
var counter = radioGroupCounter++;
if (radiogroup != null)
for (i=0;i<radiogroup.length;i++) {
var re = new RegExp(radiogroup[i]+"\\[\\d\\]","g");
text = text.replace(re,radiogroup[i]+"["+(counter)+"]");
console.log(text);
}
jQuery("#"+to).append(text);
handleHiddenPages();
handleDisplayers();
handleSwitchers();
});
}
});
}
handleAdds();
//Action tags
function handleAll() {
handleHiddenPages();
handleDisplayers();
handleSwitchers();
handleAdds();
}
});
required = jQuery(".required_field");
//Loop through required fields, adding the onblur event
//so that whenever the user deselects a required field,
//if it is blank the asterisk will turn red.
for (i=0;i<required.length;i++) {
jQuery(required[i]).after("<span>*</span>");
jQuery(required[i]).data("empty",true);
required[i].onblur = function() {
if (this.value == "") {
jQuery(this).next().css("color","#f00");
} else {
jQuery(this).next().css("color","#000");
}
};
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>On the whole</strong></p>\n\n<p>Interesting, from a philosophy perspective, you are now moving from code with potential JavaScript bugs to code with potential HTML 'configuration' bugs. Debugging configuration bugs is annoying since there is no dedicated tooling for it.</p>\n\n<p>Furthermore, you have some interesting design choices HTML wise;</p>\n\n<ul>\n<li>You have custom tags but you are not using <code>registerElement</code></li>\n<li>You have custom properties that are not compatible with <code>$().data()</code></li>\n<li>This works, but it should be avoided when possible, and I believe it is possible</li>\n</ul>\n\n<p>From a consistency perspective;</p>\n\n<ul>\n<li>You have a tag property <code>requiredmessage</code></li>\n<li>You have classes <code>required_empty</code> and <code>required_field</code></li>\n<li>Your code is lowerCamelCase</li>\n</ul>\n\n<p>I would synchronize everything to lowerCamelCase across properties, CSS classes and code, otherwise users will have to keep referring to documentation to see what the proper spelling is.</p>\n\n<p><strong>Coding*</strong></p>\n\n<p>Constants, most of these should have a well named constant name;</p>\n\n<ul>\n<li>You use <code>\".required_field\"</code> and <code>\"required_field\"</code> several times</li>\n<li>You use <code>\".alias\"</code> and <code>\"alias\"</code> several times</li>\n<li>etc. etc.</li>\n</ul>\n\n<p>Comments:</p>\n\n<ul>\n<li><code>handleSwitchers</code> <- really unclear what this is supposed to do</li>\n<li>Other than that, the commenting throughout the code is very uneven</li>\n</ul>\n\n<p>Some jQuery specific items:</p>\n\n<ul>\n<li><p>This:</p>\n\n<pre><code>jQuery(\".form_page\").each(function(i){\n jQuery(this).prepend('<button type=\"button\" class=\"back\">Back</button> <button type=\"button\" class=\"next\">Next</button>');\n});\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>var buttons = '<button type=\"button\" class=\"back\">Back</button> <button type=\"button\" class=\"next\">Next</button>';\njQuery(\".form_page\").prepend( buttons );\n</code></pre>\n\n<p>basically <code>prepend</code> works on every selected element.</p></li>\n<li><p>This:</p>\n\n<pre><code>for (i=0;i<pages.length;i++) {\n if (i != pages.length-1) {\n nextButtons[i].onclick = function() {\n jQuery(this).closest(\"div\").fadeOut();\n jQuery(this).closest(\"div\").nextAll(\":not(.disabled):first\").fadeIn();\n };\n } else {\n jQuery(nextButtons[i]).remove();\n }\n if (i != 0) {\n backButtons[i].onclick = function(i) {\n jQuery(this).closest(\"div\").fadeOut();\n jQuery(this).closest(\"div\").prevAll(\":not(.disabled):first\").fadeIn();\n };\n } else {\n jQuery(backButtons[i]).remove();\n }\n}\n</code></pre>\n\n<p>is basically trying to make every back and next button work, and remove the first back button and the last next button, the following code does the exact thing with fewer lines and more clarity of purpose:</p>\n\n<pre><code>nextButtons.last().remove(); \nbackButtons.first().remove(); \n\nnextButtons.click( function(){\n $(this).closest(\"div\").fadeOut()\n .nextAll(\":not(.disabled):first\").fadeIn(); \n});\n\nbackButtons.click( function(){\n $(this).closest(\"div\").fadeOut()\n .prevAll(\":not(.disabled):first\").fadeIn(); \n}) \n</code></pre>\n\n<p>Note also that I chained the two statement within the click handlers for efficiency.</p></li>\n<li>You use jQuery everywhere, but not here: <code>var required_fields = document.getElementsByClassName(\"required_field\");</code> why ?</li>\n<li>Cache <code>jQuery(this)</code> into <code>$this = jQuery(this)</code> in all your listeners where you access <code>jQuery(this)</code> more than once.</li>\n<li><p>When you decide to add a class or remove a class based on a Boolean, consider <code>toggleClass</code>, this:</p>\n\n<pre><code>jQuery(this).click(function(){\n if (jQuery(this).is(\":checked\")) {\n jQuery(\".\"+page).removeClass(\"disabled\");\n } else {\n jQuery(\".\"+page).addClass(\"disabled\");\n }\n});\n</code></pre>\n\n<p>could be</p>\n\n<pre><code>jQuery(this).click(function(){\n var $this = jQuery(this);\n jQuery(\".\"+page).toggleClass( 'disabled' , !$this.is(\":checked\") );\n});\n</code></pre></li>\n<li><p>Not really jQuery related, but realize that ternaries can be your friend:</p>\n\n<pre><code>required[i].onblur = function() {\nif (this.value == \"\") {\n jQuery(this).next().css(\"color\",\"#f00\");\n } else {\n jQuery(this).next().css(\"color\",\"#000\");\n }\n};\n</code></pre>\n\n<p>can be ( you can put the assignment outside of the loop )</p>\n\n<pre><code>required.blur( function() {\n jQuery(this).next().css(\"color\", (this.value == \"\") ? \"#f00\" : \"#000\"); \n});\n</code></pre>\n\n<p>When you think about it, <code>\"#f00\"</code> should be a constant, and probably you should assign a class instead of putting the color red.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T19:58:45.770",
"Id": "48008",
"ParentId": "27854",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "48008",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T17:38:46.123",
"Id": "27854",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"html",
"form",
"dom"
],
"Title": "eDomForm - dynamic forms without writing any JavaScript"
}
|
27854
|
<p>I have code for a class that will manage an OAuth authentication key, included below. Because this class's functionality means it needs to be considered with regards to security, I wanted to check to make sure that all is as it should be (or figure out what ought to be changed), and there aren't any extra risks anywhere. I'm looking for advice on best practice, and I am reasonably sure that there aren't any major bugs in it.</p>
<p>This code will end up running as part of a daemon used to update a database of reports, just a simple tool for automating a task currently performed by hand, so it doesn't need to be bullet proof. Nor does it need to be as secure as you need for an application that will be distributed to hundreds of customers. I just need to be sure it isn't likely to cause our server to become compromised, and that it isn't too easy to break.</p>
<pre><code>import java.awt.Desktop;
import java.io.*;
import java.net.*;
import com.box.boxjavalibv2.BoxClient;
import com.box.boxjavalibv2.dao.BoxOAuthToken;
import com.box.boxjavalibv2.exceptions.*;
import com.box.boxjavalibv2.requests.requestobjects.BoxOAuthRequestObject;
import com.box.restclientv2.exceptions.BoxRestException;
/**
* This class handles the storage and use of authentication keys, to
* simplify the process of obtaining n authenticated client. This class
* will store refresh keys in a file, so that it can authenticate a client
* without needing for user intervention.
* <p>
* Copyright 2013 Mallick Mechanical, Inc.
*
* @author Anson Mansfield
*/
public class Authenticator {
/**
* Constructs an {@code Authenticator} for use obtaining
* authenticated {@Code BoxClient}s
*
* @param key The OAuth client id and application key.
* @param secret The OAuth client secret.
* @param authFile The file to be used for storing authentications
* for later use.
*/
public Authenticator(String key, String secret, File authFile){
this.key = key;
this.secret = secret;
this.authFile = authFile;
}
/**
* Constructs a new {@Code BoxClient} object, authenticates it,
* and returns it.
*/
public BoxClient getAuthenticatedClient(){
BoxClient client = new BoxClient(key,secret);
client.authenticate(getToken(client));
return client;
}
private final String host = "http://localhost";
private final int port = 4000;
private final String key, secret;
private final File authFile;
private final String url =
"https://www.box.com/api/oauth2/authorize?response_type=code&client_id=";
/**
* Obtains a token that can be used to authenticate the box client,
* and stores its refresh value in a file, so it can be used later.
* @param client The client to obtain a token for.
* @return A token that can be used to authenticate the client, or
* {@code null} if one could not be obtained.
*/
private BoxOAuthToken getToken(BoxClient client){
BoxOAuthToken token = null;
try{
if((token = getOldToken(client)) != null) return token;
if((token = getNewToken(client)) != null) return token;
return token;
}finally{
writeNewToken(token);
}
}
/**
* Attempts to write a token's refresh token to a file.
* @param token The token whose refresh value is to be written.
*/
private void writeNewToken(BoxOAuthToken token) {
if(token != null)
try(BufferedWriter out = new BufferedWriter(new FileWriter(authFile))){
out.write(token.getRefreshToken());
}catch(IOException ex){
System.out.println("couldn't update new token");
}
}
/**
* Reads the last session's refresh token from a file and attempts
* to get a new authentication token with it.
* @param client The client for which the authentication token is for.
* @return The token obtained from the refresh, or {@code null} if one
* could not be obtained.
*/
private BoxOAuthToken getOldToken(BoxClient client) {
System.out.println("attempting to use old token");
BoxOAuthToken token = null;
try(BufferedReader in = new BufferedReader(new FileReader(authFile))){
token = client.getOAuthManager().refreshOAuth(
BoxOAuthRequestObject.refreshOAuthRequestObject(
in.readLine(), key, secret
));
System.out.println("refreshed old token");
}catch(IOException ex){
System.out.println("couldn't read old token");
} catch(BoxRestException | BoxServerException | AuthFatalFailureException ex){
System.out.println("couldn't refresh old token");
}
return token;
}
/**
* Connects to the OAuth server and gets a new authentication token.
* @param client The client to get a token for.
* @return The new token obtained from the server, or {@code null} if one
* could not be obtained.
*/
private BoxOAuthToken getNewToken(BoxClient client) {
System.out.println("attempting to get new token");
BoxOAuthToken token = null;
try {
Desktop.getDesktop().browse(java.net.URI.create(url + key));
token = client.getOAuthManager().createOAuth(
BoxOAuthRequestObject.createOAuthRequestObject(
getCode(), key, secret, host + port
));
} catch (BoxRestException | BoxServerException | AuthFatalFailureException
| IOException ex) {
ex.printStackTrace();
return null;
}
return token;
}
/**
* This listens on the configured port for the code included in the callback.
* It also deploys a script on the receiving socket to close the browser tab
* navigating to it.
* @return The authentication code to generate a token with.
*/
private String getCode(){
try (ServerSocket serverSocket = new ServerSocket(port);
Socket socket = serverSocket.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());){
out.println("<script type=\"text/javascript\">");
out.println( "window.open('', '_self', '');");
out.println( "window.close();");
out.println("</script>"); //closes tab
while (true){
String code = "";
code = in.readLine ();
System.out.println(code);
String match = "code";
int loc = code.indexOf(match);
if( loc >0 ) {
int httpstr = code.indexOf("HTTP")-1;
code = code.substring(code.indexOf(match), httpstr);
String parts[] = code.split("=");
code=parts[1];
return code;
} else {
// It doesn't have a code
}
}
} catch (IOException | NullPointerException e) {
return "";
}
}
}
</code></pre>
<p>Also, if anyone wants to have this code for their own use, just ask me, I just need to check with my boss to make sure it's OK before I can release it for use by anyone else (the company does mechanical contracting, not software development).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T19:18:48.527",
"Id": "43430",
"Score": "1",
"body": "It seems crazy that you would need to call the Desktop browser to get the \"code\". But then again, I'm not sure what the \"code\" is."
}
] |
[
{
"body": "<p>If this is running as a daemon - my understanding is that you mean as some kind of cron job or a background task, then who will be logging into your Box.com account to get the 'code' for the first time in the <code>getCode</code>?</p>\n<p>Are you aware of the OAuth2 framework/protocol, if not, <a href=\"https://www.rfc-editor.org/rfc/rfc6749\" rel=\"nofollow noreferrer\">please read it here</a>.</p>\n<p>Basically, anyone having the access token gets the access as long as they also present your <code>client_id</code> and <code>client_secret</code>. Anyone presenting the refresh token will be granted a new access_token if they can give client_id_secret. As you are using java class running on local machine, it's not too hard to get the <code>client_id</code> and <code>client_secret</code> even if they are some constants defined in your class file.</p>\n<p>I am not sure what kind of security you are looking for, but it seems that you are writing the refresh token to some file in the local system. If someone gets the refresh token, they can ask for an access token and have access to all your Box.com files.</p>\n<p>Also, in case of Box.com the refresh token itself expires within 14 days, so if your daemon is not used regularly, then user will have to login to <code>getCode</code> again.</p>\n<p>A more secure solution would be to have some kind of a web-server and register a redirect URL with your Box.com app which points to that server. Then from your web-server, you can get the 'code' and exchange it for the access+refresh token. Then store the refresh token securely (preferably in some db or behind some small app running on your web-server and not on each user machine) and fetch the refresh token to get the <code>access_tokens</code>.</p>\n<p>However, it looks that your requirement is just to upload some MIS reports onto the Box cloud, so this looks good enough. Also, it appears that the user of this local machine actually knows the Box ID/password, so you probably don't have to worry about the user stealing your refresh token.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T15:45:20.717",
"Id": "28422",
"ParentId": "27857",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "28422",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T17:59:47.907",
"Id": "27857",
"Score": "1",
"Tags": [
"java",
"security"
],
"Title": "Authentication Program"
}
|
27857
|
<p>I'm just starting to learn C++ and have been experimenting with various functions. Here is one that computes the number of permutations of <em>n</em> consecutive numbers as well as all possible permutations provided <em>n</em>. I'd love to receive any form of tips and criticisms on improving this function.</p>
<pre><code>#include <string>
#include <iostream>
#include <vector>
#include <sstream>
#include <fstream>
using namespace std;
string rotateRt(string input);
vector<string> permute(int num);
int main(){
cout << "n: ";
int n;
cin >> n;
vector<string> permutations(permute(n));
ofstream myfile;
myfile.open("rosalind_perm.txt");
myfile << permutations.size() << endl;
for(int i = 0; i < permutations.size(); i++){
myfile << permutations.at(i) << endl;
}
myfile.close();
}
/* Rotate input string right by 1 character */
string rotateRt(string input){
int len = input.length();
string a, b;
if(len == 0){
return "";
}
else if(len == 1){
return input;
}
else{
a = input.substr(0, len - 2);
b = input.substr(len - 1) + " ";
return b + a;
}
}
/* To compute permutations we compute the permutations of num - 1,
append num to the front of each permutation, and find every cyclic
rotation. */
vector<string> permute(int num){
vector<string> permutations;
ostringstream convert;
if(num == 1){
permutations.push_back("1");
}
else{
vector<string> prevPermutations(permute(num - 1));
int size = prevPermutations.size();
string prefix, suffix, word;
convert << num;
prefix = convert.str();
convert.str("");
for(int i = 0; i < size; i++){
suffix = prevPermutations.at(i);
word = prefix + " " + suffix;
int length = word.length();
for(int j = 0; j < length / 2 + 1; j++){
permutations.push_back(word);
word = rotateRt(word);
}
}
}
return permutations;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T19:04:12.357",
"Id": "43428",
"Score": "3",
"body": "You know there's an `std::permutations()` function in the standard library?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T19:05:15.240",
"Id": "43429",
"Score": "0",
"body": "Try the [next_permutation] method (http://www.cplusplus.com/reference/algorithm/next_permutation/)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-29T13:08:56.300",
"Id": "43571",
"Score": "0",
"body": "@h2co3 is that proposed for c++14? I don't know any library vendor that has that algorithm :/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-03T12:30:37.653",
"Id": "43795",
"Score": "0",
"body": "I have yet to get into iterators and stl yet. Until next time I guess."
}
] |
[
{
"body": "<ul>\n<li><p>Do not use <code>using namespace std</code>. Learn more about this <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">here</a>.</p></li>\n<li><p>It looks nicer to put the <code>int n</code> above the user input code. You could also give it a nicer name like <code>numberInput</code>.</p></li>\n<li><p>In all of your function bodies, separate different code line blocks with a newline. In <code>main()</code>, for instance: separate the input variable, user input, file-checking, and <code>vector</code> insertions. That way it's easier to see what each function is doing, thus increasing readability.</p></li>\n<li><p>If you're using C++11, consider this <a href=\"http://www.cprogramming.com/c++11/c++11-ranged-for-loop.html\" rel=\"nofollow noreferrer\">range-based <code>for</code>-loop</a> for your loop in <code>main()</code> and apply the same to your outer loop in <code>permute()</code>:</p>\n\n<pre><code>for (auto const &iter : permutations)\n{\n myfile << iter << std::endl;\n}\n</code></pre></li>\n<li><p>If you're not modifying the <code>input</code> parameter in <code>rotateRt()</code>, make it a <code>const&</code> instead:</p>\n\n<pre><code>std::string rotateRt(std::string const& input) {}\n</code></pre></li>\n<li><p>If you're checking to see if an <code>std::string</code> is empty, use <code>empty()</code> instead of <code>== 0</code>:</p>\n\n<pre><code>if (input.empty())\n // do something\n</code></pre></li>\n<li><p>No need to assign <code>input.length()</code> to a variable if you're not doing anything special with it. Just use the accessor itself.</p></li>\n<li><p>What is <code>std::string a, b</code>? Again, give your variables some nice names. Single-character variables are usually preferred for simple loop-counters. These variables could also be declared on separate lines for clarity.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-03T12:48:18.777",
"Id": "43797",
"Score": "0",
"body": "I have trouble making choices between using .empty() and len == 0 as calling .empty() is another function call and since len is checked later anyway, I can avoid the extra overhead of calling empty(). Is this considered often or should I prioritize on understandable code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-03T16:01:25.710",
"Id": "43803",
"Score": "0",
"body": "@whytheman, calling `empty()` shouldn't be too costly as it is an inline function within the `class`. That in mind, it is better to use that than `== 0` in terms of readability. It also boosts maintainability a bit as you don't have to worry about `len == 0` accidentally changing; `empty()` will stay the same."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T19:21:45.507",
"Id": "27860",
"ParentId": "27859",
"Score": "4"
}
},
{
"body": "<p>In addition to <code>Jamal</code>'s good points:</p>\n\n<p><strong>1:</strong> Consider sorting your <code>#include</code>s alphabetically. It's not a big issue, but I think it looks more tidy, and it's easier to see if something is already included or not.</p>\n\n<p><strong>2:</strong> Consider <code>typedef vector<string> StringCollection</code> (or some other meaningful name). This makes it easier to change the underlying data structure later, and makes the code look cleaner.</p>\n\n<p><strong>3:</strong> If you are using C++11, I'd write the <code>for</code> loop like this:</p>\n\n<pre><code>for (auto const& number : permutations) {\n myfile << number << endl;\n}\n</code></pre>\n\n<p>Since you are learning, I see no reason not to get into C++11 right away.</p>\n\n<p><strong>4:</strong> Tutorials and the like often use <code>mySomething</code> as identifiers. <code>my</code> is a bad identifier prefix. Instead, write what role it has or what it represents. <code>outputFile</code> is much better than <code>myFile</code>.</p>\n\n<p><strong>5:</strong> Initialize variables right away. The <code>std::ofstream</code> constructor takes a filename, so there is no need to first initialize and then call <code>open()</code>.</p>\n\n<p><strong>6:</strong> Instantiate variables as late as possible. In your <code>rotateRt()</code> (which should be called <code>rotateRight()</code>, by the way), you don't have to create your <code>string</code>s unless the last <code>else</code> triggers. Change it to this:</p>\n\n<pre><code>else {\n string a = input.substr(0, len - 2);\n string b = input.substr(len - 1) + \" \";\n return b + a;\n}\n</code></pre>\n\n<p>The same applies to for example <code>ostringstream convert</code>.</p>\n\n<p>When you instantiate a variable as late as possible, you avoid constructing it unless you really have to. \"As late as possible\" implies <em>as close as possible to the relevant context</em>, which makes the code easier to read.</p>\n\n<p><strong>7:</strong> Consider rewriting <code>permute()</code> to reduce nesting.</p>\n\n<p><strong>8:</strong> Your code would normally be better suited as a class. You don't have to think too much about this yet, since you just started with C++. It's a good exercise to refactor this to use classes later.</p>\n\n<p><strong>9:</strong> In the case of <code>int len = input.length();</code>, you should use <code>std::size_t</code> instead of <code>int</code>.</p>\n\n<p><strong>10:</strong> Prefer C++-style comments: <code>//</code> (<em>Effective C++</em> explains why, so I won't repeat it here.)</p>\n\n<p><strong>11:</strong> Use more whitespace. Especially more vertical whitespace. Insert an empty line in logical places to make your code much more readable.</p>\n\n<p><strong>12:</strong> You don't modify or copy the <code>string</code> you pass to <code>rotateRt</code>, so it should be reference-to-const instead: <code>rotateRt(string const& input)</code>. (If you prefer, you can write <code>const string&</code>, it's the same thing.)</p>\n\n<p><strong>13:</strong> Consider rewriting <code>permute()</code> so that it's not recursive. Recursive functions that create a couple of objects can quickly chew up a lot of memory, and are often not very efficient. In short, your <code>permute()</code> function can be improved a great deal.</p>\n\n<p><strong>14:</strong> Consider refactoring the file name out into a constant:</p>\n\n<pre><code>const string filename = \"rosalind_perm.txt\";\n</code></pre>\n\n<p>This way it's easier to find if you have to change it, and by using the constant you are guaranteed you will only have to change it in one location.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T22:12:38.620",
"Id": "43435",
"Score": "0",
"body": "+1, but to be really pedantic, `int len` should be `std::string::size_type len` rather than `std::size_t`. I can't imagine any possible situation in which it would matter, but... Yeah... :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T22:17:36.617",
"Id": "43438",
"Score": "0",
"body": "I agree with all items except for the non-recursive rewrite of `permute`: unless there are pressing performance concerns, do *not* do this. Permutation is a naturally recursive operation, a recursive formulation of the problem is much clearer than an iterative one. For this reason it’s also much simpler."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-03T12:43:29.617",
"Id": "43796",
"Score": "0",
"body": "The constructor for ostream takes in const char* for the filename. Would it be better to declare the const char* and then use it in the function call instead?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-03T12:56:49.207",
"Id": "43798",
"Score": "0",
"body": "It has a constructor that takes a `std::string const&` as well. Do like this: `std::string filename = \"bacon.txt\";` and then `std::ofstream outputFile(filename)`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T21:03:16.873",
"Id": "27865",
"ParentId": "27859",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "27865",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T19:02:05.847",
"Id": "27859",
"Score": "3",
"Tags": [
"c++",
"beginner",
"combinatorics"
],
"Title": "Computing the number of permutations of n consecutive numbers"
}
|
27859
|
<p>This will later be be posted on my website to explain quick sort so I would like how I could improve the readability and simplicity of this demo class. I do not like my use of the stack (meaning this recursion cannot process a list with millions of values).</p>
<p>How could I reduce the stack impact? I think the best way would be not to use as many <code>ArrayList</code> instances. However, I don't know how else because I cannot use lists like <code>int[] list</code> because I do not know their size and surely if I just make it too big the loops will be bigger and take longer.</p>
<p>Here is the class in question:</p>
<pre><code>import java.util.ArrayList;
import java.util.Random;
public class QuickSort {
static Random r = new Random();
public static void main(String[] args) {
int listsize = 100000, range = 100000;
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=0; i<listsize; i++)
list.add(r.nextInt(range));
sort(list);
System.out.println(list);
}
public static ArrayList<Integer> sort(ArrayList<Integer> list) {
if (list.size() <= 1)
return list;
int rotationplacement = r.nextInt(list.size());
int rotation = list.get(rotationplacement);
list.remove(rotationplacement);
ArrayList<Integer> lower = new ArrayList<Integer>();
ArrayList<Integer> higher = new ArrayList<Integer>();
for (int num : list)
if (num <= rotation)
lower.add(num);
else
higher.add(num);
sort(lower);
sort(higher);
list.clear();
list.addAll(lower);
list.add(rotation);
list.addAll(higher);
return list;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T22:34:26.747",
"Id": "43439",
"Score": "0",
"body": "sidenote: instantiate arraylists as ``List<Integer> list = new ArrayList<>()`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-01T15:22:20.363",
"Id": "43661",
"Score": "0",
"body": "BTW, recursion here won't be a problem. Each 3 digits of values adds 10 to the stack depth since the depth is log(*n*). A billion values will require only 30 stack frames at the most."
}
] |
[
{
"body": "<p>Rather than creating new <code>List</code>s, your method could sort the list in place. The method you call recursively could take the list and index values; the methods would look something like this:</p>\n\n<pre><code>/**\n * sorts the {@code list} in place\n */\npublic static void sort(ArrayList<Integer> list) {\n sort(list, 0, list.size());\n}\n\n/**\n * Sorts the {@code list} from {@code fromIndex} to {@code toIndex} - 1.\n */\nprivate static void sort(List<Integer> list, int fromIndex, int toIndex) {\n\n if (fromIndex == toIndex - 1) {\n return;\n } else {\n // find the pivot, Collections.swap elements, etc...\n // recursively call self.\n }\n\n}\n</code></pre>\n\n<p>Sorting the list in place reduces the amount of memory on the stack.</p>\n\n<p>Also, to make the code more generic, perhaps you could sort lists of <code>Comparable</code> instead of <code>Integer</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T20:51:16.127",
"Id": "43538",
"Score": "0",
"body": "I don't think I see how that would improve the stack, for the first function why should I sort a copy of the list? and surely the extra two params for the second are redundant because it will always sort from 0 to list.size(), otherwise its sending a too big list. I think you mean to put the lists in a non-recurring function? Please could you explain more on what you meant by \"sort the list in place\" (in place?). Thanks for introducing me to comparable though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T20:56:46.053",
"Id": "43539",
"Score": "0",
"body": "@LeeAllan I was incorrectly assuming your original function returned a new list and left the original unmodified. Since that is not true, I would recommend copying the Collections.sort API which returns `void`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T20:58:22.730",
"Id": "43540",
"Score": "0",
"body": "@LeeAllan, As far as sorting the list in place, I will add a bit more code to try and clarify"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-01T15:32:27.160",
"Id": "43662",
"Score": "0",
"body": "@LeeAllan - Passing the list to each successive call only adds a *reference* to the stack. The list values remain in the heap and don't get copied from call-to-call. Sorting in-place is the right way to go for an `ArrayList`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-01T15:33:49.963",
"Id": "43663",
"Score": "0",
"body": "Minor note: You may as well change the parameter to the second method to `ArrayList` since the public API specifies this already."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-01T16:31:58.217",
"Id": "43667",
"Score": "0",
"body": "Ok I think I understand what you want me to do, to pass the same beginning list recursively so the stack uses a pointer, however I don't see how it's possible without creating a lower and higher list and surely they're the culprit of the memory. Can someone please show me exactly what \"sort in place\" means with some code?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T20:25:07.193",
"Id": "27926",
"ParentId": "27861",
"Score": "1"
}
},
{
"body": "<p>Apart from the sorting in place already mentioned by @kuporific, you should</p>\n\n<ul>\n<li>provide comments in your code about assumptions, at least on the parameters \nof <code>sort()</code></li>\n<li>you should very clearly mark this as example code and what (standard) \nfunctions should be used in real sorting</li>\n<li>you should include in this code an appropriate reference to Sir Tony Hoare.</li>\n</ul>\n\n<p>All that could be done in the context of a website, but cut-and-pasted code has a life of its own, so get these comments <strong>in</strong> the class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-29T03:38:36.750",
"Id": "27933",
"ParentId": "27861",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T19:27:31.650",
"Id": "27861",
"Score": "2",
"Tags": [
"java",
"recursion",
"sorting",
"quick-sort"
],
"Title": "Simplest quick sort using one 19-line function"
}
|
27861
|
<p>For my first not-just-a-few-days-long Python project, I needed something to handle basic set theory operations (union, intersection etc.) for one dimensional integer intervals, so I came up with this module.</p>
<p>It would be cool if you could tell me if the code is OK or something you would frown upon if you had to continue my project, and if so, what I can do better.</p>
<pre><code>"""intervals
Union, intersection, set difference and symmetric difference
of possibly overlapping or touching integer intervals.
Intervals are defined right-open. (1, 4) -> 1, 2, 3
e.g.
union([(1, 4), (7, 9)], (3, 5)) -> [(1, 5), (7, 9)]
intersection([(1, 4), (7, 9)], (3, 5)) -> [(3, 4)]
set_difference([(1, 4), (7, 9)], (3, 5)) -> [(1, 3), (7, 9)]
set_difference([(3, 5)], [(1, 4), (7, 9)]) -> [(4, 5)]
symmetric_difference([(1, 4), (7, 9)], (3, 5)) -> [(1, 3), (4, 5), (7, 9)]
see: http://en.wikipedia.org/wiki/Set_theory#Basic_concepts_and_notation
"""
import copy
from itertools import accumulate, chain, islice, repeat
from operator import itemgetter
import unittest
class Intervals():
"""Holds a non overlapping list of intervals.
One single interval is just a pair.
Overlapping or touching intervals are automatically merged.
"""
def __init__(self, interval_list=[]):
"""Raises a ValueError if the length of one of the
intervals in the list is negative.
"""
if any(begin > end for begin, end in interval_list):
raise ValueError('Invalid interval')
self._interval_list = _merge_interval_lists(
interval_list, [])
def __repr__(self):
"""Just write out all included intervals.
"""
return 'Intervals ' + str(self._interval_list)
def get(self, copy_content=True):
"""Return the list of intervals.
"""
return copy.copy(self._interval_list) if copy_content\
else self._interval_list
def union(a, b):
"""Merge a and b (union).
"""
return Intervals(_merge_interval_lists(
a.get(False), b.get(False)))
def intersections(a, b):
"""Intersects a and b.
"""
return Intervals(_merge_interval_lists(
a.get(False), b.get(False), merge_type='intersections'))
def set_difference(a, b):
"""Removes b from a.
Set difference is not commutative.
"""
return Intervals(_merge_interval_lists(
a.get(False), b.get(False), merge_type='set difference'))
def symmetric_difference(a, b):
"""Symmetric difference of a and b.
"""
return Intervals(_merge_interval_lists(
a.get(False), b.get(False), merge_type='symmetric difference'))
# class Intervals makes sure, by always building the union first,
# that no invalid a's or b's are fed here.
def _merge_interval_lists(a, b, merge_type='union'):
"""Merges two lists of intervals in O(n*log(n)).
Overlapping or touching intervals are simplified to one.
Arguments:
a and b -- The interval lists to merge.
merge_type -- Can be:
'union',
'intersections',
'symmetric difference', or
'set difference'.
Return the sorted result as a list.
"""
# If we want to calculate the set difference
# we invert the second interval list,
# i.e. swap begin and end.
if merge_type == 'set difference':
b = map(lambda p: (p[1], p[0]), b)
# Separately sort begins and ends
# and pair them with the implied change
# of the count of currently open intervals.
# e.g. (1, 4), (7, 9), (3, 5) ->
# begins = [(1, 1), (3, 1), (7, 1)]
# ends = [(4, -1), (5, -1), (9, -1)]
both = list(chain(a, b))
begins = zip(sorted(map(itemgetter(0), both)),
repeat(1))
ends = zip(sorted(map(itemgetter(1), both)),
repeat(-1))
# Sort begins and ends together.
# If the value is the same, begins come before ends
# to ensure touching intervals being merged to one.
# In our example above this means:
# edges = [(1, 4), (3, 1), (4, -1), (5, -1), (7, 1), (9, -1)]
edges = sorted(chain(begins, ends), key=lambda x: (x[0], -x[1]))
# Depending on the operation carried out,
# the criteria for interval begins and ends in the result differ.
# E.g:
# a = | - - - - | | - - - |
# b = | - - - - |
# counts = 1 2 1 0 1 0 (union, intersection, sym diff)
# counts = 1 0 -1 0 1 0 (set diff)
# union = | - - - - - - | | - - - |
# inter = | - - - - |
# sym d = | - |
# set d = | - | | - - - |
#
# One can see that union begins if the count changes from 0 to 1
# and ends if the count changes from 1 to 0
# An intersection begins at a change from 1 to 2 and ends with 2 to 1.
# A symmetric difference begins at every change to one
# and ends at every change away from one.
# The conditions for the set difference are the same as for the union.
check_begin = {'union': lambda change: change == (0, 1),
'intersections': lambda change: change == (1, 2),
'symmetric difference': lambda change: change[1] == 1,
'set difference': lambda change: change == (0, 1)
}[merge_type]
check_end = {'union': lambda change: change == (1, 0),
'intersections': lambda change: change == (2, 1),
'symmetric difference': lambda change: change[1] != 1,
'set difference': lambda change: change == (1, 0)
}[merge_type]
# The number of opened intervals after each edge.
counts = list(accumulate(map(itemgetter(1), edges)))
# The changes of opened intervals at each edge.
changes = zip(chain([0], counts), counts)
# Just the x positions of the edges.
xs = map(itemgetter(0), edges)
xs_and_changes = list(zip(xs, changes))
# Now we filter out the begins and ends from the changes
# and get their x positions.
res_begins = map(itemgetter(0),
starfilter(lambda x, change: check_begin(change),
xs_and_changes))
res_ends = map(itemgetter(0),
starfilter(lambda x, change: check_end(change),
xs_and_changes))
# The result is then just pairing up the sorted begins and ends.
result = pairwise(sorted(chain(res_begins, res_ends)), False)
# No empty intervals in the result.
def length_greater_than_zero(interval):
return interval[0] < interval[1]
return list(filter(length_greater_than_zero, result))
class TestIntervals(unittest.TestCase):
def test_ctor(self):
# Check ctors sanity check.
self.assertRaises(ValueError, Intervals, [(2, 4), (3, 1)])
def test_add_behind(self):
# Check adding right of the last interval.
intervals = Intervals([(0, 2)])
intervals = union(intervals, Intervals([(3, 4)]))
self.assertEqual(intervals.get(), [(0, 2), (3, 4)])
def test_add_in_front(self):
# Check adding left to the first interval.
intervals = Intervals([(3, 4)])
intervals = union(intervals, Intervals([(1, 2)]))
self.assertEqual(intervals.get(), [(1, 2), (3, 4)])
def test_add_in_between(self):
# Check adding between two intervals.
intervals = Intervals([(1, 2)])
intervals = union(intervals, Intervals([(6, 9)]))
intervals = union(intervals, Intervals([(3, 5)]))
self.assertEqual(intervals.get(), [(1, 2), (3, 5), (6, 9)])
def test_add_touching(self):
# Check adding a interval touching an existing one.
intervals = Intervals([(1, 3)])
intervals = union(intervals, Intervals([(3, 5)]))
self.assertEqual(intervals.get(), [(1, 5)])
def test_add_overlapping(self):
# Check adding a interval overlapping an existing one.
intervals = Intervals([(1, 4)])
intervals = union(intervals, Intervals([(3, 5)]))
self.assertEqual(intervals.get(), [(1, 5)])
def test_add_overlapping_multiple(self):
# Check adding a interval overlapping multiple existing ones.
intervals = Intervals([(1, 4)])
intervals = union(intervals, Intervals([(5, 7)]))
intervals = union(intervals, Intervals([(8, 10)]))
intervals = union(intervals, Intervals([(3, 9)]))
self.assertEqual(intervals.get(), [(1, 10)])
def test_add_swallow(self):
# Check adding a interval completely covering an existing one.
intervals = Intervals([(2, 3)])
intervals = union(intervals, Intervals([(1, 4)]))
self.assertEqual(intervals.get(), [(1, 4)])
def test_sub(self):
# Check removing an interval
intervals = Intervals([(0, 3)])
intervals = union(intervals, Intervals([(5, 7)]))
intervals = set_difference(intervals, Intervals([(2, 6)]))
self.assertEqual(intervals.get(), [(0, 2), (6, 7)])
def test_intersections(self):
# Check adding right of the last interval.
intervals = Intervals([(0, 3)])
intervals = union(intervals, Intervals([(5, 7)]))
intervals = intersections(intervals, Intervals([(2, 6)]))
self.assertEqual(intervals.get(), [(2, 3), (5, 6)])
def test_symmetric_difference(self):
# Check symmetric difference
intervals = Intervals([(0, 3)])
intervals = union(intervals, Intervals([(5, 7)]))
intervals = symmetric_difference(intervals, Intervals([(2, 6)]))
self.assertEqual(intervals.get(), [(0, 2), (3, 5), (6, 7)])
def tuple_wise(iterable, size, step):
"""Tuples up the elements of iterable.
Arguments:
iterable -- source data
size -- size of the destination tuples
step -- step to do in iterable per destination tuple
tuple_wise(s, 3, 1): "s -> (s0,s1,s2), (s1,s2,s3), (s3,s4,s5), ...
tuple_wise(s, 2, 4): "s -> (s0,s1), (s4,s5), (s8,s9), ...
"""
return zip(
*(islice(iterable, start, None, step)
for start in range(size)))
def pairwise(iterable, overlapping):
"""Pairs up the elements of iterable.
overlapping: "s -> (s0,s1), (s2,s3), (s4,s5), ...
not overlapping: "s -> (s0,s1), (s1,s2), (s2,s3), ...
"""
return tuple_wise(iterable, 2, 1 if overlapping else 2)
def starfilter(function, iterable):
"""starfilter <--> filter == starmap <--> map"""
return (item for item in iterable if function(*item))
if __name__ == '__main__':
unittest.main(verbosity=2)
</code></pre>
|
[] |
[
{
"body": "<p>First off, <code>Intervals</code> should be a new style class. There's no real reason to ever use old style classes nowadays. If you want to be fancy, you could throw in a set-like ABC, but you should at least inherit from <code>object</code>.</p>\n\n<p>The default argument <code>interval_list</code> should ideally be immutable. Since you only require a sequence there anyway, you may as well just make it a tuple.</p>\n\n<p>For <code>b = map(lambda p: (p[1], p[0]), b)</code> I would use <code>zip</code> instead, though this may just be personal preference.</p>\n\n<p>The use of <code>get</code> seems potentially problematic. For instance, if you accidentally pass a dict into your union functions, it may silently work.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T09:47:33.137",
"Id": "43478",
"Score": "0",
"body": "Great, thanks for the feedback. I use Python 3, so the classes are new style by default, but explicitly inheriting from `object` surely makes it cleaner.\nI also changed `interval_list` to be immutable, so my current version looks like this:\n\nhttp://ideone.com/JhYhNC\n\nHow can I elegantly swap the elements of the pairs in list with `zip`?\nAnd do you have a suggestion for the problem with `get`?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T06:01:06.407",
"Id": "27881",
"ParentId": "27862",
"Score": "1"
}
},
{
"body": "<p>IMHO, having a function which accepts the operation as a string is an atrocity, and I would disallow it in a code review.</p>\n\n<p>Why not have separate functions? That’s much cleaner and makes the code easier to read. If you’re concerned about code duplication, take a look at the <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow\">strategy pattern</a>. You could for instance pass (named) sets of callbacks rather than strings. Like so:</p>\n\n<pre><code>id = lambda x: x\nOP_UNION = (\n id, # Only needed for symmetric difference\n lambda change: change == (0, 1),\n lambda change: change == (1, 0))\n…\n</code></pre>\n\n<p>Or alternatively using <code>namedtuple</code>:</p>\n\n<pre><code>set_op = collections.namedtuple('set_op', ['transform', 'begin', 'end'])\n\n# And here’s a handy helper to avoid lots of repetitive lambdas\ndef check_for(cond):\n return lambda change: change == cond\n\nOP_UNION = set_op(\n transform = id,\n begin = check_for((0, 1)),\n end = check_for((1, 0)))\n…\n</code></pre>\n\n<p>This would also shorten your – otherwise quite nice – <code>_merge_interval_lists</code> implementation (here without comments for brevity, though your comments were very good):</p>\n\n<pre><code># Removing the default for merge_type – why have this?\ndef _merge_interval_lists(a, b, merge_type):\n b = merge_type.transform(b)\n\n both = list(chain(a, b))\n begins = zip(sorted(map(itemgetter(0), both)),\n repeat(1))\n ends = zip(sorted(map(itemgetter(1), both)),\n repeat(-1))\n\n edges = sorted(chain(begins, ends), key=lambda x: (x[0], -x[1]))\n\n counts = list(accumulate(map(itemgetter(1), edges)))\n changes = zip(chain([0], counts), counts)\n xs = map(itemgetter(0), edges)\n xs_and_changes = list(zip(xs, changes))\n\n res_begins = map(itemgetter(0),\n starfilter(lambda x, change: merge_type.begin(change),\n xs_and_changes))\n res_ends = map(itemgetter(0),\n starfilter(lambda x, change: merge_type.end(change),\n xs_and_changes))\n\n result = pairwise(sorted(chain(res_begins, res_ends)), False)\n\n def length_greater_than_zero(interval):\n return interval[0] < interval[1]\n\n return list(filter(length_greater_than_zero, result))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T11:45:52.343",
"Id": "43484",
"Score": "0",
"body": "@Dobi Yes, `id` = identity. An indispensable tool in the functional programmer’s tool belt. ;-) And nice use of `compose` in your code!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T11:46:37.890",
"Id": "43485",
"Score": "0",
"body": "Wow, thanks for this awesome feedback!\nYes, I knew about the strategy pattern from my c++ projects, but with first class functions here it is even more elegant.\n\nI like your solution and use it now: http://ideone.com/YBNZ2p\n(I guess with `id` you meant the identity (`id` in e.g. Haskell). ^_-)\n\nbtw: Is it welcomed here to edit the question for posting the improved code? Or should I add an answer to this thread or just do nothing? :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T11:47:33.833",
"Id": "43486",
"Score": "0",
"body": "@Dobi I think it’s preferred not to edit the code in the question – it makes the answers hard to follow for other people. If you think you’ve received substantial improvement, post it as an own answer. If you have follow-up questions about the improved code, make a new question. Just my opinion, though."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T09:25:50.863",
"Id": "27886",
"ParentId": "27862",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27886",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T20:27:03.453",
"Id": "27862",
"Score": "6",
"Tags": [
"python"
],
"Title": "Set theory operations (union, intersection etc.) for one dimensional integer intervals"
}
|
27862
|
<p>For work, my colleague and I sketched this method up as a brain dump of how we want this method to work. What I am trying to figure out is how can we break this method into smaller components so that it is easier to test to write tests for this. I am trying to avoid putting this into methods where they are coupled by parameters.</p>
<pre><code>def self.for_venue(venue, options = {})
filter = options[:filter]
date_conditions = case options[:date]
when 'upcoming' then 'e.datetime > :datetime'
when 'past' then 'e.datetime < :datetime'
end
sql_query = [
"SELECT #{search_fields}",
"FROM events e #{search_joins}",
"WHERE " + [date_conditions, "e.venue_id = #{venue.id}", "e.deleted = 0"].reject(&:nil?).join(" AND ")
]
if options[:limit].present?
sql_query << "LIMIT #{options[:limit]}"
sql_query << "OFFSET #{options[:offset]}" if options[:offset].present?
end
sql_query << "ORDER BY #{options[:order]}" if options[:order].present?
sql = ActiveRecord::Base.prepare_sql([sql_query.join(" "), { :datetime => Time.now.beginning_of_day }])
results = SlaveDB.connection.select_all(sql)
filter ? filter.select(results) : results
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T16:22:52.857",
"Id": "43509",
"Score": "0",
"body": "What's SlaveDB? why are you doing sql by hand instead of using AR?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-29T22:57:22.020",
"Id": "43588",
"Score": "0",
"body": "@tokland SlaveDB is a custom class in the project that handles the our Slave. Sometimes there is no need to load data into Active Record when you are doing a read. It's a lot faster and less memory consumption."
}
] |
[
{
"body": "<p>Even if you don't want to load your data into ActiveRecord, you can use AR to prepare your SQL statement using <code>to_sql</code>:</p>\n\n<pre><code>def self.for_venue(venue, options = {})\n\n filter = options[:filter]\n\n date_conditions = case options[:date]\n when 'upcoming' then \"datetime > ?\"\n when 'past' then \"datetime < ?\"\n end\n\n sql_query = Event\n .where(:venue_id => venue.id, :deleted => 0)\n .where(date_conditions, Time.now.beginning_of_day)\n .joins(search_joins)\n .limit(options[:limit])\n .offset(options[:offset])\n .order(options[:order])\n .to_sql\n\n results = SlaveDB.connection.select_all(sql_query)\n\n filter ? filter.select(results) : results\n\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-03T19:09:38.173",
"Id": "43838",
"Score": "0",
"body": "That is definitely cleaner, our app is still on rails 2.1 unfortunately. :("
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-02T18:27:03.377",
"Id": "28043",
"ParentId": "27866",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "28043",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T22:07:36.907",
"Id": "27866",
"Score": "1",
"Tags": [
"ruby",
"sql",
"mysql",
"ruby-on-rails",
"active-record"
],
"Title": "ActiveRecord SQL search with a filter based on parameters"
}
|
27866
|
<p>I need to build a application which sends a lot of emails. These emails are based on a table. Basic idea is, I grab a bunch of records from database. Create <code>MailMessage</code> (<code>System.Net.Mail</code>) and send it. Since there are a lot of mails to be sent, I am thinking about developing a multi-threaded application. </p>
<pre><code> public void Run()
{
var mailItems = MailItemDataProvider.GetLiveMailItems();
if (mailItems.Count > 0)
{
var maxThreads = 5;
var totalItems = mailItems.Count;
int skipper = totalItems / (maxThreads - 1);
if (skipper == 0)
skipper = totalItems;
for (var i = 0; i < totalItems; i += skipper)
{
var itemsLot = mailItems.Skip(i).Take(skipper).ToList();
Task.Factory.StartNew(() => ProcessMails(itemsLot, ThreadPriority.Highest));
}
}
}
</code></pre>
<p>It basically grabs a thousand records from the database and divide them into five chunks. The chunks are passed to the mail processor. The above function is triggered from a timer (<code>Timer_Elapsed</code> event) configured to run every minute. This is actually part of Windows Service. Mail processor is like this:</p>
<pre><code> protected void ProcessMails(IEnumerable<MailItem> mailItems)
{
foreach (var mailItem in mailItems)
{
bool errorFound;
var mail = CreateMailMessage(mailItem, out errorFound);
// returns (System.Net.Mail) MailMessage object
if (!errorFound)
{
if (Mailer.SendEmail(mail))
{
mailItem.StatusId = Status.Sent;
}
else
{
mailItem.StatusId = Status.Failed;
mailItem.FailMessage = "Error sending email.";
}
}
else
{
mailItem.StatusId = Status.Failed;
}
}
UpdateMailItems(mailItems);
// this updates mail sent status in the database
}
</code></pre>
<p>In my test environment, it is working fine. I have tested for 100,000 emails.
Following are my concerns in the function that is processed by the threads:</p>
<ol>
<li>What will happen when SMTP slows down (for some unknown reason)? I start up five threads, but it will add up five more before the first five complete. How many threads can my server handle? (I know it depends on actual resources available, but practically, how will it perform?)</li>
<li>I have database update inside the process. Is that good idea?</li>
<li>Is there a chance that some threads will never finish? Do I need to make sure that threads are completed? How do I detect the ever running threads and kill them?</li>
</ol>
<p>I am new to multi threading. Please review my code. Any comments or suggestion are welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T02:06:30.580",
"Id": "43446",
"Score": "0",
"body": "Why do you need to send so many emails?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T03:36:39.473",
"Id": "43451",
"Score": "0",
"body": "It's a business requirement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T06:37:55.850",
"Id": "43465",
"Score": "0",
"body": "\"It's a business requirement.\" - Is your business the spam business scnr ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T06:57:24.187",
"Id": "43468",
"Score": "0",
"body": "No intention of spamming, honestly."
}
] |
[
{
"body": "<p>Instead of rolling your own version of a parallel for each loop, you should use <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.foreach.aspx\" rel=\"nofollow\"><code>Parallel.ForEach()</code></a>. It will make your code simpler, avoid the possibility of bugs in your <code>Run()</code> method and you will still be able to configure the number of threads used (through <code>ParallelOptions</code>).</p>\n\n<hr>\n\n<blockquote>\n <p>I start up five threads, but it will add up five more before the first five complete.</p>\n</blockquote>\n\n<p>If I understand your code correctly, the only way this could happen is if you called <code>Run()</code> for a second time. If that's the case, it might make sense to use the producer-consumer pattern using <a href=\"http://msdn.microsoft.com/en-us/library/dd267312.aspx\" rel=\"nofollow\"><code>BlockingCollection<T></code></a> and <code>GetConsumingEnumerable()</code> (or <a href=\"http://blogs.msdn.com/b/pfxteam/archive/2010/04/06/9990420.aspx\" rel=\"nofollow\"><code>GetConsumingPartitioner()</code></a> if you decide to switch to <code>Parallel.ForEach()</code>).</p>\n\n<blockquote>\n <p>How many threads can my server handle?</p>\n</blockquote>\n\n<p>There is no way for us to answer that. You will have to perform your own measurements.</p>\n\n<blockquote>\n <p>I have database update inside the process. Is that good idea?</p>\n</blockquote>\n\n<p>I don't see why would that cause any significant issues.</p>\n\n<blockquote>\n <p>Is there a chance that some threads will never finish?</p>\n</blockquote>\n\n<p>There is no way for us to know that without seeing the code you didn't show.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T13:21:35.800",
"Id": "27897",
"ParentId": "27871",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "27897",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T02:02:26.207",
"Id": "27871",
"Score": "0",
"Tags": [
"c#",
"multithreading",
"email"
],
"Title": "Multi threaded application to send large no of emails"
}
|
27871
|
<p>This is a program that I made for encrypting text files, it uses a one time pad cipher to encrypt the files, but I do not know if there are any holes in my program that could be a vulnerability. </p>
<pre><code>import os
q = 1
while q == 1:
e = raw_input("file to encypt: ")
#This will open a file for encryption
o = open(e, "r")
o1 = o.read()
#This is the plain text to encrypt
#'The quick brown fox jumps over the lazy dog'
plain = o1
#This will measure the length of the plain text
f3 = len(plain)
#generate random chacters as long as the text
a1 = os.urandom(f3)
#makes the random characters tuple format
b = list(a1)
b2 = list(plain)
s = plain
#gives the ascii value of the charters
L = [ord(c) for c in s]
s = a1
a = [ord(c) for c in s]
b = [ord(c) for c in plain]
#adds the random digits and the plain text
c = map(sum, zip(a,b))
#uses Modular arithmetic if the sum is greater than 256
x=c
z = []
for y in x:
z.append(y-256 if y>=256 else y)
z = [y-256 if y >= 256 else y for y in x]
#converts the sum back to charter form
cipher_text = ''.join(chr(i) for i in z)
#makes a folder for the files
base1 = os.path.basename(e)
base2 = os.path.splitext(base1)[0]
#makes a folder for the output
p = "/Users/kyle/one_time_pad/"+base2
print p
if os.path.exists(p):
print
else:
os.mkdir(p)
key = a1
#makes a file containg the key
p = p + "/"
f2 = p+"key.txt"
#print f2
if os.path.exists(f2):
f1 = file(f2, "w")
f1 = open(f2, "w")
f1.write(key)
f1.close()
else:
f1 = file(f2, "w")
f1 = open(f2, "w")
f1.write(key)
f1.close()
#makes a file containg the cipher text
f3 = p+"cipher_text.txt"
if os.path.exists(f3):
f1 = file(f3, "w")
f1 = open(f3, "w")
f1.write(cipher_text)
f1.close()
else:
f1 = file(f3, "w")
f1 = open(f3, "w")
f1.write(cipher_text)
f1.close()
f4 = p+"encrypt.py"
encrypt1 = open("/Users/kyle/encrypt.py", "r")
encrypt = encrypt1.read()
if os.path.exists(f4):
f1 = file(f4, "w")
f1 = open(f4, "w")
f1.write(encrypt)
f1.close()
else:
f1 = file(f4, "w")
f1 = open(f4, "w")
f1.write(encrypt)
f1.close()
f5 = p+"decrypt.py"
encrypt1 = open("/Users/kyle/decrypt.py", "r")
encrypt = encrypt1.read()
if os.path.exists(f5):
f1 = file(f5, "w")
f1 = open(f5, "w")
f1.write(encrypt)
f1.close()
else:
f1 = file(f5, "w")
f1 = open(f5, "w")
f1.write(encrypt)
f1.close()
print 50*"-"
</code></pre>
<p>This is the code that I use for decryption:</p>
<pre><code>import os
q = 1
while q == 1:
#opens the cipher text and it converts it to decimal
cipher = raw_input("cipher text: ")
cipher1 = open(cipher, "r")
cipher2 = cipher1.read()
cipher3 = [ord(c) for c in cipher2]
#opens the key and coverts it to decimal
key = raw_input("key: ")
key1 = open(key, "r")
key2 = key1.read()
key3 = [ord(c) for c in key2]
#subtracts the key from the cipher
a = cipher3
b = key3
c = map(lambda x: (x[0]-x[1]) % 256, zip(a,b))
#prints out the decrypted plain text
decrypt = ''.join(map(chr,c))
#makes a file with the decrypted output
path1 = raw_input("out folder: ")
name = "plain_text.txt"
path2 = path1 + "/" + name
if os.path.exists(path2):
f1 = file(path2, "a")
f1 = open(path2, "a")
f1.write(decrypt)
f1.close()
else:
f1 = file(path2, "w")
f1 = open(path2, "w")
f1.write(decrypt)
f1.close()
print 50*"-"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T02:45:12.380",
"Id": "43449",
"Score": "7",
"body": "Crypto is a very specialized topic. General programers will be able to critique your code style not your crypto strength. Go to a specialized group for that: http://crypto.stackexchange.com/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-31T17:53:31.437",
"Id": "48641",
"Score": "1",
"body": "At minimum your code is silly. The provable security of a one time pad relies on truly random data, so you can't use `/dev/urandom`. If you don't need provable security (hint: you don't), then a simple stream cipher is just as strong as a OTP like construction, but far nicer to use."
}
] |
[
{
"body": "<p>I am not going to comment on possible vulnarabilities (that question does not belong here). But your Python code has several issues.</p>\n\n<p>In the code:</p>\n\n<pre><code>f1 = file(path2, \"w\")\nf1 = open(path2, \"w\")\nf1.write(decrypt)\nf1.close()\n</code></pre>\n\n<p>the first two lines do the same, opening path2 twice. You should leave out the first, or better use:</p>\n\n<pre><code>with open(path2, \"w\") as f1:\n f1.write(decrypt)\n</code></pre>\n\n<p>unless you have an old version of python without <code>with</code>. This closes the file automatically on exit of the scope of the <code>with</code> statement.</p>\n\n<p>You should also put your code (apart from the import) in a function, so it can be more easily reused (the decryption file):</p>\n\n<pre><code>import os\n\ndef decrypt():\n q = 1\n while q == 1: \n #opens the cipher text and it converts it to decimal\n .\n .\n .\n print 50*\"-\"\n\nif __name__ == '__main__':\n decrypt()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-29T04:40:25.510",
"Id": "27937",
"ParentId": "27872",
"Score": "4"
}
},
{
"body": "<p>As you are no doubt aware, one-time pads are cryptographically secure according to <a href=\"https://en.wikipedia.org/wiki/Kerckhoffs%27s_principle\">Kerckhoff's principle</a>, assuming the key is sufficiently random and secret. From a brief glance, your implementation of OTP looks correct. (But I might of course have missed something.)</p>\n\n<p>However, whether the program itself has any vulnerabilities would not be relevant as long as you write the key to a file. Anyone with access to your memory or harddisk would be able to intercept the file, and therefore the key. This means the question boils down to \"Is my implementation correct?\", and the answer to that is \"Yes\", as far as I can tell.</p>\n\n<p>I might be wrong, however, because your program is not very readable. Some of the things you can do to clean it up are:</p>\n\n<p><strong>1: Improve variable names.</strong> Several of your variable names are single letters. <code>plaintext_length</code> is way more readable than <code>f3</code>.</p>\n\n<p><strong>2: Split your code into logical units.</strong> Refactor into functions, and group code that logically belongs together by separating such groups with a single empty line.</p>\n\n<p><strong>3:</strong> Why on earth are you doing this?!</p>\n\n<pre><code>if os.path.exists(f2):\n f1 = file(f2, \"w\")\n f1 = open(f2, \"w\")\n f1.write(key)\n f1.close()\nelse:\n f1 = file(f2, \"w\")\n f1 = open(f2, \"w\")\n f1.write(key)\n f1.close()\n</code></pre>\n\n<p>As far as I can see, the two blocks are identical, and one of them will be executed regardless. And as Anthon points out, the first two lines in each block do the same.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-29T06:15:13.310",
"Id": "43566",
"Score": "0",
"body": "Thank you for the advice, i should Improve variable names it will make debugging more easy, and at a second look i do not know why i am handling the files in that way, thanks for the advice."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-29T05:14:39.493",
"Id": "27938",
"ParentId": "27872",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "27938",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T02:32:42.093",
"Id": "27872",
"Score": "2",
"Tags": [
"python",
"cryptography"
],
"Title": "Is my cipher secure?"
}
|
27872
|
<p>I am writing a TCP based client that need to send and receive data. I have used the <code>Asynchronous Programming Model (APM)</code> provided for Socket class by the .NET Framework.</p>
<p>After being connected to the socket, I start waiting for data on the socket using <code>BeginReceive</code>.</p>
<p>Now, while I am waiting for the data on the Socket, I may need to send data over the socket. And the send method can be called multiple times, </p>
<p>So I have make sure that</p>
<ul>
<li>All the bytes from previous <code>Send</code> call is entirely sent.</li>
<li>The way I am sending the Data is safe considering that, while a data send is in progress, any call to send data can be made.</li>
</ul>
<p><strong>This is my first work on socket, So is my approach right to send data ?</strong></p>
<pre><code> private readonly object writeLock = new object();
public void Send(NetworkCommand cmd)
{
var data = cmd.ToBytesWithLengthPrefix();
ThreadPool.QueueUserWorkItem(AsyncDataSent, data);
}
private int bytesSent;
private void AsyncDataSent(object odata)
{
lock (writeLock)
{
var data = (byte[])odata;
int total = data.Length;
bytesSent = 0;
int buf = Globals.BUFFER_SIZE;
while (bytesSent < total)
{
if (total - bytesSent < Globals.BUFFER_SIZE)
{
buf = total - bytesSent;
}
IAsyncResult ar = socket.BeginSend(data, bytesSent, buf, SocketFlags.None, DataSentCallback, data);
ar.AsyncWaitHandle.WaitOne();
}
}
}
</code></pre>
<p>How object is changed into <code>byte[]</code>, sometimes the <code>NetworkCommand</code> can be as big as <strong>0.5 MB</strong></p>
<pre><code> public byte[] ToBytesWithLengthPrefix()
{
var stream = new MemoryStream();
try
{
Serializer.SerializeWithLengthPrefix(stream, this, PrefixStyle.Fixed32);
return stream.ToArray();
}
finally
{
stream.Close();
stream.Dispose();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T13:40:31.463",
"Id": "43498",
"Score": "0",
"body": "Why are you using the asynchronous method `BeginSend()` when you immediately synchronously wait for it to complete? Why don't you just use `Send()`? Also, can you use C# 5.0?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T17:51:45.277",
"Id": "43514",
"Score": "0",
"body": "no i am limited to .net 3.5, i have to use BeginSend as i am already awaiting for data to be received : http://stackoverflow.com/questions/17356507/transmitting-sending-big-packet-safely-using-tcpclient-socket/"
}
] |
[
{
"body": "<p>Instead of using the <code>ToArray()</code> method of the <code>MemoryStream</code> you could use <code>GetBuffer()</code> instead because this isn't creating a new array. </p>\n\n<p>Edit based on <a href=\"https://codereview.stackexchange.com/users/27497/iridium\">@Iridium</a>'s <a href=\"https://codereview.stackexchange.com/questions/27873/transmitting-sending-big-packet-safely-using-tcpclient-socket/113906?noredirect=1#comment211060_113906\">comment</a> </p>\n\n<p>But this is only good if you use one of the constructor that creates a not resizable <code>MemoryStream</code> which isn't the case for the default constructor. </p>\n\n<p>Calling <code>Dispose()</code> on the <code>MemoryStream</code> closes the <code>stream</code> too. </p>\n\n<p>If you enclose the stream inside inside a <code>using</code> block the disposing of the stream will be handled automatically.</p>\n\n<pre><code>public byte[] ToBytesWithLengthPrefix()\n{\n using (var stream = new MemoryStream())\n {\n Serializer.SerializeWithLengthPrefix(stream, this, PrefixStyle.Fixed32);\n return stream.ToArray();\n }\n}\n</code></pre>\n\n<hr>\n\n<p>I needed to look twice at <code>var data = (byte[])odata;</code> which is a clear sign that you should make the method argument <code>odata</code> easier to distinguish from <code>data</code>, so <code>objectData</code> or <code>dataToSend</code> would be better. </p>\n\n<p><code>int buf</code> isn't well named either. One shouldn't use abbreviations to name variables. A much better name would be for instance <code>dataSize</code> or just <code>size</code> to indicate that it is the amount of data being sent. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-14T15:58:29.770",
"Id": "211060",
"Score": "2",
"body": "The internal buffer returned by `GetBuffer()` may be larger than the stream's `Length`. Since the true length is not also returned, this could result in sending more data than expected (and more than indicated by the prefixed length indicator)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-14T12:42:20.900",
"Id": "113906",
"ParentId": "27873",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T02:56:54.093",
"Id": "27873",
"Score": "2",
"Tags": [
"c#",
".net",
"socket",
"tcp"
],
"Title": "Transmitting/Sending big packet safely using TcpClient/Socket"
}
|
27873
|
<p>I've been learning Python like for a year and started learning a little about pandas <code>DataFrame</code>. I made this little program to practice all the concepts and would like to hear your suggestions for improvement.</p>
<p><strong>GOAL</strong></p>
<p>This program should plot how the inventory levels behave according some initials conditions: number of periods, demand distribution, lead time distribution and the chosen control policy (see types of policy).</p>
<p><strong>DEFINITIONS AND FORMULAS</strong></p>
<p>inventory position = on hand inventory + inventory on order</p>
<p>lead time = the amount of time between the placing of an order and the receipt of the goods ordered.</p>
<p><strong>NOTATION</strong></p>
<p><em>s</em> reorder point, <em>Q</em> order quantity, <em>R</em> review period, <em>S</em> order-up-to level</p>
<p><strong>TYPES OF POLICY</strong></p>
<p>We use four different base policy types: </p>
<ol>
<li>(s, Q)-policy. Whenever the inventory position reaches the reorder point s or drops below this point, an order of size Q is triggered.</li>
<li>(s, S)-policy. Under this policy, the size of the order – triggered whenever the inventory position reaches or drops below the reorder point s – equals the difference between the order-up-to level S and the current inventory position.</li>
<li>(R, S)-policy. The review period R indicates the length of the interval in-between two reviews. At these points of time, the inventory position is observed and the difference between the inventory position and the order-up-to level S is ordered.</li>
<li>(R, s, S)-policy. Every R intervals the inventory position is checked. An order is triggered only if the inventory position has reached or dropped below the reorder point s. Then the order size equals the difference between the order-up-to level S and the current inventory position.</li>
</ol>
<p></p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
from pandas import DataFrame
# The distribution factory
def make_distribution(function,*pars):
def distribution():
return function(*pars)
return distribution
def make_data(periods=52,
initial_inventory = 10,
demand_dist = make_distribution(np.random.normal,2,1),
lead_time_dist = make_distribution(np.random.triangular,1,2,3),
policy = {'method':'Qs', 'arguments': {'Q':3,'s':5}}):
""" Return a Pandas dataFrame that contains the details of the inventory simulation.
Keyword arguments:
periods -- numbers of periods of the simulation (default 52 weeks)
initial_inventory -- initial inventory for the simulation
demand_dist -- distribution of the demand (default triangular min=1, mode=2, max=3)
lead_time_dist -- distribution of the lead time (default triangular min=1, mode=2, max=3)
policy -- dict that contains the policy specs (default = {'method':'Qs', 'arguments': {'Q':3,'s':5}})
"""
# Create zero-filled Dataframe
period_lst = np.arange(periods) # index
header = ['initial_inv_pos', 'initial_net_inv', 'demand', 'final_inv_pos',
'final_net_inv', 'lost_sales', 'avg_inv', 'order', 'lead_time'] # columns
df = DataFrame(index = period_lst, columns = header).fillna(0)
# Create a list that will store each period order
order_list = [Order(quantity=0, lead_time=0, sent=False) for x in range(periods)]
# Fill DataFrame
for period in period_lst:
if period == 0:
df['initial_inv_pos'][period] = initial_inventory
df['initial_net_inv'][period] = initial_inventory
else:
df['initial_inv_pos'][period] = df['final_inv_pos'][period-1] + order_list[period - 1].quantity
df['initial_net_inv'][period] = df['final_net_inv'][period-1] + pending_order(order_list, period)
df['demand'][period] = int(demand_dist())
df['final_inv_pos'][period] = df['initial_inv_pos'][period] - df['demand'][period]
order_list[period].quantity, order_list[period].lead_time, order_list[period].sent = placeorder(df['final_inv_pos'][period], policy, lead_time_dist, period)
df['final_net_inv'][period] = df['initial_net_inv'][period] - df['demand'][period]
if df['final_net_inv'][period] < 0:
df['lost_sales'][period] = abs(df['final_net_inv'][period])
df['final_net_inv'][period] = 0
else:
df['lost_sales'][period] = 0
df['avg_inv'][period] = 0
df['order'][period] = order_list[period].quantity
df['lead_time'][period] = order_list[period].lead_time
return df
def placeorder(final_inv_pos, policy, lead_time_dist, period):
"""Place the order acording the inventory policy:
Keywords arguments:
final_inv_pos -- final inventory position of period
policy -- chosen policy Reorder point (Qs, Ss) or Periodic Review (RS, Rss)
lead_time_dist -- distribution of lead time
period -- actual period
"""
lead_time = int(lead_time_dist())
# Qs = if we hit the reorder point s, order Q units
if policy['method'] == 'Qs' and \
final_inv_pos <= policy['arguments']['s']:
return policy['arguments']['Q'], lead_time, True
# Ss = if we hit the reorder point s, order S - final inventory pos
elif policy['method'] == 'Ss' and \
final_inv_pos <= policy['arguments']['s']:
return policy['arguments']['S'] - final_inv_pos, lead_time, True
# RS = if we hit the review period and the reorder point S, order S - final inventory pos
elif policy['method'] == 'RS' and \
period%policy['arguments']['R'] == 0 and \
final_inv_pos <= policy['arguments']['S']:
return policy['arguments']['S'] - final_inv_pos, lead_time, True
# RSs = if we hit the review period and the reorder point s, order S - final inventory pos
elif policy['method'] == 'RSs' and \
period%policy['arguments']['R'] == 0 and \
final_inv_pos <= policy['arguments']['s']:
return policy['arguments']['S'] - final_inv_pos, lead_time, True
# If the conditions arent satisfied, do not order
else:
return 0, 0, False
def pending_order(order_list, period):
"""Return the order that arrives in actual period"""
indices = [i for i, order in enumerate(order_list) if order.sent == True]
sum = 0
for i in indices:
if period - (i + order_list[i].lead_time +1) == 0:
sum += order_list[i].quantity
return sum
class Order(object):
"""Object that stores basic data of an order"""
def __init__(self, quantity, lead_time, sent):
self.quantity = quantity
self.lead_time = lead_time
self.sent = sent # True if the order is already sent
def make_plot(df, policy, period):
#Plot
plt.rcParams['figure.figsize'] = 15,4 #define the fig size
fig = plt.figure()
ax = fig.add_subplot(111)
y1 = df['final_inv_pos']
l1, = plt.plot(y1, 'k', linewidth=1.2, drawstyle='steps', label='Final Inv')
if policy['method'] == 'Qs':
title = 'Simulation Policy = (Q: {Q}, s: {s})'.format(**policy['arguments'])
y2 = policy['arguments']['s']*np.ones(period)
l2, = plt.plot(y2, 'r:', label='Reorder point')
elif policy['method'] == 'Ss':
#TODO
pass
t = ax.set_title(title)
ax.tick_params(axis='both', which='major', labelsize=8)
plt.xticks(np.arange(period))
plt.ylim(bottom=0)
plt.legend(loc='best', prop={'size':10})
plt.xlabel("Periods")
plt.ylabel("Inventory Level")
plt.show()
def simulate():
#parameters of simulation
Qs_policy = {'method':'Qs', 'arguments': {'Q':3,'s':5}}
demand_dist = make_distribution(np.random.normal,3,1)
lead_time_dist = make_distribution(np.random.triangular,1,4,5)
period = 52
df = make_data(period,10,demand_dist,lead_time_dist,Qs_policy)
#df.to_csv("out.csv")
make_plot(df, Qs_policy, period)
if __name__ == '__main__':
simulate()
</code></pre>
|
[] |
[
{
"body": "<p>Nice piece of code. Are you calculating <a href=\"https://en.wikipedia.org/wiki/Safety_stock#Methods_for_calculating_safety_stocks\" rel=\"nofollow noreferrer\">safety stock</a> based on the std dev of the demand distribution? Couldn't find in the code - sorry if it is there.</p>\n\n<p>If not not, that would be the natural next step.</p>\n\n<p>The second step would be a simulation of inventory levels based on the policy you created in step one and two.</p>\n\n<p>But you can go further and calculate the lost sales - that should involve bayesian calculations - and, given the cost of holding inventory, the money the company is saving by following your suggested policy:\n- reduced avg inventory (free working capital: one time only)\n- increased margin by selling more (every period)</p>\n\n<p>Do a basic NPV calculation and you have a very solid number to show to any client. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-27T15:50:25.217",
"Id": "248818",
"Score": "0",
"body": "This was a long time ago. I made a toy web app later, you could play with it [here](https://nsinvi.herokuapp.com). The code is [here](https://github.com/Jdash99/sinvi)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2016-06-27T12:59:32.470",
"Id": "133186",
"ParentId": "27874",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T03:16:12.087",
"Id": "27874",
"Score": "3",
"Tags": [
"python",
"simulation",
"pandas"
],
"Title": "Inventory simulation using Pandas DataFrame"
}
|
27874
|
<p>Here is an exercise I completed today from Bjarne Stroustrup's <em>Programming Principles and Practice in C++</em> book. Any tips about coding style, simplification, or perhaps modularization by means of using functions for some of the data processing would be sincerely appreciated. FYI I have only been programming for 5 months, apologies in advance for any blatant mistakes. </p>
<pre><code>// This program takes floating-point numbers and select units as input, and displays the sum,
// the amount of measurements entered, and the high and low measurements entered.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
// Globals
const double cm_to_m = 0.01;
const double m_to_cm = 100;
const double in_to_m = 2.54 * 0.01;
const double m_to_in = 100 * (1.0/2.54);
const double ft_to_m = 12 * 2.54 * 0.01;
const double m_to_ft = 100 * (1.0/2.54) * (1.0/12.0);
// Main Function
int main()
{
// Declarations
int count = 0;
double num, conv, low, high, sum = 0;
string unit, low_unit, high_unit;
vector<double> input_array;
// Input
cout << "Enter a measurement in one of the following accepted units (cm, m, in, ft): " << endl;
while (cin >> num >> unit) {
if (unit == "m" || unit == "cm" || unit == "in" || unit == "ft") {
if (unit == "m") {
input_array.push_back(num);
if (count == 0) low = num, low_unit = unit, high = num, high_unit = unit;
else if (num < low) low = num, low_unit = unit;
else if (num > high) high = num, high_unit = unit;
++count;
}
else if (unit == "cm") {
conv = num * cm_to_m;
input_array.push_back(conv);
if (count == 0) low = conv, low_unit = unit, high = conv, high_unit = unit;
else if (conv < low) low = conv, low_unit = unit;
else if (conv > high) high = conv, high_unit = unit;
++count;
}
else if (unit == "in") {
conv = num * in_to_m;
input_array.push_back(conv);
if (count == 0) low = conv, low_unit = unit, high = conv, high_unit = unit;
else if (conv < low) low = conv, low_unit = unit;
else if (conv > high) high = conv, high_unit = unit;
++count;
}
else if (unit == "ft") {
conv = num * ft_to_m;
input_array.push_back(conv);
if (count == 0) low = conv, low_unit = unit, high = conv, high_unit = unit;
else if (conv < low) low = conv, low_unit = unit;
else if (conv > high) high = conv, high_unit = unit;
++count;
}
}
else
cout << "Incorrect Unit Entered! Please try again..." << endl;
}
// Low/High Unit Re-Conversion
if (low_unit == "cm")
low *= m_to_cm;
else if (low_unit == "in")
low *= m_to_in;
else if (low_unit == "ft")
low *= m_to_ft;
if (high_unit == "cm")
high *= m_to_cm;
else if (high_unit == "in")
high *= m_to_in;
else if (high_unit == "ft")
high *= m_to_ft;
// Sort
sort(input_array.begin(), input_array.end());
// Sum the contents of the array.
for (int i = 0; i < input_array.size(); ++i)
sum += input_array[i];
// Output
cout << endl;
cout << count << " measurements were entered" << endl;
cout << "The sum of measurements entered is " << sum << " m" << endl;
cout << "The lowest measurement entered was " << low << " " << low_unit << endl;
cout << "The highest measurement entered was " << high << " " << high_unit << endl;
// Return
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>It's best not to use <code>using namespace std</code>. Read <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">here</a> for more information.</p></li>\n<li><p>Initialize all of your variables on separate lines. When I tried to run your program, it crashed because one of your variables wasn't properly initialized.</p></li>\n<li><p><code>input_array</code> sounds a bit odd, considering you're not even using an array. Since it's meant to hold inputs, just call it \"inputs\" or something similar.</p></li>\n<li><p>This entire program is created in <code>main()</code>, and that makes it very unreadable. Instead, consider splitting it into separate functions. <code>Main()</code> should just handle things such as initializations, user input, and displaying messages. For now, though, I'll just focus on what you have in <code>main()</code> since it needs some work.</p></li>\n<li><p>You don't need that first <code>if</code> statement since your following code blocks will handle that.</p></li>\n<li><p>Your if-blocks look very unreadable, especially with the assignments separated by commas. Consider this style for \"m\":</p>\n\n<pre><code>if (unit == \"m\") { \n input_array.push_back(num);\n\n if (count == 0) {\n low = num;\n low_unit = unit;\n high = num;\n high_unit = unit;\n }\n if (num < low) {\n low = num;\n low_unit = unit;\n }\n else if (num > high) {\n high = num;\n high_unit = unit;\n }\n\n count++;\n}\n</code></pre>\n\n<p>I'm sure it can get simpler than that, but this does show how to separate statements and group them within curly-braces.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-29T03:36:05.910",
"Id": "43558",
"Score": "0",
"body": "@user2164854: You're welcome! Best of luck with your programming."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T04:38:51.227",
"Id": "27878",
"ParentId": "27875",
"Score": "3"
}
},
{
"body": "<p>Do you think your code is optimal? You should be the first reviewer (along with the compiler).</p>\n\n<p>Did you notice that you had to copy the\nsame code four times, once for each unit type. Duplication of code is\ngenerally bad and you should spot it yourself. Your four input cases, meters,\ncm, inches and feet all do the same thing:</p>\n\n<ul>\n<li>convert to meters</li>\n<li>push into vector</li>\n<li>set low/high variables</li>\n</ul>\n\n<p>Here's what the loop might look without the duplication:</p>\n\n<pre><code>double low = DBL_MAX;\ndouble high = DBL_MIN;\n...\n\nwhile (cin >> num >> unit) {\n if (unit == \"m\") {\n meters = num;\n } else if (unit == \"cm\") {\n meters = num * cm_to_m;\n } else if (unit == \"in\") {\n meters = num * in_to_m;\n } else if (unit == \"ft\") {\n meters = num * ft_to_m;\n } else {\n cout << \"Incorrect Unit Entered! Please try again...\" << endl;\n continue;\n }\n input.push_back(meters);\n\n if (meters < low) {\n low = meters;\n low_unit = unit;\n } else if (meters > high) {\n high = meters;\n high_unit = unit;\n }\n}\n</code></pre>\n\n<p>This is a lot simpler than your original code, having removed all of the\nduplication. Your tests for <code>count == 0</code> are unnecessary if you set the\nlow/high variables to the limits of the range for <code>double</code> (all double values\nare going to be less than or equal to DBL_MAX etc). This leaves a <code>continue</code>\nwhich many people would consider bad form and some coding standards outlaw.\nTo avoid this we could put the conversion into a function:</p>\n\n<pre><code>static bool convert_to_meters(double num, double &meters, const string& unit)\n{\n const double cm_to_m = 0.01;\n const double in_to_m = 2.54 * 0.01;\n const double ft_to_m = 12 * 2.54 * 0.01;\n if (unit == \"m\") {\n meters = num;\n } else if (unit == \"cm\") {\n meters = num * cm_to_m;\n } else if (unit == \"in\") {\n meters = num * in_to_m;\n } else if (unit == \"ft\") {\n meters = num * ft_to_m;\n } else {\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>And call it from the main loop:</p>\n\n<pre><code>while (cin >> num >> unit) {\n if (!convert_to_meters(num, meters, unit)) {\n cout << \"Incorrect Unit Entered! Please try again...\" << endl;\n }\n else {\n input.push_back(meters);\n\n if (meters < low) {\n low = meters;\n low_unit = unit;\n } else if (meters > high) {\n high = meters;\n high_unit = unit;\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p>You then have another set of unit conversions done twice which could be\nextracted to a function:</p>\n\n<pre><code>static double convert_from_meters(double meters, const string& unit)\n{\n const double m_to_cm = 100;\n const double m_to_in = 100 * (1.0/2.54);\n const double m_to_ft = 100 * (1.0/2.54) * (1.0/12.0);\n double num = meters;\n if (unit == \"cm\") {\n num *= m_to_cm;\n } else if (unit == \"in\") {\n num *= m_to_in;\n } else if (unit == \"ft\") {\n num *= m_to_ft;\n }\n return num;\n}\n</code></pre>\n\n<p>and called with:</p>\n\n<pre><code>low = convert_from_meters(low, low_unit);\nhigh = convert_from_meters(high, high_unit);\n</code></pre>\n\n<hr>\n\n<p>You finish with a loop to add all of the values in the vector. There is a standard\nalgorith for this:</p>\n\n<pre><code>double sum = std::accumulate(input.begin(), input.end(), 0.0);\n</code></pre>\n\n<hr>\n\n<p>Note that your sorting of the vector seems to be unnecessary. However you\ncould determine the low/high values (without units) by looking at the first\nand last items in the vector after sorting. And if you gave up the\nrequirement to print the low/high values in their original units you would\nneed neither to save low/high and low_unit/high_unit every time round the\nloop, nor to convert from meters back to original units. The code then becomes\nmuch simpler. </p>\n\n<p>This might seem like cheating and in an exercise where the\nrequirements are set for you, it is. But in the real world, simplifying the\nrequirements (which can often be fairly arbitrary and many times are\ndetermined by you) can make a huge difference to the complexity and cost of\ncode. Clearly the customer has to agree to any changes that affect the end\nproduct.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-29T03:33:38.867",
"Id": "43557",
"Score": "0",
"body": "Thank you so much, will take a look at this in the morning and do some refactoring!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T22:29:12.313",
"Id": "51550",
"Score": "0",
"body": "`if-else` and `switch` statements can often be further refactored using the command pattern."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T19:42:59.537",
"Id": "27919",
"ParentId": "27875",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "27919",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T03:44:45.383",
"Id": "27875",
"Score": "7",
"Tags": [
"c++",
"beginner",
"converting"
],
"Title": "Style, simplification and modularization for unit converter"
}
|
27875
|
<p>I am looping through an object and finding whether or not the object has the "key," along with some further stuff.</p>
<p>I feel that there is some other correct way to do this apart from this:</p>
<pre><code>var initialLocalesGen = function(data){
var status;
if(!$.isEmptyObject(data)){
console.log(data);
if(data.hasOwnProperty("username") && data.hasOwnProperty("name")){
var headerHtml = Handlebars.compile($("#header-template").html());
$("#userInfoBar").append(headerHtml({"username" : data["username"], "name" : data["name"]}));
}
if(data.hasOwnProperty("allLocales")){
var formHtml = Handlebars.compile($("#locale-template").html());
$("form legend").after(formHtml(data["allLocales"])).end().find("span.submit").css({display:"block"});
}
if(data.hasOwnProperty("status") && parseInt(data["status"]) === 0){
currentStatus = 0;
var object1 = {"status" : data["status"] , "userLocales": data["userLocales"]}
userLocalesProcess(object1);
}
if(data.hasOwnProperty("status") && parseInt(data["status"]) === 1){
currentStatus = 1;
userChangeProcess({"changeLocales" : data["changeLocales"],"userLocales" : data["userLocales"] });
popupMaker({"message":data["message"],"status":data["status"]});
}
if(data.hasOwnProperty("status") && parseInt(data["status"]) === 2){
currentStatus = 2;
}
}
console.log("currentStatus:", currentStatus);
}
</code></pre>
<p>Could anyone help me minimize the condition or show me an even better way of doing it?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T06:24:51.057",
"Id": "43457",
"Score": "0",
"body": "Why do your objects always have different attributes? What is `data`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T06:26:06.670",
"Id": "43459",
"Score": "0",
"body": "data is object which i am getting from Backend, it contains all sub datas(values)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T06:28:22.243",
"Id": "43461",
"Score": "0",
"body": "Of course data is an object and has values ;) More details please."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T06:41:48.240",
"Id": "43466",
"Score": "0",
"body": "Found a nice link for [checking properties in javascript](http://jsperf.com/hasownproperty-vs-in-vs-other/4)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T13:55:27.447",
"Id": "45857",
"Score": "0",
"body": "On a side-note, you should probably use either a switch or else-ifs for the conditions if they are exclusive, if more than one will never be true. It will make the relationships between the statements more clear."
}
] |
[
{
"body": "<p>You could merge the last three ifs. (I assume there are no other states.) </p>\n\n<pre><code>if(data.hasOwnProperty(\"status\")){\n currentStatus = parseInt(data[\"status\"]);\n switch(currentStatus ) {\n case 0:\n var object1 = {\"status\" : data[\"status\"] , \"userLocales\": data[\"userLocales\"]}\n userLocalesProcess(object1); \n break;\n case 1: \n userChangeProcess({\"changeLocales\" : data[\"changeLocales\"],\"userLocales\" : data[\"userLocales\"] });\n popupMaker({\"message\":data[\"message\"],\"status\":data[\"status\"]});\n break;\n default:\n break;\n }\n\n}\n</code></pre>\n\n<p>I think there is nothing else you can do here. All other ifs are totally different. Maybe you could extract method or variables do communicate the meaning of every branch, but beside that I thing we are done.</p>\n\n<hr>\n\n<p>Of course, if is also suitable</p>\n\n<pre><code>...\nif (currentStatus ==0) {\n var object1 = {\"status\" : data[\"status\"] , \"userLocales\": data[\"userLocales\"]}\n userLocalesProcess(object1); \n} else if (currentStatus ==1){\n userChangeProcess({\"changeLocales\" : data[\"changeLocales\"],\"userLocales\" : data[\"userLocales\"] });\n popupMaker({\"message\":data[\"message\"],\"status\":data[\"status\"]});\n}\n...\n</code></pre>\n\n<hr>\n\n<p>Maybe you should just stay with <code>obj.property == null</code>. According to the <a href=\"http://jsperf.com/hasownproperty-vs-in-vs-other/4\" rel=\"nofollow\">link above</a> it seems to be faster, but at least it is easier to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T06:24:34.100",
"Id": "43456",
"Score": "0",
"body": "But i red a article saying, we should try to avoid the switch cases.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T06:25:34.810",
"Id": "43458",
"Score": "0",
"body": "Why? Link? You can do the same with an if."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T06:27:17.393",
"Id": "43460",
"Score": "0",
"body": "should we use the if or else if?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T06:32:17.417",
"Id": "43463",
"Score": "0",
"body": "Update my post. Still interested in the article!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T06:21:31.463",
"Id": "27882",
"ParentId": "27880",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T05:48:39.167",
"Id": "27880",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "How to check minimize or make if-condition on object loop more correct?"
}
|
27880
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.