body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I'm trying to implement search over two models. In this example <code>Book</code> and <code>Article</code>. Here are the attributes from both of these :</p>
<pre><code>Article(id: integer, magazine: string, title: string, body: text, created_at: datetime, updated_at: datetime)
Book(id: integer, publisher: string, author: string, title: string, foreword: text, body: text, created_at: datetime, updated_at: datetime)
</code></pre>
<p>I'm trying to search over multiple attributes on both of these Models using the same search string and combining results. Because my next goal is to have a permlink to results.</p>
<p>Here is how I implemented search on these Models:</p>
<pre><code>def self.search(q)
Article.where('magazine like :value OR title like :value OR body like :value', value: "%#{q}%")
end
def self.search(q)
Book.where('publisher like :value OR author like :value OR title like :value OR foreword like :value OR body like :value', value: "%#{q}%")
end
</code></pre>
<p>Here is the controller :</p>
<pre><code>class HomeController < ApplicationController
def search
articles = Article.search(params[:q])
books = Book.search(params[:q])
@results = articles + books
end
end
</code></pre>
<p>I use haml so here is my searchresult page :</p>
<pre><code>%div.main
%div.pull.left
=link_to 'Back to search', '/',:class => 'btn btn-primary btn-lg'
%div.clearfix
%table.table.table-condensed
%thead
%tr
%th Id
%th Title
%th Type
%tbody
- @results.each do |item|
%tr
%td #{item.id}
%td #{item.title}
%td #{item.class.name}
</code></pre>
<p>Is there a more elegant way to actually do the search? I don't have that many experience with rails but I was reading trough this article :</p>
<p><a href="http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/" rel="nofollow">http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/</a></p>
<p><strong>1.</strong> And I was thinking I could do this as <code>2. Extract Service Objects</code>, but as two search methods search over different attributes I wasn't able to do this? I'd be glad to hear your take on this.</p>
<p><strong>2.</strong> Regarding the permlink to my search. I'm wondering should I create another model named i.e <code>SearchResult</code> and then link the single search result to many Books and Articles?</p>
<p><strong>Update</strong></p>
<p>I'm not looking for solutions like Sunspot or Sphinx, as this is a small app in dev mode just for practising but still I want it to be as better as possible.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T01:34:11.030",
"Id": "58507",
"Score": "1",
"body": "The most elegant and scalable way is to use a search engine like [Sunspot](http://github.com/outoftime/sunspot/tree/master/sunspot_rails) or [Sphinx](http://pat.github.io/thinking-sphinx/) or even [Blacklight](http://projectblacklight.org/)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T09:17:49.253",
"Id": "58542",
"Score": "0",
"body": "Hi Mark, I'm looking something for development as this is not a real app I'm just practising and getting started."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T09:38:18.790",
"Id": "58547",
"Score": "1",
"body": "@GandalfStormCrow - You can **implement** full text search yourself. That said, since it's a small app in dev mode, it's even more imperative that you try out different full text search engines. Once your app has become large and you have a lot of traction and your searching requirements have specialized so much that full-text search doesn't meet your purpose (I doubt that happening any time soon), then you can think about rolling out your own."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T10:48:40.783",
"Id": "58557",
"Score": "0",
"body": "use a full-text search engine is definitely the way to go. However, there's an alternative solution, that requires to change your schema : you have to implement [multiple table inheritance](http://techspry.com/ruby_and_rails/multiple-table-inheritance-in-rails-3/) with a common table (such as \"contents\", or any other relevant name) holding common fields between your two models (title, author,etc.). Your searches and permalinks will simply operate on this intermediate resource."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T11:53:36.757",
"Id": "58563",
"Score": "0",
"body": "@m_x hi Can you show this trough example please?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T18:04:14.773",
"Id": "58635",
"Score": "0",
"body": "I'll try to write something if I have time this week"
}
] |
[
{
"body": "<p>you want a separate model for search, i.e.</p>\n\n<pre><code>class SearchResult < AR::Base\n #columns: content, title, user\n belongs_to :searchable, polymorphic: true\nend\n\nclass Book < AR::Base\n has_one :searchable, polymorphic: true, class_name: 'SearchResult'\n belongs_to :user\n\n after_create :autobuild_searchable\n after_commit :update_search\n\n\n private\n\n def autocreate_searchable\n self.create_searchable\n end\n\n def update_search_content\n searchable.update_attributes(content: \"#{title} #{author}\", title: title, user: user.username)\n end\nend\n\nclass SearchController\n def search\n @result = SearchResult.where(\"content like ?\", \"%#{params[:q]}%\")\n if params[:user]\n @result = @result.where(user: params[:user])\n end\n end\nend\n</code></pre>\n\n<p>Finally in view you can render the actual results, i.e.</p>\n\n<pre><code>= render @result.map(&:searchable)\n</code></pre>\n\n<p>(rails will render correct partial for each element, whatever it's book, magazine or anything, it will look for views/magazines/_magazine, views/books/_book)</p>\n\n<p>You can extend the search with extra columns to use them as additional filters (here i've added user) and you don't pollute your models with extra search logic.\nHow will you handle the searchable content is up to you (here is just a primitive example). You can split it into separate columns (ie. search_field1, search_field2, search_field3), you can tokenize the input or build a fulltext index.</p>\n\n<p>you can store a permalink in SearchResult or you can generate in on the fly. You may have some issues with rails path helpers on polymorphic associations, but those are easy to overcome.</p>\n\n<p>If you have postgres as database i advise you to take a look on pg_search, it's simple and brilliant solution: <a href=\"https://github.com/Casecommons/pg_search\" rel=\"nofollow\">https://github.com/Casecommons/pg_search</a> and should give you better understanding on this topic.</p>\n\n<p>The above code may not work, I didn't check it against Ruby/Rails, just trying to show an idea.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T00:38:39.503",
"Id": "36169",
"ParentId": "35878",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "36169",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T21:08:03.517",
"Id": "35878",
"Score": "4",
"Tags": [
"ruby",
"object-oriented",
"ruby-on-rails"
],
"Title": "Searching over more models rails"
}
|
35878
|
<p>I have a fairly ugly controller method I would like to refactor / extract. I can only test this in a integration type test which kind of signals a code smell.</p>
<p>The method processes the form and needs to do one of 5 things, depending on which button was pressed</p>
<ol>
<li>if submitted and valid (button 1) => update some values on the entity and re-render the form</li>
<li>if submitted and valid (button 2) => perform another controller action that shows a pdf print of the entity</li>
<li>if submitted and valid (button 3) => save entity and redirect</li>
<li>if not submitted or not valid => render form (plus errors)</li>
</ol>
<p>In code it looks kind of like this</p>
<pre><code>protected function processForm(Request $request, MyEntity $entity)
{
$form = $this->createForm(new MyEntityType, $entity);
if ($form->handleRequest($request)->isValid()) {
$alteredEntity = SomeClass:performStuffOnEntity($entity);
if ($form->get('button1')->isClicked()) {
$form = $this->createForm(
new MyEntityType, $alteredEntity
);
}
else if ($form->get('button2')->isClicked()) {
return $this->pdfPreview($alteredEntity);
}
else if ($form->get('button3')->isClicked()) {
return $this->persistAndRedirectToEntity(
$alteredEntity
);
}
}
return $this->render(
'MyBundle:MyEntity:new.html.twig', array(
'form' => $form->createView(),
));
}
</code></pre>
<p>Actually there are two buttons like button1, I left one out for brevity of the example.</p>
<p><strong>Idea 1:</strong> I have tried to extract this into a EntityFormWizard of some sort but this ended up as a cluttered Object with too many dependencies (Router, Templating, Form) which was also a pain to test.</p>
<p><strong>Idea 2:</strong> Using FormEvents I wanted to extract at least the altering of the entity depending on which button was pressed into a FormEventListener, but the only place where I can alter the Entity is the FormEvents::PRE_SET_DATA event, but in there I have problems figuring out which button was clicked.</p>
<p>So the <strong>question</strong>: Do I have to live with my integration test for this behavior or is there a way to extract it and test it with a unit test?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T08:41:13.543",
"Id": "58482",
"Score": "0",
"body": "In every case, controller has a large number of dependencies for unit testing(request, routing, templates, forms, db, etc). But it is not difficult to understand that he do and your controller not looking *fat*. I dont think it makes sense to split it into independent modules to simplify testing, but reduce code read-ablitity. Unit testing has great value with bussiness logic, but functional testing is great for testing stuff like controller responses imo. Anyway its to hard to mock all dependencies in controller for pure unit tests."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T18:17:51.783",
"Id": "35887",
"Score": "2",
"Tags": [
"php",
"unit-testing"
],
"Title": "Symfony2: Extract method from controller, form events, remove conditional"
}
|
35887
|
<p>From <a href="https://www.codeeval.com/browse/115/" rel="nofollow">https://www.codeeval.com/browse/115/</a>:</p>
<blockquote>
<p>You have a string of words and digits divided by comma. Write a program which separates words with digits. You shouldn't change the order elements. </p>
</blockquote>
<p>I tried to do it using Haskell (learning Haskell).</p>
<p>Can you give me some good practices/shortcuts/advice on how to make this code better?</p>
<pre><code>{-# LANGUAGE OverloadedStrings #-}
import qualified Data.Text as T
import System.Environment (getArgs)
main = do
args <- getArgs
content <- readFile(args !! 0)
let fileLines = lines content
mapM (\x -> putStrLn (mixedContent (generateContent (wordsWhen (==',') x)) [] [])) fileLines
data Content = String String | Num Int deriving (Show)
generateContent :: [String] -> [Content]
generateContent [] = []
generateContent (x:xs) = if isNumeric x then [(Num (read x))] ++ generateContent xs else [String x] ++ generateContent xs
mixedContent :: [Content] -> [Int] -> [String] -> String
mixedContent [] d w = foldl (\r x -> r ++ x) "" $ giveResults (generateCommaDelimitedList w) ["|"] (generateCommaDelimitedList (intToChar d))
mixedContent ((String x):xs) d w = mixedContent xs d (w ++ [x])
mixedContent ((Num x):xs) d w = mixedContent xs (d ++ [x]) w
giveResults :: [String] -> [String] -> [String] -> [String]
giveResults [] _ [] = []
giveResults [] _ d = d
giveResults w _ [] = w
giveResults w delimitor d = w ++ delimitor ++ d
intToChar :: [Int] -> [String]
intToChar l = map (\i -> show i) l
generateCommaDelimitedList :: [String] -> [String]
generateCommaDelimitedList [] = []
generateCommaDelimitedList (x:[]) = [x]
generateCommaDelimitedList (x:xs) = (x ++ ","):(generateCommaDelimitedList xs)
isInteger s = case reads s :: [(Integer, String)] of
[(_, "")] -> True
_ -> False
isDouble s = case reads s :: [(Double, String)] of
[(_, "")] -> True
_ -> False
isNumeric :: String -> Bool
isNumeric s = isInteger s || isDouble s
-- split string equivalent
wordsWhen :: (Char -> Bool) -> String -> [String]
wordsWhen p s = case dropWhile p s of
"" -> []
s' -> w : wordsWhen p s''
where (w, s'') = break p s'
</code></pre>
<p>EDIT: I follow advice given in the answer. I just wanted to show how the main should be to respect what the exercise was asking.</p>
<pre><code>main = do
args <- getArgs
content <- readFile(args !! 0)
let l = lines content
let lf = filter (\x -> length x > 0) l
mapM_ (putStrLn . arrange) lf
</code></pre>
<p>The interesting part is <a href="http://hackage.haskell.org/package/base-4.6.0.1/docs/Data-Foldable.html#v%3amapM-95-" rel="nofollow">mapM_</a>, which makes me able to print the lines re-arranged and ignore the result returned by the mapM </p>
|
[] |
[
{
"body": "<p>I think you've overcomplicated the problem because you're approaching it the way you would in an imperative language. I'll describe the way I would approach the problem. <em>Notice that I do a lot of my \"thinking\" in GHCi!</em></p>\n\n<p>Your code reads the file and splits it up into lines just fine, so I'll move onto the part where we handle each line of text. First, we need to split the line up into tokens, where the tokens are separated by commas. The <code>words</code> function is close to what we want, but it breaks at whitespace, not commas. So we'll write our own:</p>\n\n<pre><code>tokens :: String -> [String]\ntokens [] = []\ntokens as = \n case break (==',') as of\n (xs,[]) -> [xs]\n (xs,_:ys) -> xs:tokens ys\n</code></pre>\n\n<p>I put that in the program I'm writing, load it, and try it out:</p>\n\n<pre><code>λ> tokens \"wombat,7,789,tiger,33\"\n[\"wombat\",\"7\",\"789\",\"tiger\",\"33\"]\n</code></pre>\n\n<p>Now we need to separate the words from the integers. So we need a function that will tell us if a token is an integer. The problem statement implies we only need to deal with integers. So a token is an integer if it only contains digits. (The example given didn't have any spaces, but we could allow them, and even decimal points, if we want to.)</p>\n\n<p>So how do we tell if a character is a digit? Hmm... there's probably a function to do that for us.The best way to answer questions of the form \"Is there a Haskell function to do X\" is usually:</p>\n\n<ol>\n<li><p>Figure out what the type signature of the function you want would be.</p></li>\n<li><p>Search <a href=\"http://www.haskell.org/hoogle/?hoogle=\" rel=\"nofollow\">hoogle</a> or <a href=\"http://holumbus.fh-wedel.de/hayoo/hayoo.html?query=\" rel=\"nofollow\">hayoo</a>. If you don't find it in one, try the other. Usually it doesn't matter much whether you get the order of the input parameters exactly right, but you may need to experiment.</p></li>\n</ol>\n\n<p>What would the type of the function we're interested in be? Logically, it has to be:</p>\n\n<pre><code>Char -> Bool\n</code></pre>\n\n<p>Unfortunately, in the case there are a lot of functions with that signature, but eventually we find <code>isDigit</code> in <code>Data.Char</code>.</p>\n\n<pre><code>λ> import Data.Char\nλ> isDigit '7'\nTrue\nλ> isDigit 'w'\nFalse\n</code></pre>\n\n<p>Look at the source for that function. (You'll see that it would be easy to write our own function to allow blanks or decimal points as well as digits.)</p>\n\n<p>So now we have a way to tell if an individual character is valid in an integer. How do we tell if all of the characters in a token pass the test? Again, I suspect there's a function that applies a boolean test to all elements in a sequence, and tells us if they all pass. The type signature of such a function would be one of the following:</p>\n\n<pre><code>(a -> Bool) -> [a] -> Bool\n[a] -> (a -> Bool) -> Bool\n</code></pre>\n\n<p>Checking Hoogle, we find the <code>all</code> function in <code>Data.List</code>.</p>\n\n<pre><code>λ> import Data.List\nλ> all isDigit \"123\"\nTrue\nλ> all isDigit \"wombat\"\nFalse\n</code></pre>\n\n<p>We could use this expression as is, but would be more readable to define a function.</p>\n\n<pre><code>isInteger :: String -> Bool\nisInteger s = all isDigit s\n</code></pre>\n\n<p>We could also write that last line using pointfree notation.</p>\n\n<pre><code>isInteger = all isDigit\n</code></pre>\n\n<p>I add that to my program, reload it, and try it out:</p>\n\n<pre><code>λ> isInteger \"123\"\nTrue\nλ> isInteger \"wombat\"\nFalse\n</code></pre>\n\n<p>Next we need to divide our tokens up into those that are integers, and those that aren't. Again, there's probably a function that segregates a list into those items that satisfy a test, and those that don't. It would have this signature (possibly with the arguments switched):</p>\n\n<pre><code>(a -> Bool) -> [a] -> ([a],[a])\n</code></pre>\n\n<p>This time a Hayoo or Hoogle search turns up <code>break</code> and <code>partition</code>. Looking at the documentation, we see that <code>partition</code> is what we want. Let's try it:</p>\n\n<pre><code>λ> partition isInteger [\"wombat\",\"7\",\"789\",\"tiger\",\"33\"]\n([\"7\",\"789\",\"33\"],[\"wombat\",\"tiger\"])\n</code></pre>\n\n<p>That preserved the order of the elements, but it gave us the integers first. That's easily fixed:</p>\n\n<pre><code>λ> partition (not . isInteger) [\"wombat\",\"7\",\"789\",\"tiger\",\"33\"]\n([\"wombat\",\"tiger\"],[\"7\",\"789\",\"33\"])\n</code></pre>\n\n<p>Let's wrap that in a function to make it more readable:</p>\n\n<pre><code>segregate :: [String] -> ([String], [String])\nsegregate = partition (not . isInteger)\n</code></pre>\n\n<p>I'm going to move a little more quickly now, because you're probably getting the hang of how to approach these problems. Next we need to format the results. Let's focus on re-inserting the comma between tokens. I'll write a dual to the <code>tokens</code> function:</p>\n\n<pre><code>untokens :: [String] -> String\nuntokens = concat . intersperse \",\"\n</code></pre>\n\n<p>Let's try it:</p>\n\n<pre><code>λ> untokens [\"wombat\",\"tiger\"]\n\"wombat,tiger\"\n</code></pre>\n\n<p>Now all we need to combine the two parts:</p>\n\n<pre><code>format :: ([String],[String]) -> String\nformat (xs,ys) = untokens xs ++ '|' : untokens ys\n</code></pre>\n\n<p>Let's try it out:</p>\n\n<pre><code>λ> format ([\"wombat\",\"tiger\"],[\"7\",\"789\",\"33\"])\n\"wombat,tiger|7,789,33\"\n</code></pre>\n\n<p>Now we can put all the steps together:</p>\n\n<pre><code>parse :: String -> String\nparse = format . segregate . tokens\n</code></pre>\n\n<p>See how simple and readable the <code>parse</code> function is? And it works:</p>\n\n<pre><code>λ> parse \"wombat,7,789,tiger,33\"\n\"wombat,tiger|7,789,33\"\n</code></pre>\n\n<hr>\n\n<p>EDIT: Here's the entire program, with <code>main</code>.</p>\n\n<pre><code>import Data.Char\nimport Data.List\n\nmain = do\n args <- getArgs\n content <- readFile(args !! 0)\n mapM_ (putStrLn . lines) content\n\ntokens :: String -> [String]\ntokens [] = []\ntokens as = \n case break (==',') as of\n (xs,[]) -> [xs]\n (xs,_:ys) -> xs:tokens ys\n\nuntokens :: [String] -> String\nuntokens = concat . intersperse \",\"\n\nsegregate :: [String] -> ([String], [String])\nsegregate = partition (not . isInteger)\n\nisInteger :: String -> Bool\nisInteger = all isDigit\n\nformat :: ([String],[String]) -> String\nformat (xs,ys) = untokens xs ++ '|' : untokens ys\n\nparse :: String -> String\nparse = format . segregate . tokens\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T19:59:32.083",
"Id": "58646",
"Score": "0",
"body": "First, thank you for such a good answer, and for taking your time doing this. I can definitely see what you said when saying I approached it the imperative way. I didn't rely enough and hoogle and type signatures of function to create my solution. Thanks for pointing this out. I am kinda amazed by how short, readable is your solution. I will look more into it and try to do other problem following this pattern and hopefully improve my skills and my mindset using FP."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T20:47:53.373",
"Id": "58648",
"Score": "0",
"body": "There is an error though. format wont work if ys is empty (it will add a '|' char even if it shouldn't. Adding patterns will fix it"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T18:53:59.160",
"Id": "35940",
"ParentId": "35890",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35940",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T23:15:22.710",
"Id": "35890",
"Score": "3",
"Tags": [
"haskell"
],
"Title": "Rearrange content string"
}
|
35890
|
<p>Contains 3 options. Given an input array </p>
<ol>
<li>Unsorted and consecutive range, and array is 1 element short. eg: range is 6-9, and <code>array = [7, 8, 9]</code> output should be 6. </li>
<li>All conditions same as previous except 2 numbers are missing.</li>
<li>Input is sorted, numbers are consecutive, array has one missing element. </li>
</ol>
<p>Code:</p>
<pre><code>final class Variables {
private final double x;
private final double y;
Variables(double x2, double y2) {
this.x = x2;
this.y = y2;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
@Override public String toString() {
return "x = " + x + " y = " + y;
}
}
public final class FindMissing {
private FindMissing() {};
/**
* The input array must contain only 1 element lesser than range.
* Returns a missing element.
*/
public static final int unsortedConsecutiveSingleMissing(int[] a1, int low, int high) {
// check that array length should be only 1 element less - can be avoided due to its mention in javadoc
if (a1 == null) throw new NullPointerException("a1 cannot be null. ");
if (low >= high) throw new IllegalArgumentException("The low: " + low + " should be lesser than high: " + high);
int total = (high * (high + 1)/2) - (low * (low + 1)/2) + low;
for (int i = 0; i < a1.length; i++) {
total = total - a1[i];
}
return total;
}
/**
* The input array must contain only 2 element lesser than range.
* Returns a missing element.
*
* Consecutive numbers are present, array is unsorted and a single number repeats.
*
* (a + b)2 = a2 + b2 + 2ab
*
* a + b = S' - S''
* a2 + b2 = T' - T''
*
* S' & S'' : sum of first and second sequence accordingly.
* T' & T'' : sum square of each number in T' and T'' accordingly.
*/
public static final Variables unsortedConsecutiveTwoMissing(int[] a1, int low, int high) {
if (a1 == null) throw new NullPointerException("a1 cannot be null. ");
if (low >= high) throw new IllegalArgumentException("The low: " + low + " should be lesser than high: " + high);
int sum1 = 0;
int squareSum1 = 0;
int x = low;
// careful. we need to be <= not <. due to muscle memory it is easy to be careless here.
while (x <= high) {
sum1 = sum1 + x;
squareSum1 = squareSum1 + x * x;
x++;
}
int sum2 = 0;
int squareSum2 = 0;
for (int i = 0; i < a1.length; i++) {
sum2 = sum2 + a1[i];
squareSum2 = squareSum2 + a1[i] * a1[i];
}
int sumDiff = sum1 - sum2;
int squareDiff = squareSum1 - squareSum2;
// (x + y)2 = x2 + y2 + 2xy
int product = ((sumDiff * sumDiff) - squareDiff) / 2;
return getVariables(product, sumDiff);
}
private static Variables getVariables(double product, double sum) {
// using reduced quadratic equation.
double x = (sum/2) - Math.sqrt( ((sum/2) * (sum/2)) - product);
double y = sum - x;
return new Variables(x, y);
}
/**
*
* The input array must be sorted and must contain only 1 element lesser than range.
* Returns a missing element.
*/
public static Integer sortedConsecutiveSingleMissing(int[] a1, int low) {
if (a1 == null) throw new NullPointerException("a1 cannot be null. ");
int start = a1[0];
if (start != low) {
return low;
}
int last = a1[a1.length - 1];
if (last != a1.length + low) {
return last + 1;
}
int lb = 0;
int hb = a1.length - 1;
while (lb <= hb) {
int mid = (lb + hb) / 2;
if (a1[mid] + 1 != a1[mid + 1]) {
return a1[mid] + 1;
}
if ((a1[mid] - mid) > start) {
hb = mid - 1;
} else {
lb = mid + 1;
}
}
return null;
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li>I'd suggest some naming improvements for your variables:\n<ul>\n<li><code>a1</code> -> <code>numbers</code> or <code>sequence</code></li>\n<li><code>sum1</code>/<code>squareSum1</code> -> <code>sumRange</code>/<code>squareSumRange</code></li>\n<li><code>sum2</code>/<code>squareSum2</code> -> <code>sumNumbers</code> or <code>sumSequence</code> / <code>squareSumNumbers</code></li>\n</ul></li>\n<li>In the comments to <code>unsortedConsecutiveTwoMissing</code> you state: <code>(a + b)2 = a2 + b2 + 2ab</code> which is not immediately visible that this means the binomic formula. The text representation for power of is typically <code>^</code> which would mean the comment should look like this: <code>(a + b)^2 = a^2 + b^2 + 2ab</code></li>\n<li><p>While the binary search in <code>sortedConsecutiveSingleMissing</code> is <code>O(log(n))</code> in production code I'd consider using the same solution as for <code>unsortedConsecutiveSingleMissing</code>. While this is <code>O(n)</code> it has some advantages </p>\n\n<ul>\n<li>It's a simpler solution (easier to understand and maintain, less bugs to write)</li>\n<li>Use one single proven solution (share the code)</li>\n<li>Less code to write and maintain (means less bugs)</li>\n</ul>\n\n<p>Only if it would prove to be a performance problem I'd go down a more complicated path. </p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T08:01:11.277",
"Id": "35903",
"ParentId": "35902",
"Score": "2"
}
},
{
"body": "<p>My comments related to <code>unsortedConsecutiveSingleMissing</code>:</p>\n\n<ol>\n<li><p>The calculation of total using the formula <code>int total = (high * (high + 1)/2) - (low * (low + 1)/2) + low;</code>:</p>\n\n<ul>\n<li>is susceptible to integer overflow issues (Consider when <code>high</code> is really high and <code>low</code> is still positive).</li>\n<li>is doing a lot of extra work to evaluate an Arithmetic Progression. Unfortunately, you are using the formula to sum first <code>n</code> natural numbers twice to get this result. You can use the much more straightforward formula <code>n*(a+l)/2</code> where:\n<ul>\n<li><code>a</code> is the first term (<code>low</code> in your code);</li>\n<li><code>l</code> is the last term (<code>high</code>); and</li>\n<li><code>n</code> is the number of terms in the AP (<code>high - low + 1</code>)</li>\n</ul></li>\n</ul></li>\n<li><p>This calculation of total, irrespective of the process used, is susceptible to overflow. The algorithm used needs to be adapted to avoid calculating the total at all. (There is a way to do that and still keep the code O(1) in space and O(n) in time.)</p></li>\n</ol>\n\n<p>My comments related to <code>unsortedConsecutiveTwoMissing</code>:</p>\n\n<ol>\n<li>You could have used the formulae to calculate the sum of the sequence and sum of the squared sequence. Again, whatever you use is susceptible to overflow. If you have acknowledged the review comment for the above method, you can remove the problem here as well. (<em>Hint: It'll also reduce your two loops to calculate the sum1 and sum2 into a single loop.</em>)</li>\n<li>Even after solving the problem with the calculation of the sum and the squared sum, your calculation of product can overflow once again. In fact it's unavoidable in your algorithm. Consider the case when the missing numbers are <code>Integer.MAX_VALUE</code> and <code>Integer.MAX_VALUE - 1</code>, the product is -2147483646 while the sum is -3. The solution is pretty difficult to obtain now.</li>\n<li>Needless to say, you need to change your algorithm once again.</li>\n<li>Return an object containing integers not doubles. The problem states that the sequence is missing integers.</li>\n</ol>\n\n<p><code>getVariables()</code> suffers from the same problems. So, I won't be adding any comments separately.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T08:46:33.253",
"Id": "35908",
"ParentId": "35902",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35908",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T07:01:38.523",
"Id": "35902",
"Score": "2",
"Tags": [
"java",
"algorithm",
"array"
],
"Title": "Find a missing numbers, single missing number and two missing numbers, from consecutive range"
}
|
35902
|
<p>I have created a module to draw text tables. The relevant parts are below and here's the full code for <a href="https://github.com/atomgomba/txtable/blob/master/txtable/__init__.py" rel="nofollow">txtable</a>).</p>
<pre><code>class Row(Txtable):
[...]
def format(self, col_widths):
"""Return the row as formatted string.
"""
columns = []
for x, column in enumerate(self.columns):
# skip empty rows
if 0 == len(str(column)):
columns.append((" " * col_widths[x]))
continue
columns.append(self.format_cell(x, col_widths[x]))
return str(" " * self.col_spacing).join(columns)
class Table(Txtable):
[...]
def add_rows(self, rows):
"""Add multiple rows.
"""
for columns in rows:
self.add_row(columns)
[...]
def render(self):
"""Return the table as a string.
"""
# render cells and measure column widths
for y, row in enumerate(self.rows):
for x, column in enumerate(row.columns):
fmt_column = row.format_cell(x)
width = len(fmt_column)
try:
if self.col_widths[x] < width:
self.col_widths[x] = width
except IndexError:
self.col_widths.append(width)
# render the table with proper spacing
output = ""
lmarg = (" " * self.margin)
for row in self.rows:
[...do rest of the rendering...]
</code></pre>
<p>I'd like to know about ways I could optimize this please. I see I could calculate the maximum column widths in <code>Table.add_rows()</code> instead of <code>Table.render()</code>, but I'd like to keep the possibility to modify the rows before rendering the final output.</p>
<p>How could I cut back on the looping? Is there a better way to output tabular data?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T16:55:57.423",
"Id": "58615",
"Score": "1",
"body": "This code doesn't run: you must post *working* code for us to review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T18:24:06.590",
"Id": "58789",
"Score": "1",
"body": "It would make more sense to review the complete code. (You need to post it here then)"
}
] |
[
{
"body": "<p>The nested loop under <code># render cells and measure column widths</code> computes maximum cell width of each column. Using <code>itertools.zip_longest</code> to turn columns into rows lets you use <code>max</code> on them:</p>\n\n<pre><code>cell_widths = [[len(row.format_cell(x)) for x in range(len(row.columns))]\n for row in self.rows]\ncol_widths = list(map(max, itertools.zip_longest(*cell_widths, fillvalue=0)))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-02T18:52:50.713",
"Id": "36533",
"ParentId": "35909",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "36533",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T09:05:33.643",
"Id": "35909",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"formatting"
],
"Title": "Drawing a table in Python3"
}
|
35909
|
<p>I am working on a <em>SimCity</em> clone, and I am noticing a drop in frame rate as I add more objects to my map, now this is expected, but, when I fill the whole screen, the game maintains about 300 FPS.</p>
<p>Will it hold this as I add a lot more objects, or will it continue to drop?</p>
<pre><code>import pygame
from pygame.locals import *
from random import choice
#inits
pygame.init()
font=pygame.font.Font(None, 18)
screen=pygame.display.set_mode((640,480))
pygame.display.set_caption('City Game | Pre-Alpha')
clock=pygame.time.Clock()
#sprites
curspr=pygame.image.load('curs.png').convert()
curspr.set_alpha(100)
grassspr=pygame.image.load('grass.png').convert()
roadspr=pygame.image.load('road.png').convert()
forestspr=pygame.image.load('forest.png').convert()
water1=pygame.image.load('water1.png').convert()
water2=pygame.image.load('water2.png').convert()
res=pygame.image.load('res.png').convert()
house1_0=pygame.image.load('house1_0.png').convert()
house1_1=pygame.image.load('house1_1.png').convert()
res.set_alpha(215)
#vars and lists
tilelist=[grassspr,roadspr,forestspr,water1,res]
namelist=['Grass','Road','Forest','Water','Residental']
tiles=[]
sel=0
money=10000
moneydraw=font.render('Funds: '+str(money), 1, (255,255,255))
namedraw=font.render(namelist[sel],1,(255,255,255))
mse=(0,0)
waterframe=2000
pop=0
class Tile(object):
def __init__(self,pos,spr,typ):
self.typ=typ
self.spr=spr
self.pos=pos
self.rect=pygame.rect.Rect(pos[0],pos[1],32,32)
self.adv=0
while True:
pygame.display.set_caption(str(clock.get_fps()))
namedraw=font.render(namelist[sel],1,(255,255,255))
screen.fill((2,110,200))
for e in pygame.event.get():
if e.type==QUIT:
exit()
if e.type==MOUSEMOTION:
mse=pygame.mouse.get_pos()
key=pygame.key.get_pressed()
if key[K_LSHIFT] or key[K_RSHIFT]:
if pygame.mouse.get_pressed()==(1,0,0):
tilesatmouse=[t for t in tiles if t.rect.collidepoint(mse)]
if not tilesatmouse:
if sel==4:
tiles.append(Tile(((mse[0]/32)*32,(mse[1]/32)*32),tilelist[sel],'res'))
else:
tiles.append(Tile(((mse[0]/32)*32,(mse[1]/32)*32),tilelist[sel],'tile'))
elif pygame.mouse.get_pressed()==(0,0,1):
for t in tiles:
if t.rect.collidepoint(mse):
tiles.remove(t)
if e.type==KEYUP:
if e.key==K_e:
sel+=1
if sel==len(tilelist):
sel=0
if e.key==K_q:
sel-=1
if sel==-1:
sel=len(tilelist)-1
if e.type==MOUSEBUTTONUP:
if e.button==1:
tilesatmouse=[t for t in tiles if t.rect.collidepoint(mse)]
if not tilesatmouse:
if sel==4:
tiles.append(Tile(((mse[0]/32)*32,(mse[1]/32)*32),tilelist[sel],'res'))
else:
tiles.append(Tile(((mse[0]/32)*32,(mse[1]/32)*32),tilelist[sel],'tile'))
if e.button==3:
for t in tiles:
if t.rect.collidepoint(mse):
tiles.remove(t)
for t in tiles:
if t.spr==water1 or t.spr==water2:
if waterframe>999:
t.spr=water1
else:
t.spr=water2
if t.typ=='res':
if t.adv>=0:
t.adv+=1
if t.adv==2000:
t.spr=house1_0
if t.adv==4000:
t.spr=house1_1
pop+=choice([1,2,3,4])
t.adv=-1
screen.blit(t.spr,t.pos)
waterframe-=1
if waterframe==0:
waterframe=2000
clock.tick(999)
screen.blit(curspr, ((mse[0]/32)*32,(mse[1]/32)*32))
screen.blit(moneydraw, (2,2))
screen.blit(namedraw, (2,18))
pygame.display.flip()
#if any(t.rect.colliderect(x.rect) for x in tiles if x is not t):
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T18:11:11.010",
"Id": "58637",
"Score": "4",
"body": "You ask: `Will it hold this as I add a lot more objects? Or will it continue to drop?` ... well, have you tried that and observed what happens?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T04:20:32.447",
"Id": "58672",
"Score": "4",
"body": "Watch out for complicated expressions inside loops. Whereas in C it's useful to decrease strength of operation, in Python it's often worth decreasing the number of operations. As it happens, none of the instances of this are in tight loops, but you could reduce both by turning `((mse[x]/32)*32)` into `(mse[x] & 0x7fffffe0)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T23:39:31.607",
"Id": "58753",
"Score": "0",
"body": "@rolfl, I haven't tried, there is only so much room on the screen. But when I get around to adding scrolling, I will test this. @Michael Urman, What is `&0xfffffe0`??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T00:39:56.517",
"Id": "58756",
"Score": "0",
"body": "@SamTubb - `xxx/32` is the same as `xxx >>> 5` (and `xxx/2` is `xxx >>> 1` ...), and `xxx*32` is the same as `xxx << 5`. The effect of `(xxx>>>5)<<5` is to 'blank' out the five least significant bits in `xxx`, which is what `xxx & 0xffffffe0` does!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T00:40:54.410",
"Id": "58757",
"Score": "1",
"body": "Clear as mud now?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T02:57:08.407",
"Id": "58759",
"Score": "0",
"body": "I've never even heard of this? You sure it works with python?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T03:01:00.187",
"Id": "58760",
"Score": "0",
"body": "@rolfl Never mind! I implemented it and it worked like a charm! Thanks! Now, what does this do again?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T04:59:55.697",
"Id": "58764",
"Score": "2",
"body": "32 is the 5th power of 2. Any multiplication or division by a power of 2 can be expressed as a bit-shift. In decimal, the same is true for 10. E.g. `12345 / 1000` is 12345 shifted right 3 times (1000 is the 3rd power of 10), which (in integer terms truncates the decimal) is `12`. So, `(12345/1000)*1000` is 12000. Which is the same as just setting the units/tens/hundreds digits to `0`. Michael, in binary instead of decimal, has just pointed out that a binary number divided then multiplied by 32 is the same as setting the low-5 bits to 0, and that is what the `& 0xffffffe0` does"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-05T21:03:11.077",
"Id": "149802",
"Score": "0",
"body": "The title of your post should only contain the function/purpose of your code; questions are meant for the body."
}
] |
[
{
"body": "<p>As you asked in your question, I'm going to <em>try</em> and address your performance issues here. Some of this will be a style review though, so bear with me.</p>\n\n<hr>\n\n<h1>Style</h1>\n\n<ul>\n<li><p>First off, no offense, but this code looks, not so great. You have many major style issues, so here's a list of some of the major ones I see.</p>\n\n<ul>\n<li>You have no spaces between operators. You should have space between all operators. For example, if I wanted to assign <code>x</code> to <code>1</code>, it should look like this, <code>x = 1</code>, and not this. <code>x=1</code></li>\n<li>Your variable naming is just horrendous. For example, you named a variable <code>sel</code>. I have no idea what this variable does, or what it's purpose is. Good variable names should not be too short, or too long, and should reflect clearly on that variable's purpose.</li>\n<li>This code needs to be separated into various different functions/classes. Right now there's some top-level variables, one class, and a <code>while</code> loop doing most of the work. Try and see if there are ways to separate this into separate functions, e.g, a function for checking key actions, or another for rendering the tiles.</li>\n</ul>\n\n<p>You can find these and many other recommendations in <a href=\"http://www.python.org/dev/peps/pep-0008/\">PEP8</a>,\nthe Python coding style guide.</p></li>\n</ul>\n\n<hr>\n\n<h1>Performance</h1>\n\n<ul>\n<li>First off, from what I can see, you're doing a lot of looping through the list storing the tile data. This is where your problem is. The more you loop through the data, and the larger the data gets, the slower your program will run.</li>\n<li>If you have any loops that are looping through the data and checking for an item with a specific value, it's better to use <code>if..in</code> instead.</li>\n<li>As mentioned in the comments, you can also shorten some of your expressions. For example, the following expression, <code>((mse[x]/32)*32)</code>, can be shortened into <code>(mse[x] & 0x7fffffe0)</code>. While shortening expressions is something that isn't easy to do, (even I can't do it very well), see where you can do things like this.</li>\n</ul>\n\n<hr>\n\n<p>Anyways, I hope that this review helped! If you want me to add on anything else, just ask about it in the comments, and I'll see what I can do. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-13T04:34:11.723",
"Id": "93486",
"ParentId": "35914",
"Score": "11"
}
},
{
"body": "<p>You have several <code>if</code> conditions that cannot be true at the same time:</p>\n\n<blockquote>\n<pre><code>if e.type==MOUSEMOTION:\n # ...\n\nif e.type==KEYUP:\n # ...\n\nif e.type==MOUSEBUTTONUP:\n # ...\n</code></pre>\n</blockquote>\n\n<p>Such conditions should be chained with <code>elif</code> in between.\nOtherwise, even after we already know that <code>e.type == MOUSEMOTION</code>,\nthe other conditions will be evaluated too, needlessly.</p>\n\n<hr>\n\n<p>You do this kind of thing at so many places,\nit would be better to put it into a function:</p>\n\n<blockquote>\n<pre><code>(x / 32) * 32\n</code></pre>\n</blockquote>\n\n<p>Perhaps something like this:</p>\n\n<pre><code>def drop_lowest_5_bits(x):\n return x & 0x7fffffe0\n</code></pre>\n\n<p>As you notice, the name of the function documents what this does.</p>\n\n<hr>\n\n<p>You could benefit from some more imports,\nso that you can reduce all that code prefixed by <code>pygame.</code>.\nFor example I would import these names:</p>\n\n<pre><code>from pygame.image import load\nfrom pygame.rect import Rect\nfrom pygame import mouse\nfrom pygame import key\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-13T06:32:02.567",
"Id": "93492",
"ParentId": "35914",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T12:28:07.130",
"Id": "35914",
"Score": "11",
"Tags": [
"python",
"performance",
"game",
"pygame"
],
"Title": "SimCity clone performance"
}
|
35914
|
<p>How can I improve the speed of this LINQ query?</p>
<pre><code>using (var txn = new TransactionScope(TransactionScopeOption.Required,
new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted }))
{
var myAlertsList = (from alerts in _db.Alerts.AsNoTracking()
where alerts.AlertID >= Id.AlertID && alerts.DataWystapienia >Id.DataWystapienia
select new MyAlerts { AlertID = alerts.AlertID, DataWystapienia = alerts.DataWystapienia, Message = alerts.Message })
.OrderByDescending(a => a.AlertID).Take(Id.NumberOfRows).Concat((
from subAlerts in _db.SubAlerts.AsNoTracking()
where subAlerts.AlertID >= Id.AlertID && subAlerts.DataWystapienia > Id.DataWystapienia
select new MyAlerts { AlertID = subAlerts.AlertID, DataWystapienia = subAlerts.DataWystapienia, Message = subAlerts.Message })
.OrderByDescending(c => c.AlertID).Take(Id.NumberOfRows)).OrderByDescending(a => a.AlertID).Take(Id.NumberOfRows);
return myAlertsList;
}
</code></pre>
<p>It seems like the order by date is the longest process in this query. Is this correct?
The database has about a million records. <code>NumberOfRows</code> is max 200. Time of this query is 45ms (after using only one <code>orderby</code>). Is there something more that I can do to improve that LINQ query?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T14:02:19.540",
"Id": "58583",
"Score": "1",
"body": "you have 3 `OrderByDescending`s followed by takes of which you can remove all but the last"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T15:01:52.633",
"Id": "58591",
"Score": "2",
"body": "@ratchetfreak, explain that more in an answer, that is a review of the code, and is a good answer as long as you explain it a little bit more."
}
] |
[
{
"body": "<p>First lets split up the query so we can read it:</p>\n\n<pre><code>var alertList = from alerts in _db.Alerts.AsNoTracking()\n where alerts.AlertID >= Id.AlertID && alerts.DataWystapienia >Id.DataWystapienia\n select new MyAlerts { AlertID = alerts.AlertID, DataWystapienia = alerts.DataWystapienia, Message = alerts.Message };\n\nvar subAlertList = from subAlerts in _db.SubAlerts.AsNoTracking()\n where subAlerts.AlertID >= Id.AlertID && subAlerts.DataWystapienia > Id.DataWystapienia\n select new MyAlerts { AlertID = subAlerts.AlertID, DataWystapienia = subAlerts.DataWystapienia, Message = subAlerts.Message };\n\nvar myAlertsList = alertList.OrderByDescending(a => a.AlertID).Take(Id.NumberOfRows)\n .Concat(subAlertList.OrderByDescending(a => a.AlertID).Take(Id.NumberOfRows))\n .OrderByDescending(a => a.AlertID).Take(Id.NumberOfRows);\n</code></pre>\n\n<p>this is fully equivalent to your code I only extracted the 2 lists</p>\n\n<p>the last operation of code has 3 <code>OrderByDescending(a => a.AlertID).take(Id.NumberOfRows)</code> while only 1 is needed </p>\n\n<pre><code>var myAlertsList = alertList.Concat(subAlertList).OrderByDescending(a => a.AlertID).Take(Id.NumberOfRows);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T02:35:57.557",
"Id": "58758",
"Score": "0",
"body": "the inside queries aren't doing anything that needs them to be in order for any reason, you just need the final result to be in order for viewing purposes I assume."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T15:15:00.010",
"Id": "35922",
"ParentId": "35919",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T13:53:16.910",
"Id": "35919",
"Score": "2",
"Tags": [
"c#",
"sql",
"linq",
"performance"
],
"Title": "Improve speed of LINQ query"
}
|
35919
|
<p>I have the following algorithm which retrieves information in a <code>List</code> of <code>KeyValuePair</code> (prices) and write them in a <code>DataRow</code>. I was wondering if I could achieve the same result without <code>j</code>. </p>
<pre><code>if (prices != null)
{
for (int i = 8, j=0; j < prices.Count; i+=2, j++)
{
res[i] = prices[j].Value;
res[i+1] = prices[j].Key;
}
}
</code></pre>
<p>The ouput is a <code>DataRow</code> as follow :</p>
<pre><code>res[8] = prices[0].Value
res[9] = prices[0].Key
res[10] = prices[1].Value
res[11] = prices[1].Key
res[12] = prices[2].Value
res[13] = prices[2].Key
</code></pre>
<p>etc.</p>
|
[] |
[
{
"body": "<p>I would approach this first by flattening the prices dictionary into a sequence of values eg <code>{ Key, Value, Key, Value, Key, Value }</code>.</p>\n\n<pre><code>// This method is returning object for now since I'm not clear what types are in your data row..\nIEnumerable<object> Flatten<K, V>(IEnumerable<KeyValuePair<K, V>> pairs)\n{\n foreach (var pair in pairs)\n {\n yield return pair.Value;\n yield return pair.Key;\n }\n}\n</code></pre>\n\n<p>Using this I can simply loop over the flattened dictionary and copy the values into the data row:</p>\n\n<pre><code>int offset = 8;\nforeach (var x in Flatten(prices))\n{\n res[offset++] = x;\n}\n</code></pre>\n\n<p><em>I suspect there is a far better term than \"flatten\" for what I'm doing with the dictionary here.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T16:08:43.967",
"Id": "58602",
"Score": "0",
"body": "that looks a lot cleaner than what I was going to do."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T16:10:19.000",
"Id": "58603",
"Score": "2",
"body": "The question says it's a list of key-value pairs, not a dictionary. (Though that will just mean that you would change the type of `pairs`.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T16:18:15.287",
"Id": "58606",
"Score": "0",
"body": "@svick good spot, changed to `IEnumerable<KeyValuePair<K, V>>`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T19:04:03.923",
"Id": "58641",
"Score": "0",
"body": "Though your answer is good I was looking for something like what svick did. Thanks anyway !"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T22:10:42.093",
"Id": "58654",
"Score": "1",
"body": "That is probably faster than the accepted answer because there is no arithmetic overhead. (Note: you need to yield `Value` before `Key` to conform OP's situation)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T17:19:25.407",
"Id": "58700",
"Score": "0",
"body": "@ssg good spot, will update the answer. In my example the C# compiler will be generating a lot of [boilerplate code](http://tutorials.csharp-online.net/CSharp_Coding_Solutions%E2%80%94What_Does_Yield_Keyword_Generate) for me. Svicks solution should be quicker since simple integer arithmetic is effortless to the CPU - not to mention easier for the compiler to optimize. I think the main advantage of my solution is the re-usability of the `Flatten` method."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T15:58:41.027",
"Id": "35928",
"ParentId": "35924",
"Score": "12"
}
},
{
"body": "<p>You can calculate <code>i</code> from <code>j</code> as <code>2*j + 8</code> (and <code>2*j + 9</code>). That would change your code to:</p>\n\n<pre><code>for (int j = 0; j < prices.Count; j++) \n{\n res[2*j + 8] = prices[j].Value;\n res[2*j + 9] = prices[j].Key;\n}\n</code></pre>\n\n<p>Though I'm not sure whether this is actually better code than the original.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T19:04:23.533",
"Id": "58642",
"Score": "0",
"body": "Well at least this answer my question perfectly. I dont know how I missed that however."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T16:13:03.230",
"Id": "35932",
"ParentId": "35924",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "35932",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T15:38:57.963",
"Id": "35924",
"Score": "4",
"Tags": [
"c#"
],
"Title": "Writing information from a List of KeyValuePairs into a DataRow"
}
|
35924
|
<p>I would like feedback on things I can improve. If you want to see the full example in action, here is the <a href="http://labs.lesevades.com/recipe-book" rel="nofollow">link</a>.</p>
<pre><code>$(document).ready(function() {
var all = $("#slider-view");
var winWidth = window.innerWidth;
var winHeight = window.innerHeight;
$(all).css('height', window.innerHeight);
$(all).css('width', window.innerWidth);
// Assigns the container that has all the sections that will be scrolled horizontally
var sliderH = $('.nav-h');
var sliderVMiddle = $('.nav-v-middle');
var sliderVLast = $('.nav-v-last');
// Gets the number of slides of the horizontal slider
var sliderCountH = $('.nav-h').children().size();
var sliderCountVMiddle = $('.nav-v-middle').children().size();
var sliderCountVLast = $('.nav-v-last').children().size();
// Sets the properties of the arrows that have the events
setCssRect(sliderH, 'w', winWidth);
setCssRect(sliderH, 'h', winHeight);
setCssRect(sliderVMiddle, 'w', winWidth);
setCssRect(sliderVMiddle, 'h', winHeight);
setCssRect(sliderVLast, 'w', winWidth);
setCssRect(sliderVLast, 'h', winHeight);
// sets css size properties on the jQuery element.
function setCssRect(elt, property, value) {
if(property=='w') {
$('> div',elt).css('width', value);
}
else {$('> div',elt).css('height', value);}
}
// Gets the number of Horizontal or Vertical slide
var viewWidth = sliderCountH * winWidth;
var heightVMiddle = sliderCountVMiddle * winHeight;
var heightVLast = sliderCountVLast * winHeight;
// Sets the width and height for the Horizontal and Vertical slides
$('.nav-h').css('width', viewWidth);
$('.nav-v-middle').css('height', heightVMiddle);
$('.nav-v-last').css('height', heightVLast);
var isMobile = {
Android: function() { return navigator.userAgent.match(/Android/i); },
BlackBerry: function() { return navigator.userAgent.match(/BlackBerry/i); },
iOS: function() { return navigator.userAgent.match(/iPhone|iPad|iPod/i); },
Opera: function() { return navigator.userAgent.match(/Opera Mini/i); },
Windows: function() { return navigator.userAgent.match(/IEMobile/i); },
any: function() { return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows()); }
};
if ( isMobile.any() ) {
$('a#prevh').toggle();
$('a#nexth').toggle();
$('a#prevv').toggle();
$('a#nextv').toggle();
var horizontalIndex = 0;
var verticalIndexMiddle = 0;
var verticalIndexLast = 0;
// actions for the swiperight
$(sliderH).hammer({prevent_default:true}).on('swiperight', function() {
actionHorizontalAnimation(0, '+', '+');
});
// Actions for the swipeLeft
$(sliderH).hammer({prevent_default:true}).on('swipeleft', function() {
actionHorizontalAnimation((sliderCountH-1), '-', '-');
});
// Actions for the swipeUp
$(sliderH).hammer({prevent_default:true}).on('swipedown', function() {
actionVerticalAnimation(0, sliderCountVLast, '+');
});
// Actions for the swipeDown
$(sliderH).hammer({prevent_default:true}).on('swipeup', function() {
actionVerticalAnimation((sliderCountVMiddle-1), (sliderCountVLast-1), '-');
});
}
else {
var horizontalIndex = 0;
var verticalIndexMiddle = 0;
var verticalIndexLast = 0;
findSlidePosition(horizontalIndex, verticalIndexMiddle, verticalIndexLast);
$('a#prevh').on('click', function(event) {
actionHorizontalAnimation(0, '+', '+');
});
$('a#nexth').on('click', function(event) {
actionHorizontalAnimation((sliderCountH-1), '-', '-');
});
$('a#prevv').on('click', function(event) {
actionVerticalAnimation(0, sliderCountVLast, '+');
});
$('a#nextv').on('click', function(event) {
actionVerticalAnimation((sliderCountVMiddle-1), (sliderCountVLast-1), '-');
});
}
// Onclick horizontal movement
function actionHorizontalAnimation(sliderPosition, orientation, shift) {
if(verticalIndexMiddle!==0) {
verticalAnimation(sliderVMiddle, '+', (winHeight*verticalIndexMiddle))
verticalIndexMiddle = 0;
}
if(verticalIndexLast!==0) {
verticalAnimation(sliderVLast, '+', (winHeight*verticalIndexLast))
verticalIndexLast = 0;
}
if(horizontalIndex!==sliderPosition) {
horizontalAnimation(sliderH, shift, winWidth);
if(orientation==='-'){horizontalIndex+=1;}else{horizontalIndex-=1;}
}
findSlidePosition(horizontalIndex, verticalIndexMiddle, verticalIndexLast);
}
// OnClick vertical movement
function actionVerticalAnimation(middleSlidePosition, lastSlidePosition, orientation) {
if(horizontalIndex==1) {
if(verticalIndexMiddle!==middleSlidePosition) {
verticalAnimation(sliderVMiddle, orientation, winHeight);
if(orientation==='-'){verticalIndexMiddle+=1;} else {verticalIndexMiddle-=1;}
}
} else if (horizontalIndex==2) {
if(verticalIndexLast!==lastSlidePosition) {
verticalAnimation(sliderVLast, orientation, winHeight)
if(orientation==='-'){verticalIndexLast+=1;} else {verticalIndexLast-=1;}
}
}
findSlidePosition(horizontalIndex, verticalIndexMiddle, verticalIndexLast);
}
// animation for vertical slide
function verticalAnimation(slider, action, size) {
$('> div', slider).animate({
top: action+'=' + size
}, 600);
}
// animation for horizontal slide
function horizontalAnimation(slider, action, size) {
$('> div', slider).animate({
left: action+'=' + size
}, 600);
}
// Set hides or shows the arrows for the navigation
function findSlidePosition(h1, v1, v2) {
$('.nav-btns div').css('border-color', '#706E6D');
resetObjectStyle();
if(h1==0 && v1==0 && v2==0) {
$('.nav-home').css('border-color','#FFF');
activateControlFlow(['#nexth']);
}
else if(h1==1 && v1==0 && v2==0) {
$('.nav-middle-slide1').css('border-color','#FFF');
activateControlFlow(['#nexth', '#prevh', '#nextv']);
}
else if(h1==1 && v1>=1 && v1<=8 && v2==0) {
var test = '.nav-middle-slide'+ (v1+1);
$(test).css('border-color','#FFF');
activateControlFlow(['#nexth', '#prevh', '#nextv', '#prevv']);
}
else if(h1==1 && v1==9 && v2==0) {
$('.nav-middle-slide10').css('border-color','#FFF');
activateControlFlow(['#nexth', '#prevh', '#prevv']);
}
else if(h1==2 && v1==0 && v2==0) {
$('.nav-last-slide1').css('border-color','#FFF');
activateControlFlow(['#prevh', '#nextv']);
}
else if(h1==2 && v1==0 && (v2==1 || v2==2)) {
$('.nav-last-slide2').css('border-color','#FFF');
activateControlFlow(['#prevh', '#nextv', '#prevv']);
}
else if(h1==2 && v1==0 && v2==3) {
$('.nav-last-slide4').css('border-color','#FFF');
activateControlFlow(['#prevh', '#prevv']);
}
}
// Hides all the arrows
function resetObjectStyle() {
$('a.control-flow').css({color:'transparent', cursor: 'auto'});
}
// Shows specific arrows fiven as parameters in an array
function activateControlFlow(arrayControl) {
$.each(arrayControl, function(key, selector){
$(selector).css({color:'#FFF', cursor: 'pointer'});
});
}
var scene4 = document.getElementById('scene4');
var parallax = new Parallax(scene4);
var scene5 = document.getElementById('scene5');
var parallax = new Parallax(scene5);
var scene6 = document.getElementById('scene6');
var parallax = new Parallax(scene6);
var scene8 = document.getElementById('scene8');
var parallax = new Parallax(scene8);
var scene9 = document.getElementById('scene9');
var parallax = new Parallax(scene9);
var scene10 = document.getElementById('scene10');
var parallax = new Parallax(scene10);
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T16:16:23.453",
"Id": "58604",
"Score": "0",
"body": "Continuously numbered variables (css classes, IDs, etc) are always a code smell."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T16:17:53.397",
"Id": "58605",
"Score": "0",
"body": "is this a bad practice? I was having a hard time giving names"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T16:18:53.023",
"Id": "58607",
"Score": "0",
"body": "If you have multiple instances of the same thing, use arrays."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T16:36:54.390",
"Id": "58612",
"Score": "0",
"body": "You also have a lot of other duplication in your code. I'm trying to make something more compact over on jsFiddle. Might take a moment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T16:55:38.853",
"Id": "58614",
"Score": "0",
"body": "Believe me before this 2nd post it was a terrible. Thank you for all the feedback! I really appreciate it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T17:26:45.547",
"Id": "58623",
"Score": "1",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/11649/discussion-between-tomalak-and-monica)"
}
] |
[
{
"body": "<p>I took a look at your chat with Tomalak and it seems you got some good advice, so big tip-o'-the-hat to Tomalak.</p>\n\n<p>These are just some thoughts on the overall approach to some of this stuff. I'm not so much looking at your current code, but the things I touch on should be applicable regardless.</p>\n\n<p>As Tomalak mentioned, it's better to avoid sequential numbering. But you've also got the <code>middle</code> and <code>last</code> classes that also implies a sort of numbering system. A numbering system that can't go higher than 3 items in fact, so it's pretty limiting. Remember that the structure of the HTML itself can provide a lot of this stuff; ordering is maintained when you use jQuery to select elements.</p>\n\n<p>To keep the code abstract, I'd probably use <em>group</em> as the name (and class) for the \"columns\" of slides. While I just used \"column\" in the description - and you could call them that instead - it locks everything into a concrete idea of how it looks. And that isn't always necessary from a coding perspective.</p>\n\n<p>So, you've got 3 groups, and each has <em>x</em> number of slides. Within each group, you've got a first and a last slide, as determined by their order in the HTML.</p>\n\n<p>Now, if you've got a slide that's marked as, say, \"current\", navigating to another slide is fairly easy. And you don't need to keep track of the current slide, as you can always find it again by its class name.</p>\n\n<p>Within the group (column), the next and previous slides can be found from the current one using jQuery's aptly named <code>.next()</code> and <code>.prev()</code>. So to go to the next slide (i.e. \"down\" on your site), you could do something like:</p>\n\n<pre><code>var currentSlide = $(\".slide.current\"), \n targetSlide = currentSlide.next(\".slide\");\nif(targetSlide.length === 0) {\n // no more slides in this group!\n} else {\n currentSlide.removeClass(\"current\");\n targetSlide.addClass(\"current\");\n}\n</code></pre>\n\n<p>For moving from group to group, it's a little different. However, provided you want the current functionality of always moving to the first slide in a group, you can do something like this:</p>\n\n<pre><code>var currentSlide = $(\".slide.current\"), \n targetSlide = currentSlide.closest(\".group\").next(\".group\").find(\".slide:first\");\nif(targetSlide.length === 0) {\n // no slides to move to!\n} else {\n currentSlide.removeClass(\"current\");\n targetSlide.addClass(\"current\");\n}\n</code></pre>\n\n<p>(With your structure you can simply use <code>.parent()</code> instead of <code>.closest(\".group\")</code>, and <code>.next()</code> without a selector, but I'm being explicit/verbose to make things clearer. Included the pointless <code>if</code>-block for the same reason; you can obviously just do a <code>!==</code> comparison instead)</p>\n\n<p>You'll note that only one line differs between the two, so it's a prime candidate for being factored into a function - or functions, plural.</p>\n\n<p>To keep things fairly abstract, I'd refer to the slide changes as simply \"next\", \"previous\", \"next group\" and \"previous group\". Only when actually adding the event handlers would I link that to an up/down/left/right direction. Again, it's better, I find, to not tie yourself to a notion of how it looks; the groups might be stacked vertically, with the slides running horizontally, but it wouldn't matter to the code above, since it's more abstract.</p>\n\n<p>In your case, the visual layout does matter in terms of animation (up/down versus left/right), but like with the event handlers, try to make such distinctions \"late\" in the code if you can.</p>\n\n<p>As for finding a slide's position, you could do something like</p>\n\n<pre><code>var currentSlide = $(\".current.slide\"),\n slideIndex = currentSlide.prevAll(\".slide\").length,\n groupIndex = currentSlide.closest(\".group\").prevAll(\".group\").length;\n</code></pre>\n\n<p>Anyway, these are just some ideas based on your chat with Tomalak and the site's HTML. There are obviously things that can be optimized (e.g. caching slide/group indices using <code>.data()</code>). Just consider it food for thought.</p>\n\n<p><a href=\"http://jsfiddle.net/V3yhy/\" rel=\"nofollow\">Here's a simple jsfiddle</a> just to demonstrate the DOM traversal stuff</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T18:15:19.777",
"Id": "59494",
"Score": "0",
"body": "Thank you, I just read this, I will make the proper changes to make the code better. Wow! the jsfiddle is awesome!!! I really want to change the code to this. I will try and post the code again. Million thanks!!!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T23:16:28.543",
"Id": "59521",
"Score": "0",
"body": "@Monica No problem, glad you found it useful. Don't forget to checkmark the answer (if everything works out, of course)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T20:42:07.903",
"Id": "35943",
"ParentId": "35925",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "35943",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T15:40:46.750",
"Id": "35925",
"Score": "4",
"Tags": [
"javascript",
"jquery"
],
"Title": "jQuery carousel code"
}
|
35925
|
<p>I thinking of a way to start a new transaction inside a single EJB bean. Typical use case would be to process every item from a list in a separate transaction.</p>
<p>One way to do it would be to use <code>UserTransaction</code>:</p>
<pre><code>@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class ManagerBean implements Manager {
@Resource
private UserTransaction tx;
@Override
public void processAll(List<Object> list) throws Exception {
for (Object obj : list) {
tx.begin();
try {
processOne(obj);
tx.commit();
} catch (Exception ex) {
tx.rollback();
}
}
}
private void processOne(Object obj) {
/* ... */
}
}
</code></pre>
<p>But I find it error prone to directly use <code>commit()</code> and <code>rollback()</code>. I'd prefer to leave transaction handing to the container. So I've come up with this pattern:</p>
<p><strong>ManagerBean.java</strong></p>
<pre><code>@Stateless
public class ManagerBean implements Manager, ManagerInternal {
@Resource
private SessionContext context;
@Override
public void processAll(List<Object> list) {
ManagerInternal txThis = context.getBusinessObject(ManagerInternal.class);
for (Object obj : list) {
txThis.processOne(obj);
}
}
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void processOne(Object obj) {
/* ... */
}
}
@Local
interface ManagerInternal {
void processOne(Object obj);
}
</code></pre>
<p><strong>Manager.java:</strong></p>
<pre><code>@Local
public interface Manager {
void processAll(List<Object> list);
}
</code></pre>
<p>Though I'm unsure if it's ok to have <em>package-private</em> local interface. It works on JBoss 4.2, but I don't know about other app servers.<br>
What do you think about this pattern?</p>
<p><strong>Alternative using self-injection:</strong></p>
<p>Instead of using <code>SessionContext.getBusinessObject(interface)</code> I suppose you can inject EJB into itself:</p>
<p><strong>ManagerBean.java</strong></p>
<pre><code>@Stateless
public class ManagerBean implements Manager, ManagerInternal {
@EJB
private ManagerInternal txThis;
@Override
public void processAll(List<Object> list) {
for (Object obj : list) {
txThis.processOne(obj);
}
}
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void processOne(Object obj) {
/* ... */
}
}
@Local
interface ManagerInternal {
void processOne(Object obj);
}
</code></pre>
<p>Manager.java stays the same.</p>
<p>EJB interfaces with <code>package</code> access seem to be not allowed by <a href="http://wildfly.org/" rel="nofollow">Wildfly</a>.</p>
|
[] |
[
{
"body": "<h1>Variable Names:</h1>\n<p>Your variable names are very generic. The <code>List<Object></code> you pass in is just called <code>list</code>. This might be fine at coding-time, but as soon as you have to analyze the code weeks or maybe even months later, you will probably wonder, what purpose that list serves.</p>\n<p>I'd thus propose you change the variable name a bit. Something like <strong>listForPersisting</strong> or something should be fine ;) The same may apply to your <code>UserTransaction</code> and the <code>SessionContext</code>, but as they are defined enough by their typename, that shouldn't be a big problem.</p>\n<h1>Spacing / Comments</h1>\n<p>I realy like your spacing. Your code is speaking enough, that you can leave out comments and still you understand it on first reading.</p>\n<p>That's very good, keep it up!</p>\n<h1>Approach</h1>\n<p>I don't think you can solve your specific problem in many other ways as elegantly as you did.</p>\n<p>What I do not like about your code is that you needlessly create the interface <code>ManagerInternal</code> as if you needed a function to override.<br />\nYou name that interface <strong>"Internal"</strong> and go through the hassle of making it @Local. But then you do something totally incomprehensive. You expose the overriden method.</p>\n<p>If you don't need the method anywhere else, the <a href=\"http://en.wikipedia.org/wiki/Information_hiding\" rel=\"nofollow noreferrer\">principle of information hiding</a> applies.</p>\n<blockquote>\n<p>In computer science, information hiding is the principle of <strong>segregation of the design decisions</strong> in a computer program that are <strong>most likely to change</strong>, thus protecting other parts of the program from extensive modification if the design decision is changed. The protection involves providing a stable interface which protects the remainder of the program from the implementation (the details that are most likely to change).</p>\n<p>Written another way, information hiding is the ability to <strong>prevent</strong> certain aspects of a class or software component <strong>from being accessible</strong> to its clients, using either programming language features (like private variables) or an explicit exporting policy.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T21:04:25.767",
"Id": "74624",
"Score": "0",
"body": "That does not solve my case. In the code you posted either all `list` elements are saved or none (on rollback). That's not what I'm trying to achieve. I'll update the question to make it clear."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T07:45:02.473",
"Id": "74686",
"Score": "0",
"body": "@rzymek Sorry for the long pipeline.. The code posted was meant as a possible alternative. It's not tested with your specific problem. As you posted your code for review, I thought you had the functionality finished. I will edit my answer to more focus on the review character."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T09:10:54.070",
"Id": "74913",
"Score": "0",
"body": "The thing with `ManagerInternal` interface is that the JavaEE container offers transaction management only when methods are called via `@Local/@Remote` interface. At least for < JavaEE6."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T09:14:34.713",
"Id": "74915",
"Score": "0",
"body": "@rzymek my problem was more, the modifier `public`... you needlessly expose a method, you only need for internal purposes, which is a possibly exploitable weakness"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T09:37:04.380",
"Id": "74919",
"Score": "0",
"body": "Unfortunately it has to be `public` because `processOne` has to be called via interface. And I can't make an interface method not public."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T17:55:16.960",
"Id": "43232",
"ParentId": "35926",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T15:44:07.197",
"Id": "35926",
"Score": "6",
"Tags": [
"java"
],
"Title": "Starting a new transaction inside a single bean"
}
|
35926
|
<p>I'm not very good with templates, so any general tips would be appreciated. </p>
<p>Basically this class parses a CSV file with a very specific format.<br>
My original idea for this was that I wanted this to be useful in MFC desktop applications and non-MFC applications such as Windows services. Basically, I wanted this class to be compatible with <code>std::string</code>, <code>CString</code>, and possibly <code>_bstr_t</code> for strings and <code>FILE</code>, <code>std::fstream</code>, maybe <code>HANDLE</code>, and <code>CStdioFile</code> for files. I have implemented the std library specializations and now, I'm not sure if implementing all the others would be a good idea.</p>
<p>Another goal by using templates was to reduce the number of header files in my header file. I'm not sure this is a good reason to use templates. </p>
<pre><code>// TrainInfo.h
#pragma once
#ifndef TRAININFO_H
#define TRAININFO_H
#include <vector>
template <typename StringType>
struct TrainInfo {
enum {
// Values omitted
NUM_ENUM
};
std::vector <StringType> m_info ;
int GetNumberOfWheels () const ;
// Minimum number of elements that should be parsed.
static int const NELEM_MIN_PARSED = TrainInfo::NUM_ENUM - 1 ;
};
template <typename StringType>
struct WheelInfo {
enum {
// Values omitted
NUM_ENUM
};
std::vector <StringType> m_info ;
// Minimum number of elements that should be parsed.
static int const NELEM_MIN_PARSED = WheelInfo::FileIndex + 1 ;
};
struct ProfilePoint {
ProfilePoint (int x = 0, int y = 0) : x (x), y (y) {}
~ProfilePoint () {}
double x ;
double y ;
};
template <typename StringType>
struct WheelProfile {
StringType m_strAxleSequenceNumber ;
StringType m_strTrainSide ;
StringType m_strNumPoints ;
std::vector <ProfilePoint> m_vecPoints ;
int GetNumberOfPoints () const ;
static const int NELEM_WHEEL_PROFILE_HEADER = 3 ;
};
template <typename StringType, typename FileType>
class CSVInfo {
public:
TrainInfo <StringType> m_trainInfo ;
std::vector <WheelInfo <StringType> > m_wheels ;
std::vector <WheelProfile <StringType> > m_profiles ;
CSVInfo () ;
~CSVInfo() ;
void Load (const StringType &strFile) ;
private:
TrainInfo <StringType> ParseTrainData (FileType &file) const ;
std::vector <WheelInfo <StringType> > ParseWheels (const int nWheels, FileType &file) const ;
std::vector <WheelProfile <StringType> > ParseWheelProfiles (const int nWheels, FileType &file) const ;
void ParseWheelProfileHeader (const StringType &strLine, WheelProfile <StringType> &wheelprofile) const ;
std::vector <ProfilePoint> ParseWheelProfile (const int nPoints, FileType &file) const ;
template <typename RetType>
RetType TokenizeLine (const StringType &strLine) const ;
template <typename RetType>
RetType TokenizeLine (const StringType &strLine, const int nMinExpected) const ;
};
template <typename ExceptionBaseClass, typename StringType>
class CSVInfoException : public ExceptionBaseClass
{
public:
CSVInfoException () : ExceptionBaseClass () {}
CSVInfoException (const StringType &strWhat) : ExceptionBaseClass (strWhat) {}
~CSVInfoException () {}
};
#endif
</code></pre>
<p>Here are the specializations I have so far. </p>
<pre><code>// TrainInfo.cpp
#include "StdAfx.h"
#include "TrainInfo.h"
#include "My_Exception.h"
#ifndef TSTRING_TYPEDEF
#define TSTRING_TYPEDEF
#include <tchar.h>
#include <string>
typedef std::basic_string <TCHAR> tstring ;
#endif
#ifndef TSSTREAM_TYPEDEF
#define TSSTREAM_TYPEDEF
#include <sstream>
typedef std::basic_stringstream <TCHAR> tsstream ;
#endif
#ifndef TIFSTREAM_TYPEDEF
#define TIFSTREAM_TYPEDEF
#include <fstream>
typedef std::basic_ifstream <TCHAR> tifstream ;
#endif
#ifndef VECTSTRING_TYPEDEF
#define VECTSTRING_TYPEDEF
typedef std::vector <tstring> VecTString ;
#endif
#ifndef MyCSVEXCEPTION_TYPEDEF
#define MyCSVEXCEPTION_TYPEDEF
typedef CSVInfoException <MyLib::MyException, tstring> MyCSVInfoException ;
#endif
static void SanityCheckString (const tstring &str, const tstring &strExpected) ;
static void ThrowErrorParsingSection (const tstring &strSection, const tstring &strLastLineParsed) ;
static void ThrowUnexpectedTokenCount (const int nTokens, const int nTokensExpected,
const tstring &strLine) ;
template <>
CSVInfo <tstring, tifstream>::CSVInfo ()
{
}
template <>
CSVInfo <tstring, tifstream>::~CSVInfo ()
{
}
template <>
void CSVInfo <tstring, tifstream>::
Load (const tstring &strFile)
{
tifstream file ;
file.exceptions (tifstream::badbit | tifstream::failbit) ;
try {
file.open (strFile.data ()) ;
// Parse train info
m_trainInfo = this->ParseTrainData (file) ;
// For all wheels, parse Wheel Info
int nWheels = m_trainInfo.GetNumberOfWheels () ;
if (nWheels < 1) {
throw MyCSVInfoException (_T ("Wheel data is missing.")) ;
}
m_wheels = this->ParseWheels (nWheels, file) ;
// Parse wheel profiles
m_profiles = this->ParseWheelProfiles (nWheels, file) ;
}
catch (std::ios_base::failure) {
tsstream tss ;
tss << _T ("An I/O error occurred. Please verify the file: ")
<< strFile << _T (".\r\nLast error code: ") << ::GetLastError () << _T (".") ;
throw MyCSVInfoException (tss.str ()) ;
}
catch (MyCSVInfoException &e) {
tsstream tss ;
tss << _T ("An error occurred for file: ") << strFile << _T (".") ;
e.AddDetail (tss.str ()) ;
throw ;
}
}
template <> template <>
ProfilePoint CSVInfo <tstring, tifstream>::
TokenizeLine <ProfilePoint> (const tstring &strLine) const
{
ProfilePoint point ;
TCHAR comma = _T (',') ;
tsstream tss ;
tss.exceptions (tsstream::failbit | tsstream::badbit) ;
try {
tss << strLine ;
tss >> point.x ;
tss >> comma ;
tss >> point.y ;
}
catch (std::ios_base::failure) {
tsstream tssErr ;
tssErr << _T ("Failed to tokenize profile point: ") << strLine << _T (".") ;
throw MyCSVInfoException (tssErr.str ()) ;
}
return point ;
}
template <> template <>
VecTString CSVInfo <tstring, tifstream>::
TokenizeLine <VecTString> (const tstring &strLine) const
{
tsstream tss (strLine) ;
VecTString vecData ;
tstring strCell ;
while (std::getline (tss, strCell, _T (','))) {
vecData.push_back (strCell) ;
}
return vecData ;
}
template <> template <>
VecTString CSVInfo <tstring, tifstream>::
TokenizeLine (const tstring &strLine, const int nMinExpected) const
{
VecTString vecData = this->TokenizeLine <VecTString> (strLine) ;
if (vecData.size () < (VecTString::size_type) nMinExpected) {
ThrowUnexpectedTokenCount (vecData.size (), nMinExpected, strLine) ;
}
return vecData ;
}
template <>
TrainInfo <tstring> CSVInfo <tstring, tifstream>::
ParseTrainData (tifstream &file) const
{
tstring strLine ;
TrainInfo <tstring> traininfo ;
try {
// Skip line Section Train
std::getline (file, strLine) ;
SanityCheckString (strLine, _T ("Section Train")) ; // Sanity check all sections.
// Skip line Train Columns
std::getline (file, strLine) ;
// Parse Train Info
std::getline (file, strLine) ;
traininfo.m_info = this->TokenizeLine <VecTString> (strLine, TrainInfo <tstring>::NELEM_MIN_PARSED) ;
}
catch (std::ios_base::failure) {
ThrowErrorParsingSection (_T ("Section Train"), strLine) ;
}
return traininfo ;
}
template <>
std::vector <WheelInfo <tstring> > CSVInfo <tstring, tifstream>::
ParseWheels (const int nWheels, tifstream &file) const
{
tstring strLine ;
std::vector <WheelInfo <tstring> > vecWheels ;
try {
// Skip line Section Wheel
std::getline (file, strLine) ;
SanityCheckString (strLine, _T ("Section Wheel")) ; // Sanity check all sections.
// Skip line Wheel Columns
std::getline (file, strLine) ;
// Parse all wheels
for (int n = 0; n < nWheels; ++n) {
std::getline (file, strLine) ;
WheelInfo <tstring> wheel ;
wheel.m_info = this->TokenizeLine <VecTString> (strLine, WheelInfo <tstring>::NELEM_MIN_PARSED) ;
vecWheels.push_back (wheel) ;
}
}
catch (std::ios_base::failure) {
ThrowErrorParsingSection (_T ("Section Wheel"), strLine) ;
}
return vecWheels ;
}
template <>
std::vector <WheelProfile <tstring> > CSVInfo <tstring, tifstream>::
ParseWheelProfiles (const int nWheels, tifstream &file) const
{
tstring strLine ;
std::vector <WheelProfile <tstring> > vecProfiles ;
try {
// Skip line Section Wheel Profiles
std::getline (file, strLine) ;
SanityCheckString (strLine, _T ("Section Wheel Profiles")) ;
for (int n = 0; n < nWheels; ++n) {
// Skip Header AxleSequenceNumber,TrainSide,NumberOfProfilePoints
std::getline (file, strLine) ;
// Parse header information.
std::getline (file, strLine) ;
WheelProfile <tstring> wheelProfile ;
this->ParseWheelProfileHeader (strLine, wheelProfile) ;
// Skip Header X,Y
std::getline (file, strLine) ;
int nPoints = wheelProfile.GetNumberOfPoints () ;
wheelProfile.m_vecPoints = this->ParseWheelProfile (nPoints, file) ;
vecProfiles.push_back (wheelProfile) ;
}
}
catch (std::ios_base::failure) {
ThrowErrorParsingSection (_T ("Section Wheel Profiles"), strLine) ;
}
return vecProfiles ;
}
template <>
void CSVInfo <tstring, tifstream>::
ParseWheelProfileHeader (const tstring &strLine, WheelProfile <tstring> &wheelprofile) const
{
VecTString vecData = this->TokenizeLine <VecTString> (strLine, WheelProfile <tstring>::NELEM_WHEEL_PROFILE_HEADER) ;
wheelprofile.m_strAxleSequenceNumber = vecData [0] ;
wheelprofile.m_strTrainSide = vecData [1] ;
wheelprofile.m_strNumPoints = vecData [2] ;
}
template <>
std::vector <ProfilePoint> CSVInfo <tstring, tifstream>::
ParseWheelProfile (const int nPoints, tifstream &file) const
{
std::vector <ProfilePoint> vecPoints ;
for (int n = 0; n < nPoints; ++n) {
tstring strLine ;
// Parse X,Y
std::getline (file, strLine) ;
ProfilePoint point = this->TokenizeLine <ProfilePoint> (strLine) ;
vecPoints.push_back (point) ;
}
return vecPoints ;
}
template <>
int TrainInfo <tstring>::GetNumberOfWheels (void) const
{
int nWheels = 0 ;
const tstring &strAxleCount = m_info [TrainInfo::NumberOfAxles] ;
tsstream tss (strAxleCount) ;
tss.exceptions (tsstream::failbit | tsstream::badbit) ;
try {
tss >> nWheels ;
nWheels *= 2 ;
}
catch (std::ios_base::failure) {
tsstream tssErr ;
tssErr << _T ("Failed to parse number of axles from value: ") << strAxleCount << _T (".") ;
throw MyCSVInfoException (tssErr.str ()) ;
}
return nWheels ;
}
template <>
int WheelProfile <tstring>::GetNumberOfPoints (void) const
{
int nPoints = 0 ;
tsstream tss (m_strNumPoints) ;
tss.exceptions (tsstream::failbit | tsstream::badbit) ;
try {
tss >> nPoints ;
}
catch (std::ios_base::failure) {
tsstream tssErr ;
tssErr << _T ("Failed to parse number of points from value: ") << m_strNumPoints << _T (".") ;
throw MyCSVInfoException (tssErr.str ()) ;
}
return nPoints ;
}
//////////////////////
// Static Functions //
//////////////////////
static void SanityCheckString (const tstring &str, const tstring &strExpected)
{
if (str != strExpected) {
tsstream tss ;
tss << _T ("A sanity check on a string has failed.") _T ("\r\nExpected string: ") << strExpected
<< _T ("\r\nActual string: ") << str ;
throw MyCSVInfoException (tss.str ()) ;
}
}
static void ThrowErrorParsingSection (const tstring &strSection, const tstring &strLastLineParsed)
{
tsstream tss ;
tss << _T ("An I/O error occurred while parsing: ") << strSection << _T (". ")
<< _T ("Last line parsed: ") << strLastLineParsed ;
throw MyCSVInfoException (tss.str ()) ;
}
static void ThrowUnexpectedTokenCount (const int nTokens, const int nTokensExpected,
const tstring &strLine)
{
tsstream tss ;
tss << _T ("Parsed incorrect number of tokens. Number of tokens: ")
<< nTokens << _T (", number expected: ")
<< nTokensExpected << _T (". Line: ") << strLine ;
throw MyCSVInfoException (tss.str ()) ;
}
</code></pre>
<p>Now some questions,</p>
<ol>
<li>I am starting to think I should just stick with the standard library and not finish the specializations for MFC and Windows. Would it be better to leave the class as it is, or throw all the template stuff out? </li>
<li>If I decide to continue implementing the specializations, I assume I would put each specialization into its own <code>.cpp</code> file to keep the headers separated. In this case though, I would have to distribute many different <code>.cpp</code> files along with my header. This seems like a bad smell. What is the preferred way of handling this? </li>
<li>As I stated earlier, one of the reasons I wanted to use templates was to remove header files from my own header file. Now I'm not sure that was a good idea. Is it a common or bad practice to use templates to avoid having headers files in your header file?</li>
<li>Are there any other design flaws or issues that I should be worried about? </li>
</ol>
|
[] |
[
{
"body": "<p>I've long since wanted to explore doing this sort of thing myself. In different code bases, different string classes are so much more prevalent, and thus more appropriate to keep using. Your approach isn't quite the right way to go, as it scales on the wrong axis. I can totally see removing the templates and using just a single <code>tstring</code> (or even <code>wstring</code>), and realistically I would probably go that way. There are just so many downsides to using templates for large swaths of functionality (like how much typically needs to be moved to the headers). But if you want to keep the string type flexibility, a better approach would be to use traits classes.</p>\n\n<p>Traits classes help reduce coupling. With a traits class approach, you don't need to specialize your class methods for what changes. Instead you specialize what needs to change for how you use it. Create and specialize traits helper methods for each operation you need on a string. The payoff comes in your next method or next class that only uses functionality you've already put on the traits class. The only hard part is figuring out what to make your traits calls look like.</p>\n\n<p>Here's a simplified beginning to traits class following <code>std::string</code> and <code>std::stringstream</code>'s semantics. I hope it's easy to follow how this changes which way your code has to scale. I'm far from certain it's doing things \"correctly\", as MSVC's <code>traits_type</code> implementations on <code>basic_string</code> and friends look very different. (I'm still wrapping my head around how to use traits classes.)</p>\n\n<pre><code>template <typename StringType>\nstruct StreamTraits\n{\n typedef std::basic_stringstream<\n typename StringType::value_type,\n typename StringType::traits_type\n > value_type;\n};\n\n// Later to handle non basic_stringstream cases, use specialization\n// template <>\n// struct StreamTraits<CString>\n// {\n// typedef CStringStream value_type;\n// };\n\ntemplate <typename StringType>\nstruct StringTraits\n{\n typedef StringType value_type;\n typedef typename StreamTraits<StringType>::value_type stream_type;\n};\n\n// Use traits to insulate callers from need to specialize\ntemplate <typename StringType>\nstruct TrainInfo\n{\n typedef StringTraits<StringType> StringTraits;\n typedef typename StringTraits::value_type String;\n typedef StreamTraits<StringType> StreamTraits;\n typedef typename StreamTraits::value_type Stream;\n\n int GetNumberOfWheels() const;\n};\n\ntemplate <typename StringType>\nint TrainInfo<StringType>::GetNumberOfWheels() const\n{\n int nWheels = 0;\n const String& strAxleCount = \"2\";\n Stream s(strAxleCount);\n // the following should probably be encapsulated in a StreamTraits helper method\n s.exceptions(Stream::failbit | Stream::badbit);\n\n s >> nWheels;\n return nWheels * 2;\n}\n</code></pre>\n\n<p>Note that none of this solves the points your raise. At best it helps focus the headers, as you could have a header with all your string-specific specializations. This header could then be used by your train classes, or by any other class with similar needs. Users of your train classes that need a string type you didn't plan for should be able to provide traits class specializations and then use their own string class.</p>\n\n<p>But it's still a lot of programming and maintenance overhead, so I would avoid it unless you know you need it. I certainly wouldn't do it just to cut down on the number of headers I was including.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T16:14:59.087",
"Id": "58907",
"Score": "0",
"body": "+1 For \"as it scales on the wrong axis\". This was what I was unsure how to solve. As evil as this sounds, throwing all the work onto other users is what I wanted to do so that I do not have to continuously change this interface. In most cases, I will be the \"other users\" just in different programs that may use different APIs. Realistically though, as you said, I'm probably better off throwing out the templates and just using tstring (I have to support ASCII and UTF-16, so I can't just stick to wstring)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T16:30:58.957",
"Id": "58909",
"Score": "0",
"body": "@jliv902 The result of putting work in the right place is that he who needs the functionality can be the one to implement it. That's not evil; that's practical. :) As for wstring vs ASCII, note that `tstring` is only one, and chosen at compile time (not file read time). You'd be better off consistently converting to Unicode on file read, only having a Unicode internal interface, and convert back at some future file write."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T04:08:34.040",
"Id": "35963",
"ParentId": "35931",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "35963",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T16:07:31.897",
"Id": "35931",
"Score": "8",
"Tags": [
"c++",
"parsing",
"csv",
"template"
],
"Title": "Parsing a CSV file with a very specific format"
}
|
35931
|
<p>I am using <a href="https://stackoverflow.com/questions/12260493/how-to-connect-to-ms-sql-server-using-innosetup">this code</a> to run my sql scripts in inno setup. However ADO gives an error if the script contains GO syntax within it. I added my own code to overcome this problem.</p>
<p>My code below splits the script at each GO statement and run each section separately. I think this could be done in better ways. </p>
<pre><code>[code]
const
adCmdText = $00000001;
adExecuteNoRecords = $00000080;
procedure RunScript();
var
tString: TStringList;
ADOCommand: Variant;
ADORecordset: Variant;
ADOConnection: Variant;
i, len: Integer;
strToQuery, str: String;
begin
try
ADOConnection := CreateOleObject('ADODB.Connection');
ADOConnection.ConnectionString :=
'Provider=SQLOLEDB;' + // provider
'Data Source=(local)\SQL2000;' + // server name
'Initial Catalog=databasename;' + // default database
'User Id=userId;' + // user name
'Password=password;'; // password
ADOConnection.Open;
try
ADOCommand := CreateOleObject('ADODB.Command');
ADOCommand.ActiveConnection := ADOConnection;
tString:= TStringList.Create;
tString.LoadFromFile('C:\sqlscript.sql');
len:= tString.Count;
strToQuery:='';
for i:=0 to len-1 do begin
str := trim(tString[i]);
if POS('go', lowercase(str)) = 1 then begin
//If GO is found run the script added in to strToQuery since last GO
ADOCommand.CommandText := strToQuery;
ADOCommand.Execute(NULL, NULL, adCmdText or adExecuteNoRecords);
strToQuery:=''; //Clear the string to start adding till next GO
end else strToQuery:= strToQuery +#13#10+ str; //Add the script to strToQuery
end;
ADOCommand.CommandText := strToQuery;
ADOCommand.Execute(NULL, NULL, adCmdText or adExecuteNoRecords);
finally
ADOConnection.Close;
tString.Free;
end;
except
MsgBox(GetExceptionMessage, mbError, MB_OK);
end;
end;
</code></pre>
<p>Any suggestion to update the code will be much appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T17:28:27.880",
"Id": "58625",
"Score": "0",
"body": "what language is this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T17:29:36.753",
"Id": "58627",
"Score": "0",
"body": "@Malachi, it's Pascal Script from [`Inno Setup`](http://jrsoftware.org/isinfo.php)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T17:33:03.340",
"Id": "58629",
"Score": "0",
"body": "I wish there was a better tag that we could put on this question. @TLama, should it have an SQL tag?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T17:37:17.740",
"Id": "58631",
"Score": "1",
"body": "@Malachi, I would keep it as it is. Although it's about parsing SQL script, it's related more to that Pascal Script than SQL language itself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T17:39:05.010",
"Id": "58633",
"Score": "1",
"body": "@TLama, I agree. I had to create that pascal-script tag. maybe it will take off and people will be using it a lot, and this question will get the attention it deserves"
}
] |
[
{
"body": "<p><em><strong>1. Function block</em></strong></p>\n\n<p>Standalone action like loading a script from file and splitting it into SQL commands by the <code>GO</code> command, I would move into a separate function. That function might have the following prototype:</p>\n\n<pre><code>function LoadScriptFromFile(const FileName: string; out CommandList: TStrings): Integer;\nbegin\n\nend;\n</code></pre>\n\n<p>Having such function will isolate parsing and execution parts of the script. You would first load the script from a file and then in the other part of the script iterate the parsed commands and execute each one.</p>\n\n<p><em><strong>2. Object finalization</em></strong></p>\n\n<p>Always try to encose object finalization into a separate <code>try..finally</code> block. In your code it applies to the <code>tString</code> object. This part:</p>\n\n<pre><code>ADOConnection.Open;\ntry\n tString := TStringList.Create;\n ...\nfinally\n ADOConnection.Close;\n tString.Free;\nend;\n</code></pre>\n\n<p>Should become:</p>\n\n<pre><code>ADOConnection.Open;\ntry\n tString := TStringList.Create;\n try\n ...\n finally\n tString.Free;\n end;\nfinally\n ADOConnection.Close;\nend;\n</code></pre>\n\n<p><em><strong>3. Useless variable</em></strong></p>\n\n<p>The <code>len</code> variable is used for only one purpose and its value is used only once, so it's actually useless there. I would remove it and write directly:</p>\n\n<pre><code>for i := 0 to tString.Count - 1 do\nbegin\n ...\nend;\n</code></pre>\n\n<p><em><strong>4. Summary</em></strong></p>\n\n<p>Except the above (not so major) things I would say your code is fine. The string concatenation with line breaks you have used should be fine for ADO connected to the SQL Server, I think.</p>\n\n<p>For the sake of completness, here is what I'd write (untested!). <strike>Please note, that every SQL command is expected to be \"terminated\" by the <code>GO</code> command in the input file (that requires also your original code)</strike>:</p>\n\n<pre><code>function LoadScriptFromFile(const FileName: string; out CommandList: TStrings): Integer;\nvar\n I: Integer;\n SQLCommand: string;\n ScriptFile: TStringList;\nbegin\n Result := 0;\n ScriptFile := TStringList.Create;\n try\n SQLCommand := '';\n ScriptFile.LoadFromFile(FileName);\n\n for I := 0 to ScriptFile.Count - 1 do\n begin\n if Pos('go', LowerCase(Trim(ScriptFile[I]))) = 1 then\n begin\n Result := Result + 1;\n CommandList.Add(SQLCommand);\n SQLCommand := '';\n end\n else\n SQLCommand := SQLCommand + ScriptFile[I] + #13#10;\n end;\n\n //EDIT: If there is no GO syntax present int the file AND\n //To add the script after the last GO - Govs\n CommandList.Add(SQLCommand);\n Result:= Result + 1;\n finally\n ScriptFile.Free;\n end;\nend;\n\nprocedure RunScript(const FileName: string);\nvar\n I: Integer;\n CommandList: TStrings;\n ...\nbegin\n ...\n // here is already established connection\n CommandList := TStringList.Create;\n try\n if LoadScriptFromFile(FileName, CommandList) > 0 then\n for I := 0 to CommandList.Count - 1 do\n begin\n // execute each command\n ADOCommand.CommandText := CommandList[I];\n ADOCommand.Execute(NULL, NULL, adCmdText or adExecuteNoRecords);\n end;\n finally\n CommandList.Free;\n end;\n ...\nend;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T09:49:43.850",
"Id": "58876",
"Score": "0",
"body": "I guess Inc() function is not supported in Inno."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T10:00:47.227",
"Id": "58880",
"Score": "0",
"body": "Sorry for that. I didn't even tried to compile my version (hence my note \"untested\"). I just wanted to show you my thoughts ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T10:22:03.730",
"Id": "58882",
"Score": "1",
"body": "Yes I understand. Just for reference if any body want to use the code. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T10:30:13.313",
"Id": "58884",
"Score": "0",
"body": "Updated the function LoadScriptFromFile(). The script after last GO was not getting added. Also it will work if the script does not contain any GO syntax."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T10:32:44.380",
"Id": "58886",
"Score": "0",
"body": "Updated your update... I've mentioned that each command must have been terminated by `GO`, which no longer applies with your update."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-10T17:27:21.773",
"Id": "93810",
"Score": "1",
"body": "@TLama Your input would be appreciated on [this meta question](http://meta.codereview.stackexchange.com/questions/1944/pascal-delphi-pascal-script-tags) regarding the Pascal/Pascal-Script/Delphi tags we have here on Code Review."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T23:12:10.263",
"Id": "35948",
"ParentId": "35934",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "35948",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T16:50:18.240",
"Id": "35934",
"Score": "3",
"Tags": [
"pascal-script"
],
"Title": "Using ADO to run sql script (with GO syntax) in inno setup"
}
|
35934
|
Pascal Script is a free scripting engine that allows you to use most of the Object Pascal language within your Delphi or Free Pascal projects at runtime. Written completely in Delphi, it is composed of a set of units that can be compiled into your executable, eliminating the need to distribute any external files.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T17:32:08.163",
"Id": "35936",
"Score": "0",
"Tags": null,
"Title": null
}
|
35936
|
<p>I am looking for tips on improving my short program. I am using <code>system("PAUSE")</code> because this was for an assignment. </p>
<p><img src="https://i.stack.imgur.com/AfMgr.png" alt="enter image description here"></p>
<p>Code:</p>
<pre><code>#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
void Display(string* , int* , double*, int);
void Percentage(int*, double*, int);
void Intro(string*, int*, int&);
void Highest(int&, string&, double*, string*, int);
int main()
{
int students;
string names[10];
int hours[10];
double percents[10];
int highest;
string most;
Intro(names, hours, students);
Percentage(hours, percents, students);
Display(names, hours, percents, students);
Highest(highest, most, percents, names, students);
system("PAUSE");
}
void Intro(string* names, int* hours, int& students)
{
int team;
cout << "A team is made up of atleast 2 students. How many students are on the team?: ";
cin >> team;
cout << "Enter student's first name and the hours worked on the final project: " << endl;
for (int i = 0; i < team; i++)
{
cout << i + 1 << ": ";
cin >> names[i] >> hours[i];
}
students = team;
}
void Display(string* names, int* hours, double* percent, int students)
{
cout << setw(20) << "Students";
cout << setw(20) << "Hours Worked";
cout << setw(20) << "% of Total Hours";
cout << endl;
cout << "------------------------------------------------------------" << endl;
for (int i = 0; i < students; i++)
{
cout << setw(20) << names[i];
cout << setw(9) << hours[i];
cout << setw(16) << percent[i];
cout << endl;
}
}
void Percentage(int* hours, double* percent, int students)
{
int total(0);
for (int i = 0; i < students; i++)
{
total += hours[i];
}
for (int i = 0; i < students; i++)
{
percent[i] = double(hours[i]) / total * 100;
}
}
void Highest(int& highest, string& most, double* percent, string* names, int students)
{
highest = percent[0];
for (int i = 0; i < students; i++)
{
if (highest < percent[i])
{
highest = percent[i];
most = names[i];
}
}
cout << most << " worked the most hours." << endl;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T19:27:58.087",
"Id": "58644",
"Score": "4",
"body": "You can also use `getchar()`..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T23:19:59.390",
"Id": "58656",
"Score": "0",
"body": "@tintinmj: `std::cin.get()` would be preferred for C++. It also goes with `<iostream>`, whereas `getchar()` goes with `<cstdio>`/`<stdio.h>`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T00:46:58.357",
"Id": "58658",
"Score": "0",
"body": "Your \"% of Total Hours\" column doesn't line up with its header. Should be a simple enough thing to do properly, and it just looks sloppy if you don't."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T00:48:58.317",
"Id": "58659",
"Score": "0",
"body": "I realized, this was because I added an extra symbol last minute."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T08:13:36.003",
"Id": "58683",
"Score": "0",
"body": "@Jamal yeah right... I overlooked the `C++` tag!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T08:19:21.167",
"Id": "58684",
"Score": "0",
"body": "@tintinmj: You were still on the right track (hence the votes). :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T21:31:07.207",
"Id": "58804",
"Score": "0",
"body": "@Justin have you really to stick to arrays in this homework?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T21:40:41.867",
"Id": "58808",
"Score": "0",
"body": "@Wolf Yes. It was part of the assignment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T21:46:01.677",
"Id": "58811",
"Score": "0",
"body": "What a pity! Were at least structs allowed? If yes, then the `struct Student` idea will also help a lot."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T22:13:13.590",
"Id": "58813",
"Score": "0",
"body": "Nope, the class hasn't been \"taught\" struct and classes yet. I would use them, but I don't want to get marked off."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T00:59:19.923",
"Id": "58822",
"Score": "0",
"body": "@Wolf: This is why I tread carefully with homework questions (I've only made references to vectors in my answer). The OP can always go back and improve on them later, but we should also not provide too much information since this is for a grade. Either way, it's important to keep in mind that even homework questions should be beneficial to site visitors (otherwise they may be considered too localized)."
}
] |
[
{
"body": "<ul>\n<li><p>I assume you'll have no more than 10 names/hours/percents, but you could use an <a href=\"http://en.cppreference.com/w/cpp/container/vector\"><code>std::vector</code></a> in place of these arrays. This will allow you any number of inputs without fear of exceeding the allotted 10. If you don't need this for your assignment, then you can stick with what you have.</p></li>\n<li><p>If you're allowed to use more of the STL, I'd recommend <a href=\"http://en.cppreference.com/w/cpp/algorithm/accumulate\"><code>std::accumulate</code></a> for summing up the values in a container.</p>\n\n<p>For instance, your first loop in <code>Percentage()</code>:</p>\n\n<pre><code>for (int i = 0; i < students; i++)\n{\n total += hours[i];\n}\n</code></pre>\n\n<p>can be done with this function as such (with the array):</p>\n\n<pre><code>// the 10 corresponds to the array size\n// the 0 is the starting value of the accumulator\n\nint total = std::accumulate(hours, hours+10, 0);\n</code></pre>\n\n<p>If you choose to use <code>std::vector</code> (or other STL container):</p>\n\n<pre><code>// functions cbegin() and cend() return const iterators\n\nint total = std::accumulate(hours.cbegin(), hours.cend(), 0);\n</code></pre></li>\n<li><p>I'd slightly tweak the percentage calculation for clarity:</p>\n\n<pre><code>percent[i] = (double(hours[i]) / total) * 100;\n</code></pre></li>\n<li><p>Prefer to cast the C++ way:</p>\n\n<pre><code>// C way\ndouble(hours[i])\n</code></pre>\n\n<p></p>\n\n<pre><code>// C++ way\nstatic_cast<double>(hours[i])\n</code></pre></li>\n<li><p>It seems a little weird having <code>Highest()</code> display something. You could instead return <code>most</code>, thereby making the function of type <code>std::string</code>. That way, you can display this name from <code>main()</code> or wherever else.</p>\n\n<p>You don't need the first two arguments. They are passed in from <code>main()</code>, but also not modified by any previous functions. I'd remove those two and just use local variables.</p>\n\n<p><code>highest</code> should be of type <code>double</code> since it's being assigned to a <code>percent</code> element. Otherwise, you may receive a \"possible loss of data\" warning. This is especially important for when the two values are being compared in the loop.</p>\n\n<p>You could then have this:</p>\n\n<pre><code>// get the name\nstd::string most = Highest(percents, names, students);\n\n// display it\nstd::cout << most << \" worked the most hours.\" << std::endl;\n</code></pre>\n\n<p></p>\n\n<pre><code>std::string Highest(double* percent, string* names, int students)\n{\n double highest = percent[0];\n std::string most;\n\n for (int i = 0; i < students; i++)\n {\n if (highest < percent[i])\n {\n highest = percent[i];\n most = names[i];\n }\n }\n\n return most;\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T21:23:26.337",
"Id": "58801",
"Score": "0",
"body": "@Jamal I would consider your `percent[0]` dereferencing before the loop a little dangerous. Even if the homework states that at least 2 students form a team, I would not trust in this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T21:28:32.303",
"Id": "58803",
"Score": "0",
"body": "@Wolf: This is what the OP has in the code, minus the numerical types. That apecific part I didn't look at closely. I suppose this means that the entire program should use vectors instead of C-style arrays."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T21:38:44.983",
"Id": "58807",
"Score": "0",
"body": "Yes, nobody can learn all at one time. And the OP obviously didn't ask for a vector tutorial."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T21:45:26.790",
"Id": "58809",
"Score": "0",
"body": "@Wolf: Right, but it could still help to mention it, even if it cannot be used in this assignment. Heck, I'm not opposed to going back to old assignments and improving on them. Many can make great references!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T20:59:29.083",
"Id": "35945",
"ParentId": "35941",
"Score": "10"
}
},
{
"body": "<p>To add to what <a href=\"https://codereview.stackexchange.com/a/35945/31651\">Jamal is saying</a>. If you are allowed to used basic structs, you could do something like this:</p>\n\n<pre><code>struct Student\n{\n std::string name ;\n int hours ;\n};\n\nstatic void Intro (std::vector <Student> &students) ;\nstatic void Display (const std::vector <Student> &students) ;\n// ... \n</code></pre>\n\n<p>This way, you don't have to manage parallel arrays.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T21:27:21.927",
"Id": "58651",
"Score": "1",
"body": "D'oh! I forgot all about `struct`s. I was merely going by the OP's solution, but this could also work. +1 from me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T02:36:20.330",
"Id": "58666",
"Score": "1",
"body": "And then there are more good options like giving that struct an `operator>>` or similar helper method..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T20:23:50.440",
"Id": "58798",
"Score": "0",
"body": "Great answer (from the *code review* POV). I think, you agree in this, that the percentage shouldn't be stored along the real input, which is name and hours?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T17:10:54.210",
"Id": "58921",
"Score": "0",
"body": "@Wolf, Yeah I agree. Percentage information would be redundant. A function should be used to calculate that information."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T21:16:25.290",
"Id": "35946",
"ParentId": "35941",
"Score": "10"
}
},
{
"body": "<p>Again, in addition to <a href=\"https://codereview.stackexchange.com/a/35946/31651\">jliv902's addition</a> - and since we are here for code review - I think the <code>Highest</code> function needs only names and hours (and therefore <code>std::vector<Student></code> which I shorten as <code>Students</code> via <code>typedef</code>):</p>\n\n<pre><code>typedef std::vector<Student> Students;\n\nstd::string Highest(const Students& students)\n{\n int highest = 0;\n std::string most = \"nobody\";\n\n for (Students::const_iterator i=students.begin(); i!=students.end(); ++i) {\n if (highest < (*i).hours) {\n highest = (*i).hours;\n most = (*i).name;\n }\n }\n return most;\n}\n</code></pre>\n\n<p>So also <code>percents</code> are for output only and need not to be stored along with the real input. As a pragmatic introduction to <code>std::vector</code>, the according <code>Intro</code> function will do best:</p>\n\n<pre><code>void Intro(Students& students)\n{\n int teamSize = 0;\n cout << \"A team is made up of atleast 2 students. How many students are on the team?: \";\n cin >> teamSize;\n\n cout << \"Enter student's first name and the hours worked on the final project: \" << endl;\n\n for (int i = 0; i < teamSize; i++) {\n cout << i + 1 << \": \";\n Student s;\n cin >> s.name >> s.hours;\n students.push_back(s);\n }\n}\n</code></pre>\n\n<p><strong>BTW:</strong> Would you be satisfied with a solution, where two or more students <strong>share the first place in hours</strong> but only one of them is put out as the top worker?</p>\n\n<p><strong>EDIT</strong>: this simple approach allows for a list of top workers instead of single one:</p>\n\n<pre><code>typedef std::list<std::string> Names;\n\n/// output the name(s) of the student(s) that have worked the most hours\nNames HighestList(const Students& students)\n{\n int highest = 0;\n Names result;\n\n for (Students::const_iterator i=students.begin(); i!=students.end(); ++i) {\n if (highest < i->hours) {\n highest = i->hours;\n result.clear();\n result.push_back(i->name);\n } else if (highest == i->hours) {\n result.push_back(i->name);\n }\n }\n return result;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T21:22:43.733",
"Id": "58800",
"Score": "1",
"body": "`Highest()`'s parameter should also be `const` (and the iterators could also be `.cbegin()` and `.cend()`). It would also be more readable to use `i->hours` instead of `(*i).hours)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T21:24:34.390",
"Id": "58802",
"Score": "0",
"body": "@Jamal Thanks for the hint, I'll update this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T21:31:59.393",
"Id": "58805",
"Score": "0",
"body": "I've also never considered initializing `most` with \"nobody\", which seems pretty obvious now. Can't possibly identify every little point, though. ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T21:34:57.977",
"Id": "58806",
"Score": "0",
"body": "@Jamal Oh, good point, I only forgot to remove this assignment I casually added. ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T17:25:09.153",
"Id": "58925",
"Score": "1",
"body": "For `Highest()`, using `std::max_element` from `algorithm.h` would be better than rolling your own loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T21:17:39.100",
"Id": "58943",
"Score": "0",
"body": "@jliv902 good idea, indeed. What about adding your own appendix? I'll better not to incorporate this suggestion, because it cannot handle the problem with the shared top rank."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T21:18:46.750",
"Id": "36016",
"ParentId": "35941",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35945",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T19:19:43.097",
"Id": "35941",
"Score": "6",
"Tags": [
"c++",
"homework"
],
"Title": "Hour averaging program"
}
|
35941
|
<p>I have a method that generates a 10 digit random number where each digit occurs only once.</p>
<p>eg:</p>
<pre><code>0123456789
3645720918
</code></pre>
<p>Is there any way this method could be optimized/improved?</p>
<pre><code> private static String randomize(){
Random r = new Random();
List<Integer> digits= new ArrayList<Integer>();
String number = "";
for (int i = 0; i < 10; i++) {
digits.add(i);
}
for (int i = 10; i > 0; i--) {
int randomDigit = r.nextInt(i);
number+=digits.get(randomDigit);
digits.remove(randomDigit);
}
return number;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T05:54:08.483",
"Id": "58678",
"Score": "0",
"body": "If performance is truly a concern, you can actually do this with a single call to `Random.nextInt()`. [Example](http://stackoverflow.com/questions/7918806)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T07:54:32.527",
"Id": "58681",
"Score": "0",
"body": "@BlueRaja-DannyPflughoeft: Hm, that seems to be an `O(n^2)` algorithm. Not too sure if that would really be that much faster (might be for small `n` like 10 though)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T16:40:11.927",
"Id": "58695",
"Score": "1",
"body": "@ChrisWue: Maybe I should have actually looked at the implementations there. This problem can easily be done in `O(n)`, assuming `Random.nextInt()` returns a number larger than `n!`, with only a single call to `Random.nextInt()`. I'm very surprised none of the answers below point that fact out. See [here](http://math.stackexchange.com/questions/223878)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T15:28:11.343",
"Id": "58779",
"Score": "1",
"body": "public int getRandomNumber() { return 4829537106; } http://xkcd.com/221/"
}
] |
[
{
"body": "<p>Short answer: Speed optimized? Perhaps. Memory optimized? Not that I am aware of. Improved flexibility? Yes.</p>\n\n<ul>\n<li>The number <code>10</code> is a <strong>magic number</strong> in your code. If you change it on one place, you need to change it everywhere else. This number should be put in a variable and could on some places be replaced with <code>digits.size()</code></li>\n<li>You could extract some methods, one method for creating the <code>List</code> and one method for handling the list.</li>\n<li>On the method for handling the list, you can use generics (<code><T></code> in the code below) to support any kind of list.</li>\n<li>Use <code>StringBuilder</code> to create the string result.</li>\n</ul>\n\n<p>The resulting code:</p>\n\n<pre><code>private static List<Integer> createList(int size) {\n // We are friendly towards Java and declare the *capacity* of the list here\n // because we know already how many items it should contain.\n List<Integer> result = new ArrayList<Integer>(size);\n for (int i = 0; i < size; i++) {\n result.add(i);\n }\n}\nprivate static String randomize() {\n int count = 10;\n List<Integer> digits = createList(count);\n return randomizedStringOrder(digits);\n}\nprivate static <T> String randomizedStringOrder(List<T> list) {\n Random random = new Random();\n StringBuilder result = new StringBuilder();\n for (int i = list.size(); i > 0; i--) {\n int randomIndex = random.nextInt(i);\n result.append(list.get(randomDigit));\n digits.remove(randomIndex);\n }\n return result.toString();\n}\n</code></pre>\n\n<p>And one final improvement: Instead of getting elements randomly, we can use <code>Collections.shuffle</code> to shuffle the list and then simply iterate over it and add elements to the result string.</p>\n\n<pre><code>private static String randomize() {\n int count = 10;\n List<Integer> digits = createList(count);\n Collections.shuffle(digits); // this re-arranges the elements in the list\n return listToString(digits);\n}\nprivate static <T> String listToString(List<T> list) {\n StringBuilder result = new StringBuilder();\n for (T object : list) {\n result.append(object);\n }\n return result.toString();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T07:50:01.067",
"Id": "58680",
"Score": "2",
"body": "The `random` object in the last example is unnecessary. Also I'd consider having a method returning the randomized list of numbers and a different method for converting it to a string. Those are two concerns which should be separate"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T14:53:42.317",
"Id": "58692",
"Score": "0",
"body": "@ChrisWue Thanks for the suggestion. I agree and modified the code a bit. Since the shuffling is only one line I put it in the `randomize` method."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T00:09:16.720",
"Id": "35951",
"ParentId": "35950",
"Score": "10"
}
},
{
"body": "<p>There is not much to improve. What you are doing is basically the same as a <a href=\"http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"nofollow\">Fisher-Yates/Knuth shuffle</a>, so the principle is sound. It's a 75 year old algorithm that still is considered to be the most effective way to make a shuffle.</p>\n\n<p>The original implementation uses an array rather than a list, and swaps item instead of removing them. That would be slightly faster, but would not normally make a noticable difference for such a small list.</p>\n\n<p>You can however make use of the fact that you know that you use all items in the list. When you get to the last item, you know that there is only one left, so you don't need to pick that one by random:</p>\n\n<pre><code> for (int i = 10; i > 1; i--) {\n int randomDigit = r.nextInt(i);\n number+=digits.get(randomDigit);\n digits.remove(randomDigit);\n }\n number+=digits.get(0);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T05:20:15.207",
"Id": "58677",
"Score": "1",
"body": "...He's just drawing items from a list, that is not a Fisher-Yates shuffle."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T09:44:53.057",
"Id": "58686",
"Score": "0",
"body": "@BlueRaja-DannyPflughoeft: That's exactly what a Fisher-Yates shuffle is, at least as a computer implementation. The original was done using pen and paper, so if you want to be picky then it can't be implemented as a computer program at all. Have a read at the page that I linked to."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T16:42:34.547",
"Id": "58696",
"Score": "1",
"body": "Fisher-Yates is an algorithm for doing an in-place shuffle. It's somewhat similar to what he's doing, but it is **not** at all the same."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T16:49:20.083",
"Id": "58697",
"Score": "0",
"body": "@BlueRaja-DannyPflughoeft: PLEASE read the page that I linked to. The Fisher-Yates algorithm is not at all what you describe. The Knuth implementation of the algorithm is what you describe."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T17:14:14.903",
"Id": "58699",
"Score": "0",
"body": "@BlueRaja: The original Fisher-Yates shuffle was indeed not an in-place shuffle. One could argue that the in-place version (as popularized by Knuth) should really be named \"Durstenfeld shuffle\", but that name has never really caught on. (See also [Stigler's law of eponymy](http://en.wikipedia.org/wiki/Stigler's_law_of_eponymy).)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T22:25:49.093",
"Id": "58746",
"Score": "0",
"body": "Why the downvote? If you don't explain what it is that you think is wrong, it can't improve the answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T22:26:12.687",
"Id": "58747",
"Score": "0",
"body": "@BlueRaja-DannyPflughoeft: Did you just downvote this answer, and all my questions at StackOverflow? Are you that childish?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T22:52:45.970",
"Id": "58750",
"Score": "0",
"body": "I already explained my reason for my downvote on this answer. But no, of course I did not downvote any of your other questions/answers, that would be absurd. That must've been someone else."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T22:59:33.823",
"Id": "58751",
"Score": "0",
"body": "@BlueRaja-DannyPflughoeft: Ok, someone is acting very childish, but I'll take your word for it. I still don't understand your downvote of the answer, though. If you still don't think that the code uses the Fisher-Yates algorithm, then you either don't understand the code, or you don't understand the Fisher-Yates algorithm. The code could hardly be a more exact implementation of the algorithm."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T00:09:49.103",
"Id": "35952",
"ParentId": "35950",
"Score": "5"
}
},
{
"body": "<p>If you are driven to get the absolute best performance, there are a number of things I would change. These changes will not necessarily improve the readability, but the performance will be best.</p>\n\n<p>First up, creating a <code>new Random()</code> each time is going to slow you down. This may well be about half of your time, in fact. I recommend a static version if you can be sure you won't have threading issues, or alternatively I would recommend a ThreadLocal. In general a ThreadLocal is the better option because even though Random is thread-safe, you don't want contention when it locks one thread against another.</p>\n\n<p>The second thing is \"Why use a List?\". Seriously, it's overkill. Use a primitive array, and preferably use char.....</p>\n\n<p>String concatenation is slow, so the <code>number += digits.get(randomDigit);</code> is essentially the same as:</p>\n\n<pre><code>StringBuilder sb = new StringBuilder(number);\nsb.append(String.valueOf(digits.get(randomDigit));\nnumber = sb.toString();\n</code></pre>\n\n<p>If you insist on using String concatenation then you would be better off using:</p>\n\n<pre><code>StringBuilder sb = new StringBuilder(10);\nfor (...) {\n ...\n sb.append(digits.get(randomDigit));\n ...\n}\nreturn sb.toString();\n</code></pre>\n\n<p>Finally, when there is just one member left in the array there is no need to do the random lookup (it will always return 0), so you can just use <code>1</code> as the limit of your loop and simply append the last remaining Integer from your List.</p>\n\n<p>Taking the above things in to consideration, I would recommend the following (which has a couple of other differences that I 'like'):</p>\n\n<pre><code>private static final ThreadLocal<Random> RANDOM = new ThreadLocal<Random>() {\n public Random initialValue() {\n return new Random();\n }\n}\n\npublic static final String randomize() {\n final char[] digits = \"0123456789\".toCharArray();\n final Random rand = RANDOM.get();\n int index = digits.length;\n // Fisher-Yates.\n while (index > 1) {\n final int pos = rand.nextInt(index--);\n final char tmp = digits[pos];\n digits[pos] = digits[index];\n digits[index] = tmp;\n }\n return new String(digits);\n}\n</code></pre>\n\n<hr>\n\n<p>EDIT</p>\n\n<p>I just realized another tweak could squeeze a little more performance out too.... consider this implementation which does not even need to create an array on each invocation, and who cares what order the digits are when you are just going to reshuffle them anyway. Thus, this saves creating a <code>char[]</code> array each time as well. The only new instance is the returned String:</p>\n\n<pre><code>private static final class Generator {\n private final Random rand = new Random();\n private final char[] digits = \"0123456789\".toCharArray();\n\n public final String generate() {\n int index = digits.length;\n // Fisher-Yates.\n while (index > 1) {\n final int pos = rand.nextInt(index--);\n final char tmp = digits[pos];\n digits[pos] = digits[index];\n digits[index] = tmp;\n }\n return new String(digits);\n }\n}\n\nprivate static final ThreadLocal<Generator> GENERATOR = new ThreadLocal<Generator>() {\n public Generator initialValue() {\n return new Generator();\n }\n};\n\npublic static final String randomize() {\n return GENERATOR.get().generate();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T02:04:39.690",
"Id": "58663",
"Score": "0",
"body": "Added an 'even-better' option."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T08:10:32.060",
"Id": "58768",
"Score": "0",
"body": "This could probably be optimized even further by initializing the array as it is being shuffled; see [my answer](http://codereview.stackexchange.com/a/36002) below."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T00:49:38.477",
"Id": "62401",
"Score": "0",
"body": "@DaveJarvis - `index != 0` will shuffle when there's just 1 thing to shuffle, `index > 1` will do one less shuffle but at a (potentially slower comparison). So, question is whether 1 more time through the loop is slower than many slightly-slower comparisons."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T06:30:37.607",
"Id": "62428",
"Score": "0",
"body": "@rolfl: If the loop can be re-written to compare the index to 0 instead of 1, then it might save a few paltry CPU cycles."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T11:38:39.517",
"Id": "62448",
"Score": "0",
"body": "Oh, got it, ... thought I would edit the code, but then found I woul dhave to `+ 1` in the `rand.nextInt(...)` and also pre-check for empty-string input which may otherwise underflow...."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T01:38:28.990",
"Id": "35953",
"ParentId": "35950",
"Score": "18"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/a/35953\">Rolfl's code</a> can be optimized even further by using a variant of the Fisher–Yates / Durstenfeld / Knuth shuffle that initializes the array as it's being shuffled. This saves one array read per iteration and avoids the need for the <code>tmp</code> variable:</p>\n\n<pre><code>private static final class Generator {\n private final Random rand = new Random();\n private final char[] digits = new char[10];\n\n public final String generate() {\n digits[0] = '0';\n for (int index = 1; index < digits.length; index++) {\n final int pos = rand.nextInt(index + 1);\n digits[index] = digits[pos];\n digits[pos] = (char) ('0' + index);\n }\n return new String(digits);\n }\n}\n</code></pre>\n\n<p>(Caveat: I have neither benchmarked nor even tested this code. That said, I'd <em>expect</em> it to be slightly faster than the original version, although the exact performance may vary depending on compiler and JVM optimizations.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T17:15:00.467",
"Id": "58786",
"Score": "0",
"body": "I have not benchmarked 'my' suggestions either, and, comparing your changes, I think they would be similar.... but, you should know that while I may have a `tmp` variable, I do not have the arithmetic in the loop (also, you will need to cast the `'0' + index` back to a `char`). So, I am pretty certain that when Java compiles the code down, my temp variable will essentially be optimized out, but the `digits[pos] = (char)('0' + index);` is more expensive."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T20:23:24.747",
"Id": "58797",
"Score": "1",
"body": "@rolfl: I did finally [benchmark them](http://ideone.com/J1dnGO) and, to be honest, I'm seeing almost no difference. On my computer, you code took 55.574 seconds to run 100 million iterations (after a 1 million iteration burn-in); mine did it in 54.132 seconds, a difference which I'm willing to ascribe to random variation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T21:22:29.403",
"Id": "58799",
"Score": "0",
"body": "Not wholly unexpected.... of interest, did you compare with the OP's code (Just curious...)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T23:49:08.817",
"Id": "58821",
"Score": "0",
"body": "I have added a 'community-wiki' answer that puts the various solutions 'head-to-head'. I also added 'the fastest' solution as a precomputed options. Your modification compares well.... pretty much comes down to which solution is cosmetically better rather than which one is faster....."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T08:09:09.133",
"Id": "36002",
"ParentId": "35950",
"Score": "2"
}
},
{
"body": "<p>Adding a Community-Wiki Answer. Please feel free to play with the code, add your own contributions, fix issues, etc.</p>\n\n<p>This contains some test code, some answers that work, and some timing data. I have added another (potentially) cheat solution to this question, which is by far the fastest solution (but all the random numbers are pre-computed ... ;-) )</p>\n\n<p>I have used the aliases <code>RL</code>, <code>RLv2</code>, <code>IK</code> and <code>OP</code> to reference the <code>rolfl</code>, the <code>rolfl cheat</code>, the <code>Ilmari Karonen</code> and <code>Original Poster</code> versions</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Random;\nimport java.util.concurrent.atomic.AtomicInteger;\n\n\npublic class Randoms {\n\n // ============ RLv2 ==================\n\n private static final String[] permutations = buildPermutes();\n private static final AtomicInteger cursor = new AtomicInteger();\n private static final String[] buildPermutes() {\n long start = System.nanoTime();\n char[] initial = \"0123456789\".toCharArray();\n ArrayList<String> store = new ArrayList<>();\n recursePermute(new char[10], initial, store);\n Collections.shuffle(store);\n String[] ret = store.toArray(new String[store.size()]);\n System.out.printf(\"Generated %d unique permutations in %.2fms\\n\", ret.length, (System.nanoTime() - start) / 1000000.0);\n return ret;\n }\n\n private static void recursePermute(char[] sofar, char[] remaining, ArrayList<String> store) {\n if (remaining.length == 0) {\n store.add(new String(sofar));\n return;\n }\n final int pos = sofar.length - remaining.length;\n char[] next = Arrays.copyOf(remaining, remaining.length - 1);\n for (int i = remaining.length - 1; i >= 0; i--) {\n sofar[pos] = remaining[i];\n recursePermute(sofar, next, store);\n if (i > 0) {\n next[i - 1] = remaining[i];\n }\n }\n\n }\n\n public static final String randomizeRLv2() {\n return permutations[cursor.getAndIncrement() % permutations.length];\n } \n\n\n // ============ RL ==================\n\n private static final class GeneratorRL {\n private final Random rand = new Random();\n private final char[] digits = \"0123456789\".toCharArray();\n\n public final String generate() {\n int index = digits.length;\n // Fisher-Yates.\n while (index > 1) {\n final int pos = rand.nextInt(index--);\n final char tmp = digits[pos];\n digits[pos] = digits[index];\n digits[index] = tmp;\n }\n return new String(digits);\n }\n }\n\n private static final ThreadLocal<GeneratorRL> GENERATORRL = new ThreadLocal<GeneratorRL>() {\n public GeneratorRL initialValue() {\n return new GeneratorRL();\n }\n };\n\n public static final String randomizeRL() {\n return GENERATORRL.get().generate();\n } \n\n // ============ IK ==================\n\n private static final class GeneratorIK {\n private final Random rand = new Random();\n private final char[] digits = new char[10];\n\n public final String generate() {\n digits[0] = '0';\n for (int index = 1; index < digits.length; index++) {\n final int pos = rand.nextInt(index + 1);\n digits[index] = digits[pos];\n digits[pos] = (char) ('0' + index);\n }\n return new String(digits);\n }\n } \n\n private static final ThreadLocal<GeneratorIK> GENERATORIK = new ThreadLocal<GeneratorIK>() {\n public GeneratorIK initialValue() {\n return new GeneratorIK();\n }\n };\n\n public static final String randomizeIK() {\n return GENERATORIK.get().generate();\n } \n\n // ============ OP ==================\n\n private static String randomizeOP(){\n Random r = new Random();\n List<Integer> digits= new ArrayList<Integer>();\n String number = \"\";\n for (int i = 0; i < 10; i++) {\n digits.add(i);\n }\n for (int i = 10; i > 0; i--) {\n int randomDigit = r.nextInt(i);\n number+=digits.get(randomDigit);\n digits.remove(randomDigit);\n }\n return number;\n }\n\n\n // Benchmark code.\n\n private static abstract class RandSystem {\n final String name;\n\n public RandSystem(String name) {\n super();\n this.name = name;\n }\n\n String getName() {\n return name;\n }\n\n abstract String getRandom();\n }\n\n public static void main(String[] args) {\n System.out.println(\"10-digit Random Number sequences\");\n\n RandSystem[] systems = {\n new RandSystem(\"OP\") {\n String getRandom() {\n return randomizeOP();\n }\n },\n\n new RandSystem(\"RL\") {\n String getRandom() {\n return randomizeRL();\n }\n },\n\n new RandSystem(\"IK\") {\n String getRandom() {\n return randomizeIK();\n }\n },\n\n new RandSystem(\"RLv2\") {\n String getRandom() {\n return randomizeRLv2();\n }\n }\n };\n\n\n for (int i = 0; i < 10; i++) {\n long[] times = new long[systems.length];\n int[] xor = new int[systems.length];\n for (int s = 0; s < systems.length; s++) {\n long start = System.nanoTime();\n int j = 1000000;\n while (--j >= 0) {\n xor[s] += systems[s].getRandom().length();\n }\n times[s] += System.nanoTime() - start;\n }\n StringBuilder sb = new StringBuilder(\" \");\n for (int s = 0; s < systems.length; s++) {\n sb.append(String.format(\"%s: %.2fms \", systems[s].getName(), times[s]/1000000.0));\n }\n System.out.println(sb.toString());\n }\n\n }\n\n}\n</code></pre>\n\n<p>This produces, on my machine, the results:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Generated 3628800 unique permutations in 4229.44ms\n10-digit Random Number sequences\nOP: 1977.11ms RL: 282.64ms IK: 209.93ms RLv2: 94.80ms \nOP: 823.61ms RL: 153.07ms IK: 160.56ms RLv2: 92.24ms \nOP: 813.06ms RL: 182.70ms IK: 180.86ms RLv2: 92.54ms \nOP: 807.10ms RL: 163.51ms IK: 163.05ms RLv2: 94.05ms \nOP: 802.40ms RL: 162.91ms IK: 163.19ms RLv2: 91.91ms \nOP: 803.28ms RL: 163.10ms IK: 162.58ms RLv2: 91.98ms \nOP: 803.49ms RL: 162.87ms IK: 162.33ms RLv2: 91.79ms \nOP: 803.23ms RL: 163.17ms IK: 163.53ms RLv2: 92.87ms \nOP: 801.11ms RL: 164.45ms IK: 162.38ms RLv2: 91.65ms \nOP: 801.21ms RL: 165.55ms IK: 162.45ms RLv2: 92.28ms \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T22:41:01.003",
"Id": "36017",
"ParentId": "35950",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "35953",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T23:48:46.173",
"Id": "35950",
"Score": "12",
"Tags": [
"java",
"optimization",
"random"
],
"Title": "Optimize random number generator"
}
|
35950
|
<p>I created this out of curiosity and it has some code duplication issues and the fact that sticking <code>.yield()</code> on the end of a call to a unit converter is pretty strange.</p>
<p><strong>How would you improve it?</strong></p>
<pre><code>/**
* A very special velocity converter
* Designed mainly for a very natural syntax
* It allows full chainable conversion calls and maintains its on internal state.
*
* example:
* remotewind.convert(10).knots().to.mph().to.kmh().yield();
*
* Each unit has a yield "method" which returns the last value (the internal state)
*
* @param val
* @return Converter
*/
remotewind.convert = function(val) {
var val = val;
function Unit(){
this.yield = function(){
return val;
}
}
function Ms(ms){
val = ms;
this.to = {
kmh : function(){ return new Kmh(val * 3.6) },
mph : function(){ return new Mph(val * 2.2369362920544) },
knots: function(){ return new Knots(val * 1.943844492) }
}
}
Ms.prototype = new Unit();
function Kmh(kmh){
val = kmh;
this.to = {
ms : function(){ return new Ms(val * 0.277777778) },
mph : function(){ return new Mph(val * 0.621371192) },
knots: function(){ return new Knots(val * 0.539956803) }
}
}
Kmh.prototype = new Unit();
function Mph(mph){
val = mph;
this.to = {
ms : function(){ return new Ms(val * 0.44704) },
kmh : function(){ return new Kmh(val * 0.621371192) },
knots: function(){ return new Knots(val * 0.868976242) }
}
}
Mph.prototype = new Unit();
function Knots(kn){
val = kn;
this.to = {
ms : function(){ return new Ms(val * 0.514444444) },
mph : function(){ return new Mph(val * 1.150779448) },
knots: function(){ return new Knots(val * 1.852) }
}
}
Knots.prototype = new Unit();
function Converter(val){
return {
ms: function(){ return new Ms(val) },
kmh: function(){ return new Kmh(val) },
mph: function(){ return new Mph(val) },
knots: function(){ return new Knots(val) }
}
}
return new Converter(val);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T02:41:02.143",
"Id": "58667",
"Score": "0",
"body": "Just curious why there's differing spellings of yield scattered about.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T02:43:58.370",
"Id": "58668",
"Score": "0",
"body": "@Phix, because I can never remember how to spell it. I took the liberty of fixing it now though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T04:55:14.847",
"Id": "58675",
"Score": "0",
"body": "Gotcha. Just making sure it isn't something affecting your code."
}
] |
[
{
"body": "<p>You can override <code>valueOf</code> to perform the same function as <code>yield</code> in your code. Then, you could override <code>toString</code> to get the quantitative part and append the unit name. For the purposes of outputting your measures to text, and for debugging with e.g. Firebug, that would be a plus.</p>\n\n<p>As for factoring, it would be more flexible if you kept units of length separate from units of time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T03:05:09.610",
"Id": "58670",
"Score": "0",
"body": "Can you give an example of separating units of length from units of time without greatly complicating it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T18:04:43.493",
"Id": "58705",
"Score": "0",
"body": "@papirtiger Maybe. It's really not that different from the original. `km.per.hour().to.m.per.second()` is what I would want to see from a client code perspective. Each distance unit gets a `per` object, the properties of which are units time. Units time get the `to` object, the properties of which are identical to your original `to` object. I'll see if I can cook up a more detailed example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T18:15:23.777",
"Id": "58708",
"Score": "0",
"body": "Yeah except who wants to do `km.per.hour().to.nm.per.hour()` to get for example knots?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T18:27:39.740",
"Id": "58709",
"Score": "0",
"body": "@papirtiger Clearly not you, I guess. It would definitely be less concise. But if you're using a library for unit conversions, you probably want to be able to express *any* unit in your domain. Otherwise, you would write a function or two for the units you need and let that be that."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T02:32:09.120",
"Id": "35957",
"ParentId": "35955",
"Score": "0"
}
},
{
"body": "<p>Here's a fairly cryptic rewrite, focussing mostly on extensibility and minimal repetition. The trick I'm using is to pick one unit as our \"base\" unit from which all others are derived. The base-unit value (m/s in this case) is carried through the chain.</p>\n\n<pre><code>var convert = (function () {\n var conversions = {\n ms: 1, // use m/s as our base unit\n kmh: 3.6,\n mph: 2.23693629,\n knots: 1.94384449\n // feel free to add more \n };\n\n function Unit(unit, ms) {\n this.value = ms * conversions[unit];\n this.to = {};\n for(var otherUnit in conversions) {\n (function (target) {\n this.to[target] = function () {\n return new Unit(target, ms);\n }\n }).call(this, otherUnit);\n }\n }\n\n Unit.prototype = {\n yield: function () {\n return this.valueOf();\n },\n\n toString: function () {\n return String(this.value);\n },\n\n valueOf: function () {\n return this.value;\n }\n };\n\n return function (value) {\n var units = {};\n for(var unit in conversions) {\n (function (unit) {\n units[unit] = function () {\n return new Unit(unit, value / conversions[unit]);\n };\n }(unit));\n }\n return units;\n } \n}());\n</code></pre>\n\n<hr>\n\n<p>Edit: Just for fun, here's an <em>ultra-convoluted</em> version that handles different measurement types. Couldn't get temperature conversions in there, as simple multiplication/division isn't enough to deal with C/K/F conversions. Boo.</p>\n\n<p>Really though, the code's pretty dense, and I can't recommend coding like this. But again, this was just for fun.</p>\n\n<p>Anyway, the usage would be something like</p>\n\n<pre><code>convert.speed(60).mph().to.kmh(); // ~97km/h\nconvert.distance(100).m().to.ft(); // ~330ft\nconvert.mass(1000).g().to.lb(); // ~2.2lb\n</code></pre>\n\n<p>And here's the hairy code:</p>\n\n<pre><code>var convert = (function () {\n var conversions = {\n speed: {\n ms: 1, // use m/s as our base unit\n kmh: 3.6,\n mph: 2.23693629,\n knots: 1.94384449\n },\n\n distance: {\n m: 1, // use meters as our base\n inches: 39.3700787402, // can't use \"in\" as that's a keyword. Darn.\n ft: 3.280839895,\n mi: 0.000621371192,\n nm: 0.000539956803 // nautical miles, not nanometers\n },\n\n mass: {\n g: 1, // use grams as our base\n lb: 0.002204622622,\n oz: 0.0352739619\n }\n };\n\n function Unit(type, unit, base) {\n this.value = base * conversions[type][unit];\n this.to = {};\n for(var otherUnit in conversions[type]) {\n (function (target) {\n this.to[target] = function () {\n return new Unit(type, target, base);\n }\n }).call(this, otherUnit);\n }\n }\n\n Unit.prototype = {\n yield: function () {\n return this.valueOf();\n },\n\n toString: function () {\n return String(this.value);\n },\n\n valueOf: function () {\n return this.value;\n }\n };\n\n // my god, it's full of scopes!\n var types = {};\n for(var type in conversions) {\n (function (type) {\n types[type] = function (value) {\n var units = {};\n for(var unit in conversions[type]) {\n (function (unit) {\n units[unit] = function () {\n return new Unit(type, unit, value / conversions[type][unit]);\n }\n }(unit));\n }\n return units;\n };\n }(type));\n }\n\n return types;\n}());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T02:53:02.073",
"Id": "58669",
"Score": "0",
"body": "Brilliant, it took me a little while to decipher. Especially the line where you return a new Unit, from inside the Unit constructor. A+"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T14:05:12.160",
"Id": "58690",
"Score": "0",
"body": "@papirtiger Thanks. And, yeah, it's pretty convoluted. Should have commented it, but where'd the fun be in that? :) On the plus side, it's easy to add more conversions. For fun, I just added an even more tricky version that handles different types of measurements :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T02:44:52.057",
"Id": "35958",
"ParentId": "35955",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "35958",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T01:46:16.717",
"Id": "35955",
"Score": "3",
"Tags": [
"javascript",
"design-patterns"
],
"Title": "Javascript velocity converter, fully chainable"
}
|
35955
|
<p>The kinds of control flow statements supported by different languages vary, but can be categorized by their effect:</p>
<ul>
<li>continuation at a different statement (unconditional branch or jump),</li>
<li>executing a set of statements only if some condition is met (choice - i.e., conditional branch),</li>
<li>executing a set of statements zero or more times, until some condition is met (i.e., loop the same as conditional branch),</li>
<li>executing a set of distant statements, after which the flow of control usually returns (subroutines, coroutines, and continuations),</li>
<li>stopping the program, preventing any further execution (unconditional halt).</li>
</ul>
<p>from <a href="http://en.wikipedia.org/wiki/Control_flow" rel="nofollow">Wikipedia</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T03:43:23.727",
"Id": "35960",
"Score": "0",
"Tags": null,
"Title": null
}
|
35960
|
Within an imperative programming language, a control flow statement is a statement whose execution results in a choice being made as to which of two or more paths should be followed.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T03:43:23.727",
"Id": "35961",
"Score": "0",
"Tags": null,
"Title": null
}
|
35961
|
<p>I have finished my first Android App, but I am getting lots of skipped frame messages from Choreographer. So, I started reading and got the impression that I should put as less calculations/works as possible in main thread, rather should use AsyncTask.</p>
<p>To understand the thumb rule, can anybody please validate my code whether I should move any methods in AsyncTask? </p>
<pre><code>public class EditEntry extends Activity implements DatePickerFragment.TheListener{
public static int EDIT_BOOK_ID;
EditText edit_datepurchased;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_entry);
Intent eintent = getIntent();
EDIT_BOOK_ID = Integer.parseInt(eintent.getStringExtra("passid"));
populateData(EDIT_BOOK_ID);
}
/**
* Set up the {@link android.app.ActionBar}.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.edit_entry, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.editsave:
editSave();
return true;
case android.R.id.home:
String currlist = Integer.toString(EDIT_BOOK_ID);
Intent editIntent = new Intent();
editIntent.putExtra("bookid", currlist);
setResult(RESULT_OK, editIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
//populateData get the data from database and populate all the fields in the page
public void populateData(int runid){
mylibmandbhandler db = new mylibmandbhandler(this);
mylibman cn = new mylibman();
cn = db.getNextBook(runid,2); // Method in mylibmandbhandler class to fetch data
String temp;
EditText mEditText = new EditText(this);
mEditText = (EditText) findViewById(R.id.bookname); // TEXT
mEditText.setText(cn.getBookname());
mEditText = (EditText) findViewById(R.id.pages); //NUMBER
temp = Integer.toString(cn.getPages());
mEditText.setText(temp.equals("-1")?"":temp);
CheckBox mCheckBox = (CheckBox) findViewById(R.id.inlibrary); //CHECKBOX
if(cn.getInlibrary()==1){
mCheckBox.setChecked(true);
}else{
mCheckBox.setChecked(false);
}
....................
....................
// I HAVE AROUND 25 fields (mostly EditText)
....................
....................
db.close();
}
// editSave update the database based on changed values
public void editSave() {
AlertDialog.Builder editDialog = new AlertDialog.Builder(EditEntry.this);
editDialog.setTitle("Confirm Edit...");
editDialog.setMessage("Are you sure you want save changes?");
final mylibmandbhandler db = new mylibmandbhandler(this);
editDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
editDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
String[] dataarr = new String[17];
EditText xEditText;
String aTemp;
int cnt = 0;
xEditText = (EditText) findViewById(R.id.bookname);
dataarr[cnt++] = xEditText.getText().toString();
xEditText = (EditText) findViewById(R.id.pages);
aTemp = xEditText.getText().toString();
try {
Integer.parseInt(aTemp); // IF NUMBER
dataarr[cnt++] = aTemp;
} catch (NumberFormatException e) {
dataarr[cnt++] = "-1";
}
.....................
.....................
// Get All 25 fields data
.....................
.....................
db.updateRecord(new mylibman(dataarr),EDIT_BOOK_ID); // Method in mylibmandbhandler class to update database
Toast.makeText(getApplicationContext(), "Changes saved for Book#"+EDIT_BOOK_ID, Toast.LENGTH_SHORT).show();
//RETURN TO MAIN ACTIVITY PAGE AND RELOAD THE EDITED RECORD
String currlist = Integer.toString(EDIT_BOOK_ID);
Intent editIntent = new Intent();
editIntent.putExtra("bookid", currlist);
setResult(RESULT_OK, editIntent);
finish();
}
});
db.close();
editDialog.show();
}
//SHOW DATE DIALOG
public void showdate(View v) {
edit_datepurchased = (EditText) findViewById(v.getId());
DialogFragment newFragment = new DatePickerFragment();
Bundle bundle = new Bundle();
bundle.putString("dateAsText",edit_datepurchased.getText().toString());
newFragment.setArguments(bundle);
newFragment.show(getFragmentManager(), "datePicker");
}
//@Override
public void returnDate(String date) {
edit_datepurchased.setText(date);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T22:42:55.780",
"Id": "58749",
"Score": "0",
"body": "Possibly related: http://stackoverflow.com/questions/15963969/choreographer639-skipped-50-frames . Are you running on an emulator or a real device? If you are running on a real device, does it respond quickly? If it does respond quickly I wouldn't worry too much. If it doesn't let me know and I can provide a more detailed answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T03:04:04.717",
"Id": "58761",
"Score": "0",
"body": "thanks, I didn't try on a real device so far .. I'll let you know after I try .. thanks again :)"
}
] |
[
{
"body": "<p>Both the methods <code>editSave()</code> and <code>populateData()</code> require access to a database to function. They both should be modified to use <code>AsyncTask</code> in order to reduce the footprint that your code has on the 'main thread'.</p>\n\n<p>I presume the database is local to the device because otherwise you would be getting the notorious <a href=\"https://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception\">NetworkOnMainThreadException</a>... but regardless, for the same reason that NetworkOnMainThread has been designated as a critical problem, database access should be treated the same way. Any time you have IO or other non-CPU bound activities, you really should be using the AsyncTask, and there's <a href=\"https://stackoverflow.com/questions/9671546/asynctask-android-example\">a good example on StackOverflow too</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:06:22.577",
"Id": "77662",
"Score": "0",
"body": "Because populateData() is not a class ( or at least it doesn't seem to be to me), would AsyncTask need to be added to getNextBook?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T00:55:08.290",
"Id": "36170",
"ParentId": "35965",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T05:49:48.613",
"Id": "35965",
"Score": "1",
"Tags": [
"java",
"optimization",
"android"
],
"Title": "Android code optimization - AsyncTask"
}
|
35965
|
<p>MongoDB does not provide means to lock a document (like <code>SELECT FOR UPDATE</code> in RDBMS).</p>
<p>There is a recommended approach to <a href="http://docs.mongodb.org/manual/tutorial/isolate-sequence-of-operations/" rel="nofollow">Isolate Sequence of Operations</a>, which is sometimes called <em>optimistic locking</em>, but there are scenarios when this approach seems to be overly complicated or even inefficient (that is why <em>pessimistic locks</em> are still in use).</p>
<h2>Task</h2>
<p>I am trying to implement generic (can be used with various databases) document (or record) locking at application level. Assuming I have only one application working with collection (or table). And my application is <em>multi-threaded</em>.</p>
<p>Usage scenario:</p>
<pre><code>with DocumentLock(doc_id):
# make sure no other thread interferes
doc=db.doc_collection.find_one(doc_id)
... # analyse and update the document
db.doc_collection.save(doc)
</code></pre>
<h2>Solution</h2>
<p>Here is my DocumentLock class:</p>
<pre><code>class DocumentLock(object):
_lock=RLock() # protects access to _locks dictionary
_locks=WeakValueDictionary()
def __init__(self, doc_id):
self.doc_id=doc_id
def __enter__(self):
with self._lock:
self.lock=self._locks.get(self.doc_id)
if self.lock is None:
self._locks[self.doc_id]=self.lock=RLock()
self.lock.acquire()
def __exit__(self, exc_type, exc_value, traceback):
self.lock.release()
self.lock=None # make available for garbage collection
</code></pre>
<p>So basically I have a dictionary of <code>RLocks</code>, one <code>RLock</code> per accessed document. I use weak references to get rid of unused locks.</p>
<p><code>DocumentLock</code> can be subclassed for every collection (or table) that needs record locking.</p>
<h2>Question</h2>
<p>This all seems to work (although not tested under concurrency) but I am publishing it here for review and advise. Do you see any weaknesses or mistakes in this code? Is there a better approach to do this kind of things in Python?</p>
|
[] |
[
{
"body": "<ol>\n<li><p>The above code will fail with multiple worker nodes (or processes).</p></li>\n<li><p>To achieve atomic find-and-update, mongodb provides native solution (findOneAndUpdate, findAndModify, updateOne, updateMany).</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-02T07:08:48.933",
"Id": "234937",
"ParentId": "35968",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T09:06:08.383",
"Id": "35968",
"Score": "2",
"Tags": [
"python",
"multithreading",
"locking",
"mongodb"
],
"Title": "Python app-level document/record locking (eg. for MongoDB)"
}
|
35968
|
<p>I create series of objects out of Student Class and store them in a vector. I write each object in to a .ser file once it created. Then I read them back. My code is working perfectly. What I want to know is, I do this in a correct optimized way or are there any easy and optimized ways to get this done?? And also how to replace or delete specific object in a .ser file without re-witting whole the file again.</p>
<p>Student Class</p>
<pre><code>public class Student implements Comparable<Student>, Serializable{
private String firstName = "";
private int registrationNumber;
private int coursework1;
private int coursework2;
private int finalExam;
private double moduleMark;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getRegistrationNumber() {
return registrationNumber;
}
public void setRegistrationNumber(int registrationNumber) {
this.registrationNumber = registrationNumber;
}
public int getCoursework1() {
return coursework1;
}
public void setCoursework1(int coursework1) {
this.coursework1 = coursework1;
}
public int getCoursework2() {
return coursework2;
}
public void setCoursework2(int coursework2) {
this.coursework2 = coursework2;
}
public int getFinalExam() {
return finalExam;
}
public void setFinalExam(int finalExam) {
this.finalExam = finalExam;
}
public double getModuleMark() {
return moduleMark;
}
public void setModuleMark(double moduleMark) {
this.moduleMark = moduleMark;
}
public int compareTo(Student s){
if (this.moduleMark > s.moduleMark)
return 1;
else if (this.moduleMark == s.moduleMark)
return 0;
else
return -1;
}
}
</code></pre>
<p>File writing part</p>
<pre><code>public static void Write(Student mm){
try
{
FileOutputStream fileOut = new FileOutputStream("info.ser",true);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fileOut));
out.writeObject(mm);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in info.ser");
}catch(IOException i)
{
//i.printStackTrace();
}
}
</code></pre>
<p>Reading part</p>
<pre><code>public static int Read() {
int count=0;
try{
vector = new Vector<Student>();
FileInputStream saveFile = new FileInputStream("info.ser");
ObjectInputStream save;
try{
for(;;){
save = new ObjectInputStream(saveFile);
student = (Student) save.readObject();
vector.add(student);
count++;
}
}catch(EOFException e){
//e.printStackTrace();
}
saveFile.close();
}catch(Exception exc){
exc.printStackTrace();
}
return count;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T14:32:46.867",
"Id": "58691",
"Score": "1",
"body": "your very last question is off topic, we won't tell you how to write a block of code."
}
] |
[
{
"body": "<p>Why didn't you provide a constructor for <code>Student</code> class? Was that on purpose? However...</p>\n\n<ul>\n<li><p>Use <a href=\"https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it\"><code>serialVersionUID</code></a>.</p></li>\n<li><p>In Java it's recommended <a href=\"https://stackoverflow.com/questions/1386275/why-is-java-vector-class-considered-obsolete-or-deprecated\">not to use <code>Vector</code> class</a>, instead use <code>ArrayList</code>.</p></li>\n<li><p><code>Write</code> method is serializing a <code>Student</code> individually. But as you stated you are writing a whole list of student into the <code>.ser</code> file. This will take many time for a list of 10,000 students. </p>\n\n<p>Because you are opening two streams for each student. So instead pass the whole list and serialize them after opening the stream only once.</p></li>\n<li><p>Do not close the stream in the <code>try</code> block. close them into <code>finally</code> block. Even better if you are using Java7 or higher use <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\"><code>try-with-resources</code></a> block. It is easy to use and you don't have to manually close the stream.</p></li>\n<li><p>In <code>Read</code> method</p>\n\n<pre><code> for(;;){\n save = new ObjectInputStream(saveFile);\n</code></pre>\n\n<p>you are creating new stream for every object thats not necessary instead do this</p>\n\n<pre><code> save = new ObjectInputStream(saveFile);\n for(;;){\n</code></pre></li>\n<li><p>Onwards Java7 there is <a href=\"http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html\" rel=\"nofollow noreferrer\"><code>multiple catch statement</code></a>. Give it a <em>try</em>(pun intended). </p></li>\n<li><p>In Java we use <a href=\"http://java.about.com/od/javasyntax/a/nameconventions.htm\" rel=\"nofollow noreferrer\">mixed-case convention</a> for naming a method. So <code>Write</code> and <code>Read</code> would be <code>write</code> and <code>read</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T13:46:31.230",
"Id": "58688",
"Score": "1",
"body": "I'm new to java and means a lot ur quick reply. learnt a lot. Thanks for ur time :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T13:23:21.520",
"Id": "35975",
"ParentId": "35974",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "35975",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T12:33:48.463",
"Id": "35974",
"Score": "3",
"Tags": [
"java",
"vectors",
"serialization"
],
"Title": "best way to write series of objects to a .ser file using ObjectOutputStream and read them back"
}
|
35974
|
<p>I create class level static ArrayList by the following line.</p>
<pre><code>static ArrayList<Student> studentList = null;
</code></pre>
<p>Then I create and fill ArrayList with some objects inside a function.</p>
<pre><code>studentList = new ArrayList<Student>();
Write(student);
</code></pre>
<p>later I want to clear all of my ArrayList elements </p>
<pre><code>studentList = new ArrayList<Student>();
</code></pre>
<p>Will my ArrayList removed and create a variable call studentList again by the above line??</p>
<p>or is it a good practice to clear like below??</p>
<pre><code>studentList.clear();
</code></pre>
<p>or both </p>
<pre><code>studentList.clear();
studentList = new ArrayList<Student>();
</code></pre>
|
[] |
[
{
"body": "<p>First of all, speaking of good practice, I would not have the variable as <code>static</code>. Using <code>static</code> variables is like using Singletons. There can be only one. You might regret this strategy later. Instead, if possible, I would declare the <code>List</code> <em>in another object</em> and not set it to <code>static</code>.</p>\n\n<p>Technically, you said \"I create class level static ArrayList by the following line.\" but on that line you only <em>declare</em> the <code>ArrayList</code>, you <em>create</em> it by calling <code>studentList = new ArrayList<Student>();</code></p>\n\n<p>That being said, I would say that it is a better practice to call <code>clear</code> on your list instead of recreating it. If you clear it, then there is no need to recreate it (unless you have sent the <strong>object reference</strong> to other places and you don't want those objects to be the same anymore). By not recreating your list, it also allows you to set the variable to <code>final</code>, which is good practice.</p>\n\n<p>Here is how I would define your variable:</p>\n\n<pre><code>private final List<Student> studentList = new ArrayList<Student>();\n</code></pre>\n\n<p>I hope this makes sense.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T18:56:04.553",
"Id": "58712",
"Score": "0",
"body": "I think I should create variable as static because like 18 different functions are working with the same ArrayList, otherwise I have to pass the same array each n every time. It's the best way isn't it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T20:25:15.310",
"Id": "58741",
"Score": "1",
"body": "@Eclayaz I don't know what the cleanest/best way to do it here is without looking at the rest of your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T01:31:07.220",
"Id": "58824",
"Score": "1",
"body": "@Eclayaz: If you require access to the list in different places then yes you either need to pass the list around or the object which owns the list. btw: Passing the list around only passes the reference and not the entire list. Without looking at your code I can pretty much guarantee you that making it static is simply a bad idea."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T16:42:21.217",
"Id": "35978",
"ParentId": "35977",
"Score": "5"
}
},
{
"body": "<p>Clearing and replacing with a new object are different operations. The correct thing to do depends on the context of your code, which you haven't provided. (In my opinion, you haven't provided enough code for a code review. As it stands, this question is more suitable for Stack Overflow. I suggest that you add more code to this question by editing it.)</p>\n\n<p>In the absence of specific information about your usage, the preferred choice would be to just clear the list with <code>studentList.clear()</code>, because it creates the least amount of garbage to be collected. However, that may or may not be the right thing to do, depending on whether anything else also holds a reference to <code>studentList</code>.</p>\n\n<p>Echoing @Simon's advice, I would advise you to use <code>static</code> only if you have a strong justification. Static variables are essentially global variables (though slightly better because they may have <code>private</code> access, and they are in a class's namespace).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T18:50:40.283",
"Id": "58711",
"Score": "0",
"body": "got it! i can simply clean the arrayList according to my case."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T17:17:45.610",
"Id": "35981",
"ParentId": "35977",
"Score": "5"
}
},
{
"body": "<p>I hope that the function in which you actually created the object is also static otherwise the amount of mess that you can create has no limits. Make static variables only if it means sense that every instance of class should be able to use it. Don't use it for the sake of ease of sharing data like a global variable.</p>\n\n<p>Also like Simon said you didn't create the <code>ArrayList</code> at the first line. You made a reference variable that is capable of holding a reference to that kind of object.</p>\n\n<p>About the line <code>studentList = new ArrayList<Student>();</code> - The object reference is gone from the current reference variable but whether or not the object reference is completely gone depends on whether you passed it around or not. </p>\n\n<p>Use <code>clear()</code> instead of making a new object. But be aware that if you use <code>clear()</code> then there can be side-effects if you have passed the object reference around to some other object which is storing it. If you need to pass it around and want the <code>ArrayList</code> to be like a new one then it would be better to use <code>new ArrayList<Student>()</code>. That can help you to avoid side-effects of clearing. So choice is yours. Depends on the situation.</p>\n\n<p>One more thing, if you are just using the list as a global variable only so that you don't have to create a lot of local variables then don't do that. Instead make a lot of local variables which fall out of scope as soon as the function ends. It may seem inefficient to create a lot of objects but if all the objects are short-lived then it will be garbage collected easily as <code>GC</code> is optimized for it. Also that can help avoid side-effects which can become a headache and break <code>single-responsibility principle</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T18:10:34.990",
"Id": "58707",
"Score": "3",
"body": "*\"Make static variables only if [...] object of class should be able to use it\"*... umm quite opposite static means it can be (**should be**) used without any object but just by the class itself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T18:49:09.187",
"Id": "58710",
"Score": "0",
"body": "yah yah I got ur points. yah I use static methods to access static members. Thanks a lot :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T19:27:04.493",
"Id": "58723",
"Score": "0",
"body": "@tintinmj My mistake, I meant every instance of class not the objects contained in the class. Static variables can be accessed without any instance of the class but can also be accessed by all instances of the class. I have not heard about any requirement about `static` variables should be used by the class only. `public final static` class variables are used by other classes a lot."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T19:44:53.887",
"Id": "58729",
"Score": "2",
"body": "That's why I said *can be* but it leads to many confusion. This is a broad discussion and can't be fitted into a single comment. Search for some information and read [this](http://stackoverflow.com/a/1081664/2350145)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T19:51:59.453",
"Id": "58732",
"Score": "0",
"body": "@tintinmj I know what `static` variables are. Created once at class loading and should be accessed by class name and all about belonging to class(conceptually) rather than instances(which java allows). I have read oracle's Java SE tutorial on this. I am not getting what you are trying to say. What confusion are you referring to?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T20:01:39.030",
"Id": "58739",
"Score": "0",
"body": "@AseemBansal when you said *\"I have not heard about any **requirement** [...] class only\"*, I didn't say *requirement* I said it's recommended to use static variables with the class name only not with the class instance. If you are using any modern IDE it will give you a warning."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T20:05:54.880",
"Id": "58740",
"Score": "0",
"body": "@AseemBansal and about confusion see [this](http://ideone.com/tYIbMY)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T03:10:11.600",
"Id": "58762",
"Score": "0",
"body": "@tintinmj Yeah, the syntax for using static variables should be `ClassName.staticVariableName` instead of `referenceVariable.staticVariableName`. I wrote in my answer about every instance being able to use the static variable(i.e. every instance has access to the static variable) but I never said anything about the syntax for doing so."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T17:17:57.503",
"Id": "35982",
"ParentId": "35977",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T15:52:04.837",
"Id": "35977",
"Score": "3",
"Tags": [
"java",
"object-oriented",
"array",
"memory-management"
],
"Title": "Clear ArrayList"
}
|
35977
|
<p>Is there a simpler and optimized way to calculate <code>listAdminCorePriveleges</code> and <code>privileges</code> ?</p>
<pre><code>public string[] GetPrivilegesForUserByPersonEntityId(int personEntityId)
{
var listPrivileges = new List<string>();
var listAdminCorePriveleges = (_accountRepository.AsQueryable()
.Where(acc => acc.PersonEntityId == personEntityId)
.Select(acc => acc.AccountAdminPositionAssignments.Where(aap => aap.IsLocked == false && aap.IsObsolete == false).Select(aap => aap.AdminPosition.AdminType.AdminPrivileges))
).AsEnumerable();
foreach (var adminCorePriveleges in listAdminCorePriveleges)
{
foreach (var adminCorePrivelege in adminCorePriveleges)
{
listPrivileges.Add(adminCorePrivelege.Name);
}
}
string[] privileges = listPrivileges.Distinct().ToArray();
return privileges;
}
</code></pre>
|
[] |
[
{
"body": "<p>To know for sure what exactly is inefficient you'd need to hook up a profiler.</p>\n\n<p>Code wise you should be able to do it all in one query if I'm not mistaken:</p>\n\n<pre><code>return _accountRepository.AsQueryable()\n .Where(acc => acc.PersonEntityId == personEntityId)\n .SelectMany(acc => acc.AccountAdminPositionAssignments\n .Where(aap => !aap.IsLocked && !aap.IsObsolete)\n .SelectMany(aap => aap.AdminPosition.AdminType.AdminPrivileges.Select(p => p.Name)))\n .Distinct()\n .ToArray();\n</code></pre>\n\n<p>This will in theory also move the name selection and distinct filtering to the database which means that probably slightly less data has to be transferred. Adds a bit more work for the database server but that kind of stuff is what they should do well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T08:35:38.310",
"Id": "58769",
"Score": "0",
"body": "Is it good practice to write `.Where(acc => acc.PersonEntityId == personEntityId && acc.AccountAdminPositionAssignments.Any(aap => !aap.IsLocked) && ...).SelectMany(acc => acc.AccountAdminPositionAssignments.SelectMany(aap => ...` instead of yours?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T09:18:07.257",
"Id": "58770",
"Score": "1",
"body": "@Iman: Not really sure. I like to filter at the place where I'm selecting the data from, but if your version yields a better query or you simply like it better then go for it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T01:24:15.130",
"Id": "35995",
"ParentId": "35984",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "35995",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T17:39:29.107",
"Id": "35984",
"Score": "2",
"Tags": [
"c#",
"linq",
"entity-framework",
"ienumerable"
],
"Title": "Nested select Linq"
}
|
35984
|
<p>I currently have this bit of code, but I need to repeat it for red green and blue. Is there a way I can do it without copying and pasting the code 3 times?</p>
<pre><code>yellow.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {
switch (buttonCount) {
case 1:
empty1.setImageResource(R.drawable.yellow);
buttonCount++;
guess1= Colour.YELLOW;
break;
case 2:
empty2.setImageResource(R.drawable.yellow);
buttonCount++;
guess2=Colour.YELLOW;
break;
case 3:
empty3.setImageResource(R.drawable.yellow);
buttonCount++;
guess3=Colour.YELLOW;
break;
case 4:
empty4.setImageResource(R.drawable.yellow);
buttonCount++;
guess4=Colour.YELLOW;
break;
case 5:
empty5.setImageResource(R.drawable.yellow);
buttonCount++;
guess5=Colour.YELLOW;
break;
}
}
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T20:17:54.370",
"Id": "58743",
"Score": "2",
"body": "Have you tried writing a function and then pass your arguments(Colour.RED, Color.BLUE and Color.GREEN). Remember that these are constants. Try it out and then post here what have you tried if you cannot achieve the outcome."
}
] |
[
{
"body": "<p>If you look at your naming schema, you have <code>emptyX</code> and <code>guessX</code>, where <code>X</code> is an index. This is an indicator that you should be using an array or a list:</p>\n\n<pre><code>EmptyType empties[5] = { empty1, empty2, ... };\nGuessType guesses[5] = { guess1, guess2, ... };\n\nyellow.setOnClickListener(new View.OnClickListener() {\n public void onClick (View v) {\n assert buttonCount < 5;\n empties[buttonCount - 1].setImageResource(R.drawable.yellow);\n buttonCount++;\n guesses[buttonCount - 1] = Colour.YELLOW;\n }\n})\n</code></pre>\n\n<p>If you have to do the same thing for three colours, either copy&paste this small snippet, or extract it into another method, which you can call with appropriate colours:</p>\n\n<pre><code>private void doStuff(EventSource source, Color color, ImageResource resource) {\n source.setOnClickListener(new View.OnClickListener() {\n public void onClick (View v) {\n assert buttonCount < 5;\n empties[buttonCount - 1].setImageResource(resource);\n buttonCount++;\n guesses[buttonCount - 1] = color;\n }\n });\n}\n\n doStuff(yellow, Color.YELLOW, R.drawable.yellow);\n doStuff(blue, Color.BLUE, R.drawable.blue );\n doStuff(green, Color.GREEN, R.drawable.green );\n</code></pre>\n\n<p>This still looks like you could choose better data structures, so that the <code>Color</code> and the corresponding <code>ImageResource</code> and <code>EventSource</code> are explicitly connected.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T20:22:56.830",
"Id": "35987",
"ParentId": "35986",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T19:57:07.507",
"Id": "35986",
"Score": "4",
"Tags": [
"java",
"android"
],
"Title": "Best way to get rid of code repetition?"
}
|
35986
|
<p>I recently gutted and redid my game code to be object oriented (before it was just functions and a mass of global variables.</p>
<p>Before I go an make more functionality happen, I would like to take one last step backwards to make sure I have the best foundation I can before proceeding.</p>
<p>Note: the point of this game is to better learn raw JavaScript methods and design, so I do not want any plugins, or somebody telling me how jQuery would make this easier ;)</p>
<p>I VERY much apologize if this script is too long for the site, and I will remove the question if this is an improper question here.</p>
<p>index.html</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>A Vampire's Hunt</title>
<link rel="stylesheet" href="vamp.css">
</head>
<body>
<div id="msg" class="msg"></div>
<div>You have been dead for <span id="counter">0</span> hours..</div>
<div id="divCycle" class="cycle">It is currently: <span id="cycle"></span></div>
<div>Blood: <span id="blood">0</span></div>
<div class="hp" id="hpDiv">HP: <span id="hp">20</span></div>
<div class="gold" id="goldDiv">Gold: <span id="gold">0</span></div>
<script src="object-vamp.js"></script>
</body>
</html>
</code></pre>
<p>element object</p>
<pre><code>function _elements() {
this.counter;
this.blood;
this.gold;
this.spanHP;
this.divHP;
this.bloodElement;
this.raidElement;
this.msg;
this.goldDiv;
this.day;
this.cycle;
this.goHunting;
this.elm = function(name,props,style) {
var el = document.createElement(name);
for(var prop in props) if(props.hasOwnProperty(prop)) el[prop] = props[prop];
for(var prop in style) if(style.hasOwnProperty(prop)) el.style[prop] = style[prop];
return el;
}
this.showElement = function(id) {
document.getElementById(id).className = "";
}
this.disableElement = function(id,txt) {
document.getElementById(id).disabled = true;
document.getElementById(id).innerHTML = txt;
}
this.alterHTML = function(id,txt) {
document.getElementById(id).innerHTML = txt;
}
this.enableButton = function(id,e,txt) {
var element = document.getElementById(id);
if (engine.player.isDead() && engine.dayStatus != "night")
engine.elements.eventMsg("You are too weak to "+e+" until pure darkness allows it!");
else {
element.disabled = false;
this.alterHTML(id,txt);
}
}
this.addBorder = function(id) {
document.getElementById(id).style.border = "1px solid black";
}
this.eventMsg = function(txt) {
this.addBorder("msg");
var temp = document.getElementById("msg");
txt = "-"+txt+"<br />"+temp.innerHTML;
temp.innerHTML = txt;
}
this.bloodButton = function() {
this.goHunting = this.elm("button",{innerHTML:"Hunt for Blood", id:"bloodButton"},{});
document.body.appendChild(this.goHunting);
this.goHunting.addEventListener("click",engine.player.hunt.bind());
}
this.raidButton = function() {
this.goRaiding = this.elm("button",{innerHTML:"Raid for Gold", id:"raidButton"},{});
document.body.appendChild(this.goRaiding);
this.goRaiding.addEventListener("click",engine.player.raid.bind());
}
}
</code></pre>
<p>player object</p>
<pre><code>function _player() {
this.hp = 20;
this.hpMax = 20;
this.bloodcount = 0;
this.goldCount = 0;
this.isDead = function() {
if (this.hp <= 0) return true;
else return false;
}
this.revive = function() {
if (engine.dayStatus == "night") {
engine.player.healDamage(1);
}
}
this.healDamage = function(heal) {
if ((this.hp+heal) > this.hpMax) this.hp = this.hpMax;
else this.hp += heal;
}
this.triggerDeath = function(cause,bloodLoss) {
engine.elements.eventMsg("You have died from: "+cause);
engine.elements.eventMsg("Your death has cost you "+bloodLoss+" pints of your precious blood!");
if (this.bloodcount < 20) this.bloodcount = 0;
else this.bloodcount -= bloodLoss;
engine.elements.alterHTML("blood",this.bloodcount);
}
this.dealDamage = function(dmg,type,bloodLossOnDeath) {
if (!engine.firstHPLoss) {
engine.firstHPLoss = true;
engine.elements.showElement("hpDiv");
}
if ((this.hp-dmg) <= 0) {
this.hp = 0;
this.triggerDeath(type,bloodLossOnDeath);
} else {
this.hp -= dmg;
}
}
this.hunt = function() {
var bloodCollected = 0;
engine.elements.alterHTML("bloodButton","Wait to hunt...");
engine.elements.goHunting.disabled = true;
if (engine.dayStatus == engine.statusCycle[0]) {
this.dealDamage(10,"sunlight",20);
engine.elements.eventMsg("Hunting in the daylight has hurt you! -10 HP!");
} else {
bloodCollected = 1*engine.multiplier;
engine.player.bloodcount += bloodCollected;
engine.elements.alterHTML("blood",engine.player.bloodcount);
engine.elements.eventMsg("Your hunt yielded "+bloodCollected+" pint(s) of blood!");
engine.player.healDamage(1);
engine.elements.alterHTML("hp",engine.player.hp);
}
}
this.raid = function() {
engine.elements.showElement("goldDiv");
var goldCollected;
var hpLoss = 0;
engine.elements.alterHTML("raidButton","Wait to raid...");
engine.elements.goRaiding.disabled = true;
if (engine.dayStatus == engine.statusCycle[0]) {
engine.player.dealDamage(15,"sunlight");
engine.elements.eventMsg("Raiding in the daylight has hurt you! -15 HP!");
} else {
hpLoss = Math.floor(Math.random()*(5-1+1)+1);
goldCollected = Math.floor((Math.random()*100));
engine.player.goldCount += goldCollected;
engine.elements.alterHTML("gold",engine.player.goldCount);
engine.elements.eventMsg("Your raid yielded "+goldCollected+" gold coins at the cost of "+hpLoss+"HP from the townspeople!");
engine.player.dealDamage(hpLoss,"raiding",15);
engine.elements.alterHTML("hp",engine.player.hp);
}
}
}
</code></pre>
<p>the main engine object</p>
<pre><code>function _engine() {
this.count = 0;
this.cycleFlag = false;
this.firstHPLoss = false;
this.raidFlag = false;
this.multiplier = 1;
this.dayStatus = "dusk";
this.statusCycle = [
"day",
"dusk",
"night",
"dawn"
];
this.huntStatus = {
"day":0,
"dusk":3,
"night":4,
"dawn":2
};
this.dayFlavor = [
"The sun is bright outside..",
"The sun is setting..",
"The moon shines brightly..",
"The sun is rising.."
];
this.player = (function(){ return new _player(); }());
this.elements = (function(){ return new _elements(); }());
this.triggers = function(c) {
if (c == 5) this.elements.bloodButton();
if (!(c%1) && c > 5) this.elements.enableButton("bloodButton","hunt","Hunt for Blood");
if (!(c%1) && engine.player.bloodcount > 5) this.elements.enableButton("raidButton","raid","Raid for Gold");
if (engine.player.bloodcount >= 5 && !this.raidFlag) {
this.elements.raidButton();
this.raidFlag = true;
}
if (engine.player.bloodcount >= 10 && !this.cycleFlag) {
this.initDayCycle();
this.cycleFlag = true;
}
if (!(c%10) && this.cycleFlag) this.nextDayCycle();
}
this.initDayCycle = function() {
engine.elements.showElement("divCycle");
engine.elements.alterHTML("cycle",this.dayStatus);
engine.multiplier = 3;
}
this.nextDayCycle = function() {
var index = this.statusCycle.indexOf(this.dayStatus);
var cycleNext = this.statusCycle[(index+1)];
if (cycleNext) {
this.dayStatus = cycleNext;
this.multiplier = this.huntStatus[cycleNext];
}
else {
this.dayStatus = this.statusCycle[0];
this.multiplier = this.huntStatus[this.dayStatus];
}
engine.elements.alterHTML("cycle",this.dayStatus);
var newIndex = this.statusCycle.indexOf(this.dayStatus);
engine.elements.eventMsg(this.dayFlavor[newIndex]);
}
}
</code></pre>
<p>And finally the initialization and interval loop</p>
<pre><code>var engine = (function(){ return new _engine(); }());
setInterval(function() {
engine.count++;
engine.elements.alterHTML("counter",engine.count);
engine.triggers(engine.count);
if (engine.player.isDead()) {
engine.elements.disableElement("bloodButton","You are dead..");
engine.elements.disableElement("raidButton","You are dead..");
engine.player.revive();
}
}, 1000);
</code></pre>
|
[] |
[
{
"body": "<h1>Use prototypes</h1>\n\n<p>I notice you do this:</p>\n\n<pre><code>function _player() {\n ...\n this.isDead = function() {\n if (this.hp <= 0) return true;\n else return false;\n }\n</code></pre>\n\n<p>One issue with this one is that for every instance of <code>_player</code>, you are creating methods <em>per instance</em> of the constructor. This eats up memory.</p>\n\n<p>What you can do is use prototypal inheritance. This inheritance model works by \"sharing\" the prototype of the constructor across the instances. That way, the methods are only declared <em>once</em>, but shared across instances.</p>\n\n<pre><code>function _player(){...}\n\n_player.prototype = {\n isDead : function(){...},\n revive : function(){...},\n ...\n};\n\nvar p1 = new _player();\nvar p2 = new _player();\n\n// Both _player instances use the same revive method\n// but operate on different _player objects\np1.revive();\np2.revive();\n</code></pre>\n\n<h1>Decouple the code</h1>\n\n<p>Your code is tightly coupled. That means if I break one part of the code, the other parts break as well. </p>\n\n<p>Take for example this code:</p>\n\n<pre><code>this.eventMsg = function(txt) {\n this.addBorder(\"msg\");\n var temp = document.getElementById(\"msg\");\n txt = \"-\"+txt+\"<br />\"+temp.innerHTML;\n temp.innerHTML = txt;\n}\n</code></pre>\n\n<p>This assumes that an element <code>#msg</code> exists. What if I took out that part of the HTML or renamed it by accident? <code>temp</code> would be <code>undefined</code> and accessing <code>temp.innerHTML</code> will throw an error.</p>\n\n<p>As well as this code:</p>\n\n<pre><code>this.player = (function(){ return new _player(); }());\nthis.elements = (function(){ return new _elements(); }());\n</code></pre>\n\n<p>Your code assumes <code>_player</code> and <code>_elements</code> exist. If I took them out or renamed them, you'd also be looking into this code and renaming it. Not very practical. Also, this assumes that <code>_player</code> and <code>_elements</code> are only one a piece. What if you needed more players? Or elements?</p>\n\n<h2>Decoupling with registration</h2>\n\n<p>Registration allows decoupling by <em>registering objects into</em> a system rather than having the system hard-code the required objects. That way, if no objects registered (because they are removed or something), then the code won't break. Here's a simple example with players:</p>\n\n<pre><code>//Engine.js\nfunction Engine(){\n // We can have more than one player\n this.players = [];\n}\n\nEngine.prototype = {\n // A simple register\n registerPlayer : function(player){\n this.players.push(player)\n },\n doSomethingWithPlayers : function(){\n for(var i = 0; i < this.players.length; i++){\n // Do something to registered players\n // No players registered means code won't run\n }\n }\n}\n\n//Registration.js \nvar player1 = new Player();\nvar player2 = new Player();\nvar engine = new Engine();\n\nengine.register(player1);\nengine.register(player2);\nengine.doSomethingWithPlayers(); //Some mass-heal effect?\n</code></pre>\n\n<p>So in the example above we <em>\"register\" player objects into</em> the engine rather than hard-code it into the engine. As you can see, advantages are apparent:</p>\n\n<ul>\n<li><p>There's no trace of using player constructors in the engine code, which means taking out <code>Player.js</code> won't break the engine code.</p></li>\n<li><p>You can register as many players <em>as you like any time</em> through a registration, which basically just stores players in an array.</p></li>\n</ul>\n\n<h2>Decouple events</h2>\n\n<p>I notice you use a clocking mechanism to to launch events with respect to time. However, you are hardcoding events along with the objects:</p>\n\n<pre><code>this.triggers = function(c) {\n if (c == 5) this.elements.bloodButton();\n if (!(c%1) && c > 5) this.elements.enableButton(\"bloodButton\",\"hunt\",\"Hunt for Blood\");\n if (!(c%1) && engine.player.bloodcount > 5) this.elements.enableButton(\"raidButton\",\"raid\",\"Raid for Gold\");\n if (engine.player.bloodcount >= 5 && !this.raidFlag) {\n this.elements.raidButton();\n this.raidFlag = true;\n }\n if (engine.player.bloodcount >= 10 && !this.cycleFlag) {\n this.initDayCycle();\n this.cycleFlag = true;\n }\n if (!(c%10) && this.cycleFlag) this.nextDayCycle();\n}\n</code></pre>\n\n<p>What you can do this one is some sort of \"pub-sub\" pattern or event listeners. You listen for events from an object and react accordingly. Basically, the mechanism registers functions into an array and runs them when the time comes to run them. It's very simple to implement, <a href=\"https://github.com/fskreuz/MiniEvent\" rel=\"nofollow\">I have made a small library myself</a>.</p>\n\n<pre><code>//Engine.js\nfunction Engine(){\n this.count = 0;\n this.timer = null;\n}\n\n//Refer to my library for a simple Event Emitter implementation\n\nEngine.prototype.run = function(){\n //Save the context\n var instance = this;\n\n this.timer = setTimeout(function(){\n // Run registered events\n // If they return true, then run the corresponding handlers\n },1000);\n}\n\n//Main script\n\nvar engine = new Engine();\nvar player = new Player();\n\n// Register an event that determines when it happens\nengine.registerEvent('nextDayCycle',function(cycle){\n\n //nextDayCycle event is triggered on this tick when this returns true\n return (!(cycle%10) && this.cycleFlag);\n});\n\n// Register a handler that runs when an event happens\nengine.on('nextDayCycle',function(){\n\n // Runs on every nextDayCycle trigger\n players.hunt();\n});\n\nengine.run();\n</code></pre>\n\n<p>As you can see, you can decouple events from the engine that holds the mechanism for time management.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T05:44:50.573",
"Id": "58855",
"Score": "0",
"body": "So basically, all my variables are stored in the object, and I make the functions into prototype inheritance? This is a solo player game, so I'm not worried about player registration (though I will decouple the objects). I don't quite understand how the register event works though, how does the code know when to check for the nextDayCycle?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T13:24:55.653",
"Id": "58897",
"Score": "0",
"body": "@RUJordan `registerEvent` stores functions that determine what period of time it is in an internal object. `on` stores functions (event handlers) that run when a certain period of time happens in another internal object. An internal timer will run, and on each tick, will evaluate all functions stored by `registerEvent`. If a function returns true, for example, the `nextDayCycle`, you look for all registered `nextDayCycle` handlers in the handlers object and run them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T15:43:47.153",
"Id": "58902",
"Score": "0",
"body": "Oh that's so clever and awesome! This will be perfect! However, won't `var engine = new Engine()` still be a global or is that unavoidable? (Is it really THAT bad to have a global like that?)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T13:07:30.433",
"Id": "59048",
"Score": "0",
"body": "@RUJordan Well, technically it's a global value for *your app*. But if your app is safely hidden away in a scope that is not the browser's global scope, then you're fine."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T11:23:29.527",
"Id": "36008",
"ParentId": "35989",
"Score": "4"
}
},
{
"body": "<p>Apart from what Joseph has said before, here are some small suggestions:</p>\n\n<p>Overall:</p>\n\n<ol>\n<li>Please create a namespace for all your object prototypes. Even though you don't want to use a library right now, some day when you'd want to do that, you surely don't want to be haunted by your decision to not use a namespace right now.</li>\n</ol>\n\n<p>element object:</p>\n\n<ol>\n<li>Since I come from a Rails background, I like to name my prototypes as singular and their collections as plural. So, I'd prefer <code>_element</code> over <code>_elements</code>.</li>\n<li>The name <code>elm</code> is not descriptive enough. Perhaps, <code>createElement</code> would do the method more justice.</li>\n<li>It's not clear how emptying out the className of an element would show it in <code>ShowElement</code>. You need to question your assumptions here. Is there one particular class you want to remove or all the classes to show the element?</li>\n<li>Why is <code>DisableElement</code> altering the HTML content of the element as well? You already seem to have another method for it.</li>\n<li><code>enableButton</code>, <code>bloodButton</code> and <code>raidButton</code> suddenly refers to a global variable engine. I thought we were getting rid of global variables. You probably want to use <code>bind()</code> to bind these functions to the global engine object.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T11:26:42.970",
"Id": "36009",
"ParentId": "35989",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "36008",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T22:23:53.677",
"Id": "35989",
"Score": "9",
"Tags": [
"javascript",
"html",
"game",
"dom"
],
"Title": "JavaScript Game Engine Design"
}
|
35989
|
<p>this tag should be used for questions pertaining to the <a href="http://php.net/manual/en/book.spl.php" rel="nofollow">Standard PHP Library</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T00:38:08.520",
"Id": "35993",
"Score": "0",
"Tags": null,
"Title": null
}
|
35993
|
Code Focused around the use of the Standard PHP Library
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T00:38:08.520",
"Id": "35994",
"Score": "0",
"Tags": null,
"Title": null
}
|
35994
|
<p>I want to implement something like C# Linq in C++</p>
<p>Currently only <code>select</code> and <code>where</code> is implemented, but others should be fairly easy if I can make a good structure.</p>
<p>The main concerns I have is I am not sure when to pass reference and when to pass value. Also how it works with different types (array type, lvalue, rvalue, const type, etc)</p>
<pre><code>namespace linq {
namespace detail
{
template <typename T>
struct IteratorBase
{
virtual ~IteratorBase() {}
virtual T operator *() const = 0;
virtual IteratorBase & operator++() = 0; // prefix ++
virtual bool operator==(const IteratorBase &other) const = 0;
bool operator!=(const IteratorBase &other) const { return !(other == *this); }
};
template <typename T>
struct Iterator : IteratorBase<T>
{
virtual std::unique_ptr<Iterator> copy() = 0;
};
template <typename T, typename InputIterator>
struct IteratorImpl : Iterator<T>
{
IteratorImpl() : _it() {}
IteratorImpl(const InputIterator &it) : _it(it) {}
~IteratorImpl() {}
T operator *() const { return *_it; }
IteratorBase<T> & operator++() { ++_it; return *this; };
bool operator==(const IteratorBase<T> &other) const
{
const IteratorImpl *otherptr = dynamic_cast<const IteratorImpl *>(&other);
if (otherptr) {
return _it == otherptr->_it;
}
return false;
}
std::unique_ptr<Iterator<T>> copy()
{
return std::unique_ptr<Iterator<T>>{ new IteratorImpl<T, InputIterator>(_it) };
}
private:
InputIterator _it;
};
template <typename T>
struct IteratorWrapper : IteratorBase<T>
{
template <typename InputIterator>
IteratorWrapper(const InputIterator &it) : _it(new IteratorImpl<T, InputIterator>(it)) {}
IteratorWrapper(const IteratorWrapper &other) : _it(other._it->copy()) {}
~IteratorWrapper() {}
T operator *() const { return *(*_it); }
IteratorBase<T> & operator++() { ++(*_it); return *this; }
bool operator==(const IteratorBase<T> &other) const {
const IteratorWrapper *otherptr = dynamic_cast<const IteratorWrapper *>(&other);
if (otherptr) {
return (*otherptr->_it) == (*_it);
}
return false;
}
private:
const std::unique_ptr<Iterator<T>> _it;
};
template <typename T, typename U>
struct SelectIterator
{
SelectIterator(const IteratorWrapper<T> &it, std::function<U(T)>func) : _it(it), _func(func) {}
U operator *() const { return _func(*_it); }
SelectIterator & operator++() { ++_it; return *this; }
bool operator==(const SelectIterator &other) const { return _it == other._it; }
private:
IteratorWrapper<T> _it;
std::function<U(T)> _func;
};
template <typename T>
struct WhereIterator
{
WhereIterator(const IteratorWrapper<T> &begin, const IteratorWrapper<T> &end, std::function<bool(T)>func) : _it(begin), _end(end), _func(func), _val()
{
validate();
}
WhereIterator(const IteratorWrapper<T> &end) : _it(end), _end(end), _func(), _val() {};
T operator *() const { return _val; }
WhereIterator & operator++() { ++_it; validate(); return *this; }
bool operator==(const WhereIterator &other) const { return _it == other._it; }
private:
void validate()
{
if (_it != _end) {
_val = *_it;
while (_it != _end && !_func(_val)) {
++_it;
_val = *_it;
}
}
}
T _val;
IteratorWrapper<T> _it;
IteratorWrapper<T> _end;
std::function<bool(T)> _func;
};
template <typename T>
struct Range
{
template <typename InputIterator>
Range(const InputIterator &begin, const InputIterator &end)
: _begin(begin), _end(end)
{}
IteratorWrapper<T> & begin() { return _begin; }
IteratorWrapper<T> & end() { return _end; }
template <typename Functor>
auto select(Functor func) -> Range<decltype(func(T()))>
{
using ReturnType = decltype(func(T()));
return { SelectIterator<T, ReturnType>(_begin, func), SelectIterator<T, ReturnType>(_end, func) };
}
Range where(std::function<bool(T)> func)
{
return { WhereIterator<T>(_begin, _end, func), WhereIterator<T>(_end) };
}
private:
IteratorWrapper<T> _begin;
IteratorWrapper<T> _end;
};
template <typename T>
struct ValueIterator
{
ValueIterator(T val) : _val(val) {}
T operator *() const { return _val; }
ValueIterator & operator++() { ++_val; return *this; }
bool operator==(const ValueIterator &other) const { return _val == other._val; }
private:
T _val;
};
}
using detail::Range;
template <typename T>
Range<T> range(T from, T end)
{
return { detail::ValueIterator<T>(from), detail::ValueIterator<T>(end) };
}
template <typename T>
Range<T> range(T end)
{
return { detail::ValueIterator<T>(T()), detail::ValueIterator<T>(end) };
}
template <typename FromType>
auto from(FromType f) -> Range<typename std::remove_reference<decltype(*std::begin(f))>::type>
{
return { std::begin(f), std::end(f) };
}
template <typename T>
auto from(std::initializer_list<T> f) -> Range<T>
{
return { std::begin(f), std::end(f) };
}
}
</code></pre>
<p>It can be used like this</p>
<pre><code>{
std::vector<int> vec = {1,2,3,4,5}; // some iterable
auto r =
linq::from(vec)
.where([](int i){ return i % 2;})
.select([](int i){ return i * i;})
;
for (auto obj : r)
{
std::cout << obj << "\n";
}
}
{
auto r =
linq::range(1, 30)
.where([](int i){ return i % 2;})
.select([](int i){ return i * i;})
;
for (auto obj : r)
{
std::cout << obj << "\n";
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T04:21:53.220",
"Id": "58842",
"Score": "0",
"body": "This is great. I don't know enough C++ to really answer your questions though (I'm much more of a C and C# guy!)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T06:03:53.677",
"Id": "58860",
"Score": "0",
"body": "I thought Linq failed as a DB extraction (or is now considered horrible). Could be wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T06:22:49.203",
"Id": "58861",
"Score": "0",
"body": "There is framework to convert linq expression to query. But I am refer to linq style functional approach to process list here. My code have nothing to do with DB."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T16:00:33.343",
"Id": "58904",
"Score": "1",
"body": "If you're just looking for this sort of capability, see http://cpplinq.codeplex.com/ - even if you want to write your own it may still be worth looking at some of the decisions they made (such as `operator>>` instead of dot-methods to enhance extensibility)."
}
] |
[
{
"body": "<p>I am not sure this is a good idea (nor do I think the cpplinq in @MichaelUrman's post is a good idea - though it's definitely workable).</p>\n\n<p>Basically you are writing a fully templated hierarchy of classes, to replace (existing, stable and presumably tested) functionality in std algorithm:</p>\n\n<p>Your code:</p>\n\n<pre><code>auto r =\nlinq::range(1, 30)\n.where([](int i){ return i % 2;})\n.select([](int i){ return i * i;})\n;\n\nfor (auto obj : r)\n{\n std::cout << obj << \"\\n\";\n}\n</code></pre>\n\n<p>std code:</p>\n\n<pre><code>std::vector<int> src{1, /**/, 29};\nstd::vector<int> x;\nstd::copy_if(src.begin(), src.end(), std::back_inserter(x), [](int i){ return i % 2;});\nstd::transform(x.begin(), x.end(), x.begin(), [](int i){ return i * i;});\n</code></pre>\n\n<p>You could create your own <code>transform_if</code>, combining the two functions above.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T19:56:09.300",
"Id": "59140",
"Score": "2",
"body": "Yes I agree the functionality are similar and performance of std algorithm is definitely better. but don't you think my way is easier to read/write? and my iterators are lazy evaluated so if I only need first N objects I only have to evaluate functors in `select`/`where` for first N objects. Maybe there is way to do this with std library but I don't know about it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T17:00:33.910",
"Id": "36148",
"ParentId": "35997",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T04:10:10.053",
"Id": "35997",
"Score": "11",
"Tags": [
"c++",
"linq",
"c++11",
"reinventing-the-wheel"
],
"Title": "C++ linq-like library"
}
|
35997
|
<p>The <a href="http://vanilla-js.com/" rel="nofollow">Vanilla.js framework</a> isn't actually a framework, but a joke about JavaScript frameworks. Using Vanilla.js means you're <em>not</em> using a framework.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T06:59:42.323",
"Id": "36000",
"Score": "0",
"Tags": null,
"Title": null
}
|
36000
|
For "vanilla" JavaScript. I.e. JavaScript written without using a framework or library.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T06:59:42.323",
"Id": "36001",
"Score": "0",
"Tags": null,
"Title": null
}
|
36001
|
<p>I'm reading <a href="http://rads.stackoverflow.com/amzn/click/1118185463" rel="nofollow"><em>Professional Node.js: Building Javascript Based Scalable Software</em></a> by Pedro Teixeira and created a web page responding with <a href="http://www.google.de" rel="nofollow">www.google.de</a>. Could you take a look at my code and let me know if the implementation is not good?</p>
<pre><code>var request = require('request');
var url = 'http://www.google.de'; // input your url here
// use a timeout value of 10 seconds
var timeoutInMilliseconds = 10 * 10000;
var opts = {
url : url,
timeout : timeoutInMilliseconds
};
require('http').createServer(function(req, res) {
res.writeHead(200, {
'Content-Type' : 'text/html'
});
request(opts, function(err, webRes, body) {
if (err) {
console.dir(err);
return;
}
var statusCode = webRes.statusCode;
console.log('status code: ' + statusCode);
res.write(body);
});
}).listen(4000);
</code></pre>
|
[] |
[
{
"body": "<p>Here are my suggestions:</p>\n\n<ul>\n<li>Get rid of the anonymous functions. They are notoriously difficult to test. I am hoping that you have written the test cases. If not, now would be a good time to try writing these tests.</li>\n<li>There is either a documentation or implementation bug where you want the timeout to be 10s (10000ms) but are actually using a value of <code>10*10000</code>ms which is 100s.</li>\n<li>Rather than calling a method directly on <code>require('http')</code>, I'd like it if you import it the way you have imported <code>request</code>.</li>\n<li>You are always sending back a response code of 200. You should wait till after the request has finished fetching the page and set the status code accordingly unless you have some way of serving the right content (using a cahed copy, for example).</li>\n</ul>\n\n<p>Other than that, I think that you have the actual functionality pretty much nailed down.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T11:00:43.510",
"Id": "36007",
"ParentId": "36003",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "36007",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T08:17:56.910",
"Id": "36003",
"Score": "1",
"Tags": [
"javascript",
"node.js",
"http",
"server",
"timeout"
],
"Title": "Node.JS HTTP server displaying Google"
}
|
36003
|
<p>I have attemped to define a function which scan an int value in a specified range and returns that value. The lower bound is the lower of the two parameters, the upper bound is the larger of the two parameters.After invalid input, the function displays a message and repeats input (and message, if necessary ) until a valid value is entered, which is then returned. </p>
<pre><code>public static int scanYear() {
do{
int year = TextIO.getInt();
if (checkDate (year) == true)
return year;
else
TextIO.put("year not in the allowed range");
}while (true);
} // end of scanYear
</code></pre>
<p>What is your opinion about the efficiency of the code , what can be improved ? Many thanks.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T16:53:47.420",
"Id": "58783",
"Score": "0",
"body": "Could you add the `checkDate` method as well?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T18:29:07.153",
"Id": "58790",
"Score": "0",
"body": "`if (checkDate (year) == true)` the `== true` is redundant"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T19:54:44.463",
"Id": "58795",
"Score": "0",
"body": "efficiency when you are waiting on user input is kinda unimportant"
}
] |
[
{
"body": "<p>When it comes to user-input, efficiency really is not the point.... what does it matter if it takes 4 milliseconds to validate some data, or 4 nanoseconds? The user component of time dwarfs the rest.... Obvioulsy, if the code was taking more than 10 milliseconds I would be concerned, but I doubt that is the case.</p>\n\n<p>With user-interface coding though, you have to think differently. In this case, you have to <strong>help</strong> the user. Specifically, telling a user that their input is wrong is more frustrating if you don't tell the user how to correct it....</p>\n\n<p>Saying: \" year not in the allowed range\" is going to lead to lots of frustration.</p>\n\n<p>Saying: \"year must be between 1950 and 2013\" is much better.</p>\n\n<p>EDIT: In fact, when prompting the user to enter the data, it should inform the user what values will be valid <strong>before</strong> getting the value:</p>\n\n<pre><code>Please enter a year between 1950 and 2013 (inclusive):\n...\nSorry, the value 2014 is not between 1950 and 2013, please enter a valid year:\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T16:57:55.220",
"Id": "36012",
"ParentId": "36011",
"Score": "3"
}
},
{
"body": "<p>Not much to review since you didn't provide us much but 2 small things </p>\n\n<ol>\n<li><p>In Java</p>\n\n<pre><code>if (checkDate (year) == true)\n</code></pre>\n\n<p>is same as</p>\n\n<pre><code>if (checkDate (year))\n</code></pre></li>\n<li><p><code>checkDate()</code> is validating a year from your context, so it should be <code>checkYear()</code> or <code>validateYear()</code>.</p></li>\n</ol>\n\n<hr>\n\n<p>Though I like to use flag (this is my opinion) for better understanding and code-refactoring.</p>\n\n<pre><code>public static int scanYear() {\n boolean isYearValid = false; \n int year = 0; \n do{\n int year = TextIO.getInt();\n if (checkYear(year))\n isYearValid = true;\n else\n TextIO.put(\"year not in the allowed range\");\n }while (!isYearValid);\n return year;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T18:21:21.217",
"Id": "36013",
"ParentId": "36011",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T16:36:32.930",
"Id": "36011",
"Score": "1",
"Tags": [
"java"
],
"Title": "Scanning an int variable"
}
|
36011
|
<p>I am doing my best to keep this code clean and fast, but as I add more to the game, it seems to get harder to maintain a frame-rate higher than 200! I believe that the culprit is a somewhat large <code>for</code> loop inside of the main loop. It performs all of the actions for the tiles inside of the world, and as more tiles are added, the game gets slower.</p>
<pre><code>import pygame
from pygame.locals import *
from random import choice
from math import sqrt
#inits
pygame.init()
font=pygame.font.Font(None, 18)
screen=pygame.display.set_mode((640,480))
pygame.display.set_caption('City Game | Pre-Alpha')
clock=pygame.time.Clock()
#sprites
curspr=pygame.image.load('curs.png').convert()
curspr.set_alpha(100)
grassspr=pygame.image.load('grass.png').convert()
roadspr=pygame.image.load('road.png').convert()
forestspr=pygame.image.load('forest.png').convert()
water1=pygame.image.load('water1.png').convert()
water2=pygame.image.load('water2.png').convert()
power1=pygame.image.load('power1.png').convert()
power2=pygame.image.load('power2.png').convert()
res=pygame.image.load('res.png').convert()
house1_0=pygame.image.load('house1_0.png').convert()
house1_1=pygame.image.load('house1_1.png').convert()
res.set_alpha(215)
#vars and lists
taxrateR=8
tilelist=[grassspr,roadspr,forestspr,water1,res,power1]
namelist=['Grass','Road','Forest','Water','Residental','Power Plant']
costlist=[5,10,20,50,100,250]
tiles=[]
sel=0
money=10000
mse=(0,0)
tileframe=2000
pop=0
month=1
year=1
monthtime=0
R=1
C=1
I=1
def Dist(set1,set2):
vec=(set2[0]-set1[0],set2[1]-set1[1])
dist=(vec[0]**2+vec[1]**2)
return sqrt(dist)
class Tile(object):
def __init__(self,pos,spr,typ):
self.typ=typ
self.spr=spr
self.pos=pos
self.rect=pygame.rect.Rect(pos[0],pos[1],32,32)
self.adv=0
self.haspower=0
while True:
pygame.display.set_caption(str(clock.get_fps()))
screen.fill((2,110,200))
key=pygame.key.get_pressed()
othertiles=[x for x in tiles if x.spr==power1 or x.spr==power2]
for e in pygame.event.get():
if e.type==QUIT:
exit()
if e.type==KEYUP:
if key[K_s]:
if e.key==K_e:
sel+=1
if sel==len(tilelist):
sel=0
if e.key==K_q:
sel-=1
if sel==-1:
sel=len(tilelist)-1
if e.type==MOUSEMOTION:
mse=pygame.mouse.get_pos()
if key[K_LSHIFT] or key[K_RSHIFT]:
if pygame.mouse.get_pressed()==(1,0,0):
tilesatmouse=[t for t in tiles if t.rect.collidepoint(mse)]
if not tilesatmouse:
if sel==4:
money-=costlist[sel]
tiles.append(Tile((mse[0] & 0x7fffffe0,mse[1] & 0x7fffffe0),tilelist[sel],'res'))
else:
money-=costlist[sel]
tiles.append(Tile((mse[0] & 0x7fffffe0,mse[1] & 0x7fffffe0),tilelist[sel],'tile'))
elif pygame.mouse.get_pressed()==(0,0,1):
for t in tiles:
if t.rect.collidepoint(mse):
money-=5
tiles.remove(t)
if e.type==MOUSEBUTTONUP:
if e.button==1:
tilesatmouse=[t for t in tiles if t.rect.collidepoint(mse)]
if not tilesatmouse:
if sel==4:
money-=costlist[sel]
tiles.append(Tile((mse[0] & 0x7fffffe0,mse[1] & 0x7fffffe0),tilelist[sel],'res'))
else:
money-=costlist[sel]
tiles.append(Tile((mse[0] & 0x7fffffe0,mse[1] & 0x7fffffe0),tilelist[sel],'tile'))
if e.button==3:
for t in tiles:
if t.rect.collidepoint(mse):
money-=5
tiles.remove(t)
for t in tiles:
if t.spr==water1 or t.spr==water2:
if tileframe>999:
t.spr=water1
else:
t.spr=water2
if t.spr==power1 or t.spr==power2:
if tileframe>999:
t.spr=power1
else:
t.spr=power2
if t.typ=='res':
for x in othertiles:
distance=Dist((t.pos[0],t.pos[1]),(x.pos[0],x.pos[1]))
if distance<2500:
t.haspower=1
else:
t.haspower=0
if othertiles==[]:
t.haspower=0
if t.haspower==0:
t.spr.set_alpha(100)
else:
t.spr.set_alpha(255)
if t.adv>=0:
t.adv+=R
if t.adv==2000:
t.spr=house1_0
if t.adv==4000:
t.spr=house1_1
pop+=choice([4,6,8,10])
t.adv=-1
screen.blit(t.spr,t.pos)
if monthtime<10000:
monthtime+=1
else:
month+=1
money+=20
monthtime=0
if month==13:
month=0
money+=pop/2*taxrateR
year+=1
screen.blit(curspr, (mse[0] & 0x7fffffe0,mse[1] & 0x7fffffe0))
if key[K_s]:
pygame.draw.rect(screen, (0,0,0), (0,0,640,80), 0)
moneydraw=font.render('Funds: '+str(money), 1, (255,255,255))
yeardraw=font.render('Year: '+str(year), 1, (255,255,255))
monthdraw=font.render('Month: '+str(month), 1, (255,255,255))
namedraw=font.render(namelist[sel],1,(255,255,255))
screen.blit(moneydraw, (2,2))
screen.blit(namedraw, (2,18))
screen.blit(yeardraw, (2,34))
screen.blit(monthdraw, (2,50))
clock.tick(999)
tileframe-=1
if tileframe==0:tileframe=2000
pygame.display.flip()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T21:45:35.170",
"Id": "58810",
"Score": "1",
"body": "When the framerate is at 200 (I presume 200 frames per second), and the human eye is more than satisfied at the movies with a framerate of < 30 fps, I have to wonder whether you are optimizing things too soon."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T23:46:51.203",
"Id": "58820",
"Score": "0",
"body": "Does your performance change if you put everything inside a function? Python has certain optimizations for locals that it doesn't have for globals."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T04:09:50.707",
"Id": "58841",
"Score": "1",
"body": "*Only* 200fps? You realize most monitors only refresh at 60 or 70 hertz?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T11:48:19.783",
"Id": "58890",
"Score": "0",
"body": "As the frame-rate drops, so does the performance. There isn't much of a change in the display, but elements in the game work more slowly as it drops below 190."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T12:35:16.047",
"Id": "58894",
"Score": "1",
"body": "there are game loops that will allow a constant game speed but you'll have to account for partial steps"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T21:23:12.583",
"Id": "58945",
"Score": "0",
"body": "How would you do this??"
}
] |
[
{
"body": "<p>I believe comparing images isn't of the greatest efficiency, replace the spr with a enum type value, then you don't need to swap over the image, or at least not compare them.</p>\n\n<p>also you keep changing the alpha on the images, duplicate the image and keep both versions, one with alpha 100 and one with alpha 255.</p>\n\n<p>I also found a bug in the <code>for x in othertiles:</code> loop body; the <code>if othertiles == []</code> is inside it so will never be reached; just initialize it before the loop. And only the last <code>othertile</code> actually matters in the loop as you overwrite <code>haspower</code> each time. you only need to find if there is any tile in otherTiles where Dist to it if smaller than 2500, I'm pretty sure there is a list comprehension for that, but I'm no python wiz.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T11:50:00.790",
"Id": "58891",
"Score": "0",
"body": "I replaced every classes `typ` attribute with one that holds it's selection number. I used this to compare instead of sprites. Thanks for your help!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T23:44:09.843",
"Id": "36019",
"ParentId": "36015",
"Score": "2"
}
},
{
"body": "<p>Humans are bad at figuring out where the slow spots are. You will need to ask the computer by profiling your code. As rolfl said, you're likely better off saving this for when you have more of your code in place and it does enough work that it's actually slowing down.</p>\n\n<p>It's quite possible most of your slowdown related to extra tiles comes from <code>othertiles=[x for x in tiles if x.spr==power1 or x.spr==power2]</code>; perhaps you should update <code>othertiles</code> incrementally as the board changes instead of recalculating it every <code>pygame.event</code>. Other than that, I'm going to concentrate on the inner <code>for t in tiles</code> loop. There are a couple things in there that stand out to me. They may or may not make a real difference to your code's performance.</p>\n\n<ul>\n<li>The overall body reads like an <code>if</code> tree, yet all scenarios are mutually exclusive. You can probably squeak a little better performance out by changing the second and later <code>if</code>s to <code>elif</code>s. Make sure they're ordered in terms of descending frequency. If the number of possibilities will grow larger, consider other approaches that don't require a series of <code>if</code> tests. (At some point the overhead of testing each alternative will likely be more expensive than that of using alternate lookups such as draw method on various tile classes.)</li>\n<li><p>The distance check loop in a <code>res</code> tile seems flawed. It executes a for loop, but only saves the result from the last element of <code>othertiles</code>. And for each element, it checks if <code>othertiles</code> is empty (aside: you should spell that <code>if othertiles:</code> rather than creating and comparing against an empty list every time). If you want the first result, you can fix both of these by using <code>break</code> and a <code>for/else</code> loop:</p>\n\n<pre><code>for x in othertiles:\n # distance calculation\n break\nelse:\n t.haspower = 0\n</code></pre>\n\n<p>(Alternately you could just set <code>t.haspower = 0</code>—or <code>False</code>—before the for loop, and let the for loop set it to <code>1</code>—or <code>True</code>—if applicable.)</p></li>\n<li>The distance calculation is computationally heavy. Like my comment on your <a href=\"https://codereview.stackexchange.com/questions/35914/pygame-can-someone-tell-me-how-to-make-this-code-faster\">previous post</a>, this is typically more relevant to C level code, but it's still good to remember that <code>sqrt</code> takes a while to calculate, so you can look for opportunities to avoid calling it. Consider that you compare <code>Dist(...)</code> to a constant <code>2500</code>. If instead of calling <code>sqrt</code> you just returned the square of the distance, you could compare to <code>6250000</code> and have the same effect.</li>\n<li>Calling the distance function, you tear <code>t.pos</code> and <code>x.pos</code> apart and piece it back together for a function that just uses their first two elements. You might save some effort, readability, and possibly gain a hint of performance by calling your distance function with just <code>Dist(t.pos, x.pos)</code>.</li>\n</ul>\n\n<p>Two more notes:</p>\n\n<ul>\n<li><p>You probably don't want just the first or last distance to a power tile. Instead you likely want the closest. This might be easier to handle with an approach like <code>distance = min(Dist(t.pos, x.pos) for x in othertiles)) if othertiles else 2501</code> or even better:</p>\n\n<pre><code>t.haspower = False\nif othertiles:\n t.haspower = min(Dist(t.pos, x.pos) for x in othertiles)) < 2500\n # or distance_squared and compare to 6250000 per third bullet\n</code></pre></li>\n<li><p>It's unusual in python to name your functions with initial capital letters. When I read the line <code>distance=Dist((t.pos[0],t.pos[1]),(x.pos[0],x.pos[1]))</code> I assumed it was instantiating a class (which would probably be even heavier than calculating a square root). I would suggest renaming this use all lowercase letters.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T02:47:24.233",
"Id": "58827",
"Score": "0",
"body": "Thanks! I updated my code! How can I display for you to check?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T23:45:31.153",
"Id": "36020",
"ParentId": "36015",
"Score": "4"
}
},
{
"body": "<p>I'd see what happens if you refactor drawing code out of the cel update loop. Let each sprite image maintain a list of bools corresponding to all of the available tile position (as the other commenters have noticed, make separate images for the different alpha versions of the same sprite instead of tweaking it on the fly.)</p>\n\n<p>As each tile updates, see if it's state has changed enough to warrant a sprite change. If it has, toggle the corresponding entry for the old sprite list off and the same entry in the new sprite list on. In general you won't be changing the lists that much (and by keeping them as fixed size lists instead of adding and removing them you won't have to worry about moving a lot of memory around). </p>\n\n<p>Once all the sprite image lists are set, just loop through each and draw a tile for every true value (you'll need a formula to get the 2-d position from the 1-d index of the bool, but that is basically just (tile_height * floor(index / columns), tile_width * int(index % columns))</p>\n\n<p>Hopefully this means (a) you do a lot less moving of memory around - the biggest category of changes is bools toggling on and off in fixed sized arrays - and (b) you can draw the same sprite many times, which should be more cache friendly for the graphics hardware, instead of constantly cycling different art in and out of memory.</p>\n\n<p>in this context you might want to google the phrase 'Data Oriented Design' or 'Mike Acton'</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T01:07:48.123",
"Id": "58823",
"Score": "0",
"body": "Also: ++ to the comment about bypassing the Dist function. You can probably make a simple integer table lookup without using sqrts that will be much less computationally intensive..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T01:01:04.810",
"Id": "36025",
"ParentId": "36015",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "36020",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T20:36:47.200",
"Id": "36015",
"Score": "3",
"Tags": [
"python",
"performance",
"game",
"pygame"
],
"Title": "SimCity clone with PyGame"
}
|
36015
|
<p>The class supplies a simple thread pool that uses the thread class from C++11.</p>
<p>When I schedule the job, I pass two <code>std::function<void()></code> objects that the pool will execute: the first function is the real job, the second is executed to send some sort of notification that the job has been done.</p>
<p>I'm not sure if I should merge the two std::function in one and let the user decide if to send the notification or not.</p>
<p>Additionally, not so sure about the naming <code>executeJob</code> vs <code>scheduleJob</code>.</p>
<p>The checking of <code>maxJobsInQueue</code> is not there yet, but when done I cannot decide between throwing exception when the queue is full vs blocking in <code>executeJob</code> until the job can be inserted.</p>
<p>Any other improvement you can suggest?</p>
<p><strong>evr_threadpool.h:</strong></p>
<pre><code>#ifndef EVR_THREADPOOL_H
#define EVR_THREADPOOL_H
#include <thread>
#include <vector>
#include <list>
#include <memory>
#include <functional>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <tuple>
/**
* @brief The ThreadPool class launches a pre-defined number of threads and
* keeps them ready to execute jobs.
*
* Each job is composed by two functions (std::function<void()>):
* the two functions are executed one after another, and the second one
* usually sends some sort of notification that the job has been done.
*
*/
class ThreadPool
{
public:
/**
* @brief Initializes the pool and launches the threads.
*
* @param numThreads number of threads to launch.
* @param maxJobsInQueue
*/
ThreadPool(size_t numThreads, size_t maxJobsInQueue);
/**
* @brief Destructors
*
* Sends a "terminate" signal to the threads and waits for
* their termination.
*
* The threads will complete the currently running job
* before checking for the "terminate" flag.
*/
virtual ~ThreadPool();
/**
* @brief Schedule a job for execution.
*
* The first available thread will pick up the job and run it.
*
* @param job a function that executes the job. It is called
* in the thread that pickec it up
* @param notificationJob a function that usually sends a notification
* that the job has been executed. it is executed
* immediately after the first function in the same
* thread that ran the first function
*/
void executeJob(std::function<void()> job, std::function<void()> notificationJob);
private:
/**
* @brief Function executed in each worker thread.
*
* Runs until the termination flag m_bTerminate is set to true
* in the class destructor
*/
void loop();
/**
* @brief Returns the next job scheduled for execution.
*
* The function blocks if the list of scheduled jobs is empty until
* a new job is scheduled or until m_bTerminate is set to true
* by the class destructor, in which case it throws Terminated.
*
* When a valid job is found it is removed from the queue and
* returned to the caller.
*
* @return the next job to execute
*/
std::pair<std::function<void()>, std::function<void()> > getNextJob();
/**
* @brief Contains the running working threads (workers).
*/
std::vector<std::unique_ptr<std::thread> > m_workers;
/**
* @brief Queue of jobs scheduled for execution and not yet executed.
*/
std::list<std::pair<std::function<void()>, std::function<void()> > > m_jobs;
/**
* @brief Mutex used to access the queue of scheduled jobs (m_jobs).
*/
std::mutex m_lockJobsList;
/**
* @brief Condition variable used to notify that a new job has been
* inserted in the queue (m_jobs).
*/
std::condition_variable m_notifyJob;
/**
* @brief This flag is set to true by the class destructor to signal
* the worker threads that they have to terminate.
*/
std::atomic<bool> m_bTerminate;
/**
* @brief This exception is thrown by getNextJob() when the flag
* m_bTerminate has been set.
*/
class Terminated: public std::runtime_error
{
public:
Terminated(const std::string& what): std::runtime_error(what) {}
};
};
#endif // EVR_THREADPOOL_H
</code></pre>
<p><strong>evr_threadpool.cpp</strong></p>
<pre><code>#include "evr_threadpool.h"
/*
* Constructor
*************/
ThreadPool::ThreadPool(size_t numThreads, size_t maxJobsInQueue):
m_workers(numThreads), m_bTerminate(false)
{
for(std::unique_ptr<std::thread>& worker: m_workers)
{
worker.reset(new std::thread(&ThreadPool::loop, this));
}
}
/*
* Destructor
************/
ThreadPool::~ThreadPool()
{
{
std::unique_lock<std::mutex> lockList(m_lockJobsList);
m_bTerminate = true;
m_notifyJob.notify_all();
}
for(std::unique_ptr<std::thread>& worker: m_workers)
{
worker->join();
}
}
/*
* Schedule a job
****************/
void ThreadPool::executeJob(std::function<void()> job, std::function<void()> notificationJob)
{
std::unique_lock<std::mutex> lockList(m_lockJobsList);
m_jobs.push_back(std::pair<std::function<void()>, std::function<void()> >(job, notificationJob));
m_notifyJob.notify_one();
}
/*
* Retrieve the next job to execute
**********************************/
std::pair<std::function<void()>, std::function<void()> > ThreadPool::getNextJob()
{
std::unique_lock<std::mutex> lockList(m_lockJobsList);
while(!m_bTerminate)
{
if(!m_jobs.empty())
{
std::pair<std::function<void()>, std::function<void()> > job = m_jobs.front();
m_jobs.pop_front();
return job;
}
m_notifyJob.wait(lockList);
}
throw Terminated("Thread terminated");
}
/*
* Function executed by each worker
**********************************/
void ThreadPool::loop()
{
try
{
for(;;)
{
std::pair<std::function<void()>, std::function<void()> > job = getNextJob();
job.first();
job.second();
}
}
catch(Terminated& e)
{
}
}
</code></pre>
|
[] |
[
{
"body": "<p>A few thoughts:</p>\n\n<ul>\n<li><p>If I understand this correctly, if one of your job functions throws an exception, it ends processing for your entire thread pool; Threads that are running (but did not throw an exception) will keep running, but the ThreadPool object may be deleted as part of stack unwinding. Consider adding another callback to your <code>executeJob</code> similar to <code>std::function<void(/* err details here */)> on_error</code>.</p></li>\n<li><p>Your <code>executeJob</code> function doesn't actually execute the job - I would rename it to \"enqueueJob\" or \"addJob\" or similar.</p></li>\n<li><p>Your Terminated class is a runtime error specialization, but your documentation (or anything in the code really) does not explain why it is a runtime error to have an empty queue.</p></li>\n</ul>\n\n<p>I assume you use this to stop, not to signal an error state. This may not look like a big thing, but a runtime_error (or specialization) should actually signal an error during the runtime of your applicaition).</p>\n\n<p>For example, the Visual Studio debugger can be set to break automatically when a runtime_error is thrown in the application. Using this implementation would screw up debugging without you meaning to.</p>\n\n<p>Consider either using a second condition variable (or similar) instead of throwing an exception, or adding docs to the source saying \"Terminate is a runtime_error specialization because having no jobs to run is an error in this and this case\".</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T15:45:07.337",
"Id": "36142",
"ParentId": "36018",
"Score": "8"
}
},
{
"body": "<p>You tagged this as <kbd>C++11</kbd> but the code looks like you want to make it C++03 compatible (most noticably the space in <code>> ></code> and the lack of <code>auto</code> inside for-loops). Most of my suggestions require C++11 and are wrong for C++03.</p>\n\n<ul>\n<li><p>You should add a few <code>std::move</code>s for efficiency, for example inside <code>ThreadPool::executeJob</code>:<br>\n<code>m_jobs.emplace_back(std::move(job), std::move(notificationJob));</code></p></li>\n<li><p>I do not see the point of <code>maxJobsInQueue</code>. Is there ever a reason to not pass <code>(size_t)-1</code> or equivalent? I would either remove that entirely and not worry about exceptions either or at least give it that default value.</p></li>\n<li><p>This comment is not easy enough to understand:</p>\n\n<pre><code>* Each job is composed by two functions (std::function<void()>):\n* the two functions are executed one after another, and the second one\n* usually sends some sort of notification that the job has been done.\n</code></pre>\n\n<p>What is the point of having two functions? Why not just have one? In a case where I have two functions <code>f</code> and <code>g</code> where <code>f</code> does work and <code>g</code> sends a notification I would just pass <code>[]{f(); g();};</code> and have the same effect with a simpler interface. In case I only have <code>f</code> and don't care about notifications I have to pass an empty lambda as <code>g</code>, which is suboptimal.</p></li>\n<li><p><code>ThreadPool::m_workers</code> is a <code>std::vector<std::unique_ptr<std::thread>></code>. What is the <code>unique_ptr</code> for? Just use a <code>std::vector<std::thread></code> instead. This changes the constructor code to something like</p>\n\n<pre><code>ThreadPool::ThreadPool(size_t numThreads, size_t maxJobsInQueue = (size_t)-1) :\n m_bTerminate(false)\n{\n m_workers.reserve(numThreads);\n for (size_t i = 0; i < numThreads; i++)\n m_workers.emplace_back(&ThreadPool::loop, this);\n}\n</code></pre></li>\n<li><p><code>m_jobs</code> is a <code>std::list<std::pair<std::function<void()>, std::function<void()>>></code>. As a rule of thumb linked lists are useful when you have nothing better to teach in a computer science class and when you require stable iterators. You do not seem to take advantage of either one, so I would suggest <code>std::deque</code> instead.</p></li>\n<li><p>I do not like most of the comments inside <code>evr_threadpool.cpp</code>. I know what a constructor and destructor looks like, so those comments add no information.<br>\n<code>Schedule a job</code> is a contradiction to the function name <code>executeJob</code>. Execute or schedule? Pick one for the function name and remove the comment.<br>\n<code>Retrieve the next job to execute</code> is somewhat confusing. The function is already called <code>getNextJob</code> so the <code>Retrieve the next job</code>-part is redundant. <code>to execute</code> means I can only get the job for executing, so bad things happen if I, say, use <code>getNextJob</code> to clear the queue in a <code>clear</code> function? Not sure what exactly the <code>to execute</code> part is meant to tell me.<br>\nI like the comment <code>Function executed by each worker</code> because it adds useful context information that I cannot see from looking at the <code>loop</code>-function.</p></li>\n<li><p>When testing your threadpool I needed a <code>wait_until_all_jobs_are_done</code>-function, because otherwise <code>ThreadPool</code>s destructor sets the terminate flag. Consider adding that function.</p></li>\n<li><p>Consider using <code>std::make_pair</code> instead of manually naming the types in situations like <code>m_jobs.push_back(std::pair<std::function<void()>, std::function<void()> >(job, notificationJob));</code>.<br>\n<code>m_jobs.push_back(std::make_pair(job, notificationJob));</code> looks nicer.</p></li>\n<li><p>I would consider making a <code>typedef</code> or <code>using</code> declaration for <code>std::pair<std::function<void()>, std::function<void()>></code>. Not because the type is complicated or long, but because the type is duplicated across the code. If you figure out that the second function should get an <code>enum ErrorType</code> parameter so the notification can tell what happened you have a lot of error prone copy and paste to do which could be done in a single place instead.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-03T12:11:56.303",
"Id": "64642",
"ParentId": "36018",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "36142",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T22:51:04.810",
"Id": "36018",
"Score": "16",
"Tags": [
"c++",
"multithreading",
"c++11"
],
"Title": "Thread pool on C++11"
}
|
36018
|
COBOL (COmmon Business Oriented Language) was the product of a US Department of Defense initiative to develop a standard and portable programming language for business applications.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T00:36:04.773",
"Id": "36023",
"Score": "0",
"Tags": null,
"Title": null
}
|
36023
|
<p>I have this CSS selector:</p>
<pre><code>.img + *{
}
</code></pre>
<p>Which, from my understanding, will make the browser look for all the elements and then select only those which follow an element with the class <code>img</code>. Is there a better way of writing this selection to improve performance?</p>
<p>Relevant HTML structure:</p>
<pre><code><div class="media">
<div class="img">
<img src="an-image.jpg">
</div>
<random-element>content is here</random-element>
</div>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T23:10:28.817",
"Id": "59163",
"Score": "1",
"body": "Your understanding that it selects \"only \\[elements\\] which are being followed by an element with the class `img`\" is incorrect. It selects only elements which _follow_ an element with the class `img`. Your HTML excerpt, however, suggests that you correctly expect that your CSS selector selects `<random-element>`. http://www.w3.org/TR/CSS2/selector.html#adjacent-selectors"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T14:59:34.837",
"Id": "59275",
"Score": "0",
"body": "@200_success I interpreted the `<random-element/>` to be a placeholder to show where the content that can be modified starts and ends. In the templating library I use, custom tags like this are used as hooks for placing dynamic content and do not actually appear in the rendered document's source. While you are technically correct, it may not apply in this particular instance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-14T16:33:09.757",
"Id": "315566",
"Score": "0",
"body": "Can you show how you're measuring performance? I assume you're most interested in speed, but are you measuring memory (working set and/or virtual) or any other factors?"
}
] |
[
{
"body": "<p>Here is something that you could do in your HTML, you could get rid of the <code><div class=\"img></code> </p>\n\n<p>this looks like it would be extra code for you to write, anything that you can style on a <code>div</code> you should be able to style on the <code><img></code> tag as well, you can also give your image tag an attribute of <code>class=\"img\"</code> </p>\n\n<p>if you know that you want to change the style on every <code><img></code> tag on the document, you could do your CSS like this,</p>\n\n<pre><code>img\n{\n /* Style */\n}\n</code></pre>\n\n<p>this will change the style for all image tags in the document, and later if you want a one image to be different then you would give that specific image tag a class of <code>whatever</code>and do this (after the previous <code>img</code> styling)</p>\n\n<pre><code>img.whatever\n{\n /* different Style */\n}\n</code></pre>\n\n<p>this will override only the styles that you specify, for this specific image tag</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T22:00:18.763",
"Id": "59146",
"Score": "3",
"body": "There are plenty of styles that cannot be applied to img elements: before/after pseudo elements, `display: table`, etc. The styles are meant to apply to the element that *follows* the `.img` element, and modifying the markup is out of the question anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T23:55:08.790",
"Id": "59170",
"Score": "0",
"body": "@cimmanon, good point."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T16:48:54.527",
"Id": "36059",
"ParentId": "36026",
"Score": "1"
}
},
{
"body": "<p>My recommendation would be to not worry about the performance (see: <a href=\"http://www.kendoui.com/blogs/teamblog/posts/12-09-28/css_tip_star_selector_not_that_bad.aspx\" rel=\"nofollow\">http://www.kendoui.com/blogs/teamblog/posts/12-09-28/css_tip_star_selector_not_that_bad.aspx</a> for actual tests).</p>\n\n<p>If you're still not convinced that it's not as bad as everyone makes it out to be, then your only real option is to modify the contents of <code><random-element /></code>.</p>\n\n<pre><code><div class=\"media\">\n <div class=\"img\">\n <img src=\"an-image.jpg\">\n </div>\n <random-element><div id=\"foo\">content is here</div></random-element>\n</div>\n</code></pre>\n\n<p>Which allows your CSS to be:</p>\n\n<pre><code>.img + #foo { ... }\n</code></pre>\n\n<p>Or just</p>\n\n<pre><code>#foo { ... }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T22:11:20.100",
"Id": "36162",
"ParentId": "36026",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "36162",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T01:01:58.210",
"Id": "36026",
"Score": "5",
"Tags": [
"performance",
"css"
],
"Title": "CSS selector for image captions"
}
|
36026
|
<p>I've implemented a working version of Array#uniq in Ruby to answer the question here: <a href="http://www.rubeque.com/problems/like-a-snowflake" rel="nofollow">http://www.rubeque.com/problems/like-a-snowflake</a>, but I'd like to see if there's ways to clean up my code or some better practices I should follow? This is my version:</p>
<pre><code>class Array
def uniq(&block)
objs = []
yield_vals = []
self.each do |obj|
yield_val = yield obj
unless yield_vals.include?(yield_val)
yield_vals.push(yield_val)
objs.push(obj)
end
end
objs
end
end
</code></pre>
|
[] |
[
{
"body": "<p>For one, I'd use the <code><<</code> operator rather than <code>push</code> just out of convention.</p>\n\n<p>Second, you still have other Array/Enumerable methods at your disposal. So there's no need to create a new array and add unique items to it. Try filtering the array instead.</p>\n\n<p>Update: Whoo boy, I was still asleep when I wrote that first answer. In my defense it <em>was</em> early</p>\n\n<p>You can actually just do</p>\n\n<pre><code>def uniq(&block)\n group_by(&block).values.map(&:first)\nend\n</code></pre>\n\n<p>As for my previous answer... well, I did say it could be done better. Just pretend it didn't happen.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T21:43:44.860",
"Id": "58951",
"Score": "0",
"body": "Great! Thanks a lot, both of your solutions really helped me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T22:00:23.657",
"Id": "58957",
"Score": "0",
"body": "Nice simple solution. Only that you pay a bit of storage penalty."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T10:51:15.770",
"Id": "59030",
"Score": "0",
"body": "@tokland thanks, and yeah, I'm not claiming this is particularly efficient, nor does it match the built-in `Array#uniq` (this one requires a block). I was just aiming for a solution that would pass the (rather narrow) Rubeque tests"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-01T04:40:10.930",
"Id": "59720",
"Score": "0",
"body": "Wouldn't `group_by(&block).keys` be more straigtforward?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-01T11:32:05.757",
"Id": "59726",
"Score": "1",
"body": "@CarySwoveland That wouldn't work, I'm afraid. The keys produced by `group_by` are the result of the block - not the actual array values. So you wouldn't get the unique values of the original array, but something else. I.e. `[1.1, 2.2].group_by(&:to_i).keys` would give you `[1, 2]` instead of the expected `[1.1, 2.2]`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T03:46:46.503",
"Id": "63596",
"Score": "0",
"body": "Back after almost a month, wondering what I was thinking."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T07:06:53.360",
"Id": "36039",
"ParentId": "36027",
"Score": "3"
}
},
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li>Ruby's <code>Array#uniq</code> works with and without a block, yours probably should do the same.</li>\n<li><code>Array#include?</code> is O(n), so it's not a good idea to use it within loops. Sets and hashes, on the other hand, do have O(1) inclusion predicates.</li>\n<li>Your solution is very, very imperative (do this, do that), I'd try a more functional approach (based on expressions instead of change of state).</li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>class Array\n def my_uniq\n reduce(Hash.new) do |acc, x|\n key = block_given? ? yield(x) : x\n acc.has_key?(key) ? acc : acc.update(key => x)\n end.values\n end\nend\n</code></pre>\n\n<p>Note that if we had the abstraction <code>Hash#reverse_update</code> in the core (it's in <a href=\"http://rubydoc.info/docs/rails/Hash%3areverse_update\" rel=\"nofollow\">active_support</a>) the block could be simplified: <code>acc.reverse_update((block_given? ? yield(x) : x) => x)</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T09:19:51.217",
"Id": "59022",
"Score": "0",
"body": "Using Fold without reducing dimensions of a vector looks fun, but is actually bad."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T09:23:50.993",
"Id": "59023",
"Score": "0",
"body": "@Nakilon: why is it bad?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T03:44:22.583",
"Id": "63595",
"Score": "0",
"body": "A slight variant: `each_with_object({}) {|x,acc| acc[block_given? ? yield(x) : x] = x}.values`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T19:38:09.477",
"Id": "64624",
"Score": "0",
"body": "@CarySwoveland: Note that you should not override values already present in the accumulator."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T21:29:25.313",
"Id": "36077",
"ParentId": "36027",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T01:05:38.973",
"Id": "36027",
"Score": "4",
"Tags": [
"ruby",
"array"
],
"Title": "Implementing Array#uniq in Ruby"
}
|
36027
|
<p>Looking for reviewers to suggest optimization and improvements, and to evaluate coding practices.</p>
<pre><code>final class Variables {
private final int x;
private final int y;
Variables(int x2, int y2) {
this.x = x2;
this.y = y2;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override public String toString() {
return "x = " + x + " y = " + y;
}
}
public final class FindMissing {
private FindMissing() {};
/**
* Takes an input a sorted array with two variables that repeat in the
* range. Remaining variable are consecutive. and returns two variables that repeats
*
* eg: for a range of 1,2,3,4, a valid input is [1, 4], [1, 3] etc.
*
* @param a : the sorted array.
*/
/*
* Why is start needed ?
* If start is not given then if a1 is empty how do we know if missing numbers were
* [1, 2] or [4, 5] ??.
*/
public static Variables sortedConsecutiveTwoMissing (int[] a, int startOfRange) {
if (a == null) throw new NullPointerException("a1 cannot be null. ");
int low = startOfRange;
// calculating the highest value of the range. it needs to be 2 more than length since all elememts are consecutive.
int high = startOfRange + (a.length - 1) + 2;
int i = 0;
boolean foundX = false;
int x = 0;
while (i < a.length) {
if (a[i] != low) {
if (foundX) {
return new Variables(x, low);
} else {
x = low;
foundX = true;
}
} else {
i++;
}
low++;
}
return new Variables(x, high);
}
public static void main(String[] args) {
// unsortedConsecutiveTwoMissing
int[] a6 = {1, 4};
System.out.println("Expected 2 and 3, Actual " + sortedConsecutiveTwoMissing(a6, 1));
// unsortedConsecutiveTwoMissing
int[] a7 = {-4, -1};
System.out.println("Expected -3 and -2, Actual " + sortedConsecutiveTwoMissing(a7, -4));
int[] a8 = {-4, -3, -2, -1};
System.out.println("Expected 0 and 1, Actual " + sortedConsecutiveTwoMissing(a8, -4));
int[] a9 = {5};
System.out.println("Expected 4 and 6, Actual " + sortedConsecutiveTwoMissing(a9, 4));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T03:45:29.377",
"Id": "58836",
"Score": "0",
"body": "I am not convinced that this code works.... `low` is initialized to an index in the array, but then it is compared to a value in the array `if (a1[i] != low)`. This makes no sense... is `low` an index, or a value? Can it possibly be both?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T05:50:11.703",
"Id": "58859",
"Score": "0",
"body": "@rolfl: Start is not an index. It's the start of the value range (like the smallest number in the range)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T09:44:05.747",
"Id": "58873",
"Score": "1",
"body": "Can you provide us some test cases. I think for some cases your code will not behave as like you think. Specially how are you invoking the method, I mean the parameters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T14:38:14.490",
"Id": "58899",
"Score": "1",
"body": "This code is buggy, provided the method is supposed to do what its name says it does: `\"x = 6 y = 6\".equals(FindMissing.sortedConsecutiveTwoMissing(new int[]{5}, 4).toString())`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T03:49:49.047",
"Id": "58988",
"Score": "0",
"body": "@tintinmj provided test cases"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T03:50:13.770",
"Id": "58989",
"Score": "0",
"body": "@abuzittingillifirca rectified bug thanks for pointing out"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T10:16:13.443",
"Id": "59027",
"Score": "0",
"body": "Still your Javadoc doesn't match with the parameters and code."
}
] |
[
{
"body": "<p>You say the problem is to find missing values from a 'Range', but your method only takes a start value, not an end value.... is this intentional? The method comment says:</p>\n\n<blockquote>\n <p>Takes an input a sorted array with two variables that repeat in the range. and returns two variables that repeats</p>\n</blockquote>\n\n<p>The method does nothing of the sort though... it takes one variable, and there's no indication the values repeat, and it returns <strong>missing</strong> values, not repeats.</p>\n\n<p>Additionally, the method name is <code>sortedConsecutiveTwoMissing</code> but there's nothing in the implementation that suggests that the values have to be consecutive at all...</p>\n\n<p>Also you suggest the array is sorted, but not whether it is unique... for example, your code may break on (missing is 3 and 5):</p>\n\n<pre><code>0 1 2 2 4 4 6 6 7 8 9\n</code></pre>\n\n<p>General / Code Style</p>\n\n<ul>\n<li>Variables like <code>a1</code> make me want to look for <code>a2</code>, <code>a3</code>, etc. Unless it's obvious, don't use numbered variables.</li>\n<li><code>int high = start + (a1.length - 1) + 2;</code> should have a comment .... the <code>+ 2</code> is not obvious, and magic numbers should either be very obvious, or documented. That line still makes no sense to me at all.... and <code>high</code> is not used for anything reasonable anyway.</li>\n<li><code>calculatedX</code> is not a calculated anything</li>\n</ul>\n\n<p>At this point I don't believe the code does what you suggest it should, so I don't believe the code works... downvote time.</p>\n\n<p>Edit the code, make it work....</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T07:57:46.917",
"Id": "58864",
"Score": "0",
"body": "range takes start - yes its intentional. end or highbound can be computed from arraysize and knowledge that 2 elements are missing"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T07:58:17.277",
"Id": "58865",
"Score": "0",
"body": "nothing of the sort though - javadoc make it very clear that function expects sorted array"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T08:00:01.503",
"Id": "58866",
"Score": "0",
"body": "nothing in the implementation that suggests that the values have to be consecutive at all...-- what do u suggest i should do ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T08:01:34.887",
"Id": "58867",
"Score": "0",
"body": "for example, your code may break on (missing is 3 and 5): -- the code demands that only 2 variables should repeat. if 3 or more repeat then its breaking function contract. Please lets assume input is sorted consecutive with only two elements occuring twice and give feedback"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T08:02:27.703",
"Id": "58868",
"Score": "0",
"body": "code works - please dont downvote unless really needed, as it might prevent me get valuable feedback otherwise"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T08:02:51.143",
"Id": "58869",
"Score": "0",
"body": "regarding the remaining feedback - they were useful and thanks for that"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T12:20:21.077",
"Id": "58893",
"Score": "0",
"body": "I can now see that `start` in an obscure way makes sense. I have withdrawn my close vote, but, the other issues I have listed make it very challenging to make sense of the code. The Down-vote remains until you make your question a whole lot easier to understand.... it's still very unclear."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T03:52:03.497",
"Id": "58992",
"Score": "0",
"body": "did the required, added more sensible javadoc and comments."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T03:58:01.743",
"Id": "58994",
"Score": "1",
"body": "Down-vote now un-down-voted."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T03:52:16.523",
"Id": "36032",
"ParentId": "36031",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "36032",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T03:07:29.733",
"Id": "36031",
"Score": "4",
"Tags": [
"java",
"algorithm",
"array"
],
"Title": "Find two missing elements from a sorted array in given range"
}
|
36031
|
<p>I want a git repository, accessible over ssh, to be read-only when used with certain keys. With other keys access to the full system is okay.</p>
<p>Here is my solution.</p>
<p>git-readonlyshell:</p>
<pre><code>if echo "$2" | egrep -q ^git-upload-pack; then
sh -c "$2"
else
echo Error: read only access 1>&2
fi
</code></pre>
<p>.ssh/authorized_keys:</p>
<pre><code>command="./git-readonlyshell -c \"$SSH_ORIGINAL_COMMAND\"" ...
</code></pre>
<p>Thoughts?</p>
<p>Any scenario in which this would break?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T04:29:13.060",
"Id": "58845",
"Score": "2",
"body": "Why not just have a user that is read-only for the repository and use one user for full-access, and the other for read-only?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T04:35:44.643",
"Id": "58852",
"Score": "0",
"body": "@rolfl I could. But then I have to specify a longer path after the `:`, meaning `user@server:/full/path/to/repo`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T07:34:16.880",
"Id": "58863",
"Score": "2",
"body": "@nafg: Can you please roll back your last edit if it was in response to GoodPerson's answer? The answer becomes somewhat pointless when you edit your question like this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T10:21:19.500",
"Id": "58881",
"Score": "1",
"body": "@ChrisWue: I rolled back the edit, so that the answer makes sense again. nafg: If you want to ask a follow-up question, you should *append* it to the original question instead of changing your question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T07:01:40.770",
"Id": "59544",
"Score": "0",
"body": "@ChrisWue: trying to recall, are you talking about the fact that I added \"Any scenario in which this would break?\" If so no, it was no in response to GoodPerson's answer, it was my original intention and I realized I had been unclear."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T07:02:26.447",
"Id": "59545",
"Score": "0",
"body": "@GarethRees: maybe I'm forgetting something, if you're talking about the fact that I added \"Any scenario in which this would break?\" then how was that not \"appending\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T07:07:16.493",
"Id": "59546",
"Score": "0",
"body": "Wait, are you guys talking about the switch from && to if/else with an error message? If so I don't see why that bothers you. My original script was with if/else. I had posted the && on IRC for brevity, and I mistakenly had copy-pasted that version to Code Review rather than my actual code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T07:10:32.803",
"Id": "59547",
"Score": "0",
"body": "I just realized you're probably talking about printf vs. echo, okay I see your point... Any objection if I un-rollback except for that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T07:44:40.157",
"Id": "59548",
"Score": "0",
"body": "@nafg: Sure, just keep the code as you posted it originally so the answer still makes sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-05T16:03:30.607",
"Id": "60370",
"Score": "0",
"body": "Maybe you can find inspiration in gitolite"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T20:37:55.870",
"Id": "61266",
"Score": "0",
"body": "@Asenar: heh, actually I use gitolite on another server. For better or worse I chose not to use it in this case (a discussion of why would be more applicable to a SO question than code review though)"
}
] |
[
{
"body": "<p>Should be</p>\n\n<pre><code>printf \"%s\\n\" \"$2\" | grep -E \"^git-upload-pack\" && sh -c \"$2\"\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li><code>sh</code> not <code>bash</code> for portability</li>\n<li>The <code>printf</code> instead of <code>echo</code> is for safety. What happens if someone puts <code>\"-n foo\"</code> as <code>\"$2\"</code>?</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-02-28T07:26:55.757",
"Id": "360083",
"Score": "0",
"body": "It is insecure. The `$SSH_ORIGINAL_COMMAND` can contain multiple command-lines, e.g., `git-upload-pack dummy; cat /etc/passwd`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T04:30:45.930",
"Id": "36036",
"ParentId": "36034",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "36036",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T04:24:29.950",
"Id": "36034",
"Score": "3",
"Tags": [
"shell",
"git"
],
"Title": "Make a git repository read-only over ssh depending on the key used"
}
|
36034
|
<p>This is a school project that I am turning in late. The prof suggested that i somehow prove myself by improving upon the basic code. This is really tough to do for someone who is just starting to learn to code. </p>
<p>Is there something I can do to: </p>
<ol>
<li>add onto the code (have it do or ask something different)?</li>
<li>make it even more simple than it probably already is (unlikely)?</li>
<li>though it's counter intuitive, make it more complicated by adding a function or something similar? </li>
</ol>
<p>I have really looked at this and now that I've actually coded it, I don't know how to improve it.</p>
<pre><code>print("This program computes a cable bill")
account = input("Enter account number: ")
cust_type = input("Enter customer type: R (Residental) or B (Business): ")
def residential():
premium_channels = int(input("Enter number of premium channels used: "))
processing_fee = 4.50
basic_service_fee = 20.50
premium_channel_fee = 7.50
amount = processing_fee + basic_service_fee + (premium_channels * premium_channel_fee)
return (amount)
def business():
basic_connections = int(input("Enter number of basic service connections: "))
premium_channels = int(input("Enter number of premium channels used: "))
processing_fee = 15.0
basic_service_fee = 75.0
preimum_channel_fee = 50.0
if (basic_connections <= 10):
amount = processing_fee + basic_service_fee + (premium_channels * preimum_channel_fee)
else:
amount = processing_fee + basic_service_fee + ((basic_connections - 10) * 5) + (premium_channels *
preimum_channel_fee)
return (amount)
if (cust_type == "R"):
bill_amount = residential()
else:
bill_amount = business()
print("Account number: ", account)
print("Amount due: ", bill_amount)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T04:34:42.613",
"Id": "58851",
"Score": "3",
"body": "Adding code or functionality is off-topic for this site. Improving existing code is within scope. I've tagged this as [tag:homework] to indicate that answers should provide hints and suggestions rather than complete code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T04:51:58.980",
"Id": "58853",
"Score": "4",
"body": "This question appears to be off-topic because it is about code that is not yours."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T05:45:12.693",
"Id": "58856",
"Score": "1",
"body": "@rolfl: What makes you think that it's not his code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T11:33:01.790",
"Id": "58887",
"Score": "0",
"body": "@ChrisWue : `This is a school project that I am turning in late. The prof suggested that i somehow prove myself by improving upon the basic code` - I take that to mean this is example code he has to improve on.... i.e. he did not write it, but wants to alter it. On second reading, it could also be interpreted that it is his code....."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T11:36:24.490",
"Id": "58888",
"Score": "0",
"body": "@ChrisWue ... Walt can post a comment here, or edit his question and attempt to reopen."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T18:44:10.753",
"Id": "58937",
"Score": "2",
"body": "@rolfl: Well `now that I've actually coded it, I don't know how to improve it.` seems a pretty string indicator that he did it himself."
}
] |
[
{
"body": "<p>If you've learned object-oriented programming, you might see how the residential and business functions could share code by becoming classes (or more likely a class and a subclass)</p>\n\n<p>If you haven't looked at OO, think about refactoring the way 'business' and 'residential' work to avoid having methods which differ only in hard-coded constants.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T06:38:50.563",
"Id": "36037",
"ParentId": "36035",
"Score": "0"
}
},
{
"body": "<ul>\n<li>Placing all the input and output in a separate function would improve the structure of program.</li>\n<li>Computing the bill follows the exact same logic for both types of connection; they are just using a different price list. You could use a data structure to represent the price list, and pass it to the billing function as a parameter.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T06:59:34.787",
"Id": "36038",
"ParentId": "36035",
"Score": "1"
}
},
{
"body": "<ul>\n<li><p>It is rare for a company to process one invoice at a time; turn it into a function, then write another function which applies it to each row in a .csv file and writes the results to another .csv file.</p></li>\n<li><p>Add some business rules, like 'Residential accounts get 20% off for the first 6 months of their subscription' (this obviously requires a sign-up date and some calendar math).</p></li>\n<li><p>Does the company use different sets of account numbers for business and residential customers? Maybe you could autodetect customer type from the account number instead of prompting for it?</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-30T03:00:39.117",
"Id": "36392",
"ParentId": "36035",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T04:26:03.980",
"Id": "36035",
"Score": "1",
"Tags": [
"python",
"beginner"
],
"Title": "Computing cable bills using F(x)'s"
}
|
36035
|
<p>Probably the hardest part of learning lisp has been to think in the "lisp way" which is elegant and impressive, but not always easy. I know that recursion is used to solve a lot of problems, and I am working through a book that instead uses <code>apply</code> to solve a lot of problems, which I understand is not as lispy, and also not as portable.</p>
<p>An experienced lisper should be able to help with this logic without knowing specifically what <code>describe-path</code>, <code>location</code>, and <code>edges</code> refer to. Here is an example in a book I am working through:</p>
<pre><code>(defun describe-paths (location edges)
(apply (function append) (mapcar #'describe-path
(cdr (assoc location edges)))))
</code></pre>
<p>I have successfully rewritten this to avoid <code>apply</code> and use recursion instead. It seems to be working:</p>
<pre><code>(defun describe-paths-recursive (location edges)
(labels ((processx-edge (edge)
(if (null edge)
nil
(append (describe-path (first edge))
(processx-edge (rest edge))))))
(processx-edge (cdr (assoc location edges)))))
</code></pre>
<p>I would like some more seasoned pairs of eyes on this to advise if there is a more elegant way to translate the <code>apply</code> to recursion, or if I have done something unwise. This code seems decent, but would there been something even more "lispy" ?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T09:55:10.227",
"Id": "58877",
"Score": "0",
"body": "why do you think using apply is a bad style? I saw several similar opinions, but didn't get any arguments for that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-25T14:01:44.940",
"Id": "67263",
"Score": "0",
"body": "Using `apply` isn't non-Lispy, but using `(apply function ...)` can be an issue if you don't know how big the list can be."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-25T14:06:14.307",
"Id": "67265",
"Score": "0",
"body": "Cross posted on StackOverflow http://stackoverflow.com/q/20188008/1281433."
}
] |
[
{
"body": "<h1>Lisp is a multiparadigm language.</h1>\n\n<p><a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_apply.htm\" rel=\"nofollow\"><code>apply</code></a> is just as lispy as recursion, and, in a way, much more so (think in HOFs)!</p>\n\n<h1>Style</h1>\n\n<ol>\n<li><p>Please fix indentation.</p></li>\n<li><p>Please write <code>#'foo</code> instead of <code>(function foo)</code>.</p></li>\n</ol>\n\n<h1>Implementations</h1>\n\n<p>The first (HOF) version can be much more efficiently rewritten in using <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_mapc_.htm\" rel=\"nofollow\"><code>mapcan</code></a> (provided <code>defscribe-path</code> returns fresh lists):</p>\n\n<pre><code>(defun describe-paths (location edges)\n (mapcan #'describe-path\n (cdr (assoc location edges)))))\n</code></pre>\n\n<p>The second (recursive) version can be made tail recursive using an accumulator. This would help some compilers produce better code.</p>\n\n<pre><code>(defun describe-paths-recursive (location edges)\n (labels ((processx-edge (edge acc)\n (if (null edge)\n acc\n (processx-edge (rest edge) \n (revappend acc (describe-path (first edge)))))))\n (nreverse (processx-edge (cdr (assoc location edges))))))\n</code></pre>\n\n<p>Note the use of <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_revapp.htm\" rel=\"nofollow\"><code>revappend</code></a>/<a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_revers.htm\" rel=\"nofollow\"><code>nreverse</code></a> instead of <code>append</code> to avoid quadraticity.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T09:30:09.327",
"Id": "59025",
"Score": "0",
"body": "is the accumulator a requirement for tail recursion optimization, or just a hint that could potentially be ignored?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T14:26:08.483",
"Id": "59061",
"Score": "0",
"body": "I don't think you can avoid an accumulator if you write a tail recursive version, but you can try (or maybe I did not understand your question)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T14:31:40.890",
"Id": "36050",
"ParentId": "36042",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "36050",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T08:58:32.067",
"Id": "36042",
"Score": "2",
"Tags": [
"recursion",
"lisp",
"common-lisp"
],
"Title": "Rewrite apply function to use recursion instead"
}
|
36042
|
<p>I have written some code to search a for a pattern in a list of tuples. </p>
<p>It works, but I am sure that it can be improved. Any feedback or ideas would be greatly appreciated.</p>
<p>The list of tuples I am searching in looks like this:</p>
<blockquote>
<p>x = [('A', True), ('B', True), ('C', False), ('D', False),
('X', False), ('E', True), ('F', True), ('G', True)]</p>
</blockquote>
<p>I want to find X and then also grab all the values in the tuple adjacent to X that have a value of true.</p>
<p>So the expected output would be:</p>
<blockquote>
<p>X E F G</p>
</blockquote>
<p>For:</p>
<blockquote>
<p>y = [('X', True), ('1', True), ('2', True), ('3', True), ('4', False), ('5', True)]</p>
</blockquote>
<p>The expected output would be:</p>
<blockquote>
<p>X 1 2 3</p>
</blockquote>
<p>For:</p>
<blockquote>
<p>z = [('Dog', True), ('Cow', False), ('Shark', True), ('Cat', True), ('X', False)]</p>
</blockquote>
<p>The expected output would be:</p>
<blockquote>
<p>Shark Cat X</p>
</blockquote>
<p>For:</p>
<blockquote>
<p>z = [('C', True), ('X', False), ('D', True), ('C', False), ('S', True)]</p>
</blockquote>
<p>The expected output would be:</p>
<blockquote>
<p>C X D</p>
</blockquote>
<p>This is my code:</p>
<pre><code>test = [('A', False), ('B', False), ('C', True), ('D', True),
('E', True), ('X', False), ('G', True), ('H', False)]
def find_x(x):
for item in x:
if item[0] == 'X':
index = x.index(item)
return(index)
return(None)
def look_around(x, index):
left = 0
right = len(x)-1
found_left = False
found_right = False
#look left:
if index != 0:
for i in range(index, -1, -1):
if x[i][1] == True:
left = i
found_left = True
if x[i][1] == False and i != index:
break
#look right
if index != len(x)-1:
for i in range(index, len(x), +1):
if x[i][1] == True:
right = i
found_right = True
if x[i][1] == False and i != index:
break
if found_left and found_right:
return(left, right)
elif found_left and not found_right:
return(left, index)
elif not found_left and found_right:
return(index, right)
else:
return (index, index)
index_of_x = find_x(test)
if index_of_x != None:
left, right = look_around(test, index_of_x)
print "match:"
for i in range (left, right+1, +1):
print test[i][0], #comma prints everything on same line
</code></pre>
|
[] |
[
{
"body": "<p>If I understand correctly, your problem can be defined as:</p>\n\n<ul>\n<li>take the longest uninterrupted chain of True elements ending in X</li>\n<li>take X regardless of value </li>\n<li>take all True elements after X until the first False one</li>\n</ul>\n\n<p>So the actual position of X is not relevant, we only need to know if we encountered it or not. Based on this, we can generate the result with only one pass through the input list. This works if at most one X element is present. </p>\n\n<p>Bellow you can see my quick and dirty version of the implementation:</p>\n\n<pre><code>\nfrom itertools import count, izip\nfrom collections import namedtuple\nElem = namedtuple('Elem', ['name', 'value'])\n\ndef valid_elements(elem_lst):\n valid_elem = []\n found_x = False\n\n for elem in elem_lst:\n if elem.name == 'X':\n found_x = True\n valid_elem.append(elem)\n elif elem.value:\n valid_elem.append(elem)\n elif found_x:\n break\n else:\n valid_elem = []\n\n if found_x:\n return valid_elem\n return []\n\nz = [Elem('C', True), Elem('X', False), Elem('D', True), Elem('C', False), Elem('S', True)]\nprint [elem.name for elem in valid_elements(z)]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T12:59:54.667",
"Id": "58895",
"Score": "0",
"body": "Thanks alex. Yes, X will only ever be there at most once. This is much more concise that my original code! Lots to look at here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T16:10:56.460",
"Id": "58905",
"Score": "0",
"body": "The if/elif chain is really hard to follow. For quite a while I was convinced it would have included all preceding elements, rather than just uninterrupted sequences thereof. If this code is not a bottleneck I would consider making redundant tests for clarity. Or at least adding comments. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T12:50:15.420",
"Id": "36048",
"ParentId": "36045",
"Score": "4"
}
},
{
"body": "<p>I do like alex's solution. That said, you can improve yours incrementally as well. Look for places you can collapse your code. For example let's examine your \"look left\" code:</p>\n\n<pre><code>#look left:\nif index != 0:\n for i in range(index, -1, -1):\n if x[i][1] == True:\n left = i\n found_left = True\n if x[i][1] == False and i != index:\n break\n</code></pre>\n\n<p>You can leverage the behavior of <code>range()</code> to simplify things a lot here.</p>\n\n<ul>\n<li>You don't need to check at <code>index</code>, so start your <code>range</code> at <code>index - 1</code> and skip the last if.</li>\n<li>Consider the behavior of range around the edge cases. Look at what <code>range(1, -1, -1)</code>, <code>range(0, -1, -1)</code> and <code>range(-1, -1, -1)</code> return. You should quickly see that you don't need any special handling for starting at <code>index == 0</code>, so you can remove your outer if.</li>\n<li>Looking a bit more globally, if start with <code>left</code> set to <code>index</code>, you don't need <code>found_left</code> at all.</li>\n<li>Oh, and skip comparisons to <code>True</code>.</li>\n</ul>\n\n<p>The result:</p>\n\n<pre><code>left = index\n# ...\n\n#look left:\nfor i in range(index - 1, -1, -1):\n if x[i][1]:\n left = i\n else:\n break\n</code></pre>\n\n<p>You can apply similar reasoning to cut down on the \"look right\" code as well, and finally always return <code>left, right</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T17:34:16.123",
"Id": "58929",
"Score": "0",
"body": "Thanks. These are really good pointers. You have been very helpful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T16:24:26.867",
"Id": "36056",
"ParentId": "36045",
"Score": "2"
}
},
{
"body": "<p>My answer is an overkill but I think it's good to know that such tools exist. You can checkout Parser Combinators.</p>\n\n<p>Some sample code with NLTK.</p>\n\n<pre><code>list_of_tokens = [('hi', 'True'), ('bye', 'Cow'), \n ('cartoons', 'True'), ('games', 'True'),\n ('football', 'False')]\n\ngrammar_for_my_type = r\"\"\"\n MYCUSTOMTYPE:\n # One or more True followed by a False\n {<True>*<False>}\n\"\"\"\nparser = nltk.chunk.RegexpParser(grammar_for_my_type)\nparse_tree = parser.parse(list_of_tokens)\n</code></pre>\n\n<p>From here you can easily extract all possible matches. In my case this would catch <code>('cartoons', 'True'), ('games', 'True'), ('football', 'False')</code>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-13T05:15:12.433",
"Id": "198403",
"ParentId": "36045",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "36048",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T10:36:32.900",
"Id": "36045",
"Score": "2",
"Tags": [
"python"
],
"Title": "Searching for a pattern in a list of tuples"
}
|
36045
|
<p>I have a series of text boxes in a table to gather input as below:</p>
<p><img src="https://i.stack.imgur.com/v1fNL.jpg" alt="enter image description here"></p>
<p>The user will input a target and actual value for each measurement point they require. I would then like to validate the actual values against the target values based upon the tolerance inputted in the tolerance textbox. The tolerance will be the same for all measurement points inputted, however the user will not always input all 10 measurement points.</p>
<p>I have also created a very basic class containing a function that accepts the target, actual and tolerance values then returns a Boolean depending on whether the actual value is within tolerance. I realise I could use this with a ruck load of if statements to check each textbox for input then use the class to perform the validation, however this seems like a lot of code repetition and a bit crude. My question being is there a better way I can perform this validation?</p>
<p>Class content</p>
<pre><code>Public Class TolerenceHelper
Public Function IsInTolerence(ByVal target As Integer, ByVal actual As Integer, ByVal tolerence As Integer) As Boolean
Dim upper As Integer = target + tolerence
Dim lower As Integer = target - tolerence
If actual < lower OrElse actual > upper Then
Return False
Else
Return True
End If
End Function
</code></pre>
<p>Calling the function as below:</p>
<pre><code>Dim m1 As TolerenceHelper
Dim flag As Boolean = True
m1 = New TolerenceHelper
If m1.IsInTolerence(Integer.Parse(txtT1.Text), Integer.Parse(txtA1.Text), Integer.Parse(txtTolerance.Text)) = False Then
flag = False
End If
If flag = False Then
lblTest.Text = "Out of tolerance"
Else
lblTest.Text = "In tolerance"
End If
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T17:11:40.627",
"Id": "58922",
"Score": "0",
"body": "Do you have a separate `lblTest` for each check, or are you reusing the same field? Are you only checking 1 at a time?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T03:10:42.187",
"Id": "58983",
"Score": "1",
"body": "Isn't it spelled \"tolerance\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T19:05:20.453",
"Id": "59348",
"Score": "0",
"body": "Jimsan, has anyone appropriately answered your question? if not please provide some specifics on what more you would like"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T09:00:06.970",
"Id": "59412",
"Score": "0",
"body": "Malachi, I didn't mark an answer as everyone has valid points. I ended up using the code that I added in the edit of my post. Thank you all for your help though"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:05:13.407",
"Id": "61083",
"Score": "0",
"body": "@Jimsan if you chose that as a solution you should post it as an answer and accept it as the answer"
}
] |
[
{
"body": "<p>I would write it like this</p>\n\n<pre><code>Dim m1 As TolerenceHelper\nDim flag As Boolean = True\n\nm1 = New TolerenceHelper\n\nflag = m1.IsInTolerence(Integer.Parse(txtT1.Text), Integer.Parse(txtA1.Text), Integer.Parse(txtTolerance.Text))\n\nIf flag = False Then\n lblTest.Text = \"Out of tolerance\"\nElse\n lblTest.Text = \"In tolerance\"\nEnd If\n</code></pre>\n\n<p>that function returns a boolean so you can just assign it the flag or you could do it like this and avoid creating the flag boolean as well</p>\n\n<pre><code>Dim m1 As TolerenceHelper\nm1 = New TolerenceHelper\n\nIf m1.IsInTolerence(Integer.Parse(txtT1.Text), Integer.Parse(txtA1.Text), Integer.Parse(txtTolerance.Text)) Then\n lblTest.Text = \"In tolerance\"\nElse\n lblTest.Text = \"Out of tolerance\"\nEnd If\n</code></pre>\n\n<hr>\n\n<p><strong>In your Function <code>IsInTolerence</code> you could eliminate some variables by writing it like this:</strong> </p>\n\n<pre><code>Public Function IsInTolerence(ByVal target As Integer, ByVal actual As Integer, ByVal tolerence As Integer) As Boolean\n\n If (target - tolerence <= actual AND actual =< target + tolerence)\n Return True\n Else\n Return False\n End If\nEnd Function\n</code></pre>\n\n<p>Straight to the point. </p>\n\n<p>check if it is true first, and then dump out in all other cases, this would cover a null or something else.</p>\n\n<hr>\n\n<h2>Remove Code Duplication with a list of TextBox Objects</h2>\n\n<p>I am thinking that you create a list of the text boxes, then you should be able to loop through that list, checking each text box for the following.</p>\n\n<ol>\n<li>if it has a value entered</li>\n<li>if the tolerance is met</li>\n<li>some kind of highlighting to show that the tolerance was not met.</li>\n</ol>\n\n<p>I am not sure on the syntax, but this would be a good way to do it, because you would only have to type out the logic once and then loop through the list of TextBoxes, and it would be more maintainable because you could just add TextBoxes any time you like and it shouldn't affect the any of the other code.</p>\n\n<pre><code>dim TextBoxListActual as New List(Of TextBox)\nTextBoxListActual.Add(txtT1)\nTextBoxListActual.Add(txtT2)\nTextBoxListActual.Add(txtT3)\n\nDim TextBoxListTarget as New List(Of TextBox)\nTextBoxListTarget.Add(txtA1)\nTextBoxListTarget.Add(txtA2)\nTextBoxListTarget.Add(txtA3)\n\ndim m1 As TolerenceHelper\nm1 = New TolerenceHelper\n\nFor index As Integer = 0 To TextBoxListActual.Count\n If m1.IsInTolerence(Integer.Parse(TextBoxListTarget(index).value), Integer.Parse(TextBoxListActual(index).value), Integer.Parse(txtTolerance.Text))\n lblTest.Text = \"In Tolerance\"\n Else\n lblTest.Text = \"Out of Tolerance\"\n End If\nNext\n</code></pre>\n\n<p>little bit of an example. probably not perfect.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T16:56:27.733",
"Id": "58915",
"Score": "1",
"body": "I'd definitely do the 2nd revision, or the first revision but change `If flag = False` to simply `If flag` and then change the true clause to being first."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T15:44:26.393",
"Id": "36054",
"ParentId": "36047",
"Score": "7"
}
},
{
"body": "<p>You could shorten <code>IsInTolerence</code> to being a 1-liner like this:</p>\n\n<pre><code>Function IsInTolerence(ByVal target As Integer, ByVal actual As Integer, ByVal tolerence As Integer) As Boolean\n Return target - tolerence <= actual And actual <= target + tolerence\nEnd Function\n</code></pre>\n\n<p>A micro optimization note... I'd initially used <code>AndAlso</code> in my comment, but that runs slower even if the first check is always false.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T17:26:56.513",
"Id": "36063",
"ParentId": "36047",
"Score": "1"
}
},
{
"body": "<p>As written, there is no reason for <code>IsInTolerence</code> not to be a shared function because TolerenceHelper has no benefit to actually being instantiated.</p>\n\n<p>To make it shared, you would instead declare it like so:</p>\n\n<pre><code>Public Shared Function IsInTolerence(...\n</code></pre>\n\n<p>This will give you the advantage of having your initial calls instead of being:</p>\n\n<pre><code>Dim m1 As TolerenceHelper\nm1 = New TolerenceHelper\nIf m1.IsInTolerence(...\n</code></pre>\n\n<p>You would use:</p>\n\n<p><code>If TolerenceHelper.IsInTolerence(...</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T17:36:50.233",
"Id": "36065",
"ParentId": "36047",
"Score": "2"
}
},
{
"body": "<p>Instead of performing each test via a series of if statements or needing to add your textboxes to a list, you can perform a simple for loop and utilize the <a href=\"http://msdn.microsoft.com/en-us/library/31hxzsdw%28v=vs.110%29.aspx\" rel=\"nofollow\">FindControl</a> command of the page.</p>\n\n<p>This would allow you to write code something like this:</p>\n\n<pre><code>For i As Integer = 1 To 10\n Dim TargetBox As TextBox = Me.FindControl(\"txtT\" & i)\n Dim ActualBox As TextBox = Me.FindControl(\"txtA\" & i)\n If IsNothing(TargetBox) OrElse IsNothing(ActualBox) Then\n 'Couldn't find TextBox so just try the next number\n Continue For\n Else\n If TolerenceHelper.IsInTolerence(Integer.Parse(TargetBox.Text), Integer.Parse(ActualBox.Text), Tolerence) Then\n lblText.Text += String.Format(\"Trial {0} In tolerance\",i)\n Else\n lblText.Text += String.Format(\"Trial {0} Out of Tolerence\",i)\n End If\n End If\nNext\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T02:32:51.027",
"Id": "58979",
"Score": "0",
"body": "if they change the amount of Textboxes they would have to change the for loop. with the List of Text boxes the code won't change all they would have to do is in the declaration, another `textboxList.add(textbox43)` or they could find a better way of doing it like that. there has to be a collection collection or something where you could select all the textboxes in said group or something, this doesn't seem maintainable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T17:44:21.180",
"Id": "36066",
"ParentId": "36047",
"Score": "4"
}
},
{
"body": "<p>Instead of parsing the tolerence each time, you'd want to set it to a variable or possibly make a property. I like the property method simply because it allows for a lot of flexibility.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>Protected Property Tolerence As Integer\n Get\n Static _Tolerence As Integer = -1 'Static variable so Tolerence parsed only once per postback\n If _Tolerence = -1 AndAlso Not Integer.TryParse(txtTolerence.Text, _Tolerence) Then\n _Tolerence = 0 ' or your default value or whatever you like\n End If\n Return _Tolerence\n End Get\n Set(value As Integer)\n txtTolerence.Text = value\n End Set\nEnd Property\n</code></pre>\n\n<p>You may note that I used this Property in one of my other answers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T17:47:36.350",
"Id": "36068",
"ParentId": "36047",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T12:34:37.910",
"Id": "36047",
"Score": "5",
"Tags": [
"asp.net",
"vb.net",
"validation"
],
"Title": "Most efficient way to validate multiple textboxes against a tolerance value"
}
|
36047
|
<p>Allow for stuff like:</p>
<ul>
<li>API/ExampleObjects</li>
<li>API/ExampleObjects/SOME_INTEGER_ID/Children</li>
<li>...</li>
</ul>
<p>with children knowing their owners (aka parents).</p>
<p><a href="https://github.com/Evan-R/RESTfulPHP" rel="nofollow">Full repo here</a></p>
<ul>
<li>Please be brutally honest if something can be improved!</li>
<li>I couldn't add the <a href="/questions/tagged/rest" class="post-tag" title="show questions tagged 'rest'" rel="tag">rest</a> tag as I don't have 150 rep yet.</li>
</ul>
<p></p>
<pre><code><?php
class RestApi {
private
$id,
$owner
;
public function __construct( $params = false ) {
if( $params['request'] ) {
// grab first piece of the request
if( strlen($request = trim(strstr($params['request'], '/'), '/')) > 0 ) {
// php 5.2 compatible
$pieces = explode('/', $params['request']);
if( is_numeric($pieces[0]) ) {
$this->setId( $pieces[0] );
$params['request'] = $request;
}
unset( $pieces );
} else {
// if the request is numeric, then it's an id
if( is_numeric($params['request']) ) {
$this->setId( $params['request'] );
$params['request'] = '';
}
}
}
}
public function getInstance( $params ) {
if( isset($params['owner']) && is_object( $params['owner'] ) ) {
$this->setOwner( $params['owner'] );
}
// if resource starts with "api/", strip it
if( strpos($params['request'], 'api/' ) === 0 ){
$params['request'] = substr($params['request'], 4);
}
if( $params['request'] ) {
if( strlen($request = trim(strstr($params['request'], '/'), '/')) > 0 ) {
// php 5.2 compatible
$pieces = explode('/', $params['request']);
$class = $pieces[0];
unset( $pieces );
} else {
$class = $params['request'];
}
$class = get_class($this) . $class;
$instance = new $class(array('request' => &$request));
$instance->setOwner( $this );
if( $request ) {
return $instance->getInstance(array(
'request' => $request
));
}
return $instance;
}
}
public function getOwner() {
return $this->owner;
}
protected function setOwner( $owner ) {
$this->owner = $owner;
}
public function getId() {
return $this->id;
}
protected function setId( $id ) {
$this->id = (int)$id;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T17:10:06.447",
"Id": "58920",
"Score": "1",
"body": "This is just a front controller. There is nothing inherently RESTful about it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T06:30:15.990",
"Id": "59018",
"Score": "0",
"body": "sorry @Paul I don't understand - could you please elaborate on what you mean by \"inherently RESTful\"?"
}
] |
[
{
"body": "<h1>Good</h1>\n<ul>\n<li>Private attributes for storing state in the class (<code>id</code>, <code>owner</code>).</li>\n<li>Getter and setter methods are simple.</li>\n</ul>\n<hr />\n<h1>Bad</h1>\n<h2>Not a RestApi</h2>\n<ul>\n<li>REST is an architectural style it can't be represented by an object. It is the wrong level of abstraction for an object to represent an architectural style.</li>\n<li>Your RestApi object has public methods: <code>getInstance</code>, <code>getId</code> and <code>getOwner</code>. These have nothing to do with representational state transfer.</li>\n</ul>\n<h2>Constructor</h2>\n<ul>\n<li>The constructor should only create the object. By doing so much in your constructor you make it difficult to extend your class (going against the <a href=\"http://en.wikipedia.org/wiki/Open/closed_principle\" rel=\"nofollow noreferrer\">Open / Closed principle</a>). It also makes it harder to unit test this code.</li>\n<li>If you construct your object with an array that doesn't contain the key <code>'request'</code> your code will emit an error notice.</li>\n<li><code>unset($pieces);</code> is unnecessary. Don't worry about memory management.</li>\n</ul>\n<h2>getInstance</h2>\n<ul>\n<li>This method should not be called <code>getInstance</code>.</li>\n<li>This method does too much.</li>\n<li>It can call <code>setOwner</code> when it should only be getting an instance.</li>\n<li>Also, why should the class that you create depend on your RestApi object? <code>get_class($this)</code> will return 'RestApi' or 'RestApiDerived' if you derive another class from it. Why should the object that you create be so tightly coupled to the RestApi class?</li>\n</ul>\n<hr />\n<p>I'm actually left confused by this class. The naming of methods and the object itself doesn't help me to understand what sort of objects this class represents. It doesn't map to anything in the real world that I can understand.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T08:59:13.137",
"Id": "36113",
"ParentId": "36049",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T13:57:08.547",
"Id": "36049",
"Score": "4",
"Tags": [
"php",
"api"
],
"Title": "RESTfulPHP / controller / structure"
}
|
36049
|
<p>I'm about to release this application as a hobby and I'm wondering how would I improve the speed of the calculations and overall responsiveness of the class?</p>
<p>I have covered a module briefly in data structures and algorithms so I'm thinking a big factor would be reducing the amount of loops I'm using.Can some suggest/pinpoint some improvements to the code or even a way of streamlining some of the operation? I'm thinking that I could be utilizing a better structure or design.This is the main class where the user input three calculations that are piped to a calculation.</p>
<pre><code>public class MainActivity extends FragmentActivity implements OnClickListener{
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
private Vibrator myVib;
ViewPager mViewPager;
EditText offsetLength,offsetDepth,ductDepth;
Button calculate;
//DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
String getoffsetlength;
String getoffsetdepth;
String getductdepth;
double off1,off2,off3;
//button filter
PorterDuffColorFilter greenFilter = new PorterDuffColorFilter(Color.GREEN, PorterDuff.Mode.SRC_ATOP);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Intent intent1=new Intent(this,AboutActivity.class);
final Intent intent2=new Intent(this,MainActivity.class);
offsetLength = (EditText)findViewById(R.id.offLength);
offsetDepth = (EditText)findViewById(R.id.offDepth);
ductDepth = (EditText)findViewById(R.id.ductDepth);
calculate = (Button)findViewById(R.id.calc);
calculate.setOnClickListener(this);
final ViewGroup actionBarLayout = (ViewGroup) getLayoutInflater().inflate(R.layout.a,null);
// Set up your ActionBar
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(actionBarLayout);
//button vibration
myVib = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
// You customization
final int actionBarColor = getResources().getColor(R.color.action_bar);
actionBar.setBackgroundDrawable(new ColorDrawable(actionBarColor));
final Button actionBarHome = (Button) findViewById(R.id.action_bar_title);
actionBarHome.setBackgroundResource(R.drawable.ic_action_back);
actionBarHome.setOnClickListener(this);
actionBarHome.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(intent2);
}
});
//final Button actionBarSent = (Button) findViewById(R.id.action_bar_sent);
final Button actionBarInfo = (Button) findViewById(R.id.action_bar_staff);
actionBarInfo.setBackgroundResource(R.drawable.ic_action_help);
actionBarInfo.setOnClickListener(this);
actionBarInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(intent1);
}
});
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
double marking1=2,marking2=2,marking3=2;
if (offsetLength.getText().length() > 0 ) {
String getoffsetlength = offsetLength.getText().toString();
}
if (offsetDepth.getText().length() > 0 ) {
String getoffsetdepth = offsetDepth.getText().toString();
}
if (ductDepth.getText().length() > 0 ) {
String getductdepth = ductDepth.getText().toString();
}
double tri1,tri2;
//double marking1,marking2,marking3;
// validate whether the variables are not null
if(getoffsetlength != null){
double off1 = Double.parseDouble(getoffsetlength);
}
if(getoffsetdepth != null){
double off2 = Double.parseDouble(getoffsetdepth);
}
if(getductdepth != null){
double off3 = Double.parseDouble(getductdepth);
}
marking1 = Math.sqrt(Math.pow(off1,2) + Math.pow(off2,2));
tri1 = Math.atan(off2 / off1);
tri2 = (Math.PI - tri1) / 2;
marking2 = off3 / Math.tan(tri2);
marking3 = marking2 * 2;
Intent myIntent = new Intent(MainActivity.this, CalcResult.class);
myIntent.putExtra("number1", marking1);
myIntent.putExtra("number2", marking2);
myIntent.putExtra("number3", marking3);
startActivity(myIntent);
//vibrate button onClick
myVib.vibrate(20);
//calculate.setColorFilter(greenFilter);
Toast.makeText(getBaseContext(), "Calculating!", Toast.LENGTH_SHORT).show();
} catch (NumberFormatException e) {
// TODO: handle exception
System.out.println("Must enter a numeric value!");
}
//
}
/*
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
*/
@Override
public void onBackPressed() {
new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing Activity")
.setMessage("Are you sure you want to close this activity?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T15:28:34.947",
"Id": "58900",
"Score": "2",
"body": "The code you posted doesn't have any loops. As an additional comment, the repeated code in `onClick()` should be extracted into a single method that is called 3 times."
}
] |
[
{
"body": "<p>Looking through this code I feel that there must be something missing? Does it work? Does it even compile?</p>\n\n<p>For example the onClick() method all the places I have marked are 'dead' variables... variables you declare inside a block and are not visible outside the block:</p>\n\n<pre><code> double marking1=2,marking2=2,marking3=2;\n\n if (offsetLength.getText().length() > 0 ) {\n String getoffsetlength = offsetLength.getText().toString(); // MARK\n }\n\n if (offsetDepth.getText().length() > 0 ) {\n String getoffsetdepth = offsetDepth.getText().toString(); // MARK \n }\n if (ductDepth.getText().length() > 0 ) {\n String getductdepth = ductDepth.getText().toString(); // MARK \n }\n double tri1,tri2;\n //double marking1,marking2,marking3;\n\n // validate whether the variables are not null\n if(getoffsetlength != null){\n double off1 = Double.parseDouble(getoffsetlength); // MARK\n }\n if(getoffsetdepth != null){\n double off2 = Double.parseDouble(getoffsetdepth); // MARK\n }\n if(getductdepth != null){\n double off3 = Double.parseDouble(getductdepth); // MARK\n }\n</code></pre>\n\n<p>Then, you have:</p>\n\n<pre><code> marking1 = Math.sqrt(Math.pow(off1,2) + Math.pow(off2,2));\n tri1 = Math.atan(off2 / off1);\n</code></pre>\n\n<p>Firstly, these should fail to compile because the variables <code>off1</code> and <code>off2</code> are not in scope. Secondly, you should be zero-checking the division to ensure there's no division-by-zero.</p>\n\n<p>All in all, I think this code is non-functional.....</p>\n\n<hr>\n\n<h1>EDIT</h1>\n\n<p>Ahh, I see that the variables I though were failing are actually declared at the class level, not in the method.</p>\n\n<p>What this means is that your code is very buggy, and the lines I have marked above are <strong>COMPLETELY USELESS</strong> and have no impact on program execution.... </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T16:53:54.860",
"Id": "36060",
"ParentId": "36052",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "36060",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T14:57:25.747",
"Id": "36052",
"Score": "-3",
"Tags": [
"java",
"performance",
"android"
],
"Title": "How would I improve this class in terms of responsiveness and performance?"
}
|
36052
|
<p>I'm writing an AI for an italian Card game scopa <a href="http://en.wikipedia.org/wiki/Scopa" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Scopa</a> And as part of it i need to generate all moves available to the user.</p>
<p>A move consists of finding cards in the centerboard that sum to a card in the players hand. </p>
<p>For example if I have a 5 in my hand and the center contains a [5,4,3,2,1,2] the possible moves would be: </p>
<p>pick up the 5 with my five</p>
<p>pick up the 4 and 1 with my five</p>
<p>pick up one of the twos and the three with my five</p>
<p>pick up the other tow and the three with my five</p>
<p>pick up both 2s and the 1 with my five </p>
<p>After profiling my code it shows that this is by far the most expensive part of the program (about 95 percent of execution time being spent here)</p>
<p><img src="https://i.stack.imgur.com/kJ9fH.png" alt="enter image description here"></p>
<p>Can you see any way to optimize these methods?</p>
<p>this one actually generates all the possible moves.</p>
<pre><code>private void generateMoves(Card myCard,ArrayList<Card> CurrentMove,
ArrayList<Card> centerCards,ArrayList<Move> moves, int moveSum) {
if(moveSum>myCard.value)
{
return;
}
else if(moveSum == myCard.value)
{
Move m = new Move(myCard, new ArrayList<>(CurrentMove));
rateMove(m);
moves.add(m);
return;
}
for (Card card :centerCards) {
if(!card.selected)
{
CurrentMove.add(card);
card.selected = true;
moveSum += card.value;
generateMoves(myCard, CurrentMove, centerCards, moves, moveSum);
moveSum -= card.value;
CurrentMove.remove(card);
card.selected = false;
}
}
}
</code></pre>
<p>this one removes any duplicates (the code above would return 4,1 and 1,4 as different moves from the example) I know its hacky but i couldn't think of anything that would be faster. Ideally they would be combined and duplicates would never be returned but i couldn't get it to work.</p>
<pre><code> protected void removeDuplicates(ArrayList<Move> moves)
{
ArrayList<Move> temp = new ArrayList<>(moves);
for(Move move : temp)
{
while(moves.remove(move));
moves.add(move);
}
}
</code></pre>
<p>Any suggestions would be appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T16:40:10.890",
"Id": "58911",
"Score": "0",
"body": "Have you implemented `hashCode` and `equals` properly in your `Move` class and your `Card` class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T17:01:34.390",
"Id": "58918",
"Score": "0",
"body": "520 seconds runtime? How many cards do you have on the board and in your hand, really?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T17:33:21.887",
"Id": "58928",
"Score": "0",
"body": "I ran 300 games and at each move it performs 200 roll outs of a Monte Carlo tree search. And equals yes hashCode no"
}
] |
[
{
"body": "<p>In your recursive generateMoves method, you can reduce a huge amount of the duplicates by limiting where in the <code>centerCards</code> list you operate in.</p>\n\n<p>My suggestion would be to pass that list through the recursion with a pointer to your current position in the array.... for example:</p>\n\n<pre><code>generateMoves(Card myCard,ArrayList<Card> CurrentMove,\n ArrayList<Card> centerCards, int centercardpos,\n ArrayList<Move> moves, int moveSum)\n</code></pre>\n\n<p>Then, in your method you can change the loop:</p>\n\n<pre><code>for (Card card :centerCards) { ...\n</code></pre>\n\n<p>to be:</p>\n\n<pre><code>for (int ci = centercardpos; ci < centerCards.size(); ci++) {\n Card card = centerCards.get(i);\n\n generateMoves(myCard, CurrentMove, centerCards,\n centercardpos + 1, // new increased limit.....\n moves, moveSum);\n</code></pre>\n\n<p>This will substantially reduce the number of possible moves (and still get the right answers). Reducing the values you gnerate will also substantially reduce duplicates, which in turn will also improve th pwerformance of <code>removeDuplicates</code> ...</p>\n\n<p>The only time removeDuplicates will have effect is when you have something like (using your example: [5,4,3,2,1,2] ) the moves [5,2] and [5,2] (but the 'other' 2).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T05:10:25.613",
"Id": "59011",
"Score": "1",
"body": "thanks your suggestion Cut run time of the same data set from 500+ seconds to just over 100"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T11:00:54.973",
"Id": "59032",
"Score": "1",
"body": "100 seconds is a long time for this code still...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T19:31:41.650",
"Id": "59132",
"Score": "0",
"body": "36 moves per game\n6 available moves per turn (average)\n200 simulated playouts to the end of the game for each move at each turn in the simulation we need to figure out what moves are available to us so on average 18 times\n300 games so it gets called approximately 116640000 times"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T16:40:12.710",
"Id": "36057",
"ParentId": "36055",
"Score": "3"
}
},
{
"body": "<p>If you switch to using <code>HashSet</code> instead of <code>ArrayList</code>, that would remove the need for your entire <code>removeDuplicates</code> method. A <code>HashSet</code> takes care of everything that the <code>removeDuplicates</code> method does.</p>\n\n<p>I would also change a part of your <code>generateMoves</code> method</p>\n\n<pre><code>private void generateMoves(Card myCard, Set<Card> CurrentMove,\n Set<Card> centerCards, List<Move> moves, int moveSum) {\n ...\n for (Card card :centerCards) {\n if(!CurrentMove.contains(card))\n {\n Set<Card> newMove = new HashSet<Card>(CurrentMove);\n newMove.add(card);\n generateMoves(myCard, newMove, centerCards, moves, moveSum + card.value);\n }\n }\n}\n</code></pre>\n\n<p>Although perhaps not a great speed optimization, this removes the need for temporarily adding and removing with <code>moveSum</code>, <code>CurrentMove</code> and <code>card.selected</code>.</p>\n\n<p>I think the major thing you should change is to switch from <code>ArrayList</code> to <code>HashSet</code>. Just remember that when using <code>HashSet</code>, you need to take a look at your implementation of <code>hashCode</code> and <code>equals</code>. Probably you <em>don't</em> want a <code>2</code> to be equal to another <code>2</code> considering it should be possible for both 2s to be within the same move. It is possible that the default implementation from the <code>Object</code> class is enough for your purpose. But either way, make sure that it obeys the rule \"If two objects are <strong>equal</strong> they should have the same <strong>hashCode</strong>. If two objects have the same hashCode, they <strong>do not need to be</strong> equal.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T16:47:27.353",
"Id": "36058",
"ParentId": "36055",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "36057",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T16:15:44.517",
"Id": "36055",
"Score": "5",
"Tags": [
"java",
"algorithm",
"performance"
],
"Title": "Performance/Optimization of Knapsack(ish) algorithm for move generation for a game"
}
|
36055
|
<p>I just started working with ASP.NET MVC a few weeks ago, and I'm finding that it can be very easy to write spaghetti code in the controllers. For my first project, I created a very simple view with a few controls. At first, all of my code was in the <code>Index()</code> action result. That worked okay for a while, but as more features get added to the page, the more the code grows. I would like my code to be split up into multiple action results. I made an attempt at refactoring. </p>
<p>Here is my View:</p>
<pre><code>@model TpgInternalSite.Models.RepairInvoice
@{
ViewBag.Title = "Repair Invoicing";
Layout = "~/Views/Shared/_Layout100.cshtml";
}
<h2>Repair Invoice</h2>
<script type="text/javascript">
$(document).ready(function () {
$('@(ViewBag.SetFocusTo)').focus();
$('#RmaNumber, #SerialNumber').keydown(function (event) {
if (event.keyCode == 13 || event.keyCode == 9) {
var RmaNumber = $('#RmaNumber').val();
var SerialNumber = $('#SerialNumber').val();
event.preventDefault(); //Stops enter key from triggering the Process button.
if (event.target.id == 'RmaNumber'){
var link = '/Invoice/RmaNumberScan?rmaNumber=' + RmaNumber;
location.href = link;
}
else {
var link = '/Invoice/SerialNumberScan?rmaNumber=' + RmaNumber + '&serialNumber=' + SerialNumber;
location.href = link;
}
}
});
});
</script>
<br />
<br />
<div class="form-horizontal">
@using (Html.BeginForm("Index", "Invoice", FormMethod.Post))
{
<div class="control-group">
<div class="control-label">
RMA#
</div>
<div class="controls">
@Html.TextBoxFor(x => x.RmaNumber)
</div>
</div>
<div class="control-group">
<div class="control-label">
SERIAL#
</div>
<div class="controls">
@Html.TextBoxFor(x => x.SerialNumber)
</div>
</div>
<div class="control-group">
<div class="control-label">
Terminal Type:
</div>
<div class="controls">
@Html.LabelForModel(Model.TerminalType)
</div>
</div>
<div class="control-group">
<div class="control-label">
Warranty:
</div>
<div class="controls">
@Html.CheckBox("warranty", Model.UnderWarranty, new { disabled = "disabled" })
</div>
</div>
<div class="control-group">
<div class="control-label">
Repair Level:
</div>
<div class="controls">
@Html.DropDownListFor(x => x.RepairLevels, new SelectList(Model.RepairLevels))
</div>
</div>
<div class="form-actions">
<input name="process" class="btn primary" type="submit" id="process" value="Process" />
</div>
}
</div>
</>
</code></pre>
<p>And my controller looks like this:</p>
<pre><code> public ActionResult Index()
{
ViewBag.SetFocusTo = "#RmaNumber";
Session["RmaDetail"] = null;
return View(repairInvoice);
}
[HttpPost]
public ActionResult Index(RepairInvoice ri)
{
if (Session["RmaDetail"] != null)
{
var rmaDetail = Session["RmaDetail"] as SVC05200;
RepairInvoiceDataLayer.UpdateRmaRepairLevel(rmaDetail, ri.RepairLevels[0].Trim());
ViewBag.SuccessMessage = "Repair level updated successfully.";
ViewBag.SetFocusTo = "#RmaNumber";
ModelState.Clear();
ri.SerialNumber = string.Empty;
Session["RmaDetail"] = null;
}
return View(ri);
}
public ActionResult RmaNumberScan(string rmaNumber)
{
repairInvoice.RmaNumber = rmaNumber;
if (!string.IsNullOrEmpty(rmaNumber))
{
try
{
bool IsValidRma = RepairInvoiceDataLayer.IsValidRmaNumber(rmaNumber);
if (IsValidRma)
{
ViewBag.SetFocusTo = "#SerialNumber";
}
else
{
ViewBag.AlertMessage = "RMA Number not found.";
}
}
catch (Exception ex)
{
ViewBag.ErrorMessage = "An error occured searching for RMA Number. Please try again.";
log.Fatal(ex.ExceptionToString());
}
}
return View("Index", repairInvoice);
}
public ActionResult SerialNumberScan(string rmaNumber, string serialNumber)
{
if (!string.IsNullOrEmpty(rmaNumber) && !string.IsNullOrEmpty(serialNumber))
{
try
{
if (serialNumber.Length > 20)
{
serialNumber = serialNumber.Remove(20);
}
ModelState["SerialNumber"].Value = new ValueProviderResult(serialNumber, serialNumber, CultureInfo.CurrentCulture);
var result = RepairInvoiceDataLayer.SelectRmaDetail(rmaNumber, serialNumber);
if (result != null)
{
if (result.Received == 1)
{
Nullable<bool> workOrderClosed = RepairInvoiceDataLayer.WorkOrderClosed(result.RETDOCID, result.LNSEQNBR, serialNumber);
if (workOrderClosed.HasValue)
{
if (workOrderClosed.Value)
{
Session["RmaDetail"] = result;
repairInvoice.TerminalType = result.ITEMNMBR.Trim();
repairInvoice.UnderWarranty = RepairInvoiceDataLayer.UnderWarranty(result.RETDOCID, result.LNSEQNBR, serialNumber, result.CUSTNMBR);
ViewBag.SetFocusTo = "#RepairLevels";
}
else
{
ViewBag.AlertMessage = "Work order not closed.";
}
}
else
{
ViewBag.AlertMessage = "Work order not found.";
}
}
else
{
ViewBag.AlertMessage = "Line item has not been received.";
}
}
else
{
ViewBag.AlertMessage = "Serial Number not found.";
}
}
catch (Exception ex)
{
ViewBag.ErrorMessage = "An error occured searching for Serial Number. Please try again.";
log.Fatal(string.Format("An error occured searching for Serial Number. RMA Number: {0} Serial Number: {1}", rmaNumber, serialNumber, ex));
}
}
return View("Index", repairInvoice);
}
</code></pre>
<p>Basically my page is setup to handle this current process flow:</p>
<ol>
<li><p>User types a number into the RMA number textbox and hits <kbd>enter</kbd> or <kbd>tab</kbd>. JavaScript detects <kbd>enter</kbd> or <kbd>tab</kbd> key and navigates to /Invoice/RmaNumberScan and passes a query string with the number entered. Logic is performed in the <code>RmaNumberScan</code> action result. </p></li>
<li><p>Next, the user types a number into the serial scan textbox and hits <kbd>tab</kbd> or <kbd>enter</kbd>. The /Invoice/SerialNumberScan is called and passes query strings to the <code>SerialNumberScan</code> method. </p></li>
<li><p>User clicks the process button and then the <code>Index()</code> with the <code>HTTPPOST</code> method fires.</p></li>
</ol>
<p>Am I on the right track, or am I doing MVC incorrectly? I come from a webforms background, and I want to split up my code. My attempt just feels so dirty and I don't like the fact that my action result name appears in the URL. I just want my code to be easily maintained and readable.</p>
<p>Since all of my database logic is done in my <code>RepairInvoiceDataLayer</code>, I still don't understand how the service layer comes into play here. What code from this controller would go into the service layer?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T17:17:15.730",
"Id": "58923",
"Score": "1",
"body": "It's easy to write spaghetti code in *any language*, using *any framework* :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T00:40:31.757",
"Id": "58970",
"Score": "0",
"body": "Hi @broke, welcome to CR! Stick around, spend some of those votes - you may or may not know, but [we're on a mission here](http://meta.codereview.stackexchange.com/questions/999/call-of-duty-were-on-a-mission), to *shoot all zombies*. Join the party!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T10:40:58.563",
"Id": "59029",
"Score": "0",
"body": "@broke Controller = Handling of HTTP requests and the building of view-models. Data Layer = saving and retrieving of data using queries. Service Layer = business logic manipulating data objects and sometimes returning objects for the controller to use in building view-models."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T16:57:59.970",
"Id": "59099",
"Score": "0",
"body": "@broke You can forget about interfaces and DI for now, it's not necessary for a service layer. Just think of your service classes as a place to put business logic without the unnecessary burden of dealing with HTTP requests."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T17:09:51.060",
"Id": "59102",
"Score": "0",
"body": "@SilverlightFox There isn't much business logic in my controller besides setting viewbag values and trimming strings. Is that the code that should be put in a service layer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T17:14:39.997",
"Id": "59103",
"Score": "0",
"body": "@broke If you are implementing the service layer then it should be this that accesses the data layer. i.e. `Controller -> Server Layer -> Data Layer`. The service layer should be the go between for the controller and the data layer. Your controller should populate the view models from the data received from the service layer - the controller class should not care where this data is from, it is the service layer's responsibility for this to either retrieve from the data layer or to calculate it/derive it by other means and then return the values to the controller."
}
] |
[
{
"body": "<p>It sounds like you need to add a service layer where you can include all your business logic. This way your controller classes do not become bloated with business logic and they are only dealing with the handling of requests and the population of view-models.</p>\n\n<p>Using thin controllers like this you can separate your logic out to different services and make it easier to practice the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a>.</p>\n\n<p>Please see this question and accepted answer but I've included an example below: <a href=\"https://stackoverflow.com/questions/14887871/creating-a-service-layer-for-my-mvc-application\">Creating a service layer for my MVC application</a></p>\n\n<p>Your controller:</p>\n\n<pre><code>[Dependency]\npublic IInvoiceService InvoiceService;\n\npublic ActionResult Index()\n{\n //code\n return View(repairInvoice);\n}\n\n[HttpPost]\npublic ActionResult Index(RepairInvoice ri)\n{ \n this.InvoiceService.ProcessInvoice(ri.RmaNumber, ri.SerialNumber); // add on other params as appropriate\n return View(ri);\n}\n</code></pre>\n\n<p>Service layer would consist of multiple classes, each with their own responsibility such as:</p>\n\n<pre><code>public class InvoiceService : IInvoiceService\n{\n public void ProcessInvoice(string rmaNumber, string serialNumber) \n {\n // Do any processing here\n }\n}\n</code></pre>\n\n<p>I would recommend creating an interface for each separate service and then you can use <a href=\"http://msdn.microsoft.com/en-us/library/dn178463(v=pandp.30).aspx\" rel=\"nofollow noreferrer\">Dependency Injection</a> to instantiate the concrete classes using <a href=\"https://unity.codeplex.com/\" rel=\"nofollow noreferrer\">Unity</a> or similar.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T17:41:55.370",
"Id": "58931",
"Score": "0",
"body": "These links you provided show some very pretty pictures, but those don't help very much. If a service layer is what I need, then a how to guide with code examples would be way more helpful. I have no idea what the code for this service layer is supposed to look like, or where to put it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T18:04:23.977",
"Id": "58933",
"Score": "0",
"body": "@broke OK, code example added."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T17:14:05.667",
"Id": "36062",
"ParentId": "36061",
"Score": "7"
}
},
{
"body": "<p>Although @SilverlightFox is right in that you need to separate your business logic from contoller; this in itself will not improve readability of your code; as the biggest problem, namely <strong>Arrow Code</strong> will still remain.</p>\n\n<p><strong>Arrow Code</strong> results from to many nesting levels in code. \nAlso in an <code>if/else</code> statement handling the exceptional case later separates the condition from its consequence. By handling the exceptional case next to the condition and returning early solves both problems.</p>\n\n<p>Your business logic method would look like this after said transformation.</p>\n\n<pre><code>public RmaDetail SerialNumberScan(int rmaNumber, int serialNumber, RepairInvoice repairInvoice) {\n var result = SelectRmaDetail(rmaNumber, serialNumber);\n\n if (result != null) throw new BusinessException(\"Serial Number not found.\");\n\n if (result.Received != 1) throw new BusinessException(\"Line item has not been received.\");\n\n bool? workOrderClosed = WorkOrderClosed(result.LNSEQNBR, result.LNSEQNBR, serialNumber);\n\n if (!workOrderClosed.HasValue) throw new BusinessException(\"Work order not found.\");\n\n if (workOrderClosed.Value == false) throw new BusinessException(\"Work order not closed.\");\n\n repairInvoice.TerminalType = result.ITEMNMBR.Trim();\n repairInvoice.UnderWarranty = RepairInvoiceDataLayer.UnderWarranty(result.RETDOCID, result.LNSEQNBR, serialNumber, result.CUSTNMBR);\n\n return result;\n}\n</code></pre>\n\n<p>The rest of the spaghetti comes from user input validation. Although it, too, can be remedied by short-cut returns; the better way would be doing as much validation declaratively as possible. General error handling should also be done declaratively. After making those changes your <code>SerialNumberScan</code> action read like the following:</p>\n\n<pre><code>public ActionResult SerialNumberScan(string rmaNumber, string serialNumber)\n{\n if (ModelState.IsValid)\n {\n ModelState[\"SerialNumber\"].Value = new ValueProviderResult(serialNumber, serialNumber, CultureInfo.CurrentCulture);\n try\n {\n var rmaDetail = BusinessLayer.SerialNumberScan(rmaNumber, serialNumber, repairInvoice);\n Session[\"RmaDetail\"] = rmaDetail;\n ViewBag.SetFocusTo = \"#RepairLevels\";\n }\n catch (BusinessException ex)\n {\n ViewBag.AlertMessage = ex.Message;\n }\n }\n\n return View(\"Index\", repairInvoice);\n}\n</code></pre>\n\n<h2>EDIT how not to have to pass repairInvoice to business layer</h2>\n\n<pre><code>// put this class in your business layer namespace\npublic class SerialNumberScanResult\n{\n public RmaDetail RmaDetail { get; private set; }\n public bool UnderWarranty { get; private set; }\n\n public SerialNuberScanResult(RmaDetail rmaDetail, bool underWarranty)\n {\n RmaDetail = rmaDetail;\n UnderWarranty = underWarranty;\n }\n}\n\n\npublic SerialNuberScanResult SerialNumberScan(int rmaNumber, int serialNumber) {\n var rmaDetail = SelectRmaDetail(rmaNumber, serialNumber);\n\n if (rmaDetail != null) throw new BusinessException(\"Serial Number not found.\");\n\n if (rmaDetail.Received != 1) throw new BusinessException(\"Line item has not been received.\");\n\n bool? workOrderClosed = WorkOrderClosed(rmaDetail.LNSEQNBR, rmaDetail.LNSEQNBR, serialNumber);\n\n if (!workOrderClosed.HasValue) throw new BusinessException(\"Work order not found.\");\n\n if (workOrderClosed.Value == false) throw new BusinessException(\"Work order not closed.\");\n\n bool underWarranty = RepairInvoiceDataLayer.UnderWarranty(rmaDetail.RETDOCID, rmaDetail.LNSEQNBR, serialNumber, rmaDetail.CUSTNMBR);\n\n return new SerialNuberScanResult(rmaDetail, underWarranty);\n}\n\npublic ActionResult SerialNumberScan(string rmaNumber, string serialNumber)\n{\n if (ModelState.IsValid)\n {\n ModelState[\"SerialNumber\"].Value = new ValueProviderResult(serialNumber, serialNumber, CultureInfo.CurrentCulture);\n try\n {\n var result = BusinessLayer.SerialNumberScan(rmaNumber, serialNumber);\n repairInvoice.TerminalType = result.RmaDetail.ITEMNMBR.Trim();\n repairInvoice.UnderWarranty = result.UnderWarranty;\n Session[\"RmaDetail\"] = result.RmaDetail;\n ViewBag.SetFocusTo = \"#RepairLevels\";\n }\n catch (BusinessException ex)\n {\n ViewBag.AlertMessage = ex.Message;\n }\n }\n\n return View(\"Index\", repairInvoice);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-04T17:47:02.900",
"Id": "60198",
"Score": "0",
"body": "The repairinvoice object that is being passed in is my model. Would I have to pass that in by ref so the changes would be reflected to my view?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-04T19:07:22.910",
"Id": "60213",
"Score": "0",
"body": "No you wouldn't have to pass by ref. We can further refactor to remove the need to pass `repairInvoice` altogether."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-04T19:26:36.380",
"Id": "60216",
"Score": "0",
"body": "@broke I edited my answer to show how not to have to pass repairInvoice to business layer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T09:04:58.900",
"Id": "36188",
"ParentId": "36061",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "36062",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T17:08:27.720",
"Id": "36061",
"Score": "7",
"Tags": [
"c#",
"asp.net-mvc-4"
],
"Title": "ASP.NET MVC to produce a repair invoice"
}
|
36061
|
<p>My project for my class is to create a Java-based game where the user must enter a number between 1-20 and a number between 250 and 300. The computer randomly chooses a number between those 2 numbers. Then the user has 10 guesses to correctly guess what number the computer is "thinking of."</p>
<p>There is a catch, though. We cannot use <code>while</code> loops, only <code>if</code> and <code>else-if</code> statements. I have started this code and was wondering if I'm on the right track. Please point out anything that might help me!</p>
<pre><code>package guessthenumber;
import java.util.Scanner;
import java.util.Random;
public class GuessTheNumber {
public static void main(String[] args)
{
int lowBoundary, highBoundary, secretNumber, boundaryDifference,
g1, g2, g3, g4, g5, g6, g7, g8,
g9, g10;
//g1, g2,... = guess 1, guess2,...
Scanner keyboard = new Scanner(System.in);
System.out.println("Can you guess the number I'm thinking of?\nLet's "
+ "see if you can guess the right number within 10 guesses.\n\n"
+ "First please enter a number between 1 and 20.");
lowBoundary = keyboard.nextInt();
System.out.println("Excellent! Next enter a number between 250 and "
+ "350.");
highBoundary = keyboard.nextInt();
boundaryDifference = highBoundary - lowBoundary;
Random randomNumber = new Random();
secretNumber = randomNumber.nextInt(boundaryDifference) + lowBoundary;
System.out.println("The secret number has been chosen. Now you must "
+ "guess\nthe secret number within 10 guesses or else you lose."
+ "\n(Hint: The secret number is between " + lowBoundary +
" and " + highBoundary + ".)");
g1 = keyboard.nextInt();
if (g1 == secretNumber) {
System.out.println("CONGRATULATIONS! YOU'VE CORRECTLY GUESSED\nTHE"
+ "SECRET NUMBER ON YOUR FIRST GUESS!!");
}
else if (g1 < secretNumber) {
System.out.println("Higher than " + g1 + ". Guess again!");
g2 = keyboard.nextInt();
{
if (g2 == secretNumber) {
System.out.println("Awesome! You've correctly guessed\nthe"
+ "secret number in 2 guesses!");
}
else if (g2 < secretNumber) {
System.out.println("Higher than " + g2 + ". Guess again!");
g3 = keyboard.nextInt();
if (g3 == secretNumber) {
System.out.println("Great job! You've correctly guessed\n"
+ "the secert number in 3 guesses!");
}
else if (g3 < secretNumber) {
System.out.println("Higher than " + g3 + ". Guess again!");
g4 = keyboard.nextInt();
if (g4 == secretNumber) {
System.out.println("Good job! You've correctly guessed\nthe"
+ " secret number in 4 guesses!");
}
else if (g4 < secretNumber) {
System.out.println("Higher than " + g4 + ". Guess again!");
g5 = keyboard.nextInt();
if (g5 == secretNumber) {
System.out.println("Not bad! You've correctly guessed\nthe"
+ " secret number in 5 guesses!");
}
else if (g4 > secretNumber) {
System.out.println("Lower than " + g4 + ". Guess again!");
}
}
}
else if (g3 > secretNumber) {
System.out.println("Lower than " + g3 + ". Guess again!");
}
}
else if (g2 > secretNumber) {
System.out.println("Lower than " + g2 + ". Guess again!"
);
g3 = keyboard.nextInt();
}
}
}
else if (g1 > secretNumber) {
System.out.println("Lower than" + g1 + ". Guess again!");
{
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I'm guessing you're not allowed to use any kind of loop, because then you could just use a for-loop.</p>\n\n<p>Anyhow, I would suggest you encapsulate more of your code in methods. Think about what kind of operations you use repeatedly.</p>\n\n<p>Also, you don't need multiple guessing variables (g1, g2, g3, ... , g10); you can make do with one.</p>\n\n<p>Now to solve the main problem. I would suggest using a recursive method (a method that calls for itself). It can very well act as a loop and you could, for example, count the guesses with it among other things.</p>\n\n<p>Here's an example of a recursive method that returns the sum of all integers from 1 up to a given number:</p>\n\n<pre><code>public static int sumIntegers(int number){\n if (number == 1)\n return number;\n return number + sumIntegers(number - 1);\n}\n</code></pre>\n\n<p>If you would call this method like this:</p>\n\n<pre><code>sumIntegers(5);\n</code></pre>\n\n<p>You would get: \n5 + 4 + 3 + 2 + 1 = 15</p>\n\n<p>Hope it helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T21:12:49.857",
"Id": "58941",
"Score": "2",
"body": "+1 for giving a push in the right direction without revealing too much (considering the **homework** tag on the question)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T21:10:20.783",
"Id": "36076",
"ParentId": "36074",
"Score": "12"
}
},
{
"body": "<p>This code is somewhat broken (slightly):</p>\n\n<pre><code> boundaryDifference = highBoundary - lowBoundary;\n Random randomNumber = new Random();\n secretNumber = randomNumber.nextInt(boundaryDifference) + lowBoundary;\n</code></pre>\n\n<p>This is one of the most <a href=\"https://stackoverflow.com/questions/363681/generating-random-numbers-in-a-range-with-java\">common duplicate problems on StackOverflow</a>, and it's a lesson you should just learn....</p>\n\n<p>The above code will never produce the value 'highBoundary`.</p>\n\n<p>This is because <code>nextInt(boundaryDifference)</code> produces a result from 0 to <code>boundaryDistance</code> <strong>excluding <code>boundaryDistance</code></strong>.</p>\n\n<p>The right way to get a random number from a given range including both limits of the range is:</p>\n\n<pre><code> int val = min + randomNumber.nextInt((max - min) + 1);\n</code></pre>\n\n<p>Never forget the <code>+1</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T23:10:48.663",
"Id": "36087",
"ParentId": "36074",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T20:23:43.777",
"Id": "36074",
"Score": "10",
"Tags": [
"java",
"game",
"homework",
"random",
"number-guessing-game"
],
"Title": "Guess a random number between a selected interval"
}
|
36074
|
<p>I am struggling with commenting and variable naming. My teacher says my comments need to be more explanatory and explicit. He says my variable names are also sometimes confusing. I was just wondering whether you could go through my code, see whether you are able to understand the comments and whether the variables names are appropriate. And of course, suggest improvements where you feel they are needed.</p>
<pre><code>#Caesar Cipher
#Function that reads and writes data to the file, and calls the encryption and decryption methods.
#It isolates the key and choice of the user, and then calls the appropriate function.
def isolate():
#Open input file in read mode
fin = open('Input3.txt', 'r')
#Open output file in write mode
fout = open('Out1.txt', 'w')
#Create a list that holds each line of the file as an element of the list
container = fin.readlines()
#For loop that goes through each line of the file (contianed in list) and isolates the choice and key of the user
#Then it removes the key and choice from the split input list and calls the appropriate method.
for i in container:
#Each element of the list becomes a list (words) with all spaces and '\n' removed
words = i.split()
#The key of the user is always the last element of the split() list.
key = int(words[len(words) - 1])
#The choice of the user is always the second last element of the split() list.
choice = words[len(words) - 2]
#Remove the key and choice from the message
words.remove(str(key))
#Remove the choice of the user from the message for encryption/decryption.
words.remove(choice)
#Join together all the elements of the message in a string
message = ' '.join(words)
message = message.upper()
#If the user wishes to encrypt, call the encrypt method. This method will return the encrypted message as a sting, which can then be written to the output file.
if choice == 'e':
#Write the newly encrypted message to the output file.
fout.write(encrypt(message, key) + '\n')
#If the user wishes to decrypt, call the decrypt method. This method returns the decrypted message as a string, which can then be written to the output file.
else:
fout.write(decrypt(message, key) + '\n')
#Close the file to make sure data is written properly to the file.
fout.close()
#Encryption method, which takes two parameters, the users message and key, and returns the newly encrypted message.
def encrypt(message, key):
#Empty string that will contain the encrypted message.
encrypted_message = ""
#Alphabet string, which contains all the letters of the alphabet at their index locations.
alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
#For loop that goes through each character of the users message and, if a space, adds it straight to the encrypted message or encrypts it through modular division.
for i in message:
#If the character is a space, add it to the final message.
if i == ' ':
#Concatenate the space to the final message
encrypted_message += ' '
#If the character is not a space, determine the final locatin out of index range, % by 26 and re-add the character at this index to the encrypted_message.
else:
#Determine the final location of the character (out of index range)
location = key + alpha.index(i)
#% this location by 26 to determine the location within the proper index.
location %= 26
#Finally, concatenate the letter at this location to the final message.
encrypted_message += alpha[location]
#When the function is called, have it return the final encrypted message.
return encrypted_message
#Decryption method that takes two parameters, the users message and key, and returns the newly decrypted message.
def decrypt(message, key):
#Create a string that reverses the alphabet, since we are moving backwards when we decrypt.
reverse_alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[::-1]
#Empty string that will hold the decrypted message.
decrypted_message = ""
#For loop that runs through each element of the users message and, if space, re adds it to the message, or encrypts using % division and concatenates to final message.
for i in message:
#If the element is a space, do not encrypt; concatenate it to the final message.
if i == ' ':
#Concatenate the space to the final message.
decrypted_message += ' '
#If the element is not a space, encrypt the letter.
else:
#Determine the final location out of index range of the encrypted character, and store it in the variable 'location'
location = key + reverse_alpha.index(i)
#% this position by 26 to determine the index location in range of the letter.
location %= 26
#Finally, add the letter at this location to the decrypted message.
decrypted_message += reverse_alpha[location]
#Converts the decrypted message into lowercase form.
decrypted_message = decrypted_message.lower()
#When the function is called, have it 'give back' the decrypted message so that it can be written to the output file.
return decrypted_message
#Call the function isolate5(), which initiates the program.
isolate()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T21:44:31.630",
"Id": "58952",
"Score": "1",
"body": "Your variable names look mostly fine to me, and the comments look _more_ explicit than they should be. As for improvements, you could try using docstrings and function annotations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T21:46:46.500",
"Id": "58953",
"Score": "6",
"body": "i wouldn't say this `#Open input file in read mode` the function open explains itself. Maybe change the `i` in `for i in container:` to `word` or something. Personaly I think there's too many comments"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T21:48:51.753",
"Id": "58954",
"Score": "0",
"body": "not sure if your teacher wants to explain with comments to proove you didn't copy but say you don't have to explain the `return` statement. ` #When the function is called, have it 'give back'...`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T21:54:06.537",
"Id": "58956",
"Score": "0",
"body": "@FooBarUser Which comments do you feel are unnecessary"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T22:03:40.620",
"Id": "58958",
"Score": "0",
"body": "at least the 2 explaining file opening, the one that explains the return and the one that expains that the function is called. unless your teacher asked you to explain it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T22:11:57.857",
"Id": "58961",
"Score": "0",
"body": "no problem i think @Yann Vernier gave a more complete explanation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T20:52:56.193",
"Id": "59166",
"Score": "1",
"body": "Many of the comments here are spot on. A really good reference for this sort of thing is [The Art of Readable Code,](http://www.amazon.com/The-Readable-Code-Theory-Practice/dp/0596802293) which covers exactly the questions you're asking well (along with other useful hints on code layout)."
}
] |
[
{
"body": "<p>You'll find that there are many attitudes, but the type of commenting you've shown here is largely only helpful as a language learner. When I look at the code, already familiar with the language, the comments are way <em>too</em> explicit. You've essentially got comments repeating what every line of code does, often overshadowing the more important question of why. </p>\n\n<p>I already know that a <code>def</code> line defines a function, what the arguments of <code>open</code> mean, I can see the number of arguments in the code, and I know that an <code>else</code> block has the opposite condition to the <code>if</code>. It's even easier, knowing Python's slice conventions, to read <code>words[-1]</code> as the last word than something involving function calls (<code>words[len(words) - 1]</code>). Also, the descriptions of functions really belong in docstrings, so I can look them up in the interpreter. </p>\n\n<p>As for naming, there is very little to complain about. <code>fin</code> and <code>fout</code> could be expanded, mostly to avoid confusion with the word fin, and the iteration name <code>i</code> is a holdover from the old days of interpreters that only handle single letter variables; nowadays we use it to avoid tedious typing, but that's not a good reason when it's only typed twice. A descriptive name such as <code>line</code> would be better. The one bugbear is <code>isolate</code>, because that doesn't describe the procedure at all; it seems to do batch processing of files, generating a subroutine call for each line. I suppose that iteration processes lines in isolation, but it's really not clear from the call what is manipulated or in what way. </p>\n\n<p>What I'm missing in the comments is an example of how the input and output data in files would look. The actual column format (looks like <code>message e|d key</code>, where key is an integer, e means encrypt, and message may contain spaces) isn't easily read from the parsing code. We also run into logic mistakes when you remove <code>choice</code> and <code>key</code> from <code>words</code>; you really ought to use <code>key = int(words.pop())</code>, such that it's impossible to confuse which item you're removing. Converting to and from int, and searching by value rather than place, will break for some lines, e.g. <code>secret e message e 003</code>.</p>\n\n<p>The last comment demonstrates the biggest problem with comments that describe what the code does, rather than what it is intended to do. They invariably get out of sync, and at that point only cause confusion. </p>\n\n<p>The code itself could be reduced considerably using Python's high level libraries (for instance, <code>str.translate</code> and <code>str.rsplit</code>) but that is quite separate from the naming and commenting you asked opinions on. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T22:04:21.357",
"Id": "36081",
"ParentId": "36078",
"Score": "12"
}
},
{
"body": "<p>Commenting every single line is excessive by most programmers' norms. There is a coding style called <a href=\"http://en.wikipedia.org/wiki/Literate_programming\">literate programming</a> that heavily emphasizes comments, but even in literate programming, commenting every line would be frowned upon.</p>\n\n<p>The most important kind of comment in Python is the <a href=\"http://www.python.org/dev/peps/pep-0257/\">docstring</a>, and you didn't write any.</p>\n\n<p>Many of your comments just repeat self-explanatory code. For example, this comment does nothing but double the amount of text a programmer has to read:</p>\n\n<pre><code>#Open input file in read mode\nfin = open('Input3.txt', 'r')\n</code></pre>\n\n<p>If you really had to guide a novice, you could make the comment less obtrusive by relocating it to the end of the line:</p>\n\n<pre><code>fin = open('Input3.txt', 'r') # 'r' = read-only\n</code></pre>\n\n<p>It's usually easy to see what each line of code does individually. However, comments can be very useful in providing the big picture. You would also be able to do a better job of describing intentions by explaining several lines of code at once.</p>\n\n<p>Improving the naming and comments without changing the code <em>at all</em>:</p>\n\n<pre><code>def run_caesar_cipher_batch():\n \"\"\"Processes Input3.txt to generate Out1.txt.\n Input3.txt contains input lines of the form\n The quick brown dog e 3\n VJG SWKEM DTQYP FQI d 3\n\n The last two words of each line are:\n 'e' or 'd', indicating the choice to encrypt/decrypt, and\n an integer, which acts as the Caesar cipher key.\n\n Within each line, all whitespace, even multiple consecutive\n whitespace characters, is treated as a single space.\n \"\"\"\n fin = open('Input3.txt', 'r')\n fout = open('Out1.txt', 'w')\n input_lines = fin.readlines()\n\n for line in input_lines:\n # List of words, with whitespace and trailing '\\n' removed\n words = line.split()\n\n # Interpret and remove the last two words\n key = int(words[len(words) - 1])\n operation = words[len(words) - 2]\n words.remove(str(key))\n words.remove(operation)\n\n # Re-join the words of the message. The message may differ from\n # the original if there is consecutive whitespace.\n message = ' '.join(words)\n message = message.upper()\n\n # Encrypt or decrypt to fout\n if operation == 'e':\n fout.write(encrypt(message, key) + '\\n')\n else:\n fout.write(decrypt(message, key) + '\\n')\n\n fout.close()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T22:42:43.563",
"Id": "58964",
"Score": "3",
"body": "Good example of a docstring. The link to literate programming seems rather misleading though; I've never seen a literate programmer advocate commenting on a line basis, let alone commenting every line. The idea is to structure the code as the plan, instead of keeping design and functionality as separate entities."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T22:28:43.363",
"Id": "36082",
"ParentId": "36078",
"Score": "29"
}
},
{
"body": "<p>You are commenting far too much, to the point that it obscures the program. For example,</p>\n\n<pre><code># When the function is called, have it 'give back' the decrypted message so that it can be written to the output file.\nreturn decrypted_message\n</code></pre>\n\n<p>Surely <code>return decrypted_message</code> should be self-explanatory?</p>\n\n<p>In fact, this \"explanation\" is almost deceptive - the function doesn't actually know (or need to know) where the output is going - it decrypts a message, it doesn't care whether the message is going to be printed to the screen or sent in an email or thrown away.</p>\n\n<p>You are also commenting at the wrong level - explaining <em>what each line does</em> instead of <em>why it does it</em>. For example</p>\n\n<pre><code>#Converts the decrypted message into lowercase form.\ndecrypted_message = decrypted_message.lower()\n</code></pre>\n\n<p>That's nice, but <em>why</em> should the message be lowercase?</p>\n\n<p>The whole thing could be much more succinct:</p>\n\n<pre><code># Caesar Cipher\n# Encrypt or decrypt using a shift-by-N cipher\n\nORD_A = ord('a')\n\ndef caesar_cipher(msg, n):\n \"\"\"\n Return an alphanumeric string with each letter incremented N characters\n \"\"\"\n return ''.join(' ' if ch==' ' else chr((n + ord(ch) - ORD_A) % 26 + ORD_A) for ch in msg)\n\ndef process_file(infname, outfname):\n \"\"\"\n Read a text file\n Encrypt or decrypt each line\n Write the result to a text file\n \"\"\"\n with open(infname) as inf, open(outfname, 'w') as outf:\n for line in inf:\n # Each line is of the form 'text to encrypt [op] [n]'\n # where op is 'd' to decrypt or 'e' to encrypt\n # and n is the number of characters to shift by\n msg, op, n = line.rsplit(None, 2)\n\n # Decrypting by N is the same as encrypting by -N\n n = int(n) * (1 if op=='e' else -1)\n\n # Encrypt and save the result\n msg = caesar_cipher(msg.lower(), n)\n outf.write(msg + '\\n')\n\nif __name__==\"__main__\":\n inf = raw_input('Name of input file? ')\n outf = raw_input('Name of output file? ')\n process_file(inf, outf)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T23:50:17.207",
"Id": "58969",
"Score": "1",
"body": "I would move the `open()` operations outside `process_file()`, so that the caller has the flexibility to call `process_file(sys.stdin, sys.stdout)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-15T16:10:01.270",
"Id": "252795",
"Score": "0",
"body": "It would be clearer to write `line.rsplit(maxsplit=2)`. Also, I would pass `op` to `caesar_cipher(msg.lower(), int(n), op)` and there would have `if op=='d': n = -n`. You don't need the assignment before `write`, you could pass the result directly. I also posted a [different implementation of `caesar_cipher`](http://codereview.stackexchange.com/a/135004/110989) that may be more Pythonic."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T22:45:59.527",
"Id": "36085",
"ParentId": "36078",
"Score": "11"
}
},
{
"body": "<p>The code in the OP is <em>extremely</em> over-commented. (No offense)</p>\n\n<p>The other answers have covered all the bases, very well, but there is one thing I want to emphasise from <a href=\"https://codereview.stackexchange.com/a/36081/20138\">Yann Vernier's answer</a>:</p>\n\n<blockquote>\n <p>The last comment demonstrates the biggest problem with comments that describe what the code does, rather than what it is intended to do. They invariably get out of sync, and at that point only cause confusion.</p>\n</blockquote>\n\n<p>This is the biggest problem with over-commented code, in general. It's a serious concern:</p>\n\n<ul>\n<li>Comments are just like anything else in a code-base, <em>they have to be maintained</em>.</li>\n<li>Out of synch comments are not just <em>worthless</em>; they're <em>dangerous</em>. </li>\n</ul>\n\n<p>Personally, I think under-commenting is preferable to over-commenting, any day of the week. An assignment is one thing; it doesn't change when you're done. But, most code lives on and a variety of people change it, each one having to digest and maintain <em>both</em> the code and the comments.</p>\n\n<p>Please be selective when commenting.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-28T08:19:35.033",
"Id": "64064",
"ParentId": "36078",
"Score": "0"
}
},
{
"body": "<p>I understand that you welcome suggestions other than regarding comments:</p>\n\n<blockquote>\n <p>And of course, suggest improvements where you feel they are needed.</p>\n</blockquote>\n\n<p>Your <code>encode</code> and <code>decode</code> functions could be rewritten to better utilize Python facilities:</p>\n\n<pre><code>from string import ascii_lowercase\n\ndef caesar_cipher(message, n, op='e', alphabet=ascii_lowercase):\n \"\"\"\n Encode or decode `message` using Caesar cipher with shift `n`.\n\n Each letter in `message` gets replaced by a letter `n` positions\n down the `alphabet` if encoding (`op=='e'`), or up if decoding (`op=='d'`).\n\n Characters not in `alphabet` remain unchanged.\n \"\"\"\n if op=='d': n = -n\n shift = dict(zip(alphabet, alphabet[n:] + alphabet[:n]))\n return ''.join(shift.get(c, c) for c in message)\n</code></pre>\n\n<p>Slice notation makes it easy to <a href=\"https://stackoverflow.com/q/2150108/1916449\">cyclically rotate lists</a>, which is exactly what we need for Caesar cipher. It works perfectly for decoding also, because <code>a[-i:]</code> means <code>a[len(a)-i:]</code> in Python.</p>\n\n<p>We build a dictionary for the cipher mapping by zipping together respective positions of the original and shifted lists.</p>\n\n<p><code>dict</code> has the handy <a href=\"https://docs.python.org/3.5/library/stdtypes.html#dict.get\" rel=\"nofollow noreferrer\"><code>get</code></a> method that lets us provide a default value to return if the key is not present in the <code>dict</code>. This way, we don't need to check if the character is a space and return a space if it is, instead we use it as the default value. For free this handles other characters like numbers or punctuation.</p>\n\n<p>Instead of a loop, use a generator expression and pass it as argument to <code>''.join()</code>.</p>\n\n<p>By making <code>alphabet</code> a parameter, we allow the use of more characters for encoding with the cipher.</p>\n\n<p>Finally, I included a docstring that documents the method, to address your main concern of commenting the code.</p>\n\n<p>Note that if I followed the commenting style of the code from your original post, I would have to place all the explanation of how the code works in this answer as comments in the code. However, this is not what comments are for. When writing code for nondidactic purposes, you assume the person reading the code either knows the language very well, or can check the documentation for some particular parts. So instead of commenting how <code>shift.get(c, c)</code> works, I assume the reader knows it or will see the documentation of <code>dict.get</code>. I left the comment saying that characters not in alphabet remain unchanged, but I don't explain how that happens, as I expect it is easy enough to infer that from the code and documentation.</p>\n\n<p>Things that warrant an explanation in a comment are things that are not offered by the language or libraries we use. Comments should be used for the logic we create.</p>\n\n<hr>\n\n<p>Alternatively, the <code>caeser_cipher</code> could use <a href=\"https://docs.python.org/3.5/library/stdtypes.html#str.translate\" rel=\"nofollow noreferrer\"><code>str.translate</code></a> as suggested by Yann Vernier, with <a href=\"https://docs.python.org/3.5/library/stdtypes.html#str.maketrans\" rel=\"nofollow noreferrer\"><code>str.maketrans</code></a> like this:</p>\n\n<pre><code>message.translate(str.maketrans(alphabet, alphabet[n:]+alphabet[:n]))\n</code></pre>\n\n<p>Which makes for an even better implementation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-15T17:07:09.967",
"Id": "252811",
"Score": "1",
"body": "`'abcdefghijklmnopqrstuvwxyz'` can (and probably should) be written as [`string.ascii_lowercase`](https://docs.python.org/3/library/string.html#string.ascii_lowercase)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-15T16:07:06.770",
"Id": "135004",
"ParentId": "36078",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T21:31:11.250",
"Id": "36078",
"Score": "23",
"Tags": [
"python",
"homework",
"caesar-cipher"
],
"Title": "Reading and writing data for Caesar cipher"
}
|
36078
|
Comments are non-executable remarks embedded in source code that are directed at programmers or that are for documentation. Use this tag to indicate that the comments in the code are a concern (verbosity, helpfulness, or formatting).
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T21:55:23.433",
"Id": "36080",
"Score": "0",
"Tags": null,
"Title": null
}
|
36080
|
<p>I'm debating which version would be more suitable in parameters of code length, readability and maintenance. This is a portion of a set of functions which together parse a Gif file.</p>
<p><strong>Version 1:</strong></p>
<pre><code>if ((errno = GifLoadHeaders(g, &bufTemp)) != GIF_SUCCESS) {
GifDispose(g);
*gPtr = NULL;
return errno;
}
if ((errno = GifLoadGCT(g, &bufTemp)) != GIF_SUCCESS) {
GifDispose(g);
*gPtr = NULL;
return errno;
}
if ((errno = GifLoadImages(g, &bufTemp)) != GIF_SUCCESS) {
GifDispose(g);
*gPtr = NULL;
return errno;
}
</code></pre>
<p><strong>Version 2:</strong></p>
<pre><code>if ((errno = GifLoadHeaders(g, &bufTemp)) != GIF_SUCCESS
|| (errno = GifLoadGCT(g, &bufTemp)) != GIF_SUCCESS
|| (errno = GifLoadImages(g, &bufTemp)) != GIF_SUCCESS) {
GifDispose(g);
*gPtr = NULL;
return errno;
}
</code></pre>
<p>I generally prefer the latter version. Maybe there's a more optimal third solution to my issue. Any help?</p>
<p><strong>EDIT:</strong>
I'm sorry I did not include the entire routine. The code I've included is used in the function <code>GifParse</code> which initializes a given pointer to a <code>Gif</code> structure, which is named <code>gPtr</code>.</p>
|
[] |
[
{
"body": "<p>Without knowing the context, I'd write it as:</p>\n\n<pre><code>if( (errno = GifLoad( g, &bufTemp )) == GIF_SUCCESS ) {\n // Process the correctly loaded image as necessary.\n GifProcess( g );\n}\n\n// Release memory once processing is complete.\nGifDispose( g );\n*gPtr = NULL;\n\n// Single exit point to the function.\nreturn errno;\n</code></pre>\n\n<p>Then write a wrapper for GifLoad that calls the three other functions.</p>\n\n<p>This might not be a suitable solution if, for example, the processing is part of an interactive program wherein the processing is indeterminate. If processing cannot be coded at this point in the source, then consider:</p>\n\n<pre><code>if( (errno = GifLoad( g, &bufTemp )) != GIF_SUCCESS ) {\n // Perform whatever is necessary to inform the user the GIF cannot be loaded.\n GifInvalid( g );\n\n // Release memory.\n GifDispose( g );\n *gPtr = NULL;\n}\n\nreturn errno;\n</code></pre>\n\n<p>In both cases consider abstracting the three function calls into a single function, which cleans up the code and expresses the intent of those three function calls more concisely.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T23:15:41.817",
"Id": "58968",
"Score": "0",
"body": "I'm sorry I did not include the entire routine. The codes I included are used in the function `GifParse` which initializes a given pointer to a `Gif` structure, which is named `gPtr`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T23:07:47.777",
"Id": "36086",
"ParentId": "36083",
"Score": "4"
}
},
{
"body": "<p>I like your second option better than the first, and I like @DaveJarvis answer best. There are times when neither of these options is possible or elegant. For example when the called functions have many parameters your 2nd option gets ugly. And when there is more than one resource, the separate function design can be tricky. </p>\n\n<p>Just for the sake of it, here is another option:</p>\n\n<pre><code>int status = GifLoadHeaders(g, &buf);\nif (status == GIF_SUCCESS) {\n status = GifLoadGCT(g, &buf);\n}\nif (status == GIF_SUCCESS) {\n status = GifLoadImages(g, &buf);\n}\nif (status != GIF_SUCCESS) {\n GifDispose(g);\n *gPtr = NULL;\n return status;\n}\n// etc\n</code></pre>\n\n<p>You can of course start nesting things, but that usually gets unreadable after a few levels. My example above might be easier to step through in a debugger than your 2nd option. </p>\n\n<p>Note the use of <code>status</code> instead of the global <code>errno</code>. The <code>errno</code> variable is a bit special and should not normally not be written by you (and certainly not to anything other than 0). Also I replaced <code>bufTemp</code> with the shorter <code>buf</code> for readability.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T14:16:06.977",
"Id": "36135",
"ParentId": "36083",
"Score": "4"
}
},
{
"body": "<p>I would probably go with the second version if I had to choose among the two, with a slight variation like this:</p>\n\n<pre><code>bool success = (/* your if conditions here */)\nif (success) {\n // do your stuff here\n}\n</code></pre>\n\n<p>You could also use a function to check the condition, that way it is easier to add other conditions later. I had a similar thought when suggesting the <code>bool</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T14:52:30.587",
"Id": "36138",
"ParentId": "36083",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "36135",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T22:44:44.443",
"Id": "36083",
"Score": "6",
"Tags": [
"c",
"image",
"comparative-review",
"error-handling"
],
"Title": "Error handling for function calls to parse a GIF file"
}
|
36083
|
<p>I can't seem to get the formatting right, so here is the pastebin if needed:
<a href="http://pastebin.com/g6VmdYbM" rel="nofollow">http://pastebin.com/g6VmdYbM</a></p>
<pre><code>public class Hangman {
///////////////////////////////////
// Global Variables
///////////////////////////////////
private static String[] correctPhrase = new String[5];
private static String[] currentGuessPhrase = new String[5];
private static char[] currentGuesses = new char[26];
private static int totalWrong = 0;
private static int totalGuesses = 0;
private static int count;
private static char guess;
///////////////////////////////////
// Methods
///////////////////////////////////
public static void makePhrase() {
//Clear guesses
for (int x = 0; x < currentGuesses.length; x++){
currentGuesses[x] = ' ';
}
totalWrong = 0;
totalGuesses = 0;
//Preset Phrases (Must be 5 words)
String[] phraseOne = { "this", "is", "a", "sample", "phrase" };
String[] phraseTwo = { "another", "phrase", "is", "right", "here" };
String[] phraseThree = { "finally", "this", "is", "the", "last" };
//Random words for selection
String[] wordBank = { "a", "ate", "apple", "banana", "bored", "bear",
"cat", "cow", "carried", "died", "during", "deer", "elephant",
"flame", "fire", "fruit", "forgave", "forged", "fears", "goat",
"good", "game", "gave", "greeted", "glory", "ham", "hairy",
"heaven", "horrible", "I", "illegal", "important", "jammed",
"juice", "kangaroo", "liar", "loved", "money", "miracles",
"monday", "named", "never", "noun", "now", "nor", "orange",
"obligated", "person", "people", "peeled", "quit", "retired",
"rain", "saved", "sunny", "soaring", "salmon", "sealed",
"today", "tomorrow", "trained", "the", "umbrella", "up",
"under", "violent", "violin", "when", "while", "year", "zoo" };
//Get phrase type
Scanner in = new Scanner(System.in);
System.out.println("\n(1) Random Words (2) Presets (3) Custom");
int phraseType = in.nextInt();
if (phraseType == 1){
for (int x = 0; x < 5; x++) {
correctPhrase[x] = wordBank[(int) Math.round(Math.random() * 61)];
}
} else if (phraseType == 2) {
int phrase = (int) Math.round(Math.random() * 2);
switch (phrase){
case 0: correctPhrase = phraseOne.clone();
case 1: correctPhrase = phraseTwo.clone();
case 2: correctPhrase = phraseThree.clone();
}
} else if (phraseType == 3){
Scanner in2 = new Scanner(System.in);
System.out.println("5 Word Phrase: ");
correctPhrase = in2.nextLine().split("\\s");
}
//Create duplicate with underscores
for (int x = 0; x < correctPhrase.length; x++) {
currentGuessPhrase[x] = correctPhrase[x].replaceAll(".", "_");
}
}
public static char getGuess() {
Scanner in = new Scanner(System.in);
// Retrieve next guess
System.out.println("\nGuess:");
char guessInput = in.next().charAt(0);
return Character.toLowerCase(guessInput);
}
public static boolean checkGuess(char guess) {
// Add to guessed chars
currentGuesses[totalGuesses] = guess;
totalGuesses++;
// Count number of occurrences
count = 0;
for (int x = 0; x < correctPhrase.length; x++) {
for (int a = 0; a < correctPhrase[x].length(); a++) {
if (correctPhrase[x].charAt(a) == guess) {
count++;
}
}
}
if (count == 0) {
return false;
} else {
return true;
}
}
public static void updateGuess(char guess) {
// Define char array from currentGuess for alerting
char[][] currentGuessArray = new char[currentGuessPhrase.length][];
for (int x = 0; x < currentGuessPhrase.length; x++) {
currentGuessArray[x] = currentGuessPhrase[x].toCharArray();
}
//Assign valid values of guess to currentGuessArray
for (int x = 0; x < correctPhrase.length; x++) {
for (int a = 0; a < correctPhrase[x].length(); a++) {
if (correctPhrase[x].charAt(a) == guess) {
currentGuessArray[x][a] = guess;
}
}
}
// Convert chars back to string array
for (int x = 0; x < currentGuessArray.length; x++) {
currentGuessPhrase[x] = new String(currentGuessArray[x]);
}
}
public static void drawBoard(){
// Print previous guesses
System.out.println("\nGuesses:\n");
for (int x = 0; x < currentGuesses.length; x++) {
System.out.print(currentGuesses[x] + " ");
}
// Draw hangman
System.out.print(" \n ");
if (totalWrong == 0){
System.out.print("\n______" +
"\n| |" +
"\n| " +
"\n| " +
"\n| " +
"\n| " +
"\n| ");
} else if (totalWrong == 1){
System.out.print("\n______" +
"\n| |" +
"\n| O" +
"\n| " +
"\n| " +
"\n| " +
"\n| ");
} else if (totalWrong == 2){
System.out.print("\n______" +
"\n| |" +
"\n| O" +
"\n| |" +
"\n| " +
"\n| " +
"\n| ");
} else if (totalWrong == 3){
System.out.print("\n______" +
"\n| |" +
"\n| O" +
"\n| |" +
"\n| / " +
"\n| " +
"\n| ");
} else if (totalWrong == 4){
System.out.print("\n______" +
"\n| |" +
"\n| O" +
"\n| |" +
"\n| / \\" +
"\n| " +
"\n| ");
} else if (totalWrong == 5){
System.out.print("\n______" +
"\n| |" +
"\n| O" +
"\n| |-" +
"\n| / \\" +
"\n| " +
"\n| ");
} else if (totalWrong == 6){
System.out.print("\n______" +
"\n| |" +
"\n| O" +
"\n| -|-" +
"\n| / \\" +
"\n| " +
"\n| " +
"\n\n YOU DIED!");
//Print correct phrase
System.out.println("\n");
for (int x = 0; x < correctPhrase.length; x++){
System.out.print(correctPhrase[x] + " ");
}
}
//Print guessPhrase
System.out.println("\n");
for (int x = 0; x < currentGuessPhrase.length; x++){
System.out.print(currentGuessPhrase[x] + " ");
}
}
public static boolean goAgain(){
//Retreive yes/no
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(null, "Play again?", "Hangman", dialogButton);
if (dialogResult == 0 ){
return true;
} else {
return false;
}
}
///////////////////////////////////
// Main Method
///////////////////////////////////
public static void main(String[] args) {
boolean goAgain = true;
boolean isCorrect;
makePhrase();
while (goAgain){
//Print correct for debugging
/*for (int x = 0; x < correctPhrase.length; x++){
System.out.print(correctPhrase[x] + " ");
}
*/
drawBoard();
guess = getGuess();
isCorrect = checkGuess(guess);
//Update board
if (isCorrect) {
updateGuess(guess);
} else {
totalWrong++;
}
//Determine loss
if (totalWrong == 6){
drawBoard();
goAgain = goAgain();
if (goAgain){
makePhrase();
} else {
break;
}
}
//Determine win
if (Arrays.equals(correctPhrase, currentGuessPhrase)){
System.out.println("\nYOU WIN!" +
"\n O" +
"\n -|-" +
"\n / \\");
for (int x = 0; x < correctPhrase.length; x++){
System.out.print(correctPhrase[x] + " ");
}
goAgain = goAgain();
if (goAgain){
makePhrase();
}
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T22:52:14.083",
"Id": "58966",
"Score": "5",
"body": "what you mean by efficient?"
}
] |
[
{
"body": "<p>So, going through your code I am struck by a few things....</p>\n\n<ul>\n<li>static variables are seldom the 'right' way to do things in Object Oriented languages like Java. Other than for constants, it is a red flag that something is wrong.</li>\n<li>you have a problem with generating random numbers... e.g. <code>Math.round(Math.random() * 2)</code> will, in fact, generate values of 0, 1, and 2, but it will generate the value '1' twice as many times as it generates the values 0 or 2. <a href=\"https://stackoverflow.com/questions/363681/generating-random-numbers-in-a-range-with-java\">The 'right way' for doing random numbers is here on StackOverflow</a>. In this case, you want to create a <code>Random randgen = new Random()</code> instance, and use the <code>nextInt()</code> instance method to get random numbers: <code>randgen.nextInt(range)</code> or, in your 0,1,2 example, you want <code>randgen.nextInt(3);</code></li>\n<li>The code <code>correctPhrase[x] = wordBank[(int) Math.round(Math.random() * 61)];</code> is ugly. The <code>61</code> is a 'magic number' and would be best to replace with <code>wordBank.length</code>. The normal mechanism for this line of code is: <code>correctPhrase[x] = wordBank[randgen.nextInt(wordBank.length)];</code> (using the same randgen instance we created above.</li>\n<li>you do not convert the 'custom' input phrase to lowercase, which could result in issues, and you should validate that it only has 5 words... otherwise in the next piece of code you could gt an indexout-of-bounds exception when creating the underscore version.</li>\n<li><code>getGuess()</code> appears to be fine.</li>\n<li>checkGuess() is ugly because of the static variables again, and, in fact, the code is essentially a subset of the updateGuess() method. `checkGuess() can be completely removed.... I will describe how, in a moment.</li>\n<li>the <code>drawBoard()</code> method has lots of code and constant repetition. I would find a way to put a 'blank' board in an array of values (one per line), and then copy that array for each 'totalWrong, but adjust the lines where needed. Then, you can just loop through the lines that are relevant for your 'totalWrong' state (i.e. remove most of the code duplication).</li>\n<li>the <code>goAgain()</code> method suddenly has GUI components... odd...</li>\n<li>the <code>main()</code> method appears to be straight-forward enough, but would change a lot if you do what I suggest below:</li>\n</ul>\n\n<p>Suggestion, merge the logic of <code>checkGuess()</code> in to <code>updateGuess()</code>:</p>\n\n<pre><code>public static boolean guess(char guess) {\n // Define char array from currentGuess for alerting\n char[][] currentGuessArray = new char[currentGuessPhrase.length][];\n for (int x = 0; x < currentGuessPhrase.length; x++) {\n currentGuessArray[x] = currentGuessPhrase[x].toCharArray();\n }\n\n boolean goodguess = false;\n //Assign valid values of guess to currentGuessArray\n for (int x = 0; x < correctPhrase.length; x++) {\n for (int a = 0; a < correctPhrase[x].length(); a++) {\n if (correctPhrase[x].charAt(a) == guess) {\n currentGuessArray[x][a] = guess;\n goodguess = true;\n }\n }\n }\n // Convert chars back to string array\n for (int x = 0; x < currentGuessArray.length; x++) {\n currentGuessPhrase[x] = new String(currentGuessArray[x]);\n }\n return goodguess;\n}\n</code></pre>\n\n<p>You can then adapt the main method to:</p>\n\n<pre><code> if (!guess(guess)) {\n totalWrong++;\n } \n</code></pre>\n\n<hr>\n\n<h1>EDIT</h1>\n\n<p>Why static fields are ugly .... (and yes, I probably should have been more descriptive about this, but it is a big topic to answer)</p>\n\n<p>Static fields (not final/constant) are used to store program state. This is a bad pattern in OOP because it means your state is not encapsulated. Consider, for the moment, that a 'better' way to solve your problem would be:</p>\n\n<pre><code>public static final void main (String[] args) {\n do {\n String phrase = getPhrase();\n Hangman game = new HangMan(phrase);\n game.play();\n } while (goAgain());\n}\n</code></pre>\n\n<p>Then, you have a <code>Hangman</code> class that encapsulates the state for that instance of the game only:</p>\n\n<pre><code>public class Hangman {\n private final String[] correctPhrase = new String[5];\n private final String[] currentGuessPhrase = new String[5];\n private final char[] currentGuesses = new char[26];\n private int totalWrong = 0;\n private int totalGuesses = 0;\n\n ... and lots of code to make the game work....\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T08:59:22.043",
"Id": "59020",
"Score": "0",
"body": "static members are neither good nor bad, it depends on how you design your program and what its intended use is. In this particular case, yes, static is the wrong way to go about it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T23:57:43.483",
"Id": "36091",
"ParentId": "36084",
"Score": "6"
}
},
{
"body": "<p>This code in <code>makePhrase()</code> should be a <code>switch</code> block:</p>\n\n<pre><code>if (phraseType == 1) {\n ...\n} else if (phraseType == 2) {\n ...\n} else if (phraseType == 3) {\n ...\n}\n</code></pre>\n\n<p>Within the <code>phraseType == 2</code> case, your <code>switch</code> is buggy: all cases flow through to <code>correctPhrase = phraseThree.clone()</code>.</p>\n\n<p>The cascading if-elses in <code>drawBoard()</code> should also be put into a <code>switch</code>. Better yet, there should be an array with all of the images, then you could index into the array:</p>\n\n<pre><code>private static final String[] IMAGES = {\n // Initial:\n \"\\n______\" +\n \"\\n| |\" +\n \"\\n| \" +\n \"\\n| \" +\n \"\\n| \" +\n \"\\n| \" +\n \"\\n| \",\n\n // 1 wrong:\n \"\\n______\" +\n \"\\n| |\" +\n \"\\n| O\" +\n \"\\n| \" +\n \"\\n| \" +\n \"\\n| \" +\n \"\\n| \",\n\n // etc.\n\n // 6 wrong:\n \"\\n______\" +\n \"\\n| |\" +\n \"\\n| O\" +\n \"\\n| -|-\" +\n \"\\n| / \\\\\" +\n \"\\n| \" +\n \"\\n| \" +\n \"\\n\\n YOU DIED!\"\n};\n</code></pre>\n\n<p>Then it's just <code>System.out.print(IMAGES[totalWrong]);</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T01:21:19.240",
"Id": "36092",
"ParentId": "36084",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T22:44:48.210",
"Id": "36084",
"Score": "3",
"Tags": [
"java",
"optimization",
"game",
"hangman"
],
"Title": "Hanging men efficiently"
}
|
36084
|
<p>Coming from Java and Android development and Objective-C still is a bit strange to me, but I just went in head first and started writing code. Before I started getting really far into it, I just want to throw some basic code here for suggestions about correct syntax, etc. I just want to make sure that my variable and function declarations are correct as well as the way I refer to UI elements is the recommended method.</p>
<p>I was told to make a separate <code>ViewController</code> class for each UI I build as below:</p>
<pre><code>@interface CalculatorViewController : UITableViewController
@property (weak, nonatomic) IBOutlet UITextField *fatTextField;
@property (weak, nonatomic) IBOutlet UITextField *carbsTextField;
@property (weak, nonatomic) IBOutlet UITextField *fiberTextField;
@property (weak, nonatomic) IBOutlet UITextField *proteinTextField;
@property (weak, nonatomic) IBOutlet UITextField *servingsTextField;
@property (weak, nonatomic) IBOutlet UITextField *foodnameTextField;
@property (weak, nonatomic) IBOutlet UILabel *pointsLabel;
- (IBAction)calculate:(id)sender;
- (IBAction)reset:(id)sender;
- (IBAction)addtotracker:(id)sender;
- (void)resetCalculator;
- (void)calculatePoints;
</code></pre>
<p>Then inside the CalculatorViewController.m file I ended up with the following code snippets:</p>
<pre><code>// UI FUNCTIONS
- (void) resetCalculator {
// Reset all nutrion fact fields.
_fatTextField.text = @"";
_carbsTextField.text = @"";
_fiberTextField.text = @"";
_proteinTextField.text = @"";
_servingsTextField.text = @"";
// Reset food name & points label
_foodnameTextField.text = @"";
_pointsLabel.text = @"Points: 0";
// Set Fat as firstresponder
[self.fatTextField becomeFirstResponder];
}
- (void) calculatePoints {
float fatFloat = [_fatTextField.text floatValue];
float carbsFloat = [_carbsTextField.text floatValue];
float fiberFloat = [_fiberTextField.text floatValue];
float proteinFloat = [_proteinTextField.text floatValue];
float servingsFloat = [_servingsTextField.text floatValue];
float points = proteinFloat + carbsFloat + fatFloat - fiberFloat;
points = points / 100;
points = roundf(points);
points = MAX(points, 0);
_pointsLabel.text = [NSString stringWithFormat:@"Points: %f", points];
}
- (IBAction)calculate:(id)sender {
NSLog(@"Calculate button pressed!");
// Close the keyboard
[self.view endEditing:YES];
}
- (IBAction)reset:(id)sender {
NSLog(@"Reset button pressed!");
[self resetCalculator];
}
- (IBAction)addtotracker:(id)sender {
NSLog(@"Tracker button pressed!");
}
</code></pre>
|
[] |
[
{
"body": "<p>There are a lot of takes on how to structure things in Objective-C, largely based on the age of the language. It used to require you to use <em>x</em>, but now it lets you use <em>y</em>, kind of things. I like to go with the minimalist/OOAD-purist approach.</p>\n\n<p><strong>Your Header File</strong></p>\n\n<p>Your header file (CalculatorViewController.h) is your public interface for your class. This is what every other class sees when it compiles against it and has access to. As such, I keep it light. You don't want another class to set your <code>fatTextField</code> and if you did, you wouldn't want them to know the intimate details of how your form works so you'd pass a model object or something. I like my header to look like this:</p>\n\n<pre><code>@class ImportantStuff; // 4\n@protocol CalculatorViewControllerDelegate; // 5\n\n@interface CalculatorViewController : UITableViewController\n- (id)initWithImportantStuff:(ImportantStuff *)importantStuff; // 1\n@property (nonatomic, weak) id<CalculatorViewControllerDelegate> delegate; // 2\n@property (nonatomic, readonly) ImportantStuff *importantStuff; // 3\n@end\n\n@protocol CalculatorViewControllerDelegate <NSObject> // 6\n- (void)calculatorViewController:(CalculatorViewController *)calculatorViewController\n didFinishWithImportantStuff:(ImportantStuff *)importantStuff;\n@end\n</code></pre>\n\n<p>Highlighted lines:</p>\n\n<ol>\n<li>Create an initializer with everything you need to get the class started on work.</li>\n<li>Add a delegate or some other message passing pattern to send notifications back.</li>\n<li>Maybe, have some exposed properties for information that interfacing classes may want.</li>\n<li>As general practice, you should only reference the bare minimum number of headers in your header since it reduces circular dependencies and compile time. <code>@class</code> tells the compiler that a class with that name exists and it shouldn't worry about the details.</li>\n<li>With delegates you often have a chicken and egg scenario. The class references the protocol and the protocol references the class. Like with <code>@class</code> you can say you'll inherit it later.</li>\n<li>Populate your delegate with meaningful hooks.</li>\n</ol>\n\n<p><strong>Your Implementation File, Class Extension</strong></p>\n\n<p>Now that you've removed all those properties from your public header, you're getting compiler errors and need to stick them somewhere. The right spot is in your class extension, the thing that looks like a category but isn't. Xcode should have generated it as follows at the top of CalculatorViewController.m</p>\n\n<pre><code>@interface CalculatorViewController ()\n@end\n</code></pre>\n\n<p>Just stick all your <code>@property</code>'s there.</p>\n\n<p>As far as the method declarations, you don't need them. In C you need to declare functions ahead of time, but not with modern Objective-C. The only reason you need to declare them is if you're trying to expose them outside of your implementation.</p>\n\n<p><strong>Your Implementation File, Implementation</strong></p>\n\n<p>Things look good here. Just a couple things:</p>\n\n<ol>\n<li><p>Directly accessing instance variables (ivars), e.g. <code>_pointsLabel</code> has gone out of fashion. There's a lot of reasons for this with potential risks associated with both doing it and not doing it, but there's even a pedantic compiler warning you can turn on to catch it. Generally, you should use ivars only in getters, setters, and initializers, places where you need direct access or want to suppress side effects.</p></li>\n<li><p>There's no reason to have both <code>-reset:</code> and <code>-resetCalculator</code>. There are two interesting points here: First, somewhere in the codebase exists <code>#define IBAction void</code> so you can turn any <code>void</code> returning function into an <code>IBAction</code> assuming it has the right arguments. Second, controller actions support three structures: <code>-(IBAction)myAction:sender</code>, <code>-(IBAction)myAction:sender event:event</code> and <code>-(IBAction)myAction</code> with no arguments. You can just use <code>-(IBAction)resetCalculator</code>.</p></li>\n<li><p><code>addToTracker</code>, with camel case. Probably just a typo considering everywhere else. Be aware that Interface Builder provides zero compile time checking so if you change the signature or remove a method you <em>must</em> edit it in Interface Builder or it will crash your app.</p></li>\n</ol>\n\n<p><strong>The most important thing</strong></p>\n\n<p>No matter what style, or principles, or philosophies you adopt as an iOS developer, every other iOS developer will disagree with you, and you with them. Maybe it's the awesomeness/awfulness of the language or the tools or the platform or the status, but its a very opinionated group of developers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T07:35:49.910",
"Id": "64681",
"Score": "0",
"body": "Could you clarify what you said about the method declarations in terms of IBActions? Does that mean that for IBActions, you don't need to declare them at all in your header, and you can just write them in your implementation?\n\nAlso, your last point is very much the truth. For instance, I sometimes feel weird declaring \"private\" variables as properties because I don't need all the extra stuff that comes with properties. Other people feel that using ivars at all is akin to letting monkeys bang on your keyboard. To each his own."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T15:36:40.437",
"Id": "64711",
"Score": "0",
"body": "@boztalay Interface Builder will scan your files for interface *and* implementation methods defined with `IBAction` and just uses this for generating a list of binding points for when you create connections. That said, any method *just* used in the same `@implementation` it's implemented in does not need to be declared in an `@interface`. Unlike C functions, the compiler is comfortable with method definitions lower in the file."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T15:41:44.317",
"Id": "64713",
"Score": "0",
"body": "@boztalay And on instance variables, I just used one yesterday for a case where there's no good reason to access the storage type directly. The exposed methods were `shouldDisplaySiteForGroup:context:` and `invalidateGroupsToDisplaySites`. They are the only methods accessing the backing store and a property felt too formal. There's time and a place for everything, I guess."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-08T03:09:16.097",
"Id": "64819",
"Score": "0",
"body": "Thanks for replying, I didn't know that about IBActions. That should clean up some of my @interfaces significantly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T23:56:34.687",
"Id": "72874",
"Score": "0",
"body": "This is a pretty complete answer. I just don't understand the posted bit about @protocols. Not because I don't understand protocols... just because I don't think is very relevant here. Moreover, `init`-ing view controllers is quickly becoming \"the old way\", and if you're using storyboards, you won't be init-ing a view controller."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T00:35:13.083",
"Id": "72883",
"Score": "0",
"body": "I suppose that's all a matter of taste. When I spawn a view controller to create or operate on something, I typically treat the parent as the owner of the result. \"Create an X and hand it back to me.\" I like delegates for this. I suppose if you're using storyboards you would use something other than init for passing information, I've just never gotten to the point where storyboards are the right option for what I'm doing. I like init + readonly because it simplifies the state machine."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T15:56:41.450",
"Id": "36143",
"ParentId": "36088",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T23:44:11.850",
"Id": "36088",
"Score": "4",
"Tags": [
"objective-c",
"ios"
],
"Title": "Calculator ViewController"
}
|
36088
|
<p>PostgreSQL (often called "Postgres") is a powerful, object-relational database system (ORDBMS).</p>
<p>Open source since 1996, it has a proven architecture that has earned it a strong reputation for reliability, data integrity, and correctness. Standards compliance is a major focus of the development team. Postgres runs on all major operating systems, including Linux, UNIX (AIX, BSD, HP-UX, SGI IRIX, Mac OS X, Solaris, Tru64), and Windows.</p>
<p>Primary sources for information:</p>
<ul>
<li><a href="https://www.postgresql.org/docs/current/interactive/" rel="nofollow noreferrer">The comprehensive and clear manual</a></li>
<li><a href="https://wiki.postgresql.org/wiki/Identity_Guidelines" rel="nofollow noreferrer">The PostgreSQL wiki</a></li>
</ul>
<p>Related tags:</p>
<ul>
<li>Always include the <a href="/questions/tagged/sql" class="post-tag" title="show questions tagged 'sql'" rel="tag">sql</a> tag.</li>
<li>Also include the <a href="/questions/tagged/plpgsql" class="post-tag" title="show questions tagged 'plpgsql'" rel="tag">plpgsql</a> tag if applicable.</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T23:56:11.103",
"Id": "36089",
"Score": "0",
"Tags": null,
"Title": null
}
|
36089
|
PostgreSQL is an open-source, Relational Database Management System (RDBMS) available for many platforms including Linux, UNIX, MS Windows and Mac OS X. Please mention your PostgreSQL version when asking questions. Always include the "sql" tag and possibly the "plpgsql" tag if applicable.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T23:56:11.103",
"Id": "36090",
"Score": "0",
"Tags": null,
"Title": null
}
|
36090
|
<p>I have become interested in reflection and I wrote a class to wrap an Object so that I can access its private instance fields. The code works great. I do not need to wory about the exceptions in the <code>get()</code> and <code>set()</code> methods because I cast the values appropriately through my wrappers accessor/mutators, but I was wondering if there is a better way of dealing with different types?</p>
<p><strong>Example</strong></p>
<pre><code>public class Driver {
public static void main(String... args) {
Point p = new Point();
System.out.printf("Point initialized: %s\n", p);
PointDecorator mp = new PointDecorator(p);
mp.setX(2);
mp.setY(4);
p = mp.getPoint();
System.out.printf("Point updated: %s\n", p);
}
}
</code></pre>
<p><strong>Output</strong></p>
<pre><code>Point initialized: (0, 0)
Point updated: (2, 4)
</code></pre>
<p>As you can see, I have modified the Point Objects fields, although they are inaccessible through traditional method calls. I was able to bypass Java's typechecking which I find both neat and dangerous. Does this mean that anyone can just wrap another persons class, unless it is immutable, and inject data?</p>
<p><strong>Point.java</strong></p>
<pre><code>public class Point {
private int x, y;
public Point() {
this(0, 0);
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return String.format("(%d, %d)", x, y);
}
}
</code></pre>
<p><strong>PointDecorator.java</strong></p>
<pre><code>import java.lang.reflect.Field;
public class PointDecorator extends Point {
protected Point point;
public PointDecorator(Point point) {
this.point = point;
}
public void setX(int x) {
set("x", x);
}
public int getX() {
return (Integer) get("x");
}
public void setY(int y) {
set("y", y);
}
public int getY() {
return (Integer) get("y");
}
public Point getPoint() {
return point;
}
protected Object get(String fieldName) {
try {
return field(fieldName).get(point);
} catch (Exception e) { }
return null;
}
protected void set(String fieldName, Object value) {
try {
field(fieldName).set(point, value);
} catch (Exception e) { }
}
private Field field(String fieldName) {
try {
Field f = point.getClass().getDeclaredField(fieldName);
f.setAccessible(true);
return f;
} catch (Exception e) { }
return null;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T12:50:07.147",
"Id": "59043",
"Score": "2",
"body": "This question appears to be off-topic because the code to be reviewed is not 'actual code from a project' and but is 'pseudo-code or example code'. It belongs to programmers SE."
}
] |
[
{
"body": "<p>Essentially you are after the answer to:</p>\n\n<blockquote>\n <p>Does this mean that anyone can just wrap another persons class, unless it is immutable, and inject data?</p>\n</blockquote>\n\n<p>And you are not really interested in a review of your code... right? (By the way, your code looks neat, and covers the bases of your 'academic exercise' quite well).</p>\n\n<p>Java reflection is a dangerous process. On the up-side, reflection is regulated by the Java security system, and it can be enabled or disabled depending on the site, situation, and whatever else people are worried about.</p>\n\n<p>So, if someone has code in your JVM, then they have access to the internals of your program (assuming Java has a permissive setting for it's security - which is the 'default'). On the other hand, other languages (C, <em>cough</em> *cough*) have even more of a problem if someone has been able to 'inject' malicious code in to their program.</p>\n\n<p>It is all about relative-ness. Relative to many languages, Java is quite safe, and it has ways of being even safer.</p>\n\n<p>On the other hand, if you let someone untrusted run code on your JVM then you have bigger problems to worry about.... ;-)</p>\n\n<p>For what it's worth, there are easier ways to produce problematic code, like deserializing 'malicious' instances of values, or simply manipulating the JVM classpath before the program launches.</p>\n\n<p>It's all about perspective....</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T02:33:23.793",
"Id": "58980",
"Score": "0",
"body": "Well, I don't know too much about decorators, but I believe I am doing looks correct? Sorry I guess I was really asking for assurance. I thought it was neat and didn't actually think it would work at first :-p"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T02:41:51.893",
"Id": "58981",
"Score": "1",
"body": "The Point's internal `x` and `y` ar enot final, so that's one thing, and you do have it a little bit easier because you are only playing with primitive fields, and not methods and consructors. It gets a little bit hairy when you are dealing with things like constructors that have arrays of primitives (like double[]) arguments. Reflection gets complicated fast. You chose the 'hello world' problem to start on (which is a good thing)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T13:24:59.897",
"Id": "59053",
"Score": "1",
"body": "Just wanted to add this: Just because a field is final [doesn't mean that it can't be modified with reflection](http://stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection). Which is something @Mr.Polywhirl should be aware about regarding reflection."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T02:05:16.957",
"Id": "36098",
"ParentId": "36093",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T01:46:34.813",
"Id": "36093",
"Score": "0",
"Tags": [
"java",
"optimization",
"generics",
"reflection",
"type-safety"
],
"Title": "Java reflection: Inject data generically and safely"
}
|
36093
|
<p>I am trying to implement the F1 score <a href="http://www.kaggle.com/c/facebook-recruiting-iii-keyword-extraction/details/evaluation" rel="nofollow">shown here</a> in Python.</p>
<p>The inputs for my function are a list of predictions and a list of actual correct values. I thought that the most efficient way of calculating the number of true positive, false negatives and false positives would be to convert the two lists into two sets then use set intersection and differences to find the quantities of interest. Here is my code</p>
<pre><code>def F1_score(tags,predicted):
tags=set(tags)
predicted=set(predicted)
tp=len(tags.intersection(predicted))
fp=len(predicted.difference(tags))
fn=len(tags.difference(predicted))
if tp>0:
precision=float(tp)/(tp+fp)
recall=float(tp)/(tp+fn)
return 2*((precision*recall)/(precision+recall))
else:
return 0
</code></pre>
|
[] |
[
{
"body": "<p>To compute the length of a set difference, you only need to subtract the length of the intersection from the length of the set.\nYou could make use of the intersection when computing the differences. Subtracting the intersection gives the same result but processes fewer elements.</p>\n\n<pre><code>tags = set(tags)\npredicted = set(predicted)\n\ntp = len(tags & predicted)\nfp = len(predicted) - tp \nfn = len(tags) - tp\n</code></pre>\n\n<p>Note that I added spaces around operators to improve readability. I also used the <code>&</code> operator instead of the <code>intersection</code> method as a matter of preference.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T09:44:35.533",
"Id": "36118",
"ParentId": "36096",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "36118",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T01:59:16.680",
"Id": "36096",
"Score": "2",
"Tags": [
"python"
],
"Title": "Implementing F1 score"
}
|
36096
|
<p>I'm making this little game for programming class. Not as an assignment, but as a small side project. Just wanted to point out I do not know a lot about Python, so please don't be harsh, but I can take constructive criticism. </p>
<pre><code>from scene import *
from random import random
import console
import canvas
console.set_color(0.00, 0.00, 0.00)
console.set_font('Avenir', 18)
s = "Welcome to the Adventure."
width = 160
s = s.center(width)
print( s )
t = "To select a choice, simply type a number corresponding to your choice and press enter. Enjoy!"
width = 125
t = t.center(width)
print( t )
name = raw_input('\nWhat is your name?')
print 'You hear a strange sound, kind of like the tenderizing of meat.'
print '1. Open your eyes'
print '2. Keep them shut'
open = input('> ')
if open == "1":
print "You open your eyes, you look down and see you're dressed in a light blue gown. Upon further inspection you notice where you are, a hospital. To your left is a door blocked by a heavy cabinet. To your right is a window."
print '1. Look at your wrist tag'
print '2. Approach the barricaded door'
print '3. Approach the window'
rp = input('> ')
if rp == "1":
print'----------------------'
print name
print 'Camden, NJ'
print 'DOB: 1/13/89'
print 'Date: 10/15/13'
print'----------------------'
print'2013...?' # story will develop more
if rp == "2":
print 'You approach the door and try to open it, and the odd sounds of tenderizing meat stops...'
print 'BANG BANG! You jump back in fear...'
if rp == "3" or blue == "2":
print 'You step closer to the window...thick wooden boards lay'
print 'across the window, you manage to look through the small gaps, but'
print 'all you can see is some fries and a bench.'
print 'What next?'
print '1. Open Window'
print '2. Approach door'
var77 = input('> ')
if var77 == "1":
print 'You open the window, and hear a moaning sound'
print 'All of a sudden, the fries disappear...' # story will develop more
if var77 == "2":
print'You step closer to the door, on your last step eveything goes quiet'
print'BANG! BANG!'
print'Gunshots?' # story will develop more
if open == "2":
print 'You keep your eyes closed...'
print 'CLSHSHSSH, you hear the shattering of glass!'
print '1. Open your eyes'
print '2. Keep them shut'
insane = input('> ')
if insane == "1":
print 'You open your eyes and see a door with a small smashed window, brown dirty hands wave around where glass was once placed...'
print'1. Run back to the bed'
print'2. Find a weapon'
if insane == "2":
print 'You keep them shut and you hear more banging and crashing, footsteps and growling approach you. As you keep your eyes closed you feel dozens of hands go across your body! You start to feel an unbelievable sensation of burning, and pain shoots through your body...you know you are dying, and you keep your eyes shut out of fear. After a long minute of nothing you come to the conclusion that you are dead...'
yellow = input('> ')
if yellow == "1":
print'You run back to the bed and hide under the covers, all you can'
print'hear are hands waving and'
print'smacking each other, struggling to get inside.'
if yellow == "2":
print'You fly around the room searching everywhere for a weapon.'
print'You see a scalpel laying by a desk and a broom in the corner of the room.'
print'\nWhat do you want to take as a weapon?'
print'1. Scalpel'
print'2. Broom'
orn = input('> ')
if orn == "1":
print'You grab the scalpel, its kind of small, but the sharp edge will'
print'cut through skin if needed'
if orn == "2":
print'You grab the broom, decent weight, good for bashing.'
print'It could be broken in half if you need something with a point.'
if orn == "1" or "2":
print'You look around the room and see a door, and upon further inspection'
print'a window in the corner of the room'
print'1. Go towards the door'
print'2. Go towards the window'
blue = input('> ')
if blue == "1":
print'You step closer to the door, on your last step eveything goes quiet'
print'BANG! BANG!'
print'Gunshots?' # story will develop more
</code></pre>
|
[] |
[
{
"body": "<p>The biggest thing you can do to improve the code is to find ways to make the relationship between the game flow, the data, and the code more concise.</p>\n\n<p>Right now the whole game is a series of if statements, and you're using variable names as the equivalent of old-fashioned GOTOs to jump around the code. For something this short that's bearable, but it won't scale to any larger size. Moreover, your structure is going to force the user to make one-time-only decisions at each point - you don't have a way for users to, say, go to the window and THEN look at the wristband. Or to go back, for that matter. That might be your design intention but if you change your mind the current structure will be a lot of work to fix. Last but not least, you don't have any error handling - if the user enters a wrong choice, the program will just move on to the next prompt without assistance.</p>\n\n<p>On a very general level you need to establish a structure that reflects the nature of the game. Most text adventures are really a series of linked containers; the container (a 'room' in the old school dungeon game, a 'scene' in a conversation based game, etc) contains a descriptive text and a set of options for the user which link to other containers, and so on. The contents differ but the structures are basically identical; it's a good idea to write the code in a way that reflects the way the game actually works.</p>\n\n<p>If you're familiar with object oriented programming, this is a perfect problem to tackle with classes. If not, you can still make your life easier by creating a function that handles the repetitive part and putting the data into clearly labeled variables.</p>\n\n<p>Here's a very rudimentary example that uses dictionaries to represent each room and a dictionary of rooms to represent the map. The 'code' is just to keep calling the same function on whatever rooms the user gets from their choice of actions. </p>\n\n<pre><code>import sys\n\n\nPROMPT = \"> \"\n\n# rooms are just dictionaries, with a description and a list of named actions, which point at other rooms\n# the 'exit' value indicates a room which ends the game\n# the 'name' is used to give each room a unique in the map\nentrance_room = {\n'name':'entrance',\n'desc': 'You are in a dimly lit cave. To your left there is a winding staircase heading up into the darkness, to your right, a rusty iron gate',\n'actions': {'go up': 'tower', 'break the gate': 'main_stairs'},\n'exit':False\n}\n\ntower_dead_end = {\n'name':'tower' , \n'desc' : 'You emerge from the stairway in the ruins of an old tower. There is nothing here but broken stones and matted vines',\n'actions': {'go down': 'entrance'},\n'exit':False\n}\n\nmain_stairs = {\n'name':'main_stairs',\n'desc':'The gate gives way after a few hard kicks, and clangs loundly down a flight of steps into the darkness. You hear the sound of water from down below.',\n'actions': { 'go down':'pitfall', 'light torch':'stairs_torch'},\n'exit':False\n}\n\nstairs_torch= {\n'name':'stairs_torch', \n'desc':'your torch sputters to life and reveals a large gap in the stairs about ten feet ahead of you. It might be possible to edge by it to the left side...',\n'actions': { 'jump the gap':'pitfall', 'go_up':'entrance', 'edge around':'sneak_by'},\n'exit':False\n}\n\nsneak_by = {\n'name':'sneak_by',\n'desc':'You carefully step past the gap. A few feet later you are handed a check for $85,000,000 and the keys to a Tesla. Congratulations!',\n'actions':{},\n'exit':True}\n\npitfall = {\n'name':'pitfall',\n'desc':'You fall into a large gap in the stairs that you would have seen if you had only lit a torch. You plummet to a mercifully quick death in the icy water far below.',\n'actions':{},\n'exit':True\n}\n\n# this is shorthand way of making all of the above dictionaries into a dictionary keyed by the 'name' entries\n# in a real game you'd want to make sure these all actually existed and that there were no typos!\nmap = dict ( (item['name'],item) for item in (entrance_room, tower_dead_end, main_stairs, stairs_torch, sneak_by, pitfall))\n\n\ndef game_loop(room, map):\n # room is a dictionary describing an individual room or action\n # map is a dictionary of rooms, keyed by name\n\n sys.stdout.writelines(room['desc'])\n\n if room['exit']:\n sys.stdout.writelines('\\nThanks for playing!')\n return\n\n next = None\n\n while not next:\n sys.stdout.writelines (\"\\nYou can...\")\n for item in room['actions'].keys():\n sys.stdout.writelines(\"\\n\\t\" + item)\n\n sys.stdout.writelines(\"\\n>\")\n user_input = sys.stdin.readline()\n user_input = user_input.strip().lower() # just take lower case for simplicity\n if user_input in room['actions']: \n next = room['actions'][user_input]\n else:\n sys.stdout.writelines(\"'%s' is not a supported option. Please try again\\h\" % user_input)\n game_loop(map[next], map)\n\ngame_loop (entrance_room, map)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T17:42:51.657",
"Id": "59108",
"Score": "0",
"body": "To be brief: data-driven programming is more appropriate, because you want to manage the game map as data, not code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T08:26:09.580",
"Id": "36112",
"ParentId": "36101",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "36112",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T02:51:24.003",
"Id": "36101",
"Score": "1",
"Tags": [
"python",
"game",
"adventure-game"
],
"Title": "Better way to code this game?"
}
|
36101
|
<p>I recently received a <strong>'good, but not good enough'</strong> rating on a coding exercise I was asked to perform. It was to validate that if "Product complaint" option was selected that Product name, Product size, Use-by date and Batch code fields all needed to have values. <strong>What can I do to improve the JS to go from 'good, but not good enough' to 'great'?</strong></p>
<p>JS:</p>
<pre><code>document.querySelector("form").addEventListener("submit", function(e) {
var enquiryType = document.querySelector("#enquirytype");
if (enquiryType.value === "pc") {
validateProductDetails();
e.preventDefault();
}
});
function validateProductDetails() {
var requiredFields = document.querySelectorAll('[id^="product-"]'),
requiredLabel = document.querySelectorAll('[for^="product-"]'),
formSubmit = document.forms[0],
requiredIsEmpty = [],
i;
for (i = 0; i < requiredFields.length; i += 1) {
if (requiredFields[i].value.length === 0) {
alert('Please enter the ' + requiredLabel[i].innerHTML + ".");
requiredFields[i].focus();
requiredIsEmpty.push(requiredFields[i]);
return false;
}
}
if (requiredIsEmpty.length === 0) {
formSubmit.submit();
return true;
}
}
</code></pre>
<p>HTML:</p>
<pre><code><form action="/" method="get">
<label for="enquirytype">Enquiry type</label>
<select name="enquiry" id="enquirytype" required>
<option value="">Choose</option>
<option value="ge">General enquiry</option>
<option value="pf">Product feedback or enquiry</option>
<option value="pc">Product complaint</option>
</select>
<label for="product-name">Product name</label>
<input type="text" id="product-name">
<label for="product-size">Product size</label>
<input type="text" id="product-size">
<label for="product-use-by">Use-by date</label>
<input type="text" id="product-use-by">
<label for="product-batch">Batch code</label>
<input type="text" id="product-batch">
<input type="submit" value="Submit" id="form-submit">
</form>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T03:42:49.200",
"Id": "58986",
"Score": "0",
"body": "were you given the html as-is, or were you asked to create those fields as well?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T03:49:23.467",
"Id": "58987",
"Score": "0",
"body": "@Brian asked to create that as well. Also instructed not to use jQuery or another library, and it only had to work in latest Chrome. The HTML was marked as 'perfect' (this is a subset of all HTML), so I'd prefer to concentrate on the JS."
}
] |
[
{
"body": "<p>Searching for all the labels is a waste of time/resources. You only ever need a label if the validation fails on an entry, and only then should you locate the matching label for the failed validation.</p>\n\n<p>That way, when all the fields validate, then no labels need to be searched at all.</p>\n\n<p>Additionally, I would (personal preference) prefer to have a strict name-based set of values that need validation. Searching for those fields that match a pattern in the <code>id</code> is something that may lead to issues further down the road.</p>\n\n<p>Still, if you want to use patterns for finding the entry fields, at least limit the search to values which are entry fields.... you have no validation that checks to ensure that there's not some other node that has an 'id' starting with 'product-'.</p>\n\n<p>Also, you assume that the labels for the entry fields are in the same order as the fields. This is dangerous.</p>\n\n<p>When it comes down to it, if it were me reviewing the code, I would think: Sure, it does the standard stuff OK, but it does not have any robustness.</p>\n\n<hr>\n\n<p>EDIT</p>\n\n<p>When I wrote my review I assumed the HTML was supplied (I did not realize that you wrote the HTML as part of the process). This makes some of what I suggested a little less relevant... Still, you ask about the third paragraph: <code>...have a strict name-based set of values that need validation...</code></p>\n\n<p>Consider the following:</p>\n\n<pre><code> var tovalidate=[\"product-name\",\"product-size\",\"product-use-by\",\"product-batch\"];\n</code></pre>\n\n<p>Then loop on that array and pull the relevant details for each of them as needed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T04:03:34.080",
"Id": "58996",
"Score": "0",
"body": "OK that's mostly fair enough regarding the labels. I only bothered with them to provide a reasonably meaningful alert message. Thanks. Can you explain your 3rd paragraph please? I don't quite get it. Also anything regarding structure of the code? Cheers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T04:24:55.157",
"Id": "58999",
"Score": "0",
"body": "That explains things. I thought by giving the to be validated fields the same prefix it would provide flexibility, but I can see why it might be brittle."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T03:51:19.547",
"Id": "36105",
"ParentId": "36102",
"Score": "1"
}
},
{
"body": "<h2>Separation of Concerns</h2>\n<p>So I agree with rolfl, but I also want to expand a bit, and provide some small bit of skeleton code for you to go on. When I do validation on the client, I usually set up variables for errors, conditions, and dependencies. This allows me to use a simple handling structure that can be used if needed (as @rolfl suggested), and ignored if not, that way you aren't validating fields that don't need validation, or if they do, you're only performing exactly as much validation as needed.</p>\n<p>This simple "boilerplate" that I've just created will also allow you to inject functionality to any of your variables by adding objects to your arrays. As long as your <code>validate</code> function executes the conditions and dependencies injected, you should have a very nice reusable client validation boilerplate.</p>\n<p>Then, you just attach an event listener to whatever form element you want to validate, and run a <code>validate</code> function on that callback. It'll efficiently go through conditions that exist on elements, instead of the other way around, and you can be as flexible you want with your view code without tying it to your validation function.</p>\n<p>One of the key principles of coding is <code>Separation of Concerns</code>. Any of your code that performs app logic (the validation) shouldn't have any sort of view code in it if at all possible. <strong>I believe this is the biggest single concept that would have made the difference</strong> in the feedback you received . If you maintain SOC in this case, no matter how the form changes, your <code>validate</code> function won't have to change, or will be at least very flexible, and if you all of a sudden needed to use the same form but on a mobile page, you could just change the <code>renderErrors</code> function to alter your view code to fit the new display without changing anything else.</p>\n<p>That's what <em>I</em> would consider great. See my fiddle: <a href=\"http://jsfiddle.net/LongLiveCHIEF/sqwYT/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/LongLiveCHIEF/sqwYT/</a></p>\n<p>I'll update it a bit, but wanted to give you a head start on my line of thought.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T04:27:03.437",
"Id": "59000",
"Score": "0",
"body": "That boilerplate looks great. I still have to read through more carefully but I see what you're getting at."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T05:12:58.673",
"Id": "59012",
"Score": "0",
"body": "I updated it to make it more 'modular`, but keep in mind I didn't run any of it through a validator. I'm used to using other libs for this stuff, so my javascript DOM api usage is a bit rusty. When in doubth, it's the theory that counts."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T05:23:14.250",
"Id": "59015",
"Score": "0",
"body": "ok, I'm done editing everything now, time for bed. Good luck, reach out to me for questions. (info in my profile)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T05:33:36.010",
"Id": "59016",
"Score": "0",
"body": "Cheers for the fiddle. I'll try filling it all out and if I have any issues will get in touch."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T04:11:47.333",
"Id": "36106",
"ParentId": "36102",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "36106",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T03:16:14.430",
"Id": "36102",
"Score": "3",
"Tags": [
"javascript",
"form",
"validation"
],
"Title": "JavaScript form validation: improve on 'good, but not good enough'"
}
|
36102
|
<p>I've written a simple function for building a prefix tree (and searching):</p>
<pre><code>import qualified Data.List as L
import qualified Data.Map as M
data Tree a = Empty | Node a [Tree a] deriving (Show, Eq)
partitionBy f = map snd . M.toList . M.fromListWith (++) . map (\x -> (f x, [x]))
buildTree value dt = Node value (map (\x -> buildTree (head . head $ x) (map tail x)) . grps $ dt)
where grps = partitionBy (\x -> head x) . filter (\x -> 0 < length x)
treeToList (Node v lst)
| length lst > 0 = [v] : foldl (\l x -> (map (v:) $ treeToList x) ++ l) [] lst
| otherwise = [[v]]
searchTree tl [] tree = Just (map (init tl ++) . treeToList $ tree)
searchTree tl (x:xs) (Node _ lst)
| length next_sub_trees > 0 = searchTree (tl ++ [x]) xs (head next_sub_trees)
| otherwise = Nothing
where next_sub_trees = filter (\ (Node v1 _) -> v1 == x) lst
main = do
let tree = buildTree ' ' ["hi", "hello", "me", "you", "mouse", "mek", "meee"]
print tree
print $ treeToList tree
print $ searchTree "" "me" tree
</code></pre>
<p>I'm new to Haskell. Can anyone help me to make this function better/faster?</p>
|
[] |
[
{
"body": "<p>At first glance, here are some suggestions-</p>\n\n<ol>\n<li><p>(\\x -> head x) can be written as just \"head\".</p></li>\n<li><p>(\\x -> 0 < length x) can be written as \"(0 <) . length (this is point free notation, which I prefer, although some people may prefer your way.</p></li>\n<li><p>Use more built in stuff- There is already a built in groupBy and sortBy functions, you won't have to cast to a map and back. There is already a built in Tree/Forest library, you don't need to create your own.</p></li>\n<li><p>This is more for my (a reader of your code) sanity than you: Wrtie out the function types! :) It took me a while to see what each function was doing, and a type signature would have made it obvious right away. It also helps the compiler give you more meaningfull error messages. Remember, you too will be a reader of your own code in a few months also, you will thank yourself. </p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T21:17:52.543",
"Id": "36157",
"ParentId": "36107",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "36157",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T04:14:00.590",
"Id": "36107",
"Score": "5",
"Tags": [
"haskell",
"beginner",
"tree"
],
"Title": "Simple prefix tree"
}
|
36107
|
<p>So I'm writing some code to perform a quite specific task given a large numpy array with N rows and 3 columns representing points in 3D. The 3D points are to be binned along one of the dimensions between specified bin edges. For each of these bins, there is a set fraction by which I must reduce the number of points in that bin, perfectly (pseudo)randomly.</p>
<p>Here is the code I have written to perform this task. I found myself spending a lot of time trying to figure out the most 'pythonic' way to achieve this. It still seems very clunky, so I'm sure there must be a more elegant way that capitalises on numpy's array performance. Any tips?</p>
<pre><code># Initialise the array of 3D points
radecz = np.zeros((N, 3))
# grab the point data from elsewhere
points[:, 0] = ...
points[:, 1] = ...
points[:, 2] = ... # this is the dimension we bin in, call it z
# Create an array of M + 1 elements for the edges of M bins
binedges = ... # (they do not span all of the space of points by the way)
# Find the counts per bin
H = np.histogram(points[:, 2], bins=binedges)
# The number to downsample to in each bin is already known
num_down = ("""some M-dimensional array of fractions""") * H[0]
# initialise a mask for the final array for my analysis with dimension N
finmask = np.array(points.shape[0] * [False])
# loop over bins (do I really need to do this??)
for i, nd in enumerate(num_down):
# First get the array ids of the points in each bin
zbin_ids = np.where( ( (binedges[i] < points[:, 2]) & \
(points[:, 2) <= binedges[i + 1]) ) == True )
# Choose ids at random without replacement
keep = np.random.choice(zbin_ids[0], size=cn, replace=False)
# What's left is turned on in the mask for the final array
finmask[keep] = True
points = points[(finmask,)]
</code></pre>
|
[] |
[
{
"body": "<p>You could use <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html#numpy.digitize\" rel=\"nofollow\"><code>numpy.digitize</code></a> to determine which bin each point belongs in, allowing for a simpler expression inside <code>where</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T09:21:05.110",
"Id": "36116",
"ParentId": "36110",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "36116",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T05:43:21.907",
"Id": "36110",
"Score": "1",
"Tags": [
"python",
"numpy",
"statistics"
],
"Title": "Downsampling n-dimensional data from bins in one dimension"
}
|
36110
|
<p>I have created a Drupal 6 module that sends messages through PubNub when the user updates information about a Node. I have a separate app that, when launched, calls my Drupal site and receives a JSON array containing a lot of information about some nodes. I then update the info in my other app by PubNub->publish from Drupal every time the page is reloaded after the Node is updated. I have the following in my <code>foo.module</code> file:</p>
<p>hook_admin: //not really a hook</p>
<pre><code>function moduleName_admin(){
//Here we are pulling in the Pubnub.php file from the module directory
// NOTE: This file requires PubnubAES.php even when you aren't using encryption so include it too
module_load_include('php', 'moduleName', 'Pubnub');
$pubnub = new Pubnub(
"PUBKEY",
"SUBKEY",
"",
false
);
$form = array();
$query = "SELECT info FROM tables;"
$results = db_query($query);
while($r=db_fetch_object($results)){
$form['moduleName_fieldDescription_'.$r->nid] = array(
'#type' => 'radios',
'#title' => "Select one for ".$r->info.":",
'#options' => array(
t('Foo'),
t('Bar'),
t('Baz')
),
'#default_value' => variable_get('moduleName_fieldDescription_'.$r->nid, '0'),
);
$pubnub->publish(array(
'channel' => 'channelName',
'message' => array("id"=>$r->nid, "selected"=>variable_get('moduleName_fieldDescription_'.$r->nid, '0'))
));
}
return system_settings_form($form);
}
</code></pre>
<p>JSON page:</p>
<pre><code>function moduleName_JSON(){
$query = "SELECT info FROM table;"
$results = db_query($query);
$infoObject = array();
for($i=0;$r = db_fetch_object($results); $i++){
$infoObject[$i] = array(
'info' => $r->info,
'id' => $r->nid,
'selected' => variable_get('moduleName_fieldDescription_'.$r->nid, '0'),
);
}
//This next part will wrap the JSON in a function so jQuery can be called like
//$.ajax( {
//url:"example.com/moduleName/json",
//dataType: 'jsonp',
//callback: 'foo',
//success:function(data){
//checkListInfo = data;
//styleSheetLoaded();
//}
//} );
$callback = check_plain($_REQUEST['callback']);
if (isset($callback) && $callback != '') {
header("Content-type: text/javascript");
echo $callback ."(";
drupal_json($infoObject);
echo ");";
} else {
drupal_json($infoObject);
}
}
</code></pre>
<p>hook_menu:</p>
<pre><code>function moduleName_menu(){
$items = array();
$items['moduleName/editPage'] = array(
'title' => 'Module edit page',
'description' => 'Edit this page to make changes to pubnub',
'page callback' => 'drupal_get_form',
'page arguments' => array('moduleName_admin'),
'access arguments' => array('Edit moduleName Permissions'),
'type' => MENU_NORMAL_ITEM,
);
$items['moduleName/json'] = array(
'title' => 'JSON Array containing module info',
'page callback' => 'moduleName_JSON',
'access arguments' => array('Change moduleName values'),
'tpye' => MENU_CALLBACK,
);
return $items;
}
</code></pre>
<p>This is slightly changed up code from my working Drupal 6 module that uses a live PubNub account. It works great for my purpose. I just want to know how to do it a little more to Drupal standards.</p>
<p>I know I probably have the publish time wrong. Right now it publishes when the page is reloaded instead of right before the page sends the info. I don't think this is right but I am very new to Drupal.</p>
<p>There is a Drupal Module that is in the process of being built that will allow PubNubs integration in Drupal 7/8 but I am on D6 and I am just including the files myself.</p>
|
[] |
[
{
"body": "<p>If you are receiving the data you expect, I think you are 99% there. </p>\n\n<p>Alternatively, you could include the PubNub JS client into your Drupal app (vs. the PHP client), then you can publish asynchronously, or even completely after page load.</p>\n\n<p><a href=\"http://www.pubnub.com/docs/javascript/javascript-sdk.html\" rel=\"nofollow\">Link to the JS client and docs are available here</a>, with a <a href=\"http://www.pubnub.com/docs/javascript/tutorial/data-push.html#publish\" rel=\"nofollow\">specific example of how to publish here</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T19:42:43.287",
"Id": "59136",
"Score": "0",
"body": "I thought about this but I don't really have a reason to publish the message before the form is submitted and it is easier to do the PHP pubnub because it is server-side and doesn't rely on the client-side javascript. Also it would be kinda tricky to implement because of the way Drupal forms are generated. Thanks for the suggestion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T00:22:25.633",
"Id": "59173",
"Score": "0",
"body": "Surely! And if you have any additional PubNub-specific questions, feel free to ping us at support@pubnub.com, we're here to help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T04:55:44.183",
"Id": "70095",
"Score": "0",
"body": "Could you give some code examples to *show* the OP how to do something? That would garner an up-vote from me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T02:54:41.900",
"Id": "70547",
"Score": "0",
"body": "@syb0rg please clarify what you are looking for?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T06:03:36.303",
"Id": "70571",
"Score": "0",
"body": "I'd need a more specific example of exactly what you'd be looking for an example of... need a use case, etc @syb0rg"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:27:10.553",
"Id": "70634",
"Score": "0",
"body": "@Geremy Give a link to the JS client in your answer, and maybe include an example for publishing asynchronously/after page load."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T19:28:40.417",
"Id": "36152",
"ParentId": "36111",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T05:59:16.993",
"Id": "36111",
"Score": "4",
"Tags": [
"php",
"json",
"drupal",
"pubnub"
],
"Title": "Module for sending messages through PubNub"
}
|
36111
|
<p>Suggestions for cleanup and optimization request. </p>
<p><strong>This question is a follow-up question on <a href="https://codereview.stackexchange.com/questions/35902/find-a-missing-numbers-single-missing-number-and-two-missing-numbers-from-cons">this post</a></strong>. </p>
<p>Lets assume the range of </p>
<blockquote>
<p>1, 2, 3, 4. </p>
</blockquote>
<p>This function takes in an array of repeated elements, <code>[1,1,4,4]</code> and the output is <code>[2, 3]</code>. </p>
<p><em>The question marked as duplicate takes an input of <code>[1, 4]</code> and output is <code>[2, 3]</code>.</em>
While output is same, the input differs.
Please make a note of this difference between two questions causing confusion.</p>
<pre><code>final class Variables {
private final int x;
private final int y;
Variables(int x2, int y2) {
this.x = x2;
this.y = y2;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override public String toString() {
return "x = " + x + " y = " + y;
}
}
public final class FindMissingRepeating {
/**
* Takes an input a sorted array with only two variables that repeat once. in the
* range. and returns two variables that are missing.
*
* If any of the above condition does not hold true at input the results are unpredictable.
*
* Example of input:
* range: 1, 2, 3, 4
* input array [1, 1, 4, 4]
* the variables should contain 2 missing elements ie 2 and 3
*
* @param a : the sorted array.
*/
public static Variables sortedConsecutiveTwoRepeating (int[] a, int startOfRange) {
if (a == null) throw new NullPointerException("a1 cannot be null. ");
int low = startOfRange;
int high = low + (a.length - 1);
int x = 0;
int i = 0;
boolean foundX = false;
while (i < a.length) {
if (a[i] < low) {
i++;
} else {
if (a[i] > low) {
if (foundX) {
return new Variables(x, low);
} else {
x = low;
foundX = true;
}
}
low++;
i++;
}
}
int val = foundX ? x : high - 1;
return new Variables(val, high);
}
public static void main(String[] args) {
int[] ar1 = {1, 2, 2, 3, 4, 4, 5};
Variables v1 = FindMissingRepeating.sortedConsecutiveTwoRepeating (ar1, 1);
System.out.println("Expected x = 6, y = 7 " + v1);
int[] ar2 = {2, 2, 4, 4, 5, 6, 7};
Variables v2 = FindMissingRepeating.sortedConsecutiveTwoRepeating (ar2, 1);
System.out.println("Expected x = 1, y = 3 " + v2);
int[] ar3 = {3, 3, 4, 4, 5, 6, 7};
Variables v3 = FindMissingRepeating.sortedConsecutiveTwoRepeating (ar3, 1);
System.out.println("Expected x = 1, y = 2 " + v3);
int[] ar4 = {1, 3, 3, 4, 4, 6, 7};
Variables v4 = FindMissingRepeating.sortedConsecutiveTwoRepeating (ar4, 1);
System.out.println("Expected x = 2, y = 5 " + v4);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T18:31:13.610",
"Id": "59123",
"Score": "0",
"body": "@JavaDeveloper Please see [this meta question](http://meta.codereview.stackexchange.com/questions/1065/how-to-deal-with-follow-up-questions/) about follow-up questions. You would help us greatly by adding more information to your follow-up questions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T18:39:43.437",
"Id": "59124",
"Score": "5",
"body": "@JavaDeveloper please also select an answer on the original question, having unanswered questions that you are posting a follow up question to doesn't look right."
}
] |
[
{
"body": "<p>Firstly there are 2 classes so don't show them as a single code when showing your code. Place a heading with the class name then your code then second class name then your second class's code. That makes it easier to copy paste it into Eclipse when seeing the code.</p>\n\n<p>Why have you named the parameters as <code>x2</code> and <code>y2</code> and still using the <code>this</code> keyword? Why are you making the variable names different in the first place? It just adds confusion. Name them as <code>x</code> and <code>y</code> and then use the <code>this</code> keyword. Period.</p>\n\n<p>You are throwing a <code>null pointer exception</code> when <code>a</code> is <code>null</code> and the message is <code>a1 is null</code>. That will become confusing... Also you don't need to throw that explicitly. The assignment to <code>high</code> will throw the exception and give you a proper stacktrace already without any extra code. </p>\n\n<p>The <code>while</code> loop can be made a <code>for</code> loop very easily and will limit the scope and extra variable (<code>i</code> in this case). Note that you are doing <code>i++</code> in both <code>if</code> as well as <code>else</code>. That shows you didn't take the time to look at your own code.</p>\n\n<p>You passed <code>startOfRange</code> to the function and forgot that it is a variable also. If you have any intention of not changing it then make it explicit and declare the parameter as <code>final</code> in the method's signature.</p>\n\n<p>Also If I am correct then you have used <code>x = 0</code> only to make it one less than the <code>startRange</code> so that your algorithm works. That means your function will break the moment you decide the startRange to be anything other than 1. Also using such magic numbers and such variable names as x is a bad idea. Really bad idea.</p>\n\n<p>Take some time to refactor the code yourself. It pays if your code is easy to understand by other programmers. Your code can be changed to this and I think now it is much easier to understand the flow of execution of the current program.</p>\n\n<pre><code>public static ExVariables sortedConsecutiveTwoRepeating(int[] a,\n final int startOfRange) {\n\n int low = startOfRange;\n int high = low + (a.length - 1);\n\n int x = low - 1;\n boolean foundX = false;\n\n for (int i = 0; i < a.length; i++) {\n if (a[i] > low) {\n if (foundX) {\n return new ExVariables(x, low);\n }\n x = low;\n foundX = true;\n }\n if (a[i] >= low) {\n low++;\n }\n }\n\n if (foundX) {\n return new ExVariables(x, high);\n } else {\n return new ExVariables(high - 1, high);\n }\n}\n</code></pre>\n\n<p>I think it should be possible to refactor it more so that the <code>return</code> comes only inside the <code>for</code> loop but I didn't take the time to do that.</p>\n\n<p>Hope this helps.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T17:03:24.450",
"Id": "36229",
"ParentId": "36117",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "36229",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T09:34:47.267",
"Id": "36117",
"Score": "4",
"Tags": [
"java",
"optimization",
"array",
"sorting"
],
"Title": "Find missing numbers in a range, with duplicate numbers in a sorted array"
}
|
36117
|
<p>This is my forked branch attempting to make the code better, This is an application for having a slide show of photographs in current directory or supplied as argument.</p>
<p>Use keyboard controls[left to go backward and Right key to go forward and spacebar to toggle play/pause] only.</p>
<p><strong>File 1. utils.py</strong></p>
<pre><code>import os
import sys
def isExtensionSupported(filename):
""" Supported extensions viewable in SlideShow
"""
if filename.endswith('.PNG') or filename.endswith('.png') or\
filename.endswith('.JPG') or filename.endswith('.jpg'):
return True
def imageFilePaths(paths):
imagesWithPath = []
for _path in paths:
dirContent = getDirContent(_path)
for each in dirContent:
selFile = os.path.join(_path, each)
if ifFilePathExists(selFile) and isExtensionSupported(selFile):
imagesWithPath.append(selFile)
return list(set(imagesWithPath))
def ifFilePathExists(selFile):
return os.path.isfile(selFile)
def getDirContent(path):
try:
return os.listdir(path)
except OSError:
raise OSError("Provided path '%s' doesn't exists." % path)
</code></pre>
<p><strong>File 2. slideShowBase.py</strong></p>
<pre><code>import utils
class SlideShowBase(object):
""" SlideShowBase class contains methods that defines the
logic for SlideShow to plate forward or backword and
pause.
"""
def __init__(self, imgLst, ppState, count, animFlag):
self._imagesInList = imgLst
self._pause = ppState
self._count = count
self.animFlag = animFlag
def populateImagestoSlideShow(self, path):
""" helper method to populate the list with paths
of images from path argument.
"""
self._imagesInList = utils.imageFilePaths([path])
def nextImage(self):
""" switch to next image or previous image
"""
if self._imagesInList:
if self._count == len(self._imagesInList):
self._count = 0
if self.animFlag:
self._count += 1
else:
self._count -= 1
def playPause(self):
if not self._pause:
self._pause = True
self.updateTimer.start(2500)
return self._pause
else:
self._pause = False
self.updateTimer.stop()
def ingestData(paths):
""" This method is used to create a list containing
images path to slideshow.
"""
if isinstance(paths, list):
imgLst = utils.imageFilePaths(paths)
elif isinstance(paths, str):
imgLst = utils.imageFilePaths([paths])
else:
print " You can either enter a list of paths or single path"
return imgLst
</code></pre>
<p><strong>File 3. slideShow.py</strong></p>
<pre><code>import sys
import os
import utils
from PyQt4 import QtGui,QtCore
import slideShowBase
class SlideShowPics(QtGui.QMainWindow, slideShowBase.SlideShowBase):
""" SlideShowPics class defines the methods for UI and
working logic
"""
def __init__(self, imgLst, num=0, flag=True, parent=None):
super(SlideShowPics, self).__init__(parent)
slideShowBase.SlideShowBase.__init__(self, imgLst=imgLst, ppState=False, count=num, animFlag=flag)
self.prepairWindow()
def prepairWindow(self):
if not self._imagesInList:
msgBox = QtGui.QMessageBox()
msgBox.setText("No Image found." )
msgBox.setStandardButtons(msgBox.Cancel | msgBox.Open);
if msgBox.exec_() == msgBox.Open:
self.populateImagestoSlideShow(self._browseDir())
else:
sys.exit()
# Centre UI
screen = QtGui.QDesktopWidget().screenGeometry(self)
size = self.geometry()
self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)
self.setStyleSheet("QWidget{background-color: #000000;}")
self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
self._buildUi()
self.updateTimer = QtCore.QTimer()
self.connect(self.updateTimer, QtCore.SIGNAL("timeout()"), self.nextImage)
self.showFullScreen()
self.playPause()
#Shows the first image
self.showImageByPath(self._imagesInList[0])
def _buildUi(self):
self.label = QtGui.QLabel()
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.setCentralWidget(self.label)
def _browseDir(self):
selectedDir = str(QtGui.QFileDialog.getExistingDirectory(None,
"Select Directory to SlideShow",
os.getcwd()))
if selectedDir:
return selectedDir
else:
sys.exit()
def nextImage(self):
super(SlideShowPics, self).nextImage()
self.showImageByPath(self._imagesInList[self._count])
def showImageByPath(self, path):
if path:
image = QtGui.QImage(path)
pp = QtGui.QPixmap.fromImage(image)
self.label.setPixmap(pp.scaled(
self.label.size(),
QtCore.Qt.KeepAspectRatio,
QtCore.Qt.SmoothTransformation))
def keyPressEvent(self, keyevent):
""" Capture key to exit, next image, previous image,
on Escape , Key Right and key left respectively.
"""
event = keyevent.key()
if event == QtCore.Qt.Key_Escape:
self.close()
if event == QtCore.Qt.Key_Left:
self.animFlag = False
self.nextImage()
if event == QtCore.Qt.Key_Right:
self.animFlag = True
self.nextImage()
if event == 32:
self._pause = self.playPause()
def main(imgLst=None):
app = QtGui.QApplication(sys.argv)
window = SlideShowPics(imgLst)
window.show()
window.raise_()
sys.exit(app.exec_())
if __name__ == '__main__':
curntPaths = os.getcwd()
if len(sys.argv) > 1:
curntPaths = sys.argv[1:]
main(slideShowBase.ingestData(curntPaths))
</code></pre>
<p><strong>Test 1: test_utils.py</strong></p>
<pre><code>import unittest
import mox
import sys
import os
sys.path.insert(0, os.path.abspath( os.path.join(os.path.dirname(__file__),
'../python/') ))
import utils
class TestUtils(unittest.TestCase):
""" docstring for Test_Utils
"""
def setUp(self):
self._filePaths = ["/test/file/path"]
self.mox = mox.Mox()
def tearDown(self):
self.mox.UnsetStubs()
self.mox.ResetAll()
def test_isExtensionSupported(self):
self.assertTrue(utils.isExtensionSupported("testFile.PNG"))
self.assertTrue(utils.isExtensionSupported("testFile.jpg"))
self.assertFalse(utils.isExtensionSupported("testFile.kkg"))
def test_imageFilePaths(self):
filePaths = self._filePaths
fileList = ['file1.bmp']
self.mox.StubOutWithMock(utils, 'getDirContent')
dirContent = utils.getDirContent(filePaths[0]).AndReturn(fileList)
self.mox.StubOutWithMock(utils,'ifFilePathExists')
filePat = os.path.join(filePaths[0], dirContent[0])
utils.ifFilePathExists(filePat).AndReturn(True)
self.mox.StubOutWithMock(utils, 'isExtensionSupported')
utils.isExtensionSupported(filePat).AndReturn(True)
self.mox.ReplayAll()
self.assertEquals(['/test/file/path/file1.bmp'], utils.imageFilePaths(filePaths))
self.mox.VerifyAll()
def test_getDirContent(self):
self.assertRaises(OSError, utils.getDirContent, self._filePaths[0])
def test_ifFilePathExists(self):
self.assertFalse(utils.ifFilePathExists(self._filePaths[0]))
self.assertTrue(utils.ifFilePathExists(__file__))
if __name__ == '__main__':
unittest.main()
</code></pre>
<p><strong>Test 2.test_slideShowbase.py</strong></p>
<pre><code>import unittest
import mox
import stubout
import sys
import os
from PyQt4 import QtGui
sys.path.insert(0, os.path.abspath( os.path.join(os.path.dirname(__file__),
'../python/') ))
from slideShowBase import SlideShowBase as _slideShowBase
import slideShowBase
import utils
class TestSlideShow(unittest.TestCase):
""" docstring for TestSlideShow
"""
def setUp(self):
self.mox = mox.Mox()
self.__stubs = stubout.StubOutForTesting()
self.imgLst = ['/folder/test/images/test1.jpg', '/folder/test/images/test2.JPG',
'/folder/test/images/test3.png', '/folder/test/images/test4.PNG']
def tearDown(self):
self.mox.UnsetStubs()
self.mox.ResetAll()
def test_nextImage(self):
self.show = _slideShowBase(imgLst=self.imgLst, ppState=False, count=0, animFlag=True)
self.show.nextImage()
self.assertEquals(1, self.show._count)
self.assertEquals(self.imgLst[1], self.show._imagesInList[1])
def test_nextImage_animFlag_False(self):
self.show = _slideShowBase(imgLst=self.imgLst, ppState=False, count=2, animFlag=False)
self.show.nextImage()
self.assertEquals(1, self.show._count)
self.assertEquals(self.imgLst[2], self.show._imagesInList[2])
def test_ingestData_list(self):
# monkeypatch
self.__stubs.Set(utils, 'imageFilePaths', lambda x: self.imgLst)
listData = slideShowBase.ingestData(self.imgLst)
self.assertEquals(self.imgLst, listData)
def test_ingestData_string(self):
# monkeypatch
self.__stubs.Set(utils, 'imageFilePaths', lambda x: self.imgLst[0])
listData = slideShowBase.ingestData(self.imgLst[0])
self.assertEquals(self.imgLst[0], listData)
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>One thing that doesnt seem to work correctly the first image on the startup is not scaled up for the first play of slideShow. Any Idea why is that ?</p>
<p>Also, I think I can use generator instead oflist in the slideshowbase class but cannot think of how to approach for it. Any Suggestions/hints ?</p>
|
[] |
[
{
"body": "<p>Two general observations:</p>\n\n<p>1) Use more lookups and fewer if-else checks. For example: </p>\n\n<pre><code>def isExtensionSupported(filename):\n \"\"\" Supported extensions viewable in SlideShow\n \"\"\"\n if filename.endswith('.PNG') or filename.endswith('.png') or\\\n filename.endswith('.JPG') or filename.endswith('.jpg'):\n return True\n</code></pre>\n\n<p>could be replaced with the much simpler, more data-driven:</p>\n\n<pre><code>def isExtensionSupported(filename):\n \"\"\" Supported extensions viewable in SlideShow\n \"\"\"\n ALLOWABLE = (\"png\", \"jpg\")\n return filename.lower()[-3:] in ALLOWABLE\n</code></pre>\n\n<p>2) using dual inheritance to get the functions of SlideShowBase into SlideShowPics seems more complex than needed. I'd think about just including a SlideShowBase into your SlideShowPics and letting it manage all of the image paths by delegation, while SlideShowPics handles the display. The old saying here is <a href=\"http://en.wikipedia.org/wiki/Composition_over_inheritance\" rel=\"nofollow\">'prefer composition over inheritance'</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T05:36:43.980",
"Id": "59190",
"Score": "0",
"body": "first of, Long time no see,so u use same name on tech-artists too, anyway, as per your second observation, I had it like that what you suggested earlier but why I decided to put the logic in SlideShowBase is because I am able to test it with ease, If I have all the code in `SlideShowPics` then I would have to mock `QtGui.QMainWindow` and I would even have to mock `showImageByPath` method, I know it looks kinda little bit complex but now the logic is in separate class and it seems it is easily testable too"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T06:23:54.260",
"Id": "59197",
"Score": "1",
"body": "I thought I recognized the name :) My only observation there would be that slideShowBase should be testable on its own - that's effectively what you're doing -- and a separate set of (simpler) tests for SlideShowPics would handle the parts of that code which are testable. GUI like that is always hard to test anyway, since so many of the bugs are not data bugs but visual errors. I always feel that easier tests = more tests = better code, so I opt for lots of dumb tests instead of finicky fancy ones -- if I have to do too much mocking it's often time for a refactor to cut down cross-coupling."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T06:48:51.923",
"Id": "59200",
"Score": "0",
"body": "once again thanks @theodox for the inputs."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T21:06:32.153",
"Id": "36156",
"ParentId": "36119",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T09:57:44.243",
"Id": "36119",
"Score": "0",
"Tags": [
"python",
"design-patterns",
"unit-testing"
],
"Title": "Feedback on logic implementation and testing"
}
|
36119
|
<p>Suppose I am listening for network changes with the following listener:</p>
<pre><code>interface NetListener {
void onNetworkAvailable(boolean isWifi);
void onNetworkUnavailable();
}
</code></pre>
<p>I want to have an object, accessible from anywhere within the app, holding the registered <code>NetListener</code>s, that can trigger the appropriate methods when necessary. The solution I came up with is this "singleton": </p>
<pre><code>class NetListenerManager {
private static List<NetListener> _listeners = new CopyOnWriteArrayList<NetListener>();
static void addListener(final NetListener listener) {
if (null != listener) { _listeners.add(listener); }
}
static void removeListener(final NetListener listener) {
if (null != listener) { _listeners.remove(listener); }
}
/**
* Called when a network connection is available.
*/
static void notifyOnNetworkAvailable(boolean isWifi) {
for (NetListener listener : _listeners) { listener.onNetworkAvailable(isWifi); }
}
/**
* Called when a network connection becomes unavailable.
*/
static void notifyOnNetworkUnavailable() {
for (NetListener listener : _listeners) { listener.onNetworkUnavailable(); }
}
private NetListenerManager() { /* Instantiation disabled. */ }
}
</code></pre>
<p>So whenever e.g. a network change broadcast is received, I call <code>NetListenerManager.notifyOnNetworkAvailable</code> or <code>NetListenerManager.notifyOnNetworkUnavailable</code>,
depending on the network state. </p>
<p>I’m wondering if this is a good solution or if there are better ways to implement this.
Thanks!</p>
<h1>UPDATE no.2</h1>
<p>This is the modified listener: </p>
<pre><code>interface NetListener {
static enum NetworkType {NO_NETWORK, WIFI, MOBILE}
void onNetworkChange(NetworkType type);
}
</code></pre>
<p>And the manager:</p>
<pre><code>public final class NetListenerManager {
private static final List<NetListener> NET_LISTENERS = new CopyOnWriteArrayList<NetListener>();
private static final BlockingQueue<NetListener.NetworkType> QUEUE = new LinkedBlockingQueue<NetListener.NetworkType>();
private static final Thread QUEUE_PROCESSOR = new Thread(new QueueProcessor());
static { QUEUE_PROCESSOR.start(); }
public static void addListener(final NetListener listener) {
if (null != listener) { NET_LISTENERS.add(listener); }
}
public static void removeListener(final NetListener listener) {
if (null != listener) { NET_LISTENERS.remove(listener); }
}
/**
* Called when there is a network change.
*/
public static void notifyOnNetworkChange(final NetListener.NetworkType type) {
QUEUE.add(type);
}
private NetListenerManager() { /* Instantiation disabled. */ }
/**
* This Runnable propagates network change events to the registered NetListener listeners in a queue.
*/
private static final class QueueProcessor implements Runnable {
@Override
public void run() {
while (true) {
try {
final NetListener.NetworkType type = QUEUE.take();
for (NetListener listener : NET_LISTENERS) { listener.onNetworkChange(type); }
} catch (InterruptedException ie) { /* Do nothing */ }
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T10:59:03.923",
"Id": "59031",
"Score": "0",
"body": "Can a listener trigger a change in the network availability and therefore re-trigger the event while it is being processed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T11:51:23.610",
"Id": "59035",
"Score": "0",
"body": "Consider using en enum for Singleton designs, as proposed by Joshua Blochs in Effective Java. (ex: http://stackoverflow.com/a/71399/1021726)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T13:18:26.427",
"Id": "59051",
"Score": "1",
"body": "I have updated my answer to match your revised questions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T11:09:02.360",
"Id": "59233",
"Score": "0",
"body": "Why evil singleton?"
}
] |
[
{
"body": "<p>In general this is a good solution, but there are a few points you should consider:</p>\n\n<ul>\n<li>General style: Make the class <code>final</code>. There is no reason for anyone to subclass it, and the private Constructor shows that intent, but making the class itself final is a good thing.</li>\n<li>Similarly, make the _listeners list final as well.</li>\n</ul>\n\n<p>The next item is whether you can guarantee that the static methods on your class will only ever be called from a single thread. If you can guarantee this then the code will be good. If not, then it is possible for there to be 'transient' situations where the network 'blips', sending a 'network down' followed by a 'network up' notification. If they come from different threads then it is possible the the NetListener instances may get the notifications out of order.</p>\n\n<p>For a thread-safe system I would create an enum with three states:</p>\n\n<pre><code>enum (NET_DOWN, NET_UP_WIFI, NET_UP_REGULAR);\n</code></pre>\n\n<p>and then feed those states on to a Concurrent*Queue on the notify side. Then, have a seperate thread that reads from that queue (guaranteeing the order) and feeds the events to the listeners.</p>\n\n<p>This also removes potentially long-running method calls from the service that provides you the notification events.... (i.e. this may make the OS more responsive to other applications)</p>\n\n<hr>\n\n<h1>EDIT</h1>\n\n<p>After your edit you have introduced the concept of a separate thread for managing the notification process.</p>\n\n<p>The only comment I have for the modification is that the <code>java.util.concurrent</code> typically has 'the right tool for the job' somewhere. In this case, you chose the wrong tool. It is pretty complicated sometimes, but the right tool would probably be an implementation of a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html\" rel=\"nofollow\">BlockingQueue</a>. In this case I would choose <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/LinkedBlockingQueue.html\" rel=\"nofollow\">LinkedBlockingQueue</a>. Your methods can then lose the <code>synchronization</code> blocks and simply become:</p>\n\n<pre><code>public static void notifyOnNetworkChange(final NetListener.NetworkType type) {\n QUEUE.put(type);\n}\n</code></pre>\n\n<p>and your read-side becomes (note you had a bug before because if you had multiple listeners you would poll different values for each of them):</p>\n\n<pre><code>while(...) {\n NetworkType state = QUEUE.take();\n for (NetListener listener : NET_LISTENERS) { listener.onNetworkChange(state);\n\n}\n</code></pre>\n\n<p>The LinkedBlockingQueue deals with all the synchronization issues for you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T11:53:00.490",
"Id": "59036",
"Score": "0",
"body": "I think your enum types are named wrong. DOWN and OTHER are, as you said, states. WIFI on the other hand is a network type, and WIFI as a network can be DOWN, RUNNING, OTHER, etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T12:11:10.063",
"Id": "59038",
"Score": "0",
"body": "The three states relate to the three possible method calls to the handler... but you are right, the names are poor.... editing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T13:05:25.440",
"Id": "59047",
"Score": "0",
"body": "Hi guys, thank you very much for your feedback. I've updated my post, could you please take a look? Any feedback highly appreciated! Thanks again."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T11:41:00.380",
"Id": "36127",
"ParentId": "36120",
"Score": "2"
}
},
{
"body": "<p>(Disclaimer: I posted this as a comment first but feel like it should also be an answer)</p>\n\n<p>You should consider to use enum as a singleton as proposed by Joshua Blochs in Effective Java. This will protect you from both serialization attacks and reflection attacks on your singleton instance. </p>\n\n<p>Here is a post which discusses it a lot more in-depth.\n<a href=\"https://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java/71399#71399\">https://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java/71399#71399</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T13:06:24.523",
"Id": "36132",
"ParentId": "36120",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "36127",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T10:03:56.037",
"Id": "36120",
"Score": "3",
"Tags": [
"java",
"performance",
"android"
],
"Title": "Singleton holding and notifying registered listeners"
}
|
36120
|
<p>I have something like that:</p>
<ol>
<li><p>My custom exception class:</p>
<pre><code>public class SolvableException extends RuntimeException {
protected boolean solved = false;
public SolvableException(String message) {
super(message);
}
public void setSolved() {
this.solved = true;
}
public boolean isSolved() {
return this.solved;
}
}
</code></pre></li>
<li><p>Class for some very specific calculations which in some unpredictable cases throws my exception:</p>
<pre><code>class VerySpecificCalculator {
public void makeSomeSpecificCalculations(double someParameter){
// make some actions...
// Now I have to make some specific calculations, but sth wrong happend and I do know what to do with it in this place...
throw new SolvableException("Something wrong happend... Problem with XYZ");
}
}
</code></pre></li>
<li><p>My very specific calculator is used in other class and provides some part of its logic:</p>
<pre><code>class Calculator {
public void makeSomeCalculations(double someParameter){
// Some variuos calculations...
VerySpecificCalculator calc = new VerySpecificCalculator();
try {
calc.makeSomeSpecificCalculations(4.34);
} catch (SolvableException e){
// I know what to do here, so I'm fixing a bug on this level:
// some fixing code, some rollback whatever...
e.setSolved();
// But I want to inform, that the fixing process took place...
throw e;
}
}
}
</code></pre></li>
<li><p>I use the entire stuff as follows:</p>
<pre><code>class Test {
public static void main(String[] args) {
Calculator calculator = new Calculator();
try {
calculator.makeSomeCalculations(344.47);
}catch (SolvableException e){
if(e.solved){
System.out.println("Ok, there was a problem but it has been solved... You can display some JOptionPane to inform a user if you want...");
} else {
System.out.println("Buuu, there was a problem an it's still not solved... Action is interrupted ");
return;
}
}
}
}
</code></pre></li>
</ol>
<p>Is this approach reasonable? I mean, is it ok to rethrow an exception if the problem has been already solved, and rethrowing plays only some informative role like in my example?</p>
<p>Let's consider such a situation (without rethrowing):</p>
<pre><code>public void f(){
try {
methodCausingException();
} catch (SolvableException e) {
// fixing code...
}
//
// Code executed when problem is fixed...
//
}
</code></pre>
<p>But with rethrowing I need to duplicate my code:</p>
<pre><code>public void f(){
try {
methodCausingException();
} catch (SolvableException e) {
// fixing code...
e.setSolved();
//
// Code executed when problem is fixed...
//
throw e;
}
//
// Code executed when problem is fixed...
//
}
</code></pre>
<p>I can use a <code>finally</code> block, but I don't find this place as good for business logic code.</p>
|
[] |
[
{
"body": "<p>Especially if you expect these exceptions to occur (relatively) often, I think that using exceptions is a bad idea here. <a href=\"https://stackoverflow.com/questions/729379/why-not-use-exceptions-as-regular-flow-of-control\">Exceptions should not be used for regular flow of control</a>, this applies to Java as well. Creating and throwing exceptions is among the most costly operations there is in many programming languages.</p>\n\n<p>One comment especially that caught my attention was: \"Now I have to make some specific calculations, but sth wrong happend <strong>and I do know what to do with it</strong> in this place...\" If you know what to do with it, then why are you throwing an exception? If you look in the <a href=\"http://www.thefreedictionary.com/exception\" rel=\"nofollow noreferrer\">dictionary</a> an exception is:</p>\n\n<blockquote>\n <p>special case, departure, <em>freak,</em> <strong>anomaly,</strong> inconsistency, deviation, quirk, <strong>oddity,</strong> peculiarity, <strong>irregularity</strong>\" (+ exclusion, omission, objection).</p>\n</blockquote>\n\n<p>Is your case really an <em>anomaly</em>? (Doesn't sound like it but I can't make this decision for you)</p>\n\n<p><strong>Instead, consider</strong> creating a <code>CalculationResult</code> class, which can be returned from your methods. The class can contain your <code>solved</code> variable (possibly among other things). Then when a method has returned a <code>CalculationResult</code> to it's caller, you can read the <code>CalculationResult</code> and decide what to do with it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T12:11:34.350",
"Id": "59039",
"Score": "0",
"body": "Being more specific: The problem causing an exception is solved deep in the model... Simply if some values are to high, they are reduced apropriately. But I want to inform about the fact of reducing some values in the view layer. That's why I'm rethrowing an exception with flag \"solved\". I know that it is probably not a perfect solution... I need simply something like that in this case... I do not want to show message dialogs in model layer (I'm working with swing). I consider your solution as well, thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T12:18:05.607",
"Id": "59040",
"Score": "0",
"body": "@guitar_freak Then it sounds like you should pass the `CalculationResult` to the view. Rethrowing exceptions itself is OK, but I don't think you should use exceptions here. If some values are too high, then modify them without throwing an exception - just change some information in the `CalculationResult`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-12T19:42:50.397",
"Id": "87169",
"Score": "0",
"body": "Other than that, you can alternatively Log a Warning, in case you have some logging mechanism in place ;)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T11:49:18.127",
"Id": "36128",
"ParentId": "36125",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "36128",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T11:03:05.613",
"Id": "36125",
"Score": "5",
"Tags": [
"java",
"exception-handling",
"exception"
],
"Title": "Rethrowing exception just as an information"
}
|
36125
|
<p>I am looking to make a generic config file using variables such as:
$PLACEHOLDER_USER</p>
<p>Then after moving the file into the correct position I want to replace every instance of *$PLACEHOLDER_VARIABLE* into the value of <em>$VARIABLE</em> from my settings.sh file. </p>
<p>In the example below *"$PLACEHOLDER_USER"* in log.conf would be replace by <em>"tom"</em></p>
<p><strong>log.conf</strong></p>
<pre><code>deploy = $PLACEHOLDER_USER
</code></pre>
<p><strong>settings.sh</strong></p>
<pre><code>USER="tom"
</code></pre>
<p><strong>deploy.sh</strong></p>
<pre><code>FILE="/home/logging/log.conf"
ln -s /home/log.conf $FILE
while IFS== read variable value
do
sed -i "s/\$PLACEHOLDER_$variable/$value/g" $FILE
done < settings.sh
</code></pre>
<p>Is there a better way of doing this?</p>
|
[] |
[
{
"body": "<p>First up, the shell variable <code>USER</code> is already defined in bash, and is the log-in name of the current user.... so, if you log in as 'rolfl' then <code>echo $USER</code> will print <code>rolfl</code>. There are a number of programs and other systems that may be confused if you change the <code>USER</code> environment variable the way you have.</p>\n\n<p>Next, I don't think that the symbolic link you create does what you think it does:</p>\n\n<pre><code>ln -s /home/log.conf $FILE\n</code></pre>\n\n<p>This will try to create a symbolic link at <code>/home/logging/log.conf</code> that points to the (presumably pre-existing) file <code>/home/log.conf</code></p>\n\n<p>This means that whenever <strong>anyone</strong> processes your settings script, they all modify the same file <code>/home/log.conf</code> and, since the first person will replace the tokens with their name, the other users will have nothing to do....</p>\n\n<p>I presume the line:</p>\n\n<pre><code>ln -s /home/log.conf $FILE\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>cp /home/log.conf $FILE\n</code></pre>\n\n<p>Apart from this though, the program seems reasonable (I have not run it). My only comment is that this uses relatively advanced features of the shell. In my experience, it is often better to write these things in perl because people expect perl to do more complicated things. I don't know if this is sounding right, but, even though perl may be slower than this solution, it is also something that sys admins are familiar with, and will be happier to maintain than a complex shell script.... Still, if the people maintaining this code are familiar with what you are doing (and the fact that you are asking on CodeReview rather than using your peers is a suggestion that is not the case) then I would say it is fine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T16:11:29.283",
"Id": "59082",
"Score": "0",
"body": "In the code, the shell variable `USER` is never modified. The settings file is parsed, not sourced."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T16:13:27.143",
"Id": "59083",
"Score": "0",
"body": "@MarkReed - I must have been side-tracked by the .sh extension on the file ;-) but still, the current code does not suggest it changes the $USER variable. I will leave my comment as a warning to others not to use it anyway, it can be very confusing."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T12:59:06.867",
"Id": "36131",
"ParentId": "36130",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T12:46:22.503",
"Id": "36130",
"Score": "2",
"Tags": [
"bash",
"linux",
"shell"
],
"Title": "Bash to find all placeholder variables in a file and replace will real variables"
}
|
36130
|
<p>I'm dealing with huge amount of data. I've written following code into a function to find out similar questions. It's working perfectly but it is taking too much time in execution. Can anyone help me to optimize the function code so that the execution time will be less?</p>
<pre><code><?php
class QuestionMatch {
var $mError = "";
var $mCheck;
var $mDb;
var $mValidator;
var $mTopicId;
var $mTableName;
function __construct() {
global $gDb;
global $gFormValidation;
$this->mDb = $gDb;
$this->mValidator = $gFormValidation;
$this->mTableName = TBL_QUESTIONS;
}
/**
* This function is used to get all the questions from the given subject id and topic id
*/
function GetSimilarQuestionsBySubjectIdTopicId($subject_id, $topic_id) {
/*SQL query to find out questions from given subject_id and topic_id*/
$sql = " SELECT question_id, question_text FROM ".TBL_QUESTIONS." WHERE question_subject_id=".$subject_id;
$sql .= " AND question_topic_id=".$topic_id;
$this->mDb->Query($sql);
$questions_data = $this->mDb->FetchArray();
/*Array of words to be excluded from comparison process*/
$exclude_words = array('which','who','what','how','when','whom','wherever','the','is','a','an','and','of','from');
/*This loop removes all the words of $exclude_words array from all questions and converts all
*questions' text into lower case
*/
foreach($questions_data as $index=>$arr) {
$questions_array = explode(' ',strtolower($arr['question_text']));
$clean_questions = array_diff($questions_array, $exclude_words);
$questions_data[$index]['question_text'] = implode(' ',$clean_questions);
/*Logic to find out the no. of count question appeared into tests*/
$sql = " SELECT count(test_que_id) as question_appeared_count FROM ".TBL_TESTS_QUESTIONS." WHERE test_que_id=";
$sql .= $arr['question_id'];
$this->mDb->Query($sql);
$qcount = $this->mDb->FetchArray(MYSQL_FETCH_SINGLE);
$question_appeared_count = $qcount['question_appeared_count'];
$questions_data[$index]['question_appeared_count'] = $question_appeared_count;
}
/*Now the actual comparison of each question with every other question stats here*/
foreach ($questions_data as $index=>$outer_data) {
/*Crerated a new key in an array to hold similar question's ids*/
$questions_data[$index]['similar_questions_ids_and_percentage'] = Array();
$outer_question = $outer_data['question_text'];
$qpcnt = 0;
/*This foreach loop is for getting every question to compare with outer foreach loop's
question*/
foreach ($questions_data as $secondIndex=>$inner_data) {
/*This condition is to avoid comparing the same questions again*/
if ($secondIndex <= $index) {
/*This is to avoid comparing the question with itself*/
if ($outer_data['question_id'] != $inner_data['question_id']) {
$inner_question = $inner_data['question_text'];
/*This is to calculate percentage of match between each question with every other question*/
similar_text($outer_question, $inner_question, $percent);
$percentage = number_format((float)$percent, 2, '.', '');
/*If $percentage is >= $percent_match only then push the respective question_id into an array*/
if($percentage >= 85) {
$questions_data[$index]['similar_questions_ids_and_percentage'][$qpcnt]['question_id'] = $inner_data['question_id'];
$questions_data[$index]['similar_questions_ids_and_percentage'][$qpcnt]['percentage'] = $percentage;
$qpcnt++;
}
}
}
}
if(!empty($outer_data['similar_questions_ids_and_percentage'])) {
$return_url = ADMIN_SITE_URL.'modules/questions/match_question.php?';
$return_url .= 'op=get_question_detail&question_ids='.$outer_data['question_id'];
foreach($outer_data['similar_questions_ids_and_percentage'] as $secondIndex=>$inner_data) {
$return_url = $return_url.','.$inner_data['question_id'];
}
$questions_data[$index]['return_url'] = $return_url.'#searchPopContent';
}
}
/*This will return the complete array with matching question ids*/
return $questions_data;
}
function GetAllErrors() {
return $this->mValidator->mErrorMsg;
}
}
?>
</code></pre>
<p>If you want any further details I can provide you the same. Waiting for your precious help and valuable replies. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T14:09:52.427",
"Id": "59059",
"Score": "1",
"body": "sql injection alert"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T18:23:03.813",
"Id": "59118",
"Score": "0",
"body": "How does `similar_text()` work ? Can we see the code on that. Also, what kind of data size do you have?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T09:49:51.800",
"Id": "59220",
"Score": "0",
"body": "@Kami http://www.php.net/manual/en/function.similar-text.php it counts the percentage of common characters."
}
] |
[
{
"body": "<p>Unfortunately there's not much you can do here. Unless you try the difficult but efficient approach at the end of my answer, your for loops won't go away and you will need to understand what takes you time inside those loops to get small wins.</p>\n\n<h2>Micro-optimizations</h2>\n\n<p>You need to profile the code to understand what takes time:</p>\n\n<ul>\n<li>Is it the SQL query?</li>\n<li>Is it excluding words from the stop word list? (Those lists already exist for English and other languages, by the way.)</li>\n<li>Is it <code>similar_text()</code>?</li>\n<li>Is it building the array?</li>\n</ul>\n\n<p>You don't need <code>$percentage</code> and <code>number_format</code>: <code>$percent</code> is already a float.</p>\n\n<h2>Context</h2>\n\n<p>Another thing to consider is the 'context' of this function: is it called only once, or do you call it for every subject and topic? If that's the case, then it would be better to do the similarity search for all topics and questions, and then display only questions with the same topic and subject. You would go from many SQL queries (one per topic and subject combination) to only one.</p>\n\n<h2>All Pairs Similarity Search</h2>\n\n<p>The problem you're trying to solve is called All Pairs Similarity Search. There is a <a href=\"http://www.bayardo.org/ps/www2007.pdf\" rel=\"nofollow\">scientific paper</a> and an <a href=\"https://code.google.com/p/google-all-pairs-similarity-search/\" rel=\"nofollow\">implementation</a> from Google if you're interested in the research problem. The research applies to sparse vectors but it's possible to turn your sentence into a vector of the size of your vocabulary: a cell i is 1 if the word corresponding to cell i is in your cell, and 0 otherwise. Such a vector is sparse because most cells are 0 for a given sentence. Feel free to ask more questions if you want to try this out.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T16:00:55.473",
"Id": "59474",
"Score": "0",
"body": "Thats fasinating reading thanks I really enjoyed that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T09:56:02.940",
"Id": "36194",
"ParentId": "36134",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T13:24:37.743",
"Id": "36134",
"Score": "2",
"Tags": [
"php",
"optimization",
"php5"
],
"Title": "How to optimize the following code in order to decrease the execution time?"
}
|
36134
|
<p>I'm trying to solve a programming challenge for fun. The programming challenge is <a href="http://uva.onlinejudge.org/external/100/10029.html" rel="nofollow">here</a> and my solution for the same can be found here.</p>
<p>It currently causes an exceeded time limit.</p>
<pre><code>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
int a[25001];
bool is_edit_distance_one(string one, string two) {
if ( one.size() == two.size() ) {
bool found_diff = false;
for ( int i = 0 ; i < one.size(); i++ ) {
if ( found_diff && one[i] != two[i] ) return false;
else if ( one[i] != two[i] ) found_diff = true;
}
return true;
}
else if ( (one.size() - two.size()) == 1 && one.find(two) != string::npos )
return true;
else if ( (two.size() - one.size()) == 1 && two.find(one) != string::npos )
return true;
return false;
}
map<string, bool> generate(string one) {
map<string, bool> edits;
string all_chars = "abcdefghijklmnopqrstuvwxyz";
// Generate all strings by adding another letter
for ( int i = 0; i <= one.size(); i++ ) {
for ( int j = 0; j < all_chars.size(); j++ ) {
// split the string at i
string temp = one.substr(0, i);
temp += all_chars[j];
temp += one.substr(i, one.size()-i);
edits[temp] = true;
}
}
// Generate all strings by deleting a letter
for ( int i = 0; i < one.size(); i++ ) {
string temp = one.substr(0, i);
temp += one.substr(i+1, one.size()-i);
edits[temp] = true;
}
// Generate all strings by changing a letter
for ( int i = 0; i < one.size(); i++ ) {
for ( int j = 0; j < all_chars.size(); j++ ) {
string temp = one.substr(0, i);
temp += all_chars[j];
temp += one.substr(i+1, one.size()-i);
edits[temp] = true;
}
}
return edits;
}
int main() {
string s;
int i = 0;
int l;
vector<string> all;
while ( cin >> s ) {
a[i] = 0;
all.push_back(s);
l = all.size();
for ( int i = 0; i < l-1; i++ ) {
map<string, bool> edits = generate(all[l-1]);
if ( edits[all[i]] ) {
a[l-1] = max(a[i]+1, a[l-1]);
}
}
}
sort(a, a+l);
cout << a[l-1] + 1 << endl;
}
</code></pre>
<p>Instead of calculating the edit distance between strings (using <code>is_edit_distance_one</code>), I'm generating a map with all possible edit strings of a string and checking if previous strings are present in it (using the function "generate").</p>
<ul>
<li>Are there any implementation level mistakes that I'm making that's slowing it down?</li>
<li>Any particular data structure I should/should not be using?</li>
<li>Any other algorithm I could use to speed things up?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T14:58:05.723",
"Id": "59070",
"Score": "0",
"body": "don't use std::strings if you want performance"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T15:03:03.773",
"Id": "59072",
"Score": "0",
"body": "it seems you want the [levenshtein distance](http://en.wikipedia.org/wiki/Levenstein_distance) between 2 strings"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T07:54:32.070",
"Id": "59203",
"Score": "0",
"body": "The longest ladder! In the sample input I see (just by looking) an 8: `fog -> log -> dig -> dog -> fig -> fin -> fine -> wine`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T09:09:39.147",
"Id": "59209",
"Score": "0",
"body": "@LokiAstari I think the point is that it should be consecutive words, which is why it's only 5."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T09:13:34.543",
"Id": "59211",
"Score": "0",
"body": "@QuentinPradet: Then how do they get 5 as the output."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T09:17:06.760",
"Id": "59213",
"Score": "0",
"body": "@LokiAstari dig -> dog -> fig -> fin -> fine, 5 words (only a guess)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T09:20:37.853",
"Id": "59216",
"Score": "0",
"body": "dog->fig dies not work. It changes two letters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T11:14:26.173",
"Id": "59235",
"Score": "1",
"body": "@LokiAstari The sequence is dig → fig → fin → fine → wine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T11:27:04.400",
"Id": "59240",
"Score": "0",
"body": "@QuentinPradet The problem doesn't say that the stepladder must consist only of words that appear consecutively in the dictionary. It says that _if_ you choose to call the elements of the stepladder w1, w2, …, w_n, where w_i are listed in lexicographical order, then every w_i and w_(i+1) are separated by edit distance one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T12:59:31.790",
"Id": "59253",
"Score": "0",
"body": "@LokiAstari and in your example, log -> dig doesn't work either. Thanks 200_success for the clarification."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T17:23:52.550",
"Id": "59330",
"Score": "0",
"body": "@QuentinPradet: Then my longest edit distance for the example is 6: `dig -> dog -> fig -> fin -> fine -> wine` or is that 6 words and 5 edits."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T17:31:32.660",
"Id": "59334",
"Score": "0",
"body": "@QuentinPradet: But I can a longer edit path by adding a loop. `dog -> dig -> dog -> dig -> fig -> fine -> wine`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T09:08:24.193",
"Id": "59415",
"Score": "0",
"body": "@LokiAstari dog -> fig also changes two letters, you meant dog -> dig -> fig -> fin -> fine -> wine. The difference with 200_success's sequence is that you change the order. I don't know if that's allowed, and I don't know whether you should count edits or words."
}
] |
[
{
"body": "<p>when you generate the map you immediately throw it away, this will likely be your biggest slowdown</p>\n\n<p>because the map doesn't change in the <code>for</code> you can cache it:</p>\n\n<pre><code>l = all.size();\nmap<string, bool> edits = generate(s);\nfor ( int i = 0; i < l-1; i++ ) {\n if ( edits[all[i]] ) {\n a[l-1] = max(a[i]+1, a[l-1]);\n }\n}\n</code></pre>\n\n<p>going back to using is_edit_distance_one would be better if you fix the bug in it (a remove or add in arbitrary location is seen as false)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T09:16:08.240",
"Id": "59212",
"Score": "0",
"body": "It's a good idea, but nothing says it's indeed the biggest slowdown. The correct algorithm uses the Levenshtein distance, which eliminates the need for `generate()` anyway."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T15:36:09.197",
"Id": "36141",
"ParentId": "36137",
"Score": "1"
}
},
{
"body": "<p>Generating all possible single-edit variations of a word results in a huge number of possibilities! With a 10-letter word, for example, you could add 26 letters in each of 11 positions (before, after, or between letters), remove any of the 10 letters, or modify any of the 10 letters. That's 26 × 11 + 10 + 25 × 10 = 546 possibilities. On average, you could trim that in half if you only consider words that come lexicographically later than the input word. Still, that's a huge inefficiency — enough to rule out that approach altogether.</p>\n\n<hr>\n\n<p>Your <code>is_edit_distance_one()</code> should take <code>const string &</code> arguments to avoid copying. The body would be improved if you break down the cases as:</p>\n\n<pre><code>switch (one.size() - two.size()) {\n case -1: // Is one is a subsequence of two (not necessarily consecutive)?\n case +1: // Is two is a subsequence of one (not necessarily consecutive)?\n case 0: // Check for single-letter difference\n default: return false;\n}\n</code></pre>\n\n<p>The challenge with the <code>is_edit_distance_one()</code> approach is that if you apply it naïvely (comparing every pair of words), your running time will be O(<em>n</em><sup>2</sup>), where <em>n</em> is the number of words.</p>\n\n<hr>\n\n<p>One technique to consider is to take the hint that no word exceeds 16 letters. Create a char[25001][16] matrix and fill it with <code>'\\0'</code> NULs. You can then treat the NULs just like any other <code>char</code> for the purpose of determining edit distances.</p>\n\n<p>Once you have determined which words are one edit distance apart, the search for the longest stepladder should be similar to the <a href=\"http://en.wikipedia.org/wiki/Longest_increasing_subsequence#Efficient_algorithms\" rel=\"nofollow\">Longest Increasing Subsequence problem</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T11:21:12.843",
"Id": "59237",
"Score": "0",
"body": "@QuentinPradet You haven't understood the problem correctly; please refrain from editing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T12:58:20.223",
"Id": "59252",
"Score": "0",
"body": "(When I edited I thought I understood it, sorry.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T17:30:08.217",
"Id": "59333",
"Score": "1",
"body": "But only words in the dictionary are valid. So 546 is you upper bound. Lower bound will be much more constrained. But if your dict is n words. Each word will have (on average) k.n words one edit away (as n increases the probability for more words one edit away increases). So this is a graph search problem with n nodes and k.n^2 edges. You have to find the longest path in the graph (presumably without adding a loop)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T19:50:20.170",
"Id": "59354",
"Score": "0",
"body": "@LokiAstari But `generate()` was clearly not approaching it as a graph search problem."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T22:07:30.677",
"Id": "36160",
"ParentId": "36137",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T14:27:55.527",
"Id": "36137",
"Score": "4",
"Tags": [
"c++",
"algorithm",
"performance",
"stl",
"edit-distance"
],
"Title": "\"Edit distance\" UVA programming challenge"
}
|
36137
|
<p>I attempt to create a reusable and scalable Cron Wrapper in PHP.</p>
<p>I'm at the begining of the project and I wanted have some tips/ critics / improvments to make before going too far.</p>
<p>The final objective is to have a complete cron wrapper which allows to lauch :</p>
<ul>
<li>'one-shot' task (like huge DB export) from Web</li>
<li>manage Crontask from a web interface or from the 'default way'</li>
<li>Maybe more ;)</li>
</ul>
<p>There is the main core class </p>
<pre><code><?php
/**
* Nozdormu is a PHP5 cron wapper.
*
* @package Nzdrm
* @version 0.1
* @author vfo
*/
namespace Nzdrm;
require_once('log.php');
require_once('profiler.php');
require_once('process.php');
require_once('vendors/PHPMailer/PHPMailerAutoload.php');
class Nzdrm {
const VERSION = '0.1-dev';
const CNFPATH = '../etc/';
const BINPATH = '../bin/';
public static $locale = 'C';
public static $timezone = 'UTC';
public static $process = '';
public static $encoding = 'UTF-8';
public static $profiling = false;
public static $logging = false;
public static $mail_on_success = true;
public static $organisation = 'domain.tld';
public static $mail_recipient = 'mail@domain.tld';
public static $profile_in_mail = true;
public static $log_threshold = '300';
public static $log_folder_path = '../var/log/';
public static $log_file_name = 'Nozdormu';
public static $initialized = false;
public static $cnf = array();
final public function __construct() { }
public static function init($cnf_fn = 'nzdrm.conf')
{
if (static::$initialized)
{
logger('WARNING',"Can't be init more than once",__METHOD__);
}
$cnf = array();
if (!file_exists(self::CNFPATH.$cnf_fn))
{
logger('WARNING', "Can't find ".self::CNFPATH.$cnf_fn."! Use default parameters", __METHOD__);
}
else
static::$cnf = parse_ini_file(self::CNFPATH.$cnf_fn, true);
static::$profiling = (empty($cnf['profiler']))?false:true;
static::$profiling and \Nzdrm\Profiler::init();
static::$logging = (empty($cnf['logger']))?false:true;
static::$locale = (empty($cnf['locale']))?null:$cnf['locale'];
static::$log_folder_path = (empty($cnf['log_folder_path']))?'../var/log/':$cnf['log_folder_path'];
static::$log_file_name = (empty($cnf['log_file_name']))?'Nozdormu':$cnf['log_file_name'];
if (static::$locale)
{
setlocale(LC_ALL, static::$locale) or
logger('WARNING', 'The configured locale '.static::$locale.' is not installed on your system.', __METHOD__);
}
static::$timezone = (!empty($cnf['timezone'])) ? $cnf['timezone']: date_default_timezone_get();
if (!date_default_timezone_set(static::$timezone))
{
date_default_timezone_set('UTC');
logger('WARNING', 'The configured locale '.static::$timezone.' is not valid.', __METHOD__);
}
static::$log_threshold = (!empty($cnf['log_threshold'])) ? $cnf['log_threshold']: '300';
static::$initialized = true;
if (static::$profiling)
{
\Nzdrm\Profiler::mark(__METHOD__.' End');
}
}
public static function get_from_db()
{
/** @TODO
** Set DB connection
** Get Waiting Task(s)
** Set Pending state
** Lauch Task
** Update state not oneshot task
**/
}
public static function launch($process)
{
static::$process = $process;
if (static::$profiling)
\Nzdrm\Profiler::mark(__METHOD__.' Start');
if (!file_exists(self::BINPATH.$process.'.php'))
logger('ERROR', "Can't find ".self::BINPATH.$process."! Shut down", __METHOD__);
else
if (!is_executable(self::BINPATH.$process.'.php'))
logger('ERROR', self::BINPATH.$process." isn't executable! Shut down", __METHOD__);
else
{
if (static::$logging)
logger('INFO', 'Nozdormu launches '.$process.'.php');
$pr = new \Nzdrm\Process($process.'.php');
while(true)
if ($pr->status === false)
break;
}
if (static::$profiling)
\Nzdrm\Profiler::mark(__METHOD__.' End');
if (static::$logging)
logger('INFO', 'Nozdormu ended '.$process.'.php');
self::shut_down();
}
public static function shut_down()
{
if (static::$logging)
logger('INFO', 'Nozdormu is Shuting down.');
$mail = new \PHPmailer();
$mail->From = 'noreply@'.static::$organisation;
$mail->FromName = 'Nozdormu';
$mail->addAddress(static::$mail_recipient);
$mail->addReplyTo('noreply@'.static::$organisation, 'No-Reply');
$mail->WordWrap = 50;
if (file_exists(static::$log_folder_path.date('Y/m/d-').static::$process.'.log'))
$mail->addAttachment(static::$log_folder_path.date('Y/m/d-').static::$process.'.log');
$mail->isHTML(false);
$title = '';
$err= false;
if (file_exists(static::$log_folder_path.date('Y/m/d-').static::$process.'.log'))
{
$ftmp = file_get_contents(static::$log_folder_path.date('Y/m/d-').static::$process.'.log');
$titlechange = array('WARNING', 'ERROR','ALERT');
foreach ($titlechange AS $tc)
if (substr_count($ftmp, $tc))
{
$title = 'Cron ended with '.strtolower($tc).'(s)';
$err= true;
}
if (!$title)
$title = "Cron sucessfully ended";
}
$mail->Subject = '[NZDRM]['.self::$process.']'.$title;
$body= "Hi,\n";
if ($err)
$body .="The script '".static::$process."' generates the error/warning messages during his last execution.\nPlease read log file in attachment.\n";
else
$body .= "The script '".static::$process."' successfully ended";
if (static::$profile_in_mail)
$body .= "Profile overviews:\n" . \Nzdrm\Profiler::displayLogs();
$body .="\n-- \n[This is an automatic message send by Nozdormu v. ".self::VERSION."]\n";
$mail->Body = $body;
if ($err !== true AND !static::$mail_on_success)
if(!$mail->send())
logger('WARNING', 'Mailer Error: ' . $mail->ErrorInfo, __METHOD__);
}
}
?>
</code></pre>
<p><a href="https://github.com/vfo/Nozdormu" rel="nofollow">Full repo here</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T15:27:48.300",
"Id": "59075",
"Score": "0",
"body": "What's up with the `static` explosion?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T13:57:09.823",
"Id": "59254",
"Score": "2",
"body": "Your code contains: _waay_ to many `static`'s, syntax errors (`else\n static::$cnf = parse_ini_file(self::CNFPATH.$cnf_fn, true);\n static::$profiling = (empty($cnf['profiler']))?false:true;` wont produce the desired result) , (ab)use of ternary operators, doesn't use a proper autoloader, and will cause loss of hair, sleep, sanity and faith in humanity for whoever ends up debugging/maintaining it a couple of months from now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T14:06:53.057",
"Id": "59255",
"Score": "0",
"body": "@EliasVanOotegem there is no syntax error(s) maybe a bad indentation ;). Why did you say `tatic::$profiling = (empty($cnf['profiler']))?false:true;` wont produce the desired result? You make a point for the autoloader i'm working on it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T14:13:51.413",
"Id": "59257",
"Score": "0",
"body": "The `else` will only execute the first statement, the other statements will be executed regardless. You're logging an error if the ini file can't be found, else you're parsing it into `$cnf` and continue processing what may well be an empty array. Also: you're using `empty`, which is [woefully unreliable](http://kunststube.net/isset/). If you can't find the config file, _stop_, that's a fatal error, don't try to blunder along, you might end up doing more harm than good."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T14:19:42.817",
"Id": "59258",
"Score": "0",
"body": "@EliasVanOotegem the app can run with default parameters, so a missing conf file isn't a fatal error, but you're right, if the file can't be find, i should skip the test and directly run with defaults values."
}
] |
[
{
"body": "<p>Going to try to answer my own question. So I should use :</p>\n\n<ul>\n<li>Less <code>static</code>s, and implement an interface to deal with config parameters, and just keep the most useful in attributs (<code>logging</code>, <code>profilling</code>)</li>\n<li>Move the mailing functionnality to her own method.</li>\n<li>In <code>\\Nzdrm::init</code> just keep the init for <code>logging</code>, <code>profilling</code> and <code>locale</code> configuration.</li>\n<li>Use <code>Exception</code>s</li>\n<li>(Minor) Comment code while coding, otherwise it's going to never be done.</li>\n</ul>\n\n<p>Based on Elias comments :</p>\n\n<ul>\n<li>Use an autoloader</li>\n<li>Don't try to deal without a conf file and just exit with a <code>FATAL ERROR</code>, so delete all default values.</li>\n</ul>\n\n<p>Finally I realize that is the approach may be a bit outdated, and a <a href=\"http://puppetlabs.com/\" rel=\"nofollow\">puppet</a> based solution would be more suitable, and this project is going to go in study case archive.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T13:52:53.687",
"Id": "36355",
"ParentId": "36140",
"Score": "3"
}
},
{
"body": "<p>in one of your functions you have two different coding styles.</p>\n\n<pre><code>public static function init($cnf_fn = 'nzdrm.conf')\n{\n if (static::$initialized)\n {\n logger('WARNING',\"Can't be init more than once\",__METHOD__);\n }\n $cnf = array();\n if (!file_exists(self::CNFPATH.$cnf_fn))\n {\n logger('WARNING', \"Can't find \".self::CNFPATH.$cnf_fn.\"! Use default parameters\", __METHOD__);\n }\n else\n static::$cnf = parse_ini_file(self::CNFPATH.$cnf_fn, true);\n static::$profiling = (empty($cnf['profiler']))?false:true;\n static::$profiling and \\Nzdrm\\Profiler::init();\n static::$logging = (empty($cnf['logger']))?false:true;\n static::$locale = (empty($cnf['locale']))?null:$cnf['locale'];\n static::$log_folder_path = (empty($cnf['log_folder_path']))?'../var/log/':$cnf['log_folder_path'];\n static::$log_file_name = (empty($cnf['log_file_name']))?'Nozdormu':$cnf['log_file_name'];\n</code></pre>\n\n<p>in your <code>if</code> statements you consistently use brackets, even for one liners, but then in the else statement you don't use any brackets, this gets confusing and can lead to you not knowing where the statement really ends, it is better coding practice to use the brackets (in my opinion).</p>\n\n<hr>\n\n<p>then the next <code>if</code> statements that you come to are indented again, and they really shouldn't be, this makes them look like they should be inside of another code block.</p>\n\n<hr>\n\n<p>I keep going and find a Function indented where it shouldn't be.</p>\n\n<pre><code> public static function get_from_db()\n</code></pre>\n\n<p>this is indented too far.</p>\n\n<hr>\n\n<p>it really looks like there are two people writing this code.</p>\n\n<p>my suggestion is that if you borrow code from somewhere else that you style it the way that you would write it so that it is easier for you to read in a year, or two or more. you don't want to look back at your code and think to yourself \"what was a I doing here?\" you want to be able to read the code and be able to tell what is going on, even if you have learned more about the language and would do things differently, you should still be able to read the code easily.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T14:26:23.150",
"Id": "59574",
"Score": "1",
"body": "Agreed with you on all coding style point. In fact I havea lot of bad habits while coding (wrong/mixing indents...). I'm trying to lose those quick&dirty habits to have a good and reusable coding style for this kind of project, but isn't easy to lose years of bad habits."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T14:56:58.473",
"Id": "59577",
"Score": "0",
"body": "I know what you mean, I am always learning new techniques and such, different styles of coding (where to put brackets) stuff like that"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T14:14:14.637",
"Id": "36357",
"ParentId": "36140",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T15:10:09.757",
"Id": "36140",
"Score": "5",
"Tags": [
"php",
"object-oriented"
],
"Title": "PHP Cron wrapper"
}
|
36140
|
<p>I'm working on an application which has a defined and immutable (for our purposes) communication protocol. One of the features is that users on the controlling terminal can enter text commands that in many ways mimic interacting with a commandline application.</p>
<p>The structure of these commands (wrapped within a normal communication message as defined by this system) is:</p>
<pre><code><command> -<subcommand> [param] [param] [param]..
</code></pre>
<p>For example:</p>
<pre><code>sys -messagedelay 123
</code></pre>
<p>Given that the commands act on the behavior of the communication manager itself (the internals of which I don't want to expose outside of that class) <strong>which of the following is the better approach?</strong></p>
<h2>Using a nested switch:</h2>
<pre><code>private SendReceiveResult HandleCommand(string command)
{
string[] splitCommand = command.Split(CommandSplitChars);
switch (splitCommand[0])
{
case "sys":
if (splitCommand.Length < 2)
{
HandleError("Invalid sys command");
break;
}
switch (splitCommand[1])
{
case "-messagedelay":
if (splitCommand.Length < 2 ||
!float.TryParse(splitCommand[1], out messagedelay))
{
HandleError("Missing or invalid messagedelay parameter");
}
break;
// .. more cases
}
break;
// .. more cases
}
}
</code></pre>
<h2>Using a private parser class, with delegates per command:</h2>
<pre><code>// Private nested command parser class
private class CommandParser : IEqualityComparer<string[]>
{
private Dictionary<string[], Func<string[], SendReceiveResult>> commandHandlers;
private Func<string[], SendReceiveResult> defaultHandler;
public CommandParser(Func<string[], SendReceiveResult> defaultHandler)
{
commandHandlers = new Dictionary<string[], Func<string[], SendReceiveResult>>(this)
this.defaultHandler = defaultHandler;
}
public void AddCommandHandler(Func<string[], SendReceiveResult> commandHandler, params string[] pattern)
{
commandHandlers[pattern] = commandHandler;
}
SendReceiveResult ParseCommand(string command)
{
if (string.IsNullOrEmpty(command)) return SendReceiveResult.Success;
string lowerCommand = command.ToLower();
string[] splitCommand = lowerCommand.Split(CommandSplitChars);
Func<string[], SendReceiveResult> commandHandler;
if (commandHandlers.TryGetValue(splitCommand, out commandHandler))
{
return commandHandler(splitCommand);
}
return defaultHandler();
}
public bool Equals(string[] x, string[] y)
{
return y.Length > 2 &&
y[0] == x[0] &&
y[1] == x[1];
}
public int GetHashCode(string[] obj)
{
return obj.GetHashCode();
}
}
// Set up of parser in enclosing class
private void SetupCommandParser()
{
parser = new CommandParser(
(command) =>
{
Log(unsupportedMessage);
return SendReceiveResult.Success;
});
parser.AddCommandHandler(
(command) =>
{
if (command.Length < 2 ||
!float.TryParse(command[1], out messagedelay))
{
HandleError("Missing or invalid messagedelay parameter");
}
return SendReceiveResult.Success;
},
"sys", "-messagedelay");
// Add more commands, but in real implementation use named methods for readability
}
// Use of parser
private SendReceiveResult HandleCommand(string command)
{
return parser.ParseCommand(command);
}
</code></pre>
<p>The nested switches just generally have a nasty smell about them, and while the single case is readable the real implementation that would have tens of cases would be far less so. Extending it feels like it could potentially introduce bugs easily. </p>
<p>The parser feels like a more complete and extensible option-and might be something I can pull out later and generalize even more to reuse. At the same time though, it feels like overkill for the task at hand.</p>
<p>Assuming the parser does turn out to be the better option, it could probably use regexes instead of the string array patterns, I just don't know the Regex lib well enough to slap together a quick example like this without some lookup ;)</p>
|
[] |
[
{
"body": "<blockquote>\n <p><strong>Nested Switch</strong></p>\n</blockquote>\n\n<p>Nasty smell, but not such a bad idea - if it <em>gets it done</em>, then it could easily be refactored into a much better-looking and less error-prone form. There are already tons of posts here and on StackOverflow about refactoring <code>switch</code> blocks, the common way would be to use a <code>Dictionary</code> and map each key to a method.</p>\n\n<blockquote>\n <p><strong>Parser Class / Delegates per Command</strong></p>\n</blockquote>\n\n<p>Another, different smell, but still smelly: over-complicated. [K]eep [I]t [S]imple, [S]tupid. This is definitely shredding KISS into nano-pieces, and I have yet to understand <em>why</em> you would want a <em>parser</em> class to implement <code>IEqualityComparer<string[]></code> (merely just glanced at the code).</p>\n\n<p>I think the solution is <em>simplicity</em>: I'd start with the <code>switch</code> blocks, get the logic together, and refactor until satisfaction is achieved (I'd maybe end up <em>extracting classes</em> for each command, <em>extracting interfaces</em> for everything they all have in common, etc).</p>\n\n<p>Or, use a command-line parser library!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T04:42:40.273",
"Id": "59187",
"Score": "0",
"body": "What command line parser library would you suggest?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T04:44:05.213",
"Id": "59188",
"Score": "0",
"body": "Never used one myself, so I can't quite recommend any. It *could* be overkill, I'd probably go with the dictionary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T04:45:45.867",
"Id": "59189",
"Score": "0",
"body": "I'd decide by the rule of three."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T06:03:49.507",
"Id": "59194",
"Score": "0",
"body": "I did actually look at a couple of commandline parser libraries, but in general the syntax they supported didn't quite map to the one we have to deal with. The custom parser seemed like a decent halfway point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T06:17:03.050",
"Id": "59195",
"Score": "0",
"body": "It is. I see a need for some `IParser.Parse(string)`; the rest is *implementation details*, and that's where it gets interesting. I might review this code more thoroughly at a later time; I'll let you know if I edit this answer :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T06:27:01.643",
"Id": "59198",
"Score": "1",
"body": "IEqualityComparer was to specifiy how the dictionary in the parser implementation compares keys. An internal class would be better, but again that was to get a quick proof of concept out.\n\nThe parser does have anti-KISS smell to it, which is why I was concerned. Looking at it again, the switch also doesn't really need to be nested since there is really no shared logic between the different subcommands, so I could just be switching on split[0]+split[2] and having a method per subcommand, which is what I'll probably go with."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T05:15:21.270",
"Id": "59389",
"Score": "0",
"body": "Yup, was just waiting to see if any other interesting answers came along. Accepting yours based on KISS, which is what swayed me towards the (non-nested) switch."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T21:37:42.700",
"Id": "36159",
"ParentId": "36144",
"Score": "4"
}
},
{
"body": "<p>The latter approach is, of course, object-oriented, and leads to better decoupling + easier maintenance in the long term. As always, if you have to parse two or three messages, then just write anything that works and refactor later, but why are you even asking the question then?</p>\n\n<p>Here are some comments that might be useful, if you choose to consider them:</p>\n\n<ol>\n<li><p>I don't think that a <code>CommandParser</code> needs to be a comparer of string arrays. You should have a separate class for doing that, and then you can reuse it properly if you ever need so.</p></li>\n<li><p>The interface which it <em>should</em> implement is missing: if you want to split this functionality into multiple classes, then you need a contract (i.e. a <code>IParser</code> interface of some kind).</p></li>\n</ol>\n\n<p>There are also some other approaches to consider, if you want to decouple it even further. What if your parser class would parse input data and provide intermediate results (i.e. messages, as in messaging systems) as actual objects, not caring who will use them afterwards? Once you parse the input into an instance of a \"message\" (whatever that is), then you essentially have a typed object which carries the actual, parsed information for someone else to process.</p>\n\n<p>The thing which you need to decide in that case is whether you want to:</p>\n\n<ol>\n<li><p>Have a parser which creates strongly-typed intermediate results (messages), and have a separate parser class for each message, or</p></li>\n<li><p>Have a parser which creates weakly-typed intermediate results, but the parser is configured declaratively (even through XML files, similar to most logging frameworks, if you will) and all processing is done through a single class.</p></li>\n</ol>\n\n<p><strong>Strongly-typed hand made parsers</strong></p>\n\n<p>For the first approach, you would like your <code>\"sys -messageDelay 123\"</code> input to be parsed into an instance of a <code>MessageDelay</code> DTO, defined something like:</p>\n\n<pre><code>// namespace MyApp.Messages.System\nclass MessageDelay\n{\n public float DelayInMs { get; set; }\n}\n</code></pre>\n\n<p>Your parser interface would look something like:</p>\n\n<pre><code>public class Result<T>\n{\n // Parser result (success, error) \n public ResultType Type { get; set; }\n\n // Actual parsed object (if Type is Success)\n public T Value { get; set; }\n\n // Parsing-related message (nice to have it in case of errors)\n public string Message { get; set; }\n}\n\npublic interface IParser<T>\n{\n Result<T> Parse(string[] tokens);\n}\n</code></pre>\n\n<p>Note: always create an interface for your class. This will help you define the contract and serve as a sanity check:</p>\n\n<ol>\n<li>Your class really solves a certain problem for its callers</li>\n<li>Doesn't try to solve too much; your basic <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow\">SOLID</a> principles</li>\n</ol>\n\n<p>The idea is also to reuse common functionality in an abstract base class defined something like this:</p>\n\n<pre><code>public abstract class BaseParser<T> : IParser<T>\n{\n public abstract string Command { get; }\n public abstract string Subcommand { get; }\n public abstract int NumberOfParameters { get; }\n protected abstract Result<T> ParseParams(string[] input);\n\n public Result<T> Parse(string[] input)\n {\n // first do some common checks\n if (input == null || input.Any(s => s == null))\n throw new ArgumentNullException(\"input\");\n\n if (input.Length < NumberOfParameters)\n return new Result<T>() { Type = ResultType.NotEnoughData };\n\n if (input[0] != Command || input[1] != \"-\" + Subcommand)\n return new Result<T>() { Type = ResultType.NotSupported };\n\n // at this point we know that command and subcommand are ok\n // and we have enough tokens to parse\n try\n {\n return ParseParams(input);\n }\n catch (Exception ex)\n {\n return new Result<T>() { Type = ResultType.Error, Message = ex.ToString() };\n }\n }\n}\n</code></pre>\n\n<p>Catching all exceptions might not be the best idea, but I leave the choice to you. Since it's only responsible for parsing, you might want to ensure that it doesn't crash your app in case of a poorly formatted input.</p>\n\n<p>Your concrete implementations now need to do very little, but you still need to hand-craft each of them. By inheriting from the <code>BaseParser</code>, you skip the boring crap (command checking and parameter length) and get right to the main part:</p>\n\n<pre><code>public class MessageDelayParser : BaseParser<MessageDelay>\n{\n public override string Command\n { get { return \"sys\"; } }\n\n public override string Subcommand\n { get { return \"messagedelay\"; } }\n\n public override int NumberOfParameters\n { get { return 3; } }\n\n protected override Result<MessageDelay> ParseParams(string[] input)\n {\n var delay = 0f;\n if (!float.TryParse(input[2], out delay))\n return new Result<MessageDelay>() \n {\n Type = ResultType.Error, \n Message = \"expected float value but got \" + input[2] \n };\n\n return new Result<MessageDelay>()\n {\n Type = ResultType.Success,\n Value = new MessageDelay() { DelayInMs = delay }\n };\n }\n}\n</code></pre>\n\n<p>You could now wire this through a messaging system which would allow you to remove even more plumbing (e.g. log each parsed message, specify multiple consumers for a single message, etc):</p>\n\n<pre><code>var dispatcher = new CoolMessageDispatcher();\n\ndispatcher.AddParser<MessageDelay>(new MessageDelayParser());\ndispatcher.AddParser<SomethingElse>(new SomethingElseParser());\n\ndispatcher.AddConsumer<MessageDelay>(delay => { });\ndispatcher.AddConsumer<MessageDelay>(new SomeotherConsumer());\n</code></pre>\n\n<p><strong>Weakly-typed hand made parsers</strong></p>\n\n<p>Since your \"protocol\" is pretty simple and uniform, it can be actually described entirely using <em>metadata</em>:</p>\n\n<blockquote>\n <p>A \"Message Delay\" parser starts wity <code>sys</code> and <code>-messagedelay</code>, and has a single parameter named \"delay\" of type <code>float</code></p>\n</blockquote>\n\n<p>Using C# fluent-style code:</p>\n\n<pre><code>// a nice fluent interface to make it prettier, although not necessary\nvar delayParser = CoolParserBuilder\n .ForCommand(\"sys\", \"messagedelay\")\n .WithFriendlyName(\"Message Delay\")\n .AddParameter<float>(\"delay\")\n .CreateParser();\n</code></pre>\n\n<p>Using XML based configuration:</p>\n\n\n\n<pre class=\"lang-xml prettyprint-override\"><code><Parser>\n <Name>message delay</Name>\n <Command>sys</Command>\n <SubCommand>messagedelay</SubCommand>\n <Parameters>\n <Parameter Name=\"delay\" Type=\"System.Single\" />\n </Parameters>\n</Parser>\n</code></pre>\n\n<p>This concept is even more cool, because once you create your parameter parsers, you don't need to create any additional code for parsing, which means less bugs, easier testing, and better metadata in runtime.</p>\n\n<p>Your parser is now completely capable of splitting the string into tokens, identifying commands and validating parameters:</p>\n\n\n\n<pre class=\"lang-none prettyprint-override\"><code>- New message received: \"sys -messagedelay 123\"\n- Split into tokens:\n Command: sys\n SubCommand: messagedelay\n Parameters: string[] { \"123\" }\n- Found matching parser \"Message Delay\"\n- Successfully parsed parameter \"delay\" of type \"float\": 123\n- Profit!\n</code></pre>\n\n<p>This is a joy to maintain and extend, and provides rich logging information in runtime, but can lead to runtime errors for consumers, due to its weak-typeness. I leave the actual implementation to you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T14:57:26.140",
"Id": "59273",
"Score": "0",
"body": "I have a very similar pattern to your first suggestion for the containing message type (of which the command message is just one of many). The system I'm dealing with is odd in that it has strictly defined message structures for everything other than these command messages-of which there are relatively few. Another layer of messages seemed overkill.\n\nI really like your second pattern, and will probably use it in other projects, but again for this case it seems overkill :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T16:48:19.263",
"Id": "59318",
"Score": "0",
"body": "@Flint: yeah, I am pretty sure I wouldn't do the entire second approach for anything but a really large project, but if you disregard the fluent and xml declarations, actual concept shouldn't take too much work. The main thing I always look for is less code repetition and easier unit testing, and you will end up with lots of length checks and value conversions which have potential bugs and could ideally be done only once. But, the truth is, your first approach will work perfectly well for now, will allow you to deliver the solution quickly, and can easily be refactored once there is a need."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T14:47:03.350",
"Id": "36211",
"ParentId": "36144",
"Score": "4"
}
},
{
"body": "<p>as an <a href=\"http://www.antlr.org/\" rel=\"nofollow\">ANTLR</a> fan, and assuming you dont have a raging hatred for auto-generated code, I'd be remiss if parser generators didn't get mentioned here. </p>\n\n<p>With a parser generator, you'd specify your desired syntax in a grammar file and the interpreter in a listener (or 'walker' or 'visitor') C# file.</p>\n\n\n\n<pre><code>//ANTLR comlang.g4 grammar file:\ngrammer comlang;\n\ncmd \n : sys\n | run \n | status\n\nstart\n : 'sys' (msgDelay | specialTreatment)? generalArg+\n\nrun \n : 'run' generalArg*\n\nmsgDelay\n : '-messagedelay' [0-9]+\nspecialTreatment\n : '-specialTreatment' ('UI_ONLY' | 'BIG_DEAL' | 'SILENT')\n\ngeneralArg\n : [0-9a-zA-Z_]+\n\n//... and so on.\n</code></pre>\n\n<p>And your code generating file:</p>\n\n\n\n<pre><code>//quick disclaimer: I've never worked with the C# ANTLR target, \n//only the java one, but I've used that one extensively, so I'm estimating:\nclass ComlangInterpreter : ComlangBaseListener{\n\n Command command;\n\n public override void exitCmd(ComlangParser.CmdContext ctx) {\n command.run();\n }\n\n public override void exitSys(ComlangParser.SysContext ctx) {\n SysCommand command = new SysCommand{\n messageDelay = ctx.msgDelay?.Children?.[1]?.Text ?? \"\",\n specialTreatment = Enum.parse(SpecialTreatment, ctx.specialTreatment?.Children?.[1].Text ?? \"DEFAULT\")\n args = ctx.generalArgs.select(tnode => tnode.Text).toList()\n }\n this.command = command;\n }\n\n public override void exitRun(ComlangParser.RunContext ctx) {\n //...\n }\n\n //...\n}\n</code></pre>\n\n<p>You will also have to write some 10-20 lines of boilerplate to get ANTLR to lex and parse the text, then run your listener over it. </p>\n\n<p>The two big wins in this approach are that you get to specify your language in EBNF (or an ASCII version of it), and you don't have to write the branching logic yourself. This makes the listener and grammar vastly easier to read and reason about (and have interns/newbies modify) than hand-written parsers. </p>\n\n<p>Another cool win is that ANTLR does a reasonable job at best-effort recovery. You can configure it to act differently, but by default it will coalesce the tree to a close legal approximation, and give you warnings (rather annoyingly pushed to std-err by default) when it does. </p>\n\n<p><em>then the nasty bit</em>:</p>\n\n<p>you'd have to modify your build system to tolerate the generated code that comes out of your parser generator. The tools for doing this are reasonable on the java side (ant, gradle, and maven tasks all ready to go), but I don't know how they are in .net land. </p>\n\n<p>Further, for your situation, this is a pretty heavy-handed measure. If you can get away with writing your parser by hand and never touching it again, doing that is the best option. If you find yourself going back to that parser time and time again I would urge you to consider a solution involving a parser generator. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-26T20:30:50.870",
"Id": "111954",
"ParentId": "36144",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "36159",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T16:17:34.767",
"Id": "36144",
"Score": "5",
"Tags": [
"c#",
"parsing"
],
"Title": "Nested switches vs domain specific parser"
}
|
36144
|
<p>I'm working on a path planning algorithm that will be converted to RobotC. I'm trying to optimize it so that it uses the least amount of memory, as the robot it will be implemented on has supposedly as little as 15k available memory.</p>
<p>It may just be the nature of the algorithm used, but it is apparent that it is making some bad choices when it gets to the middle left part of the grid. Any idea how I might optimize this a bit? Perhaps using a real distance measurement? This is important because the program searching the entire map could result in running out of memory. I understand that this probably can't be completely prevented, but I'd like to mitigate it as much as possible.</p>
<p><strong>Extracted algorithm from code snippet below</strong></p>
<p>setTimeout is for visual feedback / understanding of algorithm.</p>
<pre><code>function scanCells() {
if (openCells > 0) {
setTimeout(function() {
if (current == undefined) {
finished();
return;
}
open[current.x][current.y] = false;
$(td[current.x][current.y]).css({ "background-color": '#FFFF00' });
if (current.x == goal.x && current.y == goal.y) {
pathFound = true;
finished();
return;
}
var nodeDistances = {
node1: 1000,
node2 : 1000,
node3 : 1000,
node4 : 1000
};
// Get the best node.
// Search adjacent tiles.
var distance = 1000;
var node = {};
node.x = -1;
node.y = -1;
if (current.x - 1 >= 0 && open[current.x - 1][current.y]) {
node.x = current.x - 1;
node.y = current.y;
distance = genericDistance(current.x - 1, current.y, goal.x, goal.y);
}
if (current.y - 1 >= 0 && open[current.x][current.y - 1] && (genericDistance(current.x, current.y - 1, goal.x, goal.y) < distance)) {
node.x = current.x;
node.y = current.y - 1;
distance = genericDistance(current.x, current.y - 1, goal.x, goal.y);
}
if (current.x + 1 < 10 && open[current.x + 1][current.y] && genericDistance(current.x + 1, current.y, goal.x, goal.y) < distance) {
node.x = current.x + 1;
node.y = current.y;
distance = genericDistance(current.x + 1, current.y, goal.x, goal.y);
}
if (current.y + 1 < 10 && open[current.x][current.y + 1] && genericDistance(current.x, current.y + 1, goal.x, goal.y) < distance) {
node.x = current.x;
node.y = current.y + 1;
distance = genericDistance(current.x, current.y + 1, goal.x, goal.y);
}
if (node.x == -1 || node.y == -1) {
// We need to step backwards until a node is available.
//path[pathIndex] = null;
path[pathIndex - 1] = null;
pathIndex -= 1;
current = path[pathIndex - 1];
scanCells();
return;
//continue;
}
$(td[current.x][current.y]).css({ "background-color": '#AAAA00' });
current = node;
path[pathIndex++] = current;
scanCells();
}, 1000);
}
else {
finished();
}
}
scanCells();
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var grid = [];
var open = [];
var current = {};
var start = {};
var goal = {};
var openCells = 0;
var path = [];
var pathIndex = 0;
// init grid
for (var x = 0; x < 10; x++) {
grid[x] = [];
open[x] = [];
for (var y = 0; y < 10; y++) {
grid[x][y] = 0;
open[x][y] = true;
openCells++;
}
}
open[3][5] = false;
//open[2][5] = false;
//open[2][4] = false;
open[2][3] = false;
open[3][3] = false;
open[8][8] = false;
open[8][6] = false;
open[8][7] = false;
open[8][5] = false;
open[8][4] = false;
open[8][3] = false;
open[8][2] = false;
open[8][1] = false;
open[6][1] = false;
open[6][2] = false;
open[6][3] = false;
open[4][5] = false;
open[4][6] = false;
open[5][4] = false;
open[6][4] = false;
open[7][4] = false;
open[4][7] = false;
open[4][8] = false;
open[4][9] = false;
open[7][8] = false;
open[6][8] = false;
open[5][6] = false;
open[6][6] = false;
open[1][0] = false;
open[1][1] = false;
open[1][2] = false;
open[1][3] = false;
open[1][4] = false;
open[1][5] = false;
open[1][6] = false;
open[1][7] = false;
open[1][8] = false;
open[0][0] = false;
openCells--;
start.x = 0;
start.y = 0;
goal.x = 5;
goal.y = 5;
var pathFound = false;
function genericDistance(x1, y1, x2, y2) {
return Math.abs(x2 - x1) + Math.abs(y2 - y1);
}
// Draw grid / path
var table = $("<table></table>").appendTo("body");
var tr = [];
var td = [];
for (var x = 0; x < 10; x++) {
tr[x] = $("<tr></tr>").appendTo(table);
td[x] = [];
for (var y = 0; y < 10; y++) {
td[x][y] = $("<td></td>").appendTo(tr[x]).css({
width : "50px",
height : "50px",
border : "1px solid #000000"
});
}
}
for (var x = 0; x < 10; x++) {
for (var y = 0; y < 10; y++) {
var t = '#FF0000';
if (open[x][y]) t = '#00FF00';
td[x][y].css({ "background-color": t });
}
}
td[goal.x][goal.y].css({ "background-color" : '#0000FF' });
current = start;
path[pathIndex++] = current;
//while (openCells > 0) {
function scanCells() {
if (openCells > 0) {
setTimeout(function() {
if (current == undefined) {
finished();
return;
}
open[current.x][current.y] = false;
$(td[current.x][current.y]).css({ "background-color": '#FFFF00' });
if (current.x == goal.x && current.y == goal.y) {
pathFound = true;
finished();
return;
}
var nodeDistances = {
node1: 1000,
node2 : 1000,
node3 : 1000,
node4 : 1000
};
// Get the best node.
// Search adjacent tiles.
var distance = 1000;
var node = {};
node.x = -1;
node.y = -1;
if (current.x - 1 >= 0 && open[current.x - 1][current.y]) {
node.x = current.x - 1;
node.y = current.y;
distance = genericDistance(current.x - 1, current.y, goal.x, goal.y);
}
if (current.y - 1 >= 0 && open[current.x][current.y - 1] && (genericDistance(current.x, current.y - 1, goal.x, goal.y) < distance)) {
node.x = current.x;
node.y = current.y - 1;
distance = genericDistance(current.x, current.y - 1, goal.x, goal.y);
}
if (current.x + 1 < 10 && open[current.x + 1][current.y] && genericDistance(current.x + 1, current.y, goal.x, goal.y) < distance) {
node.x = current.x + 1;
node.y = current.y;
distance = genericDistance(current.x + 1, current.y, goal.x, goal.y);
}
if (current.y + 1 < 10 && open[current.x][current.y + 1] && genericDistance(current.x, current.y + 1, goal.x, goal.y) < distance) {
node.x = current.x;
node.y = current.y + 1;
distance = genericDistance(current.x, current.y + 1, goal.x, goal.y);
}
if (node.x == -1 || node.y == -1) {
// We need to step backwards until a node is available.
//path[pathIndex] = null;
path[pathIndex - 1] = null;
pathIndex -= 1;
current = path[pathIndex - 1];
scanCells();
return;
//continue;
}
$(td[current.x][current.y]).css({ "background-color": '#AAAA00' });
current = node;
path[pathIndex++] = current;
scanCells();
}, 250);
}
else {
finished();
}
}
scanCells();
function finished() {
if (pathFound) {
// Clean up path.
// Work from the goal back to the start position, see if we can shortcut any neighboring nodes.
var pathCleanedUp = true;
while (pathCleanedUp) {
pathCleanedUp = false;
for (var x = pathIndex - 1; x > 0; x--) {
if (pathCleanedUp) break;
for (var i = 0; i < pathIndex && i < x - 1; i++) {
if (pathCleanedUp) break;
// Node comes before x and is a neighbor of x
if (genericDistance(path[i].x, path[i].y, path[x].x, path[x].y) == 1) {
pathCleanedUp = true;
// Trim the inbetween.
var newPath = [];
for (var z = 0; z <= i; z++) {
newPath[z] = { x : path[z].x, y : path[z].y };
}
var newPathIndex = z;
for (var z = x; z < pathIndex; z++) {
newPath[newPathIndex++] = { x : path[z].x, y : path[z].y };
}
path = newPath;
pathIndex = newPathIndex;
}
else if ((path[i].x != path[x].x && path[i].y == path[x].y) || (path[i].x == path[x].x && path[i].y != path[x].y)) {
console.log("Connection:");
console.log(path[i]);
console.log(path[x]);
var connected = true;
// If nodes are within line of site and no used nodes are in between.
if (path[i].x == path[x].x) {
if (path[x].x == 1 && path[x].y == 2) console.log("X shared");
// Walk the Y value over until the values are the same or the node is closed.
if (path[i].y < path[x].y) {
for (var ty = path[i].y + 1; ty < path[x].y; ty++) {
console.log("x: " + path[i].x + " y: " + ty + " open: " + open[path[i].x][ty]);
if (!open[path[i].x][ty]) {
connected = false;
break;
}
}
}
else {
for (var ty = path[i].y - 1; ty > path[x].y; ty--) {
if (!open[path[i].x][ty]) {
connected = false;
break;
}
}
}
}
else if (path[i].y == path[i].y) {
// Walk the X value over until the values are the same or the node is closed.
if (path[i].x < path[x].x) {
for (var ty = path[i].x + 1; ty < path[x].x; ty++) {
if (!open[ty][path[i].y]) {
connected = false;
break;
}
}
}
else {
for (var ty = path[i].x - 1; ty > path[x].x; ty--) {
if (!open[ty][path[i].y]) {
connected = false;
break;
}
}
}
}
if (connected) {
console.log("Connected.");
var dist = 0;
var newPath = [];
for (var z = 0; z <= i; z++) {
newPath[z] = { x : path[z].x, y : path[z].y };
}
// Connect the two paths cutting out the inbetween steps.
if (path[i].x < path[x].x) {
// Increase x until we hit path[x].x.
for (var ix = i + 1; path[i].x + dist != path[x].x; ix++) {
dist++;
newPath[ix] = { x : path[i].x + dist, y : path[i].y };
open[newPath[ix].x][newPath[ix].y] = false;
}
}
else if (path[i].x > path[x].x) {
// Increase x until we hit path[x].x.
for (var ix = i + 1; path[i].x + dist != path[x].x; ix++) {
dist--;
newPath[ix] = { x : path[i].x + dist, y : path[i].y };
open[newPath[ix].x][newPath[ix].y] = false;
}
}
else if (path[i].y < path[x].y) {
// Increase x until we hit path[x].x.
for (var ix = i + 1; path[i].y + dist != path[x].y; ix++) {
dist++;
newPath[ix] = { x : path[i].x, y : path[i].y + dist };
open[newPath[ix].x][newPath[ix].y] = false;
}
}
else if (path[i].y > path[x].y) {
// Increase x until we hit path[x].x.
for (var ix = i + 1; path[i].y + dist != path[x].y; ix++) {
dist--;
newPath[ix] = { x : path[i].x, y : path[i].y + dist };
open[newPath[ix].x][newPath[ix].y] = false;
}
}
for (var iz = x; iz < pathIndex; iz++) {
newPath[ix++] = path[iz];
}
pathCleanedUp = true;
path = newPath;
console.log(path);
pathIndex = ix;
}
}
}
}
}
for (var x = 0; x < pathIndex; x++) {
td[path[x].x][path[x].y].html("x");
}
}
else {
console.log("No path found.");
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>The pathological hunting in the left region of your test case is an unfortunate consequence of using a naïve greedy algorithm. It really is at least as good locally to move up rather than left, and that's true whether you use Manhattan distances or Euclidean distances. If you want to avoid pathological hunting, try the <a href=\"http://en.wikipedia.org/wiki/A%2a_search_algorithm#Process\" rel=\"nofollow\">A* algorithm</a> instead.</p>\n\n<p>There are a few simple local improvements to your code.</p>\n\n<ul>\n<li><code>var nodeDistances</code> is never used.</li>\n<li><code>var distance = 1000</code> is a magic number. <code>var distance = Number.POSITIVE_INFINITY</code> would be better.</li>\n<li>Instead of a global <code>pathFound</code> flag, pass it as a parameter to <code>finished()</code> callback. You can also take advantage of the fact that <code>finished()</code> returns <code>void</code>. The idiom would be <code>return finished(true)</code> or <code>return finished(false)</code>.</li>\n<li>Prefer early returns wherever possible. In <code>scanCells()</code>, if you start with <code>if (openCells <= 0) { return finished(false); }</code> you could save a level of indentation in the entire body of the function. More importantly, your code would be more readable because you eliminate the element of suspense. The same advice goes for the body of your <code>finished()</code> function.</li>\n<li><code>10</code> is a magic number. Prefer <code>open[length]</code> and <code>open[0].length</code>.</li>\n<li>When using <code>path</code> as a stack, use <code>path.push(current = node)</code> and <code>path.pop()</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T19:52:00.380",
"Id": "59139",
"Score": "0",
"body": "I actually tried using the A* algorithm first in RobotC. But just defining the grid, path, gscore and fscore maps caused an out of memory error. Should the A* use less memory than best first?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T23:00:39.597",
"Id": "59158",
"Score": "0",
"body": "How large of a maze do you want to handle? Perhaps you would like to post your A* code for review as well."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T19:21:31.890",
"Id": "36151",
"ParentId": "36145",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "36151",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T16:20:25.250",
"Id": "36145",
"Score": "4",
"Tags": [
"javascript",
"performance",
"algorithm",
"pathfinding"
],
"Title": "Path Planning - Greedy Best First Search"
}
|
36145
|
<p>I have written about 180 lines of code that implements an Event system.</p>
<p>I would like a general review about the code and I'd love comments about the usability of it. (Is the code useful? Would you like to use it or a similar system like it?)</p>
<h3>Summary of the parts involved</h3>
<ul>
<li><code>IEvent</code> is a marker interface for event classes</li>
<li><code>Event</code> is an annotation that must be added for all methods that are listening to events</li>
<li><code>EventListener</code> is a marker interface for classes that wants to listen to events</li>
<li><code>EventHandler</code> is a class that is responsible for executing an event on a single <code>EventListener</code></li>
<li><code>EventExecutor</code> is the main class that binds everything together. It is where listeners must go to get registered and it is where IEvents must go to get executed.</li>
</ul>
<h3>Reason for implementing</h3>
<p>I don't want to use a whole bunch of different interfaces (one for each type of <code>IEvent</code>), along with <code>addThisEventHandler</code>, <code>addThatEventHandler</code>, <code>dispatchThisEvent</code>, <code>dispatchThatEvent</code> and a <a href="https://stackoverflow.com/questions/8247926/java-event-listener-to-detect-a-variable-change">whole bunch of other repeatedly added stuff</a>.</p>
<p>I want the system to be flexible and useful mainly. Speed is not a <em>primary</em> concern, but if you see something that is having in your opinion a too heavy performance cost then I'd love to hear about it.</p>
<h3>The Code (Approximately 180 code lines, not including whitespace and comments)</h3>
<p><code>CustomFacade.getLog...</code> is my own logging system which I don't think is relevant to the review, therefore the source is not included for this part. Besides this, the code is stand-alone (only depending on the regular Java classes, of course).</p>
<p>Event.java</p>
<pre><code>/**
* Indication that a method should handle an {@link IEvent}<br>
* The method needs to return {@link Void} and expect exactly one parameter of a type that implements {@link IEvent}.<br>
* Only methods in classes that implements {@link EventListener} should use this annotation.
*/
@Retention(value = RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Event {
int priority() default 50;
}
</code></pre>
<p>EventExecutor.java</p>
<pre><code>public class EventExecutor {
public static final int PRE = -1;
public static final int ALL = 0;
public static final int POST = 1;
private final Map<Class<? extends IEvent>, Collection<EventHandler>> bindings;
private final Set<EventListener> registeredListeners;
private boolean debug = false;
public void setDebug(boolean debug) {
this.debug = debug;
}
public EventExecutor() {
this.bindings = new HashMap<Class<? extends IEvent>, Collection<EventHandler>>();
this.registeredListeners = new HashSet<EventListener>();
}
public List<EventHandler> getListenersFor(Class<? extends IEvent> clazz) {
if (!this.bindings.containsKey(clazz))
return new ArrayList<EventHandler>(); // No handlers so we return an empty list
return new ArrayList<EventHandler>(this.bindings.get(clazz));
}
public <T extends IEvent> T executeEvent(T event, int i) {
Collection<EventHandler> handlers = this.bindings.get(event.getClass());
if (handlers == null) {
if (this.debug)
CustomFacade.getLog().d("Event " + event.getClass().getSimpleName() + " has no handlers.");
return event;
}
if (this.debug)
CustomFacade.getLog().d("Event " + event.getClass().getSimpleName() + " has " + handlers.size() + " handlers.");
for (EventHandler handler : handlers) {
// Basic support for multi-stage events. More can be added later by specifying exactly which priority to be executed - executeEventPre(event, lessThanPriority) for example
if (i == PRE && handler.getPriority() >= 0)
continue;
if (i == POST && handler.getPriority() < 0)
continue;
handler.execute(event);
}
return event;
}
public <T extends IEvent> T executeEvent(T event) {
return this.executeEvent(event, ALL);
}
public void registerListener(final EventListener listener) {
CustomFacade.getLog().v("Register event listener: " + listener);
if (registeredListeners.contains(listener)) {
CustomFacade.getLog().w("Listener already registred: " + listener);
return;
}
Method[] methods = listener.getClass().getDeclaredMethods();
this.registeredListeners.add(listener);
for (final Method method : methods) {
Event annotation = method.getAnnotation(Event.class);
if (annotation == null)
continue;
Class<?>[] parameters = method.getParameterTypes();
if (parameters.length != 1) // all listener methods should only have one parameter
continue;
Class<?> param = parameters[0];
if (!method.getReturnType().equals(void.class)) {
CustomFacade.getLog().w("Ignoring method due to non-void return: " + method.getName());
continue;
}
if (IEvent.class.isAssignableFrom(param)) {
@SuppressWarnings("unchecked") // Java just doesn't understand that this actually is a safe cast because of the above if-statement
Class<? extends IEvent> realParam = (Class<? extends IEvent>) param;
if (!this.bindings.containsKey(realParam)) {
this.bindings.put(realParam, new TreeSet<EventHandler>());
}
Collection<EventHandler> eventHandlersForEvent = this.bindings.get(realParam);
CustomFacade.getLog().v("Add listener method: " + method.getName() + " for event " + realParam.getSimpleName());
eventHandlersForEvent.add(createEventHandler(listener, method, annotation));
}
}
}
private EventHandler createEventHandler(final EventListener listener, final Method method, final Event annotation) {
return new EventHandler(listener, method, annotation);
}
public void clearListeners() {
this.bindings.clear();
this.registeredListeners.clear();
}
public void removeListener(EventListener listener) {
for (Entry<Class<? extends IEvent>, Collection<EventHandler>> ee : bindings.entrySet()) {
Iterator<EventHandler> it = ee.getValue().iterator();
while (it.hasNext()) {
EventHandler curr = it.next();
if (curr.getListener() == listener)
it.remove();
}
}
this.registeredListeners.remove(listener);
}
public Map<Class<? extends IEvent>, Collection<EventHandler>> getBindings() {
return new HashMap<Class<? extends IEvent>, Collection<EventHandler>>(bindings);
}
public Set<EventListener> getRegisteredListeners() {
return new HashSet<EventListener>(registeredListeners);
}
}
</code></pre>
<p>EventHandler.java</p>
<pre><code>public class EventHandler implements Comparable<EventHandler> {
private final EventListener listener;
private final Method method;
private final Event annotation;
public EventHandler(EventListener listener, Method method, Event annotation) {
this.listener = listener;
this.method = method;
this.annotation = annotation;
}
public Event getAnnotation() {
return annotation;
}
public Method getMethod() {
return method;
}
public EventListener getListener() {
return listener;
}
public void execute(IEvent event) {
try {
method.invoke(listener, event);
} catch (IllegalAccessException e1) {
CustomFacade.getLog().e("Exception when performing EventHandler " + this.listener + " for event " + event.toString(), e1);
} catch (IllegalArgumentException e1) {
CustomFacade.getLog().e("Exception when performing EventHandler " + this.listener + " for event " + event.toString(), e1);
} catch (InvocationTargetException e1) {
CustomFacade.getLog().e("Exception when performing EventHandler " + this.listener + " for event " + event.toString(), e1);
}
}
@Override
public String toString() {
return "(EventHandler " + this.listener + ": " + method.getName() + ")";
}
public int getPriority() {
return annotation.priority();
}
@Override
public int compareTo(EventHandler other) {
// Because we are using a TreeSet to store EventHandlers in, compareTo should never return "equal".
int annotation = this.annotation.priority() - other.annotation.priority();
if (annotation == 0)
annotation = this.listener.hashCode() - other.listener.hashCode();
return annotation == 0 ? this.hashCode() - other.hashCode() : annotation;
}
}
</code></pre>
<p>EventListener.java</p>
<pre><code>/**
* Marker interface for classes that can be scanned for @Event annotations
* @see Event
*/
public interface EventListener {}
</code></pre>
<p>IEvent.java</p>
<pre><code>/**
* Marker interface for events
*/
public interface IEvent {}
</code></pre>
<h3>A simple JUnit test</h3>
<p>Normally the class(es) that implements <code>EventListener</code> and the class that contains the <code>EventExecutor</code> are in entirely different packages.</p>
<pre><code>public class EventTest implements EventListener {
private EventExecutor events;
private int messages;
@Before
public void before() {
this.events = new EventExecutor();
this.events.registerListener(this);
}
@Test
public void test() {
assertEquals(0, messages);
this.events.executeEvent(new SimpleEvent("Message"));
assertEquals(1, messages);
}
@Event
public void onSimpleEvent(SimpleEvent event) {
messages++;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Being particularly pedantic, but I have the following observations:</p>\n\n<h1>Annotation @Event</h1>\n\n<p>You go to great lengths to document <code>@Event</code> but not to document the <code>priority()</code> setting .... just saying... The priority is the sort of thing that needs documentation... is priority == 80 more or less important than priority == 0?</p>\n\n<h1>EventExecutor</h1>\n\n<ul>\n<li>There is nothing in here that suggests it is thread-safe. This may well be by design, but for a general-purpose system it will need to be, especially if you are advertising it as being a 'library' implementation.</li>\n<li>It is <a href=\"http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#getListeners%28java.lang.Class%29\">'traditional' for <code>getListeners()</code> type methods to return an <code>array\\[\\]</code></a> rather than a List. I prefer the <code>array[]</code> because I like primitives, but, additionally, it is 'clearer' that you cannot add and remove items from the array.... Your code returns a list, but it is a modifyable List (even when empty). I believe I would prefer your code as (note how there's now only one lookup in the bindings map now as well):</li>\n</ul>\n\n<p>...</p>\n\n<pre><code> private static final EventHandler[] EMPTYHANDLERS = {};\n\n public EventHandler[] getListenersFor(Class<? extends IEvent> clazz) {\n Collection<EventHandler> handlers = this.bindings.get(clazz);\n if (handlers == null || handlers.isEmpty()) \n return EMPTYHANDLERS; // No handlers so we return an empty list\n return handlers.toArray(new EventHandler[handlers.size()]);\n }\n</code></pre>\n\n<ul>\n<li>In <code>registerListener()</code> I think you have inconsistent logging (why log when a single-argument method is non-void, bot not log when you have a multi-argument method?) I think the code should all be condensed to: <code>if (parameters.length == 1\n && IEvent.class.isAssignableFrom(parameters[0])\n && method.getReturnType().equals(void.class)) { ...</code></li>\n<li>should <code>getBindings()</code> and <code>getRegisteredListeners()</code> really be public?</li>\n</ul>\n\n<h1>EventHandler</h1>\n\n<p>I thin kit is naive to have the <code>execute(IEvent)</code> method have no error handling (it swallows all exceptions). I think you should at least document that there is an unchecked exception thrown from the method.... (these are significant problems) like:</p>\n\n<pre><code>/**\n * ......\n * throws IllegalStateException if it is not possible to invoke the event on a listener.\n */\npublic void execute(IEvent event) throws IllegalStateException {\n try {\n method.invoke(listener, event);\n } catch (IllegalAccessException e1) {\n CustomFacade.getLog().e(\"Exception when performing EventHandler \" + this.listener + \" for event \" + event.toString(), e1);\n throw new IllegalStateException(\"Unable to call \" + method, e1);\n } catch (IllegalArgumentException e1) {\n CustomFacade.getLog().e(\"Exception when performing EventHandler \" + this.listener + \" for event \" + event.toString(), e1);\n throw new IllegalStateException(\"Unable to call \" + method, e1);\n } catch (InvocationTargetException e1) {\n CustomFacade.getLog().e(\"Exception when performing EventHandler \" + this.listener + \" for event \" + event.toString(), e1);\n throw new IllegalStateException(\"Unable to call \" + method, e1);\n } \n} \n</code></pre>\n\n<p>Also, what if the invoked method throws an exception... do you propagate that?</p>\n\n<p>Why do you feel it is necessary to have <code>getMethod()</code>. The reflection you are doing should not be exposed....</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T21:41:14.920",
"Id": "59143",
"Score": "0",
"body": "If the invoked method throws an exception, that gets wrapped as an `InvocactionTargetException`, which is a checked exception and is therefore catched."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T22:04:42.177",
"Id": "59620",
"Score": "0",
"body": "Thanks for pointing out that some methods shouldn't be public, turned out that those methods weren't even used... :) Could you give some hints about what I need to do to ensure thread safety? Is it only about synchronizing `bindings` and `registeredListeners` (or use `Concurrent` versions of those types) or is there something else needed as well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T13:11:02.033",
"Id": "393176",
"Score": "0",
"body": "1. avoid mutability when returning some state in collections by using `Collections.unmodifiableMap()` / `Collections.unmodifiableSet()` to make sure it will not be modified by anyone in a separate thread\n2. use concurrent collections, like so:\n\n`this.bindings = new ConcurrentHashMap();` and `this.registeredListeners = ConcurrentHashMap.newKeySet();`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T21:34:23.867",
"Id": "36158",
"ParentId": "36153",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "36158",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T19:53:47.340",
"Id": "36153",
"Score": "14",
"Tags": [
"java",
"event-handling"
],
"Title": "My Event-handling system"
}
|
36153
|
<p>The code works just fine, but recently performace has taken a hit and it has SQL Timeouts far too often. I have it set up so I can run 50 different version of the application two for each different <code>m.qlevel</code>.</p>
<p>This allows it to run fairly fast, but the SQL timeouts are requiring to much babysitting.</p>
<p><code>document_attachments</code> has over 3 millions rows and <code>jm_documentationissues</code> gains a row anytime I successfully update a row from <code>document_attachments</code>.</p>
<p>The reason it times out is because depending on the time of the day we have some pretty intense jobs running which hog all of the SQL resources causing my application to time out and fail.</p>
<p>I run two applications per <code>qlevel</code> one <code>asc order</code> and one <code>desc order</code>. This creates a problem when there is only one row left and both applications pull that same row it throws a primary key failure.</p>
<p>The above bug and the SQL time out are the two biggest problems with this application. It runs slow since it is trying to navigate through 3 millions rows to find a document path, go into a directory of 5 million files, move it to a new directory and then update the table if successful. </p>
<p>Any improvements to this are welcome!</p>
<p>** I've thought maybe of grabbing 100,000 rows and throwing it into a variable, and then processing from that list until it is 0 then grabbing another 100,000. I'm just not sure if that is the best or even a good approach. The only drawback to this approach is it might limit me to one application at a time which would takes months to complete.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Threading.Tasks;
namespace LattitudeDocumentationOrganizer
{
internal class Program
{
private static readonly string connString = LattitudeDocumentationOrganizer.Properties.Settings.Default.ConnectionString;
private static void Main()
{
int fileCount = 0;
int errorCount = 0;
bool RunLoop = true;
//List<Task> tasks = new List<Task>();
while (RunLoop)
{
Console.Clear();
using (SqlConnection connection = new SqlConnection(connString))
{
connection.Open();
// Run through
const string Sql = @"select top 1 d.UID, d.CreatedDate, d.Location, m.number from master m with (NOLOCK)
inner join documentation_attachments da with (NOLOCK)
on m.number = da.accountid
inner join documentation d with (NOLOCK)
on da.documentid = d.uid
where m.qlevel = 999
and d.location is not null
and uid not in (select documentid from JM_DocumentationIssues)
order by m.number desc";
using (SqlCommand command = new SqlCommand(Sql, connection))
using (SqlCommand updateCommand = CreateUpdateCommand(connection))
using (SqlCommand logErrorCommand = CreateLogErrorCommand(connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
// If no data is returned assume no data is left and report statistic and exit loop
if (!reader.HasRows)
{
Console.WriteLine("Processed {0} files successfully.", fileCount);
Console.WriteLine("Did not process {0} files successfully.", errorCount);
Console.WriteLine("No more files were found with the current query");
Console.ReadLine();
Console.WriteLine("Exiting program.");
break;
}
// Close the loop out as a specific day and time.
DateTime currentDate = DateTime.Now;
if (currentDate.DayOfWeek == DayOfWeek.Monday && currentDate.Hour >= 20)
{
Console.WriteLine("Processed {0} files successfully.", fileCount);
Console.WriteLine("Did not process {0} files successfully.", errorCount);
Console.WriteLine(
"The time set for this process to end has been reached. Program exited at {0}",
DateTime.Now);
Console.ReadLine();
Console.WriteLine("Exiting program.");
break;
}
Console.WriteLine("Processing data...");
while (reader.Read())
{
SqlCommand updateCommand1 = updateCommand;
SqlCommand logErrorCommand1 = logErrorCommand;
// Row Values
// 0 = UID
// 1 = CreatedDate
// 2 = Location
Guid documentID = reader.GetGuid(0);
string fileName = reader.GetSqlValue(0) + ".zip";
string location = reader.GetString(2);
DateTime createdDate = reader.GetDateTime(1);
int number = reader.GetInt32(3);
Console.WriteLine("Current File #: {0}", fileCount);
Console.WriteLine("Working on document {0}", documentID);
FileInfo fileinfo = new FileInfo(Path.Combine(location, fileName));
string msg;
if (!fileinfo.Exists)
{
// Log error to JM_DocumentationIssues
msg = "This file does not exist";
LogError(logErrorCommand1, documentID, location, null, msg, number);
Console.WriteLine(
"This file did not exist, logged it to the database and moving on to the next file.");
errorCount++;
reader.NextResult();
}
else
{
// file exists begin process to create new folders
var fileYear = "DOCS" + createdDate.Year;
var fileMonth = createdDate.ToString("MMM");
const string RootDir = @"\\192.168.22.23";
Console.WriteLine(
"File Exists, checking to make sure the directories needed exist.");
if (!Directory.Exists(Path.Combine(RootDir, fileYear)))
{
// Should no longer error out here all root level folders are created 2006-2014.
// Error, cannot create root level network share folder. Log to Database.
// Error Root Level Folder Missing
// Directory.CreateDirectory(Path.Combine(rootDir,fileYear));
// Log error to JM_DocumentationIssues
//msg = "Could not create root folder, log to skip this file";
//LogError(logErrorCommand1, documentID, location, Path.Combine(RootDir, fileYear), msg, number);
//errorCount++;
}
else
{
if (!Directory.Exists(Path.Combine(RootDir, fileYear, fileMonth)))
{
// Create the month folder
Directory.CreateDirectory(Path.Combine(RootDir, fileYear, fileMonth));
Console.WriteLine(
"The month folder did not exist, created {0} folder", fileMonth);
}
// Call method to update location in database and move tile
UpdateDocument(updateCommand1, documentID, Path.Combine(RootDir, fileYear, fileMonth));
fileinfo.MoveTo(Path.Combine(RootDir, fileYear, fileMonth, fileName));
////File.Move(Path.Combine(location, fileName), Path.Combine(rootDir, fileYear, fileMonth, fileName));
msg = "SUCCESS";
LogError(
logErrorCommand1,
documentID,
location,
Path.Combine(RootDir, fileYear, fileMonth),
msg,
number);
Console.WriteLine(
"Successfully moved and logged the file, checking for more files.");
fileCount++;
reader.NextResult();
////break;
}
}
}
//Task.WaitAll(tasks.ToArray());
}
}
}
}
}
private static SqlCommand CreateUpdateCommand(SqlConnection connection)
{
const string Sql = "update documentation set location = @newLocation where uid = @id";
SqlCommand command = new SqlCommand(Sql, connection);
command.Parameters.Add(new SqlParameter("id", SqlDbType.UniqueIdentifier));
command.Parameters.Add(new SqlParameter("newLocation", SqlDbType.VarChar, 50)); // guessing varchar(50) here
command.Prepare();
return command;
}
private static void UpdateDocument(SqlCommand command, Guid id, string newLocation)
{
command.Parameters["id"].Value = id;
command.Parameters["newLocation"].Value = newLocation;
command.ExecuteNonQuery();
}
private static SqlCommand CreateLogErrorCommand(SqlConnection connection)
{
const string Sql =
@"insert into JM_DocumentationIssues (documentid, oldLocation, newLocation, errorMessage, dateAdded, number)
values (@id, @prevLocation, @newLocation, @msg, GETDATE(), @number)";
SqlCommand command = new SqlCommand(Sql, connection);
command.Parameters.Add(new SqlParameter("id", SqlDbType.UniqueIdentifier));
command.Parameters.Add(new SqlParameter("prevLocation", SqlDbType.VarChar, 260)); // guessing varchar(255) here
command.Parameters.Add(new SqlParameter("newLocation", SqlDbType.VarChar, 260)); // guessing varchar(255) here
command.Parameters.Add(new SqlParameter("msg", SqlDbType.VarChar, -1)); // guessing varchar(255) here
command.Parameters.Add(new SqlParameter("number", SqlDbType.Int));
command.Prepare();
return command;
}
private static void LogError(SqlCommand command, Guid id, string prevLocation, string newLocation, string msg, int number)
{
if (newLocation == null)
{
newLocation = "no new location";
}
command.Parameters["id"].Value = id;
command.Parameters["prevLocation"].Value = prevLocation;
command.Parameters["newLocation"].Value = newLocation;
command.Parameters["msg"].Value = msg;
command.Parameters["number"].Value = number;
command.ExecuteNonQuery();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T22:35:14.483",
"Id": "59151",
"Score": "0",
"body": "Have you done an execution plan on the SQL statements inside your code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T22:44:27.290",
"Id": "59155",
"Score": "0",
"body": "@JohnDeters I have not during times when the sql resources are free it returns a single row in less than a second. It isn't until other things tie up the sql resources that my code is pushed down the job cycle and thus times out."
}
] |
[
{
"body": "<p>Try this Query</p>\n\n<pre><code>const string Sql = @\"select top 1 d.UID, d.CreatedDate, d.Location, m.number from master m with (NOLOCK)\n inner join documentation_attachments da with (NOLOCK)\n on m.number = da.accountid\n inner join documentation d with (NOLOCK)\n on da.documentid = d.uid\n LEFT JOIN JM_DocumentationIssues WITH (NOLOCK) \n ON d.UID = JM_DocumentationIssues.UID\n where m.qlevel = 999\n and d.location is not null\n -- and uid not in (select documentid from JM_DocumentationIssues)\n order by m.number desc\";\n</code></pre>\n\n<p>I think that I have the correct join in there</p>\n\n<p>If you use the <code>NOT IN</code> or the <code><></code> in the where statement it can cause issues with large queries because it has to run the nested query every time that it goes through a record.</p>\n\n<p>With this query you should be able to do the <code>SELECT TOP 50000</code> or whatever, which is what you should do.</p>\n\n<p>The code needs to be changed. you need the DataReader to call a Query that returns more than 1 row and then go row by row, maybe do a mass update. this would speed up the application and/or SQL Query and release a lot of resources. </p>\n\n<p>You should be looping through the returned records and not calling the SQL 500,000 times. That is what is slowing down the SQL Database.</p>\n\n<hr>\n\n<p>You need to look at what you are doing here, because your two if blocks of code are the only place where you can break out of the while loop.</p>\n\n<p>You set a boolean variable <code>RunLoop</code> to <code>True</code> and then tell a while loop to run while that boolean is <code>True</code> but never set it to <code>False</code></p>\n\n<p>Inside your While loop you have a bunch of using statements that if they fail, the exception is never caught. There is no Exception Handling going on at all. </p>\n\n<p><strong>I am sure that one of your loops is probably doing more work than you think it is.</strong></p>\n\n<hr>\n\n<p>It also looks like you are using <code>LogError</code> to log the results of the application and not actually logging errors</p>\n\n<hr>\n\n<p>Inside your <code>UpdateDocument</code> you execute a command with out exception handling again.</p>\n\n<hr>\n\n<h2>to wrap this up</h2>\n\n<p>I think that you should take out all of the <code>Console.WriteLine()</code> nonsense and actually log that stuff to a text file or something maybe,</p>\n\n<p><code>Console.WriteLine()</code> takes a lot of time, I wish that I could remember the post where I saw this, the post actually gave the times of a <code>Console.WriteLine</code> and it wasn't pretty. </p>\n\n<p>Maybe just start out by calling <code>Console.WriteLine()</code> less by merging the strings together.</p>\n\n<hr>\n\n<p>To Elaborate what @rolfl said in his answer.\nall of your <code>using</code> blocks should be outside of your <code>while</code> loop</p>\n\n<p>Your <code>while</code> loop should be inside of your <code>SqlDataReader</code> using block</p>\n\n<pre><code>using (SqlDataReader reader = command.ExecuteReader())\n{\n While (RunLoop)\n {\n // If no data is returned assume no data is left and report statistic and exit loop\n if (!reader.HasRows)\n {\n Console.WriteLine(\"Processed {0} files successfully.\", fileCount);\n Console.WriteLine(\"Did not process {0} files successfully.\", errorCount);\n Console.WriteLine(\"No more files were found with the current query\");\n Console.ReadLine();\n Console.WriteLine(\"Exiting program.\");\n break;\n }\n }\n\n......\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T22:55:18.513",
"Id": "59156",
"Score": "0",
"body": "I was unaware of the time console.writeline() used. I will remove them, but I highly doubt those are the cause of the SQL timeouts. The applications runs incredible fast when the SQL resources are plentiful. It runs so fast that I cannot even read the writelines(). The code is ordered ugly because it worked one way then went through a significant changes and rather than rewriting i just hijacked existing working code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T23:13:44.690",
"Id": "59164",
"Score": "0",
"body": "I'm just trying to understand this better. If I move my RunLoop to where you suggested after my reader wouldn't this application run a single time affecting a single row only? My reader will only have a single row by design. Or the application finishes the last line of code here will it automatically go back up to my reader line and select a new top 1?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T23:18:49.397",
"Id": "59165",
"Score": "0",
"body": "@JamesWilson, let me digest that for a little bit"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T06:35:31.110",
"Id": "59199",
"Score": "0",
"body": "@JamesWilson I haven't forgot about this. you will have to change the select statement so that it grabs all the records that you want, and then go through each record in the query. I will look at it again tomorrow and see what I can figure out to make it nicer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T14:57:04.120",
"Id": "59272",
"Score": "1",
"body": "@JamesWilson, the speed of which the Console.WriteLine's are printing, or your inability to read them, is not a very good indicator of the performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T14:59:59.260",
"Id": "59276",
"Score": "0",
"body": "@user1021726, you should give yourself a Nickname on your profile so we can tell you apart from everyone else, and also join us in [chat](http://chat.stackexchange.com/rooms/8595/code-review-general-room)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T22:33:51.493",
"Id": "36164",
"ParentId": "36161",
"Score": "5"
}
},
{
"body": "<p>Just so I get this straight in my head..... (My C# is non-existent).</p>\n\n<p>You have:</p>\n\n<ol>\n<li>a connection to a SQL Server database</li>\n<li>with that connection you <code>select TOP 1 ....</code> from a complex join query</li>\n<li>with that record you create a couple of other prepared statements, one for the update, and another for a possible error condition.</li>\n<li>you then update the record's location with a new file location.... and at the same time also add an 'issue record' so that the record is not selected the next time through the loop.</li>\n<li>you then return to step 1.</li>\n</ol>\n\n<p>If this is the case, you should:</p>\n\n<p>Only connect once! The connection to the database should happen outside the loop (not a new connection for every record).</p>\n\n<p>The <code>command</code>, <code>updateCommand</code> and <code>errorCommand</code> should all be 'prepared' outside the loop too.</p>\n\n<p>You should select more than just 'TOP 1' from the results, and you should probably be careful with your transactions so that the database performance is not limited by the amount of time it takes to unzip a file</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T22:59:03.513",
"Id": "59157",
"Score": "0",
"body": "That should just be as simple as moving my RunLoop to right after my connection.Open() I assume?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T23:02:33.063",
"Id": "59160",
"Score": "0",
"body": "your While loop should be inside of your SqlDataReader `using` block"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T23:05:24.353",
"Id": "59161",
"Score": "0",
"body": "@Malachi but wouldn't that prevent my original select top 1 from running multiple times? If I change that to be select top 10000 I can no longer safely run multiple instances of my application because of possibility of primary key violation. Unless I am just missing something."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T23:07:26.623",
"Id": "59162",
"Score": "0",
"body": "@JamesWilson, you actually aren't calling that query before the SqlDataReader"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T00:57:00.123",
"Id": "59174",
"Score": "1",
"body": "@JamesWilson - just so you are aware, the connect to the database is probably half your time.... and the prepared statements is about half of the remaining time...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T14:25:55.527",
"Id": "59259",
"Score": "0",
"body": "@JamesWilson, the code needs to be changed. you need the DataReader to call a Query that returns more than 1 row and then go row by row, maybe do a mass update. this would speed up the application and/or SQL Query and release a lot of resources."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T22:36:37.327",
"Id": "36165",
"ParentId": "36161",
"Score": "3"
}
},
{
"body": "<h2>Instantiate Objects Once, and early</h2>\n\n<ul>\n<li>Move declarations to the top, above any while or using blocks</li>\n<li>Move assignment of constants to the top.</li>\n</ul>\n\n<p>Here are some:\n.</p>\n\n<pre><code>const string Sql = @\"select top 1 d.UID, d.CreatedDate, d.Location, m.number from master m with (NOLOCK)\n inner join documentation_attachments da with (NOLOCK)\n on m.number = da.accountid\n inner join documentation d with (NOLOCK)\n on da.documentid = d.uid\n where m.qlevel = 999\n and d.location is not null\n and uid not in (select documentid from JM_DocumentationIssues)\n order by m.number desc\";\n</code></pre>\n\n<p>.</p>\n\n<pre><code>string msg;\n</code></pre>\n\n<p>.</p>\n\n<pre><code>const string RootDir = @\"\\\\192.168.22.23\";\n</code></pre>\n\n<p>.</p>\n\n<pre><code>const string Sql =\n @\"insert into JM_DocumentationIssues (documentid, oldLocation, newLocation, errorMessage, dateAdded, number)\n values (@id, @prevLocation, @newLocation, @msg, GETDATE(), @number)\";\n</code></pre>\n\n<p>.</p>\n\n<pre><code>const string Sql = \"update documentation set location = @newLocation where uid = @id\";\n</code></pre>\n\n<h2>System.Data.SqlClient objects are <em>composites</em>. Instantiate the parts at the top and then compose them as needed</h2>\n\n<ul>\n<li>This means you will not be \"newing-up\" objects in the <code>using</code> block parameter. But it does not mean you can't use <code>using</code>.</li>\n<li>If you need multiple <code>SqlConnection</code> objects, <code>SqlConnection</code> implements <code>ICloneable</code></li>\n</ul>\n\n<p>.</p>\n\n<pre><code>SqlConnection oneConnToRuleThemAll = new SqlConnection(connString);\nSqlCommand command = new SqlCommand(oneConnToRuleThemAll);\nSqlCommand updateCommand = CreateUpdateCommand(oneConnToRuleThemAll);\n\n// if we swap out parameters for a command, make individual SqlParameter collections\nSqlParameterCollection updateParameters = new SqlParameterCollection() {\n new SqlParameter( \"id\", SqlDbType.UniqueIdentifier ),\n new SqlParameter( \"prevLocation\", SqlDbType.VarChar, 260 )\n};\nSqlCommand logErrorCommand = CreateLogErrorCommand(oneConnToRuleThemAll);\n</code></pre>\n\n<p>Then</p>\n\n<pre><code>using ( SqlCommand thisCommand = command )\nusing ( SqlCommand updateCommand = updateCommand )\nusing ( SqlCommand logErrorCommand = logErrorCommand )\n</code></pre>\n\n<h2>String Theory</h2>\n\n<p>Turn multiple <code>WriteLine</code>s into a single write:</p>\n\n<pre><code> Console.WriteLine( \"Processed {0} files successfully.\", fileCount );\n Console.WriteLine( \"Did not process {0} files successfully.\", errorCount );\n Console.WriteLine( \"No more files were found with the current query\" );\n</code></pre>\n\n<p>into this:</p>\n\n<pre><code>// and do this \"at the top\"!\nstring processNotice = \"Processed {0} files successfully.\\n\" +\n \"Did not process {1} files successfully.\\n\" +\n \"Did not process {0} files successfully.\";\n\n // and use it thus:\n Console.Writeline(processNotice,fileCount, errorCount);\n</code></pre>\n\n<h2>One more thing(s)</h2>\n\n<ul>\n<li>Open the connection immediately before you execute the command. Close it ASAP after reading.</li>\n<li>Make a <code>struct</code> rather than separate variables - <code>documentID, fileName,location,createDate, number</code>. Keeps the record association. Will simplify method parameters. Makes sense.</li>\n<li>Remove <code>ExecuteNonQuery</code> from <code>CreateLogErrorCommand()</code>, <code>UpdateDocument()</code>, etc. Keep configuration separate from execution. This will help with refactoring this code monstrosity.</li>\n<li>Wrap the db calls - <code>ExecuteNonQuery()</code>, including the <code>connection.Open()</code> that should be immediately above it, in a <code>try/catch</code> and catch <code>SqlException</code></li>\n</ul>\n\n<h3>EDIT: added <code>SqlException</code> bullet above.</h3>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T14:45:12.773",
"Id": "36210",
"ParentId": "36161",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "36164",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T22:10:34.057",
"Id": "36161",
"Score": "4",
"Tags": [
"c#",
"sql",
"sql-server"
],
"Title": "Speed up application and avoid SQL Timeouts"
}
|
36161
|
<p>I would like advice on making my code more elegant and straightforward. The code works great, but it lacks these things.</p>
<pre><code><?php
if(isset($_POST['retrieve_posts'])) {
$post_ret = $_POST['retrieve_posts'];
}
if(isset($_POST['retrieve_images'])) {
$image_ret = $_POST['retrieve_images'];
} else $image_ret = 0;
require_once('classes.php');
require_once('functions.php');
if($post_ret == 1) {
$obj = new kigo();
$obj->url = "https://app.kigo.net/api/ra/v1/listProperties";
$obj->user = "bla";
$obj->pass = "bla";
$obj->data = json_encode(null);
$list = $obj->curlkigo();
$directory = 'uploads';
$list = $list['API_REPLY'];
$c = count($list);
$kigopropid = array();
for($i=0;$i<$c;$i++) {
$kigopropid[] = $list[$i]['PROP_ID'];
$propname[] = $list[$i]['PROP_NAME'];
}
if(namecheck($kigopropid, $directory)!=null) {
$namecheck = namecheck($kigopropid, $directory);
$tau = 0;
foreach ($namecheck as $key => $prop_id) {
$obj = new kigo();
$obj->url = "https://app.kigo.net/api/ra/v1/readProperty";
$obj->user = "bla";
$obj->pass = "bla";
$obj->data = json_encode(array("PROP_ID" => $prop_id));
$obj->curlkigo();
$data = $obj->curlkigo();
//-----------Prop Name
$title = $propname[$tau].'
';
$tau++;
//-----------Adress informations
$strnr = unarr($data, 'PROP_STREETNO');
$addr1 = unarr($data, 'PROP_ADDR1');
$addr2 = unarr($data, 'PROP_ADDR2');
$addr3 = unarr($data, 'PROP_ADDR3');
$aptno = unarr($data, 'PROP_APTNO');
$prop_postcode = unarr($data, 'PROP_POSTCODE');
$prop_city = unarr($data, 'PROP_CITY');
$prop_region = unarr($data, 'PROP_REGION');
$prop_country = unarr($data, 'PROP_COUNTRY');
$prop_lat = unarr($data, 'PROP_LATITUDE');
$prop_long = unarr($data, 'PROP_LONGITUDE');
$prop_axcode = unarr($data, 'PROP_AXSCODE');
$adress = '
<div class="adress">
<h2>Adress</h2>
<ul>
<li>Primary Adress: '.$addr1.'</li>
<li>Secondary adress: '. $addr2.'</li>
<li>Tertiary adress: '.$addr3.'</li>
<li>Street number: '. $strnr.'</li>
<li>Apartment number: '. $aptno.'</li>
<li>Postcode: '. $prop_postcode.'</li>
<li>City: '. $prop_city.'</li>
<li>Country: '. $prop_country.'</li>
<li>Latitude: '. $prop_lat.'</li>
<li>Longitude: '. $prop_long.'</li>
</ul>
</div>
';
//-----------Property descriptions
$name = unarr($data, 'PROP_NAME');
$instant_book = unarr($data, 'PROP_INSTANT_BOOK');
$metadescription = unarr($data, 'PROP_SHORTDESCRIPTION');
$description = unarr($data, 'PROP_DESCRIPTION');
$areadescription = unarr($data, 'PROP_AREADESCRIPTION');
$properties = '
<div class="content">
<h2>'. $name.'</h2>
<p>'.format($description).'</p>
</div>
';
//-----------Property details
$prop_bedrooms = unarr($data, 'PROP_BEDROOMS');
$prop_beds = unarr($data, 'PROP_BEDS');
$prop_baths = unarr($data, 'PROP_BATHROOMS');
$prop_toilets = unarr($data, 'PROP_TOILETS');
$prop_size = unarr($data, 'PROP_SIZE').strtolower(unarr($data, 'PROP_SIZE_UNIT'))."s";
$prop_floor = unarr($data, 'PROP_FLOOR');
$prop_elevator = unarr($data, 'PROP_ELEVATOR');
$details = '
<div class="propdetails">
<h2>Property details</h2>
<ul>
<li>Bedrooms: '.$prop_bedrooms.'</li>
<li>Beds: '. $prop_beds.'</li>
<li>Baths: '.$prop_baths.'</li>
<li>Toilets: '. $prop_toilets.'</li>
<li>Size: '. $prop_size.'</li>
<li>Floor: '. $prop_floor.'</li>
<li>Elevator: '. $prop_elevator.'</li>
</ul>
</div>
';
//-----------Rates
$nightly_rate_from = unarr($data, 'PROP_RATE_NIGHTLY_FROM');
$nightly_rate_to = unarr($data, 'PROP_RATE_NIGHTLY_TO');
$weekly_rate_from = unarr($data, 'PROP_RATE_WEEKLY_FROM');
$weekly_rate_to = unarr($data, 'PROP_RATE_WEEKLY_TO');
$monthly_rate_from = unarr($data, 'PROP_RATE_MONTHLY_FROM');
$monthly_rate_to = unarr($data, 'PROP_RATE_MONTHLY_TO');
$prop_rate_currency = unarr($data, 'PROP_RATE_CURRENCY');
$rates = '
<div class="rates">
<h2>Rates</h2>
<ul>
<li>Nigtly rate from: '.$nightly_rate_from.'</li>
<li>Nightly rate to: '.$nightly_rate_to.'</li>
<li>Weekly rate from: '.$weekly_rate_from.'</li>
<li>Weekly rate to: '.$weekly_rate_to.'</li>
<li>Montly rate from: '.$monthly_rate_from.'</li>
<li>Montly rate to: '.$monthly_rate_to.'</li>
<li>Rate currency: '.$prop_rate_currency.'</li>
</div>
';
//-----------Contact
$prop_phone = unarr($data, 'PROP_PHONE');
if($prop_phone==null) {$prop_phone = " - ";}
$contact = '
<div class="contact">
<h2>Contact</h2>
<p>'.$prop_phone.'</p>
</div>
';
if($image_ret==2) {
//-----------Property Images
$prop_array_img = unarr($data, 'PROP_PHOTOS');
$img_ct = count($prop_array_img);
$year = date('Y'); $month = date('m');
for($i=0;$i<$img_ct;$i++) {
$photo_id = $prop_array_img[$i]['PHOTO_ID'];
$obj = new kigo();
$obj->url = "https://app.kigo.net/api/ra/v1/readPropertyPhotoFile";
$obj->user = 'bla';
$obj->pass = 'bla';
$obj->data = json_encode(array("PROP_ID" => $prop_id, "PHOTO_ID"=>$photo_id));
$img = $obj->curlkigo();
$img = str_replace(' ', '+', $img['API_REPLY']);
$data = base64_decode($img);
$file ="../../uploads/".$year."/".$month."/".uniqid() . '.jpg';
$success = file_put_contents($file, $data);
}
echo "The Images were automatically added in media files!";
}
$final = $title.$adress.$details.$rates.$properties.$contact;
$create = fopen($directory.'/'.$prop_id.'.txt', 'w+');
$put = file_put_contents($directory.'/'.$prop_id.'.txt', $final);
}//end for
}//end if
$filenames = listfiles($directory);
if (file_exists($directory.'/archive.txt')) {
$filenames = array_values(array_diff($filenames, array('archive.txt')));
}
$pathtozipfiles = array();
foreach ($filenames as $value) {
$pathtozipfiles[] = $directory.'/'.$value;
}
$result = create_zip($pathtozipfiles,'articles.zip');
echo $dir;
}//end post
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T21:48:14.980",
"Id": "66571",
"Score": "0",
"body": "Please do not remove your code after receiving answers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T06:41:43.763",
"Id": "66627",
"Score": "0",
"body": "I hope that is not your real user/pass in 3 different places in the code, you should mask it and change the password as anyone can view the history for this post even if you change it now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-22T15:23:58.953",
"Id": "66784",
"Score": "0",
"body": "Nope, it was just in a test environement."
}
] |
[
{
"body": "<p>It's not too bad.</p>\n\n<ul>\n<li>First, make sure your indentation is always correct, eg. in your last <code>if</code> and your last <code>foreach</code>.</li>\n<li>Second, never store passwords in your main source file! They should go in a file that is not version-controlled and only contains the login informations.</li>\n<li>Last, you need to learn about separation of concerns: modern PHP code does not output HTML in the main logic functions: you should first prepare the data, then another function or class will output it. Learning to use a PHP framework is the best way to use those best practices.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T09:29:03.900",
"Id": "36193",
"ParentId": "36163",
"Score": "6"
}
},
{
"body": "<p>Yep not bad certainly seen worse</p>\n\n<ul>\n<li>Try to keep your spacing consistant for example you do <code>for()</code> but\n<code>foreach ()</code> one or the other</li>\n<li>Doing this <code>} else $image_ret = 0;</code> is generally bad for readability / good code try to either use full if () { } else { } with the results of the if on separate lines or use ternary's where possible.</li>\n<li>Try to segment off your process code from your display code so put your process code in functions/methods etc and have those accept the inputs and spit back vars then have your display side of things prepare the html and put your output into it. Ignore people telling you to use frameworks as they're all generally horrible anyway. Better off learning to write better code yourself and if required use something like twig for layout.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-02T03:42:26.383",
"Id": "59806",
"Score": "0",
"body": "Frameworks are a good way of learning design patterns. I've never worked with one in a large scale project so I can't recommend their use but I do highly recommend looking over them for inspiration."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T14:59:11.877",
"Id": "36293",
"ParentId": "36163",
"Score": "7"
}
},
{
"body": "<p>See inline comments</p>\n\n<pre><code><?php\n\n// i have moved the requires to the top, as your class should fail as early as possible if these files don't exist\nrequire_once('classes.php');\nrequire_once('functions.php');\n\n// these constants should be stored in a separate config file\nconst KIGO_USER = 'blabla';\nconst KIGO_PASS = 'blabla';\nconst DIR_UPLOADS = 'uploads';\n\n\n//if(isset($_POST['retrieve_posts'])) {\n// $post_ret = $_POST['retrieve_posts'];\n//}\n\n// at this point $post_ret may not be set and will cause and error below when you test it\n// a nicer way is to use the ternary operator to ensure it has a default value\n$post_ret = isset($_POST['retrieve_posts']) ? $_POST['retrieve_posts'] : 0;\n\n\n//if(isset($_POST['retrieve_images'])) {\n// $image_ret = $_POST['retrieve_images'];\n//} else $image_ret = 0;\n\n// same here with ternary operator\n$image_ret = isset($_POST['retrieve_images']) ? $_POST['retrieve_images'] : 0;\n\n\n\nif($post_ret == 1) {\n\n // the url, user, pass should all be constants or put into a helper class of sorts,\n // see mykigo helper class below\n // $obj = new kigo();\n // $obj->url = \"https://app.kigo.net/api/ra/v1/listProperties\";\n // $obj->user = \"bla\";\n // $obj->pass = \"bla\";\n // $obj->data = json_encode(null);\n\n $mykigo = new mykigo(KIGO_USER, KIGO_PASS);\n\n // directory looks like config data and should be stored out of the main code unless it changes often\n // see const DIR_UPLOADS above\n // $directory = 'uploads';\n // $list = $list['API_REPLY'];\n $list = $mykigo->listProperties();\n\n $kigopropid = array();\n\n // $c = count($list);\n // for($i=0;$i<$c;$i++) {\n\n // i know people will say to do the count first so it is optimized better, but in reality count($list) will take such a tiny amount of time,\n // that i prefer it like this, as i find it more readable.\n for($i=0; $i<count($list); $i++) {\n $kigopropid[] = $list[$i]['PROP_ID'];\n $propname[] = $list[$i]['PROP_NAME'];\n }\n\n // namecheck is not a very obvious description of what the function does\n // for example, would something like this be more appropriate\n // if(is_directory_valid($kigopropid, $directory)!=null) {\n\n // here we are doing namecheck twice, what for?\n // if(namecheck($kigopropid, $directory)!=null) {\n // $namecheck = namecheck($kigopropid, $directory);\n\n // I am not sure what namecheck actually does, but this might be better\n $namecheck = namecheck($kigopropid, DIR_UPLOADS);\n if($namecheck != null) {\n\n $tau = 0;\n\n foreach ($namecheck as $key => $prop_id) {\n\n // $obj is such a generic name, it would be nicer to give it a name that means something\n // eg $kigo = new kigo();\n // $obj = new kigo();\n // $obj->url = \"https://app.kigo.net/api/ra/v1/readProperty\";\n //\n // // i hope you haven't just posted your real username/password to the world\n // $obj->user = \"xxx\";\n // $obj->pass = \"xxx\";\n //\n // $obj->data = json_encode(array(\"PROP_ID\" => $prop_id));\n //\n // // why do we call this twice, i am guessing it is a mistake?\n // $obj->curlkigo();\n // $data = $obj->curlkigo();\n\n // don't need to instantiate mykigo again, we have done that already, and can reuse it\n $data = $mykigo->readProperty($prop_id);\n\n //-----------Prop Name\n $title = $propname[$tau].'\n ';\n $tau++;\n\n // this code should be split into function, see below\n // i have done this one for example, I will leave the rest for you to do\n // by splitting into functions you will have a clear concise main function,\n // that should be easily readable\n\n $adress = render_address_to_html($data);\n\n // //-----------Adress informations\n // $strnr = unarr($data, 'PROP_STREETNO');\n // $addr1 = unarr($data, 'PROP_ADDR1');\n // $addr2 = unarr($data, 'PROP_ADDR2');\n // $addr3 = unarr($data, 'PROP_ADDR3');\n // $aptno = unarr($data, 'PROP_APTNO');\n // $prop_postcode = unarr($data, 'PROP_POSTCODE');\n // $prop_city = unarr($data, 'PROP_CITY');\n // $prop_region = unarr($data, 'PROP_REGION');\n // $prop_country = unarr($data, 'PROP_COUNTRY');\n // $prop_lat = unarr($data, 'PROP_LATITUDE');\n // $prop_long = unarr($data, 'PROP_LONGITUDE');\n // $prop_axcode = unarr($data, 'PROP_AXSCODE');\n //\n // $adress = '\n // <div class=\"adress\">\n // <h2>Adress</h2>\n // <ul>\n // <li>Primary Adress: '.$addr1.'</li>\n // <li>Secondary adress: '. $addr2.'</li>\n // <li>Tertiary adress: '.$addr3.'</li>\n // <li>Street number: '. $strnr.'</li>\n // <li>Apartment number: '. $aptno.'</li>\n // <li>Postcode: '. $prop_postcode.'</li>\n // <li>City: '. $prop_city.'</li>\n // <li>Country: '. $prop_country.'</li>\n // <li>Latitude: '. $prop_lat.'</li>\n // <li>Longitude: '. $prop_long.'</li>\n // </ul>\n // </div>\n // ';\n\n\n\n //-----------Property descriptions\n $name = unarr($data, 'PROP_NAME');\n $instant_book = unarr($data, 'PROP_INSTANT_BOOK');\n $metadescription = unarr($data, 'PROP_SHORTDESCRIPTION');\n $description = unarr($data, 'PROP_DESCRIPTION');\n $areadescription = unarr($data, 'PROP_AREADESCRIPTION');\n\n $properties = '\n <div class=\"content\">\n <h2>'. $name.'</h2>\n <p>'.format($description).'</p>\n </div>\n ';\n\n //-----------Property details\n $prop_bedrooms = unarr($data, 'PROP_BEDROOMS');\n $prop_beds = unarr($data, 'PROP_BEDS');\n $prop_baths = unarr($data, 'PROP_BATHROOMS');\n $prop_toilets = unarr($data, 'PROP_TOILETS');\n $prop_size = unarr($data, 'PROP_SIZE').strtolower(unarr($data, 'PROP_SIZE_UNIT')).\"s\";\n $prop_floor = unarr($data, 'PROP_FLOOR');\n $prop_elevator = unarr($data, 'PROP_ELEVATOR');\n\n $details = '\n <div class=\"propdetails\">\n <h2>Property details</h2>\n <ul>\n <li>Bedrooms: '.$prop_bedrooms.'</li>\n <li>Beds: '. $prop_beds.'</li>\n <li>Baths: '.$prop_baths.'</li>\n <li>Toilets: '. $prop_toilets.'</li>\n <li>Size: '. $prop_size.'</li>\n <li>Floor: '. $prop_floor.'</li>\n <li>Elevator: '. $prop_elevator.'</li>\n </ul>\n </div>\n ';\n\n //-----------Rates\n $nightly_rate_from = unarr($data, 'PROP_RATE_NIGHTLY_FROM');\n $nightly_rate_to = unarr($data, 'PROP_RATE_NIGHTLY_TO');\n $weekly_rate_from = unarr($data, 'PROP_RATE_WEEKLY_FROM');\n $weekly_rate_to = unarr($data, 'PROP_RATE_WEEKLY_TO');\n $monthly_rate_from = unarr($data, 'PROP_RATE_MONTHLY_FROM');\n $monthly_rate_to = unarr($data, 'PROP_RATE_MONTHLY_TO');\n $prop_rate_currency = unarr($data, 'PROP_RATE_CURRENCY');\n\n $rates = '\n <div class=\"rates\">\n <h2>Rates</h2>\n <ul>\n <li>Nigtly rate from: '.$nightly_rate_from.'</li>\n <li>Nightly rate to: '.$nightly_rate_to.'</li>\n <li>Weekly rate from: '.$weekly_rate_from.'</li>\n <li>Weekly rate to: '.$weekly_rate_to.'</li>\n <li>Montly rate from: '.$monthly_rate_from.'</li>\n <li>Montly rate to: '.$monthly_rate_to.'</li>\n <li>Rate currency: '.$prop_rate_currency.'</li>\n </div>\n ';\n\n //-----------Contact\n $prop_phone = unarr($data, 'PROP_PHONE');\n if($prop_phone==null) {$prop_phone = \" - \";}\n $contact = '\n <div class=\"contact\">\n <h2>Contact</h2>\n <p>'.$prop_phone.'</p>\n </div>\n ';\n\n if($image_ret==2) {\n //-----------Property Images\n $prop_array_img = unarr($data, 'PROP_PHOTOS');\n $img_ct = count($prop_array_img);\n $year = date('Y'); $month = date('m');\n for($i=0;$i<$img_ct;$i++) {\n $photo_id = $prop_array_img[$i]['PHOTO_ID'];\n\n // moved into mykigo helper class\n $data = $mykigo->readPropertyPhotoFile($prop_id, $photo_id);\n\n // $obj = new kigo();\n // $obj->url = \"https://app.kigo.net/api/ra/v1/readPropertyPhotoFile\";\n // $obj->user = \"xxx\";\n // $obj->pass = \"xxx\";\n // $obj->data = json_encode(array(\"PROP_ID\" => $prop_id, \"PHOTO_ID\"=>$photo_id));\n // $img = $obj->curlkigo();\n // $img = str_replace(' ', '+', $img['API_REPLY']);\n // $data = base64_decode($img);\n\n\n $file =\"../../uploads/\".$year.\"/\".$month.\"/\".uniqid() . '.jpg';\n $success = file_put_contents($file, $data);\n }\n echo \"The Images were automatically added in media files!\";\n }\n\n $final = $title.$adress.$details.$rates.$properties.$contact;\n $create = fopen(DIR_UPLOADS.'/'.$prop_id.'.txt', 'w+');\n $put = file_put_contents(DIR_UPLOADS.'/'.$prop_id.'.txt', $final);\n }//end for\n }//end if\n\n $filenames = listfiles(DIR_UPLOADS);\n if (file_exists(DIR_UPLOADS.'/archive.txt')) {\n $filenames = array_values(array_diff($filenames, array('archive.txt')));\n }\n $pathtozipfiles = array();\n foreach ($filenames as $value) {\n $pathtozipfiles[] = DIR_UPLOADS.'/'.$value;\n }\n $result = create_zip($pathtozipfiles,'articles.zip');\n echo $dir;\n\n\n function render_address_to_html($data) {\n\n //-----------Adress informations\n $strnr = unarr($data, 'PROP_STREETNO');\n $addr1 = unarr($data, 'PROP_ADDR1');\n $addr2 = unarr($data, 'PROP_ADDR2');\n $addr3 = unarr($data, 'PROP_ADDR3');\n $aptno = unarr($data, 'PROP_APTNO');\n $prop_postcode = unarr($data, 'PROP_POSTCODE');\n $prop_city = unarr($data, 'PROP_CITY');\n $prop_region = unarr($data, 'PROP_REGION');\n $prop_country = unarr($data, 'PROP_COUNTRY');\n $prop_lat = unarr($data, 'PROP_LATITUDE');\n $prop_long = unarr($data, 'PROP_LONGITUDE');\n $prop_axcode = unarr($data, 'PROP_AXSCODE');\n\n $adress = '\n <div class=\"adress\">\n <h2>Adress</h2>\n <ul>\n <li>Primary Adress: '.$addr1.'</li>\n <li>Secondary adress: '. $addr2.'</li>\n <li>Tertiary adress: '.$addr3.'</li>\n <li>Street number: '. $strnr.'</li>\n <li>Apartment number: '. $aptno.'</li>\n <li>Postcode: '. $prop_postcode.'</li>\n <li>City: '. $prop_city.'</li>\n <li>Country: '. $prop_country.'</li>\n <li>Latitude: '. $prop_lat.'</li>\n <li>Longitude: '. $prop_long.'</li>\n </ul>\n </div>\n ';\n\n return $adress;\n }\n\n\n}//end post\n\n// i always remove the ending php closure, it has no use, and can actually mask whitespace getting output to page,\n// which can effect the setting of cookies, etc\n\nprivate class mykigo extends kigo {\n\n const URL_PROPERTY_PHOTO_FILE = 'https://app.kigo.net/api/ra/v1/readPropertyPhotoFile';\n const URL_LIST_PROPERTIES = 'https://app.kigo.net/api/ra/v1/listProperties';\n const URL_READ_PROPERTY = \"https://app.kigo.net/api/ra/v1/readProperty\";\n\n\n function __construct($user, $pass) {\n parent::__construct();\n\n $this->user = $user;\n $this->pass = $pass;\n }\n\n public function readProperty($prop_id) {\n $this->url = self::URL_READ_PROPERTY;\n $this->data = json_encode(array(\"PROP_ID\" => $prop_id));\n return $this->curlkigo();\n }\n\n public function listProperties() {\n $this->url = self::URL_LIST_PROPERTIES;\n $this->data = json_encode(null);\n $ret = $this->curlkigo();\n return $ret['API_REPLY'];\n }\n\n public function readPropertyPhotoFile($prop_id, $photo_id) {\n $this->url = self::URL_PROPERTY_PHOTO_FILE;\n $this->data = json_encode(array(\"PROP_ID\" => $prop_id, \"PHOTO_ID\"=>$photo_id));\n $ret = $this->curlkigo();\n $img = str_replace(' ', '+', $ret['API_REPLY']);\n\n return base64_decode($img);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-25T09:43:18.900",
"Id": "67245",
"Score": "0",
"body": "Thank's a lot...I know something about OOP but now I really saw it in action. It really makes the code great.Also, thanks for the great tips."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T06:40:47.587",
"Id": "39721",
"ParentId": "36163",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T22:20:44.793",
"Id": "36163",
"Score": "6",
"Tags": [
"php",
"json",
"api"
],
"Title": "Retrieving information and images for rental properties using an API"
}
|
36163
|
<p>I was tasked with refactoring our existing <code>IniReader</code> class, which is Windows only compatible, to be cross-platform ( specifically UNIX compatible ). We decided that <code>boost::property_tree</code> was a good fit for this and a quick play with property_tree confirms this.</p>
<p>The original class had many <code>readValue</code> overloads for the various data types. During the refactoring I was happy to discover that <code>boost::property_tree::get_value</code> is templatized so it made it simple to declare the following new <code>readValue</code> functions:</p>
<pre><code>// read and return a value from the inifile
// throws boost::property_tree:ptree_error if not found
template <class T>
T readValue( const std::string& section, const std::string& param ) const;
// read and return value from section.param in the inifile
// if the param does not exists in the section return |defaultValue|
template <class T>
T readValue( const std::string& section, const std::string& param, const T& defaultValue ) const;
</code></pre>
<p>However, I later discover there's a couple of special overridden <code>readValue</code> functions which accept an additional <code>int</code> index. This allows values to be read using param name appended with the index value like this:</p>
<pre><code>[TextFileFilters]
count=3
filter1=*.txt
filter2=*.csv
filter3=*.log
num1=50
num2=20
num3=10
</code></pre>
<p>Originally I thought of adding two more <code>readValue</code> overrides which includes the index argument:</p>
<pre><code>// read and return a value from the inifile
// throws boost::property_tree:ptree_error if not found
template <class T>
T readValue( const std::string& section, const std::string& param, const int index ) const;
// read and return value from section.param in the inifile
// if the param does not exists in the section return |defaultValue|
template <class T>
T readValue( const std::string& section, const std::string& param, const T& defaultValue, const int index ) const;
</code></pre>
<p>BUT, there's a problem. When using <code>T = int</code> it becomes ambiguous to the compiler:</p>
<pre><code>// is 3 the default int value OR the index ?
int count = ini.readValue<int>( "TextFileFilters", "num", 3 );
</code></pre>
<p>What I've done, currently, is to remove the 3 parameter "indexed" override of <code>readValue</code>. Therefore mandating that all indexed <code>readValue</code> calls must be called with the default argument. This is not ideal.</p>
<p>The only thoughts around this I have was to introduce an new <code>IniPath</code> class, which attempts to replace the section, param or section, param, index combinations:</p>
<pre><code>class IniPath
{
public:
IniPath( const std::string& section, const std::string& path );
IniPath( const std::string& section, const std::string& path, const int index );
};
...
template <class T>
T readValue( const IniPath& path ) const;
template <class T>
T readValue( const IniPath& path, T& defaultValue ) const;
</code></pre>
<p>but does that seems excessive? Too many temporaries?</p>
<pre><code>int count = ini.readValue<int>( IniPath( "TextFileFilters", "count" ) );
int log_num = ini.readValue<int>( IniPath( "TextFileFilters", "num", 3 ) );
</code></pre>
<p>Do you have any suggestions or ideas?</p>
|
[] |
[
{
"body": "<p>I wouldn't worry too much about temporaries (shouldn't they be optimized away?), but I think you're focusing on the smaller problem. You fundamentally have the following options:</p>\n\n<ul>\n<li>Disambiguate by disallowing certain combinations, like you say you've currently done (<code>readValue<T>(string, string)</code>, <code>readValue<T>(string, string, T)</code>, and <code>readValue<T>(string, string, int, T)</code> but no <code>readValue<T>(string, string, int)</code>)</li>\n<li>Disambiguate by changing parameters to the function (this could be by reordering non-template parameters e.g. <code>readValue<T>(string, string, T)</code> vs <code>readValue<T>(string, int, string, T)</code>, or by the <code>readValue<T>(IniPath, T)</code> approach you describe where you make it someone else's problem)</li>\n<li>Disambiguate by changing function names, e.g. <code>readValue<T>(string, string, T)</code> vs. <code>readIndexedValue<T>(string, string, int)</code> (and of course <code>readIndexedValue<T>(string, string, int, T)</code>)</li>\n<li>Disambiguate by changing function names the other way, e.g. <code>readValue<T>(string, string)</code> and <code>readValue<T>(string, string, int)</code> vs <code>readValueDefault<T>(string, string, T)</code> and <code>readValueDefault<T>(string, string, int, T)</code>.</li>\n</ul>\n\n<p>My opinion is that the first is too likely to create a pit of failure. Just like when you tried to add a non-defaulted <code>readValue<T>(string, string, int)</code> without immediately realizing the problem of doing so, users of your functions are likely to make the same mistake on the consumption side (hey, I've got <code>readValue(sFoo, sBar)</code> but now I need <code>sBar</code> 1, 2, and 3...) and wonder why things are compiling but not working correctly.</p>\n\n<p>The second is okay; making it someone else's problem is a really good approach for some scenarios. Merely reordering the parameters like I mentioned can result in funky APIs like the deprecated parts of <a href=\"http://msdn.microsoft.com/en-us/library/k07tc8k5%28v=vs.90%29.aspx\" rel=\"nofollow\">CRegKey::QueryValue</a> where the order of parameters results in wildly different overloads that make the API hard to remember. I don't know whether this one is that bad, but I'm still predisposed against it.</p>\n\n<p>The third is my favorite. It's simple, clean, and makes it easier to figure out what this extra int parameter is. The fourth is about as good, depending on whether indexes or defaults are more \"natural\", and of course you can combine both bullet's approaches.</p>\n\n<p>But that's not the end of the story.</p>\n\n<p>The bigger problem is this: You're migrating from existing usage with working code. You have to consider what the damage is, how to detect it, and how to fix it. Ideal case is things magically work 100%. Next best, in my opinion, is each call site either works the same as it used to or results in a compile-time error. Worse is a series of call sites you have to update, will find a pattern to do so, but sometimes the pattern is wrong (a change to <code>IniPath</code> might result in this). Worst by a long shot is call sites that change their meaning without any warning (you might be stuck here anyway if your call sites are ambiguous enough).</p>\n\n<p>So do you have any call sites that will change meaning, and if so how will you address this? That will help determine how you disambiguate your function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:37:44.697",
"Id": "59297",
"Score": "0",
"body": "I think the best way of handling this in general is either creating an input struct (like the OP is already doing) or your third option. For this particular case, I think your third option would be the better solution. Modifying the call sites will have to occur in either case. [The top answer here](http://stackoverflow.com/questions/5120768/how-to-implement-the-factory-pattern-in-c-correctly) is an example for when an input struct would be a good idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-05T21:55:16.043",
"Id": "60421",
"Score": "0",
"body": "I agree the 3rd option is best and I think that's the way I'll go. With respects to the existing code base - that has all been updated to reflect the new changes. Thanks."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T04:28:53.460",
"Id": "36176",
"ParentId": "36166",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "36176",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T23:13:24.347",
"Id": "36166",
"Score": "3",
"Tags": [
"c++",
"template"
],
"Title": "IniReader template overrides become ambiguous"
}
|
36166
|
<p>As a school project in my navigator 12 class, I've decided to try and learn Java. I thought that I'd try and make the Game of Life, because it would be a good way to start learning Java (watched a bunch of Java tutorials).</p>
<p>Could I get your feedback on this program I wrote? I would like input on if everything is inputted properly and what I should've done differently, and if there is more effective and efficient ways to do a certain task. Also, just any type feedback would be helpful.</p>
<p>I made the game so the sides of the board would be connected to each other, and so the simulation would be contained(it will loop to the other side). I also have a slider to change the speed the game iterates. Other features are randomizing the board, and play and stop buttons. You can also, change the size of the board, with inputting the size you want it to generate.</p>
<p>Main </p>
<pre><code>public class Main {
public static void main(String[] args) {
new Settingsboard();
}
}
</code></pre>
<p>Settings</p>
<pre><code>public class Settingsboard extends JFrame{
JFrame Frame2 = new JFrame();
JLabel label1, label2, value1, value2;
JTextField x_Value, y_Value;
JButton button1, button2, button3, clear;
static JCheckBox random;
int run = 0;
static JSlider howManyTimes;
int delay = 1000; // 1000 ms == 1 second
javax.swing.Timer myTimer = new javax.swing.Timer(delay,
new MyTimerActionListener());
public Settingsboard(){
Frame2.setSize(400,400);
JPanel thePanel = new JPanel();
//JPanel thePanel2 = new JPanel();
label1 = new JLabel("Set Size Of Board: ");
thePanel.add(label1);
value1 = new JLabel(" Width: ");
thePanel.add(value1);
x_Value = new JTextField("", 5);
thePanel.add(x_Value);
value2 = new JLabel(" Height: ");
thePanel.add(value2);
y_Value = new JTextField("", 5);
thePanel.add(y_Value);
button1 = new JButton("Generate Board");
button1.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1){
if(run == 0){
int number1 = Integer.parseInt(x_Value.getText());
int number2 = Integer.parseInt(y_Value.getText());
new Board(number1,number2);
run = 1;
}
else{JOptionPane.showMessageDialog(null, "Board is already running", "InfoBox: ", JOptionPane.INFORMATION_MESSAGE);}
}
}
}
);
thePanel.add(button1);
button2 = new JButton("Play");
button2.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button2){
myTimer.start();
}
}
}
);
thePanel.add(button2);
button3 = new JButton("Stop");
button3.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button3){
myTimer.stop();
}
}
}
);
thePanel.add(button3);
random = new JCheckBox("Randomize?");
thePanel.add(random);
label2 = new JLabel(" Speed of loop (in milliseconds): ");
thePanel.add(label2);
howManyTimes = new JSlider(0, 1000, 1000);
howManyTimes.setMinorTickSpacing(50);
howManyTimes.setMajorTickSpacing(250);
howManyTimes.setPaintTicks(true);
howManyTimes.setPaintLabels(true);
ListenForSlider lForSlider = new ListenForSlider();
howManyTimes.addChangeListener(lForSlider);
thePanel.add(howManyTimes);
clear = new JButton("Reset board");
clear.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == clear){
for(int y=0; y<Board.lengthT; y++){
for(int x=0; x<Board.widthT; x++){
if(Settingsboard.random.isSelected()) {
int random = (int )(Math.random() * 2);
if(random == 0){
Board.grid[x][y].setBackground(Color.red);
Board.boolBoard[x][y] = false;
}
else if(random == 1){
Board.grid[x][y].setBackground(Color.blue);
Board.boolBoard[x][y] = true;
}
}
else{
Board.grid[x][y].setBackground(Color.red);
Board.boolBoard[x][y] = false;
}
}
}
}
}
}
);
thePanel.add(clear);
Frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame2.add(thePanel);
Frame2.setVisible(true);
}
private class ListenForSlider implements ChangeListener{
@Override
public void stateChanged(ChangeEvent e) {
// Check if the source of the event was the button
if(e.getSource() == howManyTimes){
delay = howManyTimes.getValue();
String speed = Integer.toString(delay);
System.out.print(speed);
if(delay == 0){
System.out.print("hit");
speed = "As fast as it will go!";
}
label2.setText(" Speed of loop(in milliseconds): " + speed );
myTimer.setDelay(delay);
}
}
}
}
</code></pre>
<p>Board</p>
<pre><code>public class Board extends JFrame{
JFrame Frame = new JFrame(); //creates frame
static JButton[][] grid; //names the grid of buttons
JTextArea textArea1;
static int lengthT = 0;;
static int widthT = 0;
static Boolean[][] boolBoard;
List<String> onXY_Values = new ArrayList<String>();
public Board(int width, int length){ //constructor
boolBoard = new Boolean [width][length];
Frame.setSize(1000,1000);
Frame.setLocationRelativeTo(null);
Frame.setTitle("The Game of Life");
ListenForKeys lForKeys = new ListenForKeys();
widthT = width;
lengthT = length;
Frame.setLayout(new GridLayout(width,length)); //set layout
grid = new JButton[width][length]; //allocate the size of grid
for(int y=0; y<length; y++){
for(int x=0; x<width; x++){
grid[x][y]=new JButton("("+x+","+y+")"); //creates new button
Frame.add(grid[x][y]); //adds button to grid
grid[x][y].setBorderPainted(false);
grid[x][y].setContentAreaFilled(false);
if(Settingsboard.random.isSelected()) {
int random = (int )(Math.random() * 2);
if(random == 0){
grid[x][y].setBackground(Color.red);
boolBoard[x][y] = false;
}
else if(random == 1){
grid[x][y].setBackground(Color.blue);
boolBoard[x][y] = true;
}
}
else{
grid[x][y].setBackground(Color.red);
boolBoard[x][y] = false;
}
grid[x][y].setForeground(Color.black);
grid[x][y].setOpaque(true);
grid[x][y].setPreferredSize(new Dimension(30, 30));
grid[x][y].setBorder(BorderFactory.createLineBorder(Color.black, 2));
grid[x][y].setMargin(new Insets(0, 0, 0, 0));
ListenForButton lForButton = new ListenForButton();
grid[x][y].addActionListener(lForButton);
grid[x][y].addKeyListener(lForKeys);
}
}
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.pack(); //sets appropriate size for frame
Frame.setVisible(true); //makes frame visible
}
public static void main(String[] args) {
}
private class ListenForButton implements ActionListener{
public void actionPerformed(ActionEvent e){
String xString = e.getActionCommand();
String yString = e.getActionCommand();
int index = xString.indexOf(',');
xString = xString.substring(0, index);
String yStringRemove = xString;
xString = xString.replace("(", "");
int x = Integer.parseInt(xString);
yString = yString.replace(yStringRemove, "");
yString = yString.replace(",", "");
yString = yString.replace(")", "");
int y = Integer.parseInt(yString);
((JButton)e.getSource()).setEnabled(true);
if(e.getSource() == grid[x][y]){
grid[x][y].getActionCommand();
if(!boolBoard[x][y]){//turning on
grid[x][y].setBackground(Color.blue);
onXY_Values.add(x + "," + y);
boolBoard[x][y] = true;
}
else if(boolBoard[x][y]){//turning off
grid[x][y].setBackground(Color.red);
onXY_Values.remove(x + "," + y);
boolBoard[x][y] = false;
}
}
}
}
private class ListenForKeys implements KeyListener{
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
if( e.getKeyChar() == 10 ){
Logic.logic(lengthT,widthT,grid,boolBoard);
}
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
}
</code></pre>
<p>Timer</p>
<pre><code>public class MyTimerActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
int widthT = Board.widthT;
int lengthT = Board.lengthT;
JButton[][] grid = Board.grid;
Boolean [][] boolBoard = Board.boolBoard;
Logic.logic(lengthT, widthT, grid, boolBoard);
}
}
</code></pre>
<p>Logic</p>
<pre><code>public class Logic {
public static void logic(int lengthT, int widthT, JButton[][] grid, Boolean[][] boolBoard) {
List<Integer> turnOnX = new ArrayList<Integer>();
List<Integer> turnOnY = new ArrayList<Integer>();
List<Integer> turnOffX = new ArrayList<Integer>();
List<Integer> turnOffY = new ArrayList<Integer>();
int fullspace = 0;
for(int w = 0; w < 1; w++){//right bottom piece
int j = lengthT - 1;
int i = widthT - 1;
if(!boolBoard[i][j]){//off
fullspace = 0;
if(boolBoard[i- 1][j-1]){
fullspace++;
}
if(boolBoard[i- 1][j]){
fullspace++;
}
if(boolBoard[i][j-1]){
fullspace++;
}
if(boolBoard[i-widthT+1][j-lengthT+1]){
fullspace++;
}
if(boolBoard[i-widthT+1][j]){
fullspace++;
}
if(boolBoard[i][j-lengthT+1]){
fullspace++;
}
if(boolBoard[i-widthT+1][j-1]){
fullspace++;
}
if(boolBoard[i-1][j-lengthT+1]){
fullspace++;
}
if(fullspace == 3){
turnOnX.add(i);
turnOnY.add(j);
}
}
else if(boolBoard[i][j]){
fullspace = 0;
if(boolBoard[i- 1][j-1]){
fullspace++;
}
if(boolBoard[i- 1][j]){
fullspace++;
}
if(boolBoard[i][j-1]){
fullspace++;
}
if(boolBoard[i-widthT+1][j-lengthT+1]){
fullspace++;
}
if(boolBoard[i-widthT+1][j]){
fullspace++;
}
if(boolBoard[i][j-lengthT+1]){
fullspace++;
}
if(boolBoard[i-widthT+1][j-1]){
fullspace++;
}
if(boolBoard[i-1][j-lengthT+1]){
fullspace++;
}
if(fullspace < 2){
turnOffX.add(i);
turnOffY.add(j);
}
else if(fullspace > 3){
turnOffX.add(i);
turnOffY.add(j);
}
}
}
for(int w = 0; w < 1; w++){//left bottom piece
int j = lengthT - 1;
int i = w;
if(!boolBoard[i][j]){//off
fullspace = 0;
if(boolBoard[i+widthT- 1][j-1]){
fullspace++;
}
if(boolBoard[i+widthT- 1][j]){
fullspace++;
}
if(boolBoard[i][j-1]){
fullspace++;
}
if(boolBoard[i+1][j-lengthT+1]){
fullspace++;
}
if(boolBoard[i+1][j]){
fullspace++;
}
if(boolBoard[i][j-lengthT+1]){
fullspace++;
}
if(boolBoard[i+1][j-1]){
fullspace++;
}
if(boolBoard[i+widthT-1][j-lengthT+1]){
fullspace++;
}
if(fullspace == 3){
turnOnX.add(i);
turnOnY.add(j);
}
}
else if(boolBoard[i][j]){
fullspace = 0;
if(boolBoard[i+widthT- 1][j-1]){
fullspace++;
}
if(boolBoard[i+widthT- 1][j]){
fullspace++;
}
if(boolBoard[i][j-1]){
fullspace++;
}
if(boolBoard[i+1][j-lengthT+1]){
fullspace++;
}
if(boolBoard[i+1][j]){
fullspace++;
}
if(boolBoard[i][j-lengthT+1]){
fullspace++;
}
if(boolBoard[i+1][j-1]){
fullspace++;
}
if(boolBoard[i+widthT-1][j-lengthT+1]){
fullspace++;
}
if(fullspace < 2){
turnOffX.add(i);
turnOffY.add(j);
}
else if(fullspace > 3){
turnOffX.add(i);
turnOffY.add(j);
}
}
}
for(int w = 0; w < 1; w++){//right top piece
int j = 0;
int i = widthT - 1;
if(!boolBoard[i][j]){//off
fullspace = 0;
if(boolBoard[i- 1][j+lengthT-1]){
fullspace++;
}
if(boolBoard[i- 1][j]){
fullspace++;
}
if(boolBoard[i][j+lengthT-1]){
fullspace++;
}
if(boolBoard[i-widthT+1][j+1]){
fullspace++;
}
if(boolBoard[i-widthT+1][j]){
fullspace++;
}
if(boolBoard[i][j+1]){
fullspace++;
}
if(boolBoard[i-widthT+1][j+lengthT-1]){
fullspace++;
}
if(boolBoard[i-1][j+1]){
fullspace++;
}
if(fullspace == 3){
turnOnX.add(i);
turnOnY.add(j);
}
}
else if(boolBoard[i][j]){
fullspace = 0;
if(boolBoard[i- 1][j+lengthT-1]){
fullspace++;
}
if(boolBoard[i- 1][j]){
fullspace++;
}
if(boolBoard[i][j+lengthT-1]){
fullspace++;
}
if(boolBoard[i-widthT+1][j+1]){
fullspace++;
}
if(boolBoard[i-widthT+1][j]){
fullspace++;
}
if(boolBoard[i][j+1]){
fullspace++;
}
if(boolBoard[i-widthT+1][j+lengthT-1]){
fullspace++;
}
if(boolBoard[i-1][j+1]){
fullspace++;
}
if(fullspace < 2){
turnOffX.add(i);
turnOffY.add(j);
}
else if(fullspace > 3){
turnOffX.add(i);
turnOffY.add(j);
}
}
}
for(int w = 0; w < 1; w++){//left top piece
int j = 0;
int i = w;
if(!boolBoard[i][j]){//off
fullspace = 0;
if(boolBoard[i + widthT - 1][j+lengthT-1]){
fullspace++;
}
if(boolBoard[i + widthT- 1][j]){
fullspace++;
}
if(boolBoard[i][j+lengthT-1]){
fullspace++;
}
if(boolBoard[i+1][j+1]){
fullspace++;
}
if(boolBoard[i+1][j]){
fullspace++;
}
if(boolBoard[i][j+1]){
fullspace++;
}
if(boolBoard[i+1][j+lengthT-1]){
fullspace++;
}
if(boolBoard[i+ widthT-1][j+1]){
fullspace++;
}
if(fullspace == 3){
turnOnX.add(i);
turnOnY.add(j);
}
}
else if(boolBoard[i][j]){
fullspace = 0;
if(boolBoard[i+ widthT - 1][j+lengthT-1]){
fullspace++;
}
if(boolBoard[i+ widthT- 1][j]){
fullspace++;
}
if(boolBoard[i][j+lengthT-1]){
fullspace++;
}
if(boolBoard[i+1][j+1]){
fullspace++;
}
if(boolBoard[i+1][j]){
fullspace++;
}
if(boolBoard[i][j+1]){
fullspace++;
}
if(boolBoard[i+1][j+lengthT-1]){
fullspace++;
}
if(boolBoard[i+ widthT-1][j+1]){
fullspace++;
}
if(fullspace < 2){
turnOffX.add(i);
turnOffY.add(j);
}
else if(fullspace > 3){
turnOffX.add(i);
turnOffY.add(j);
}
}
}
for(int w = 1; w < widthT - 1; w++){//top bar
int j = 0;
int i = w;
if(!boolBoard[i][j]){//off
fullspace = 0;
if(boolBoard[i - 1][j+lengthT-1]){
fullspace++;
}
if(boolBoard[i - 1][j]){
fullspace++;
}
if(boolBoard[i][j+lengthT-1]){
fullspace++;
}
if(boolBoard[i+1][j+1]){
fullspace++;
}
if(boolBoard[i+1][j]){
fullspace++;
}
if(boolBoard[i][j+1]){
fullspace++;
}
if(boolBoard[i+1][j+lengthT-1]){
fullspace++;
}
if(boolBoard[i-1][j+1]){
fullspace++;
}
if(fullspace == 3){
turnOnX.add(i);
turnOnY.add(j);
}
}
else if(boolBoard[i][j]){
fullspace = 0;
if(boolBoard[i - 1][j+lengthT-1]){
fullspace++;
}
if(boolBoard[i - 1][j]){
fullspace++;
}
if(boolBoard[i][j+lengthT-1]){
fullspace++;
}
if(boolBoard[i+1][j+1]){
fullspace++;
}
if(boolBoard[i+1][j]){
fullspace++;
}
if(boolBoard[i][j+1]){
fullspace++;
}
if(boolBoard[i+1][j+lengthT-1]){
fullspace++;
}
if(boolBoard[i-1][j+1]){
fullspace++;
}
if(fullspace < 2){
turnOffX.add(i);
turnOffY.add(j);
}
else if(fullspace > 3){
turnOffX.add(i);
turnOffY.add(j);
}
}
}
for(int w = 1; w < widthT - 1; w++){//bottom bar
int j = lengthT - 1;
int i = w;
if(!boolBoard[i][j]){//off
fullspace = 0;
if(boolBoard[i - 1][j - 1]){
fullspace++;
}
if(boolBoard[i - 1][j]){
fullspace++;
}
if(boolBoard[i][j - 1]){
fullspace++;
}
if(boolBoard[i+1][j-lengthT+1]){
fullspace++;
}
if(boolBoard[i+1][j]){
fullspace++;
}
if(boolBoard[i][j-lengthT+1]){
fullspace++;
}
if(boolBoard[i+1][j - 1]){
fullspace++;
}
if(boolBoard[i-1][j-lengthT+1]){
fullspace++;
}
if(fullspace == 3){
turnOnX.add(i);
turnOnY.add(j);
}
}
else if(boolBoard[i][j]){
fullspace = 0;
if(boolBoard[i - 1][j-1]){
fullspace++;
}
if(boolBoard[i - 1][j]){
fullspace++;
}
if(boolBoard[i][j-1]){
fullspace++;
}
if(boolBoard[i+1][j-lengthT+1]){
fullspace++;
}
if(boolBoard[i+1][j]){
fullspace++;
}
if(boolBoard[i][j-lengthT+1]){
fullspace++;
}
if(boolBoard[i+1][j-1]){
fullspace++;
}
if(boolBoard[i-1][j-lengthT+1]){
fullspace++;
}
if(fullspace < 2){
turnOffX.add(i);
turnOffY.add(j);
}
else if(fullspace > 3){
turnOffX.add(i);
turnOffY.add(j);
}
}
}
for(int l = 1; l < lengthT - 1; l++){//left bar
int i = 0;
int j = l;
if(!boolBoard[i][j]){//off
fullspace = 0;
if(boolBoard[i + widthT -1][j-1]){
fullspace++;
}
if(boolBoard[i + widthT -1][j]){
fullspace++;
}
if(boolBoard[i][j-1]){
fullspace++;
}
if(boolBoard[i+1][j+1]){
fullspace++;
}
if(boolBoard[i+1][j]){
fullspace++;
}
if(boolBoard[i][j+1]){
fullspace++;
}
if(boolBoard[i+1][j-1]){
fullspace++;
}
if(boolBoard[i + widthT -1][j+1]){
fullspace++;
}
if(fullspace == 3){
turnOnX.add(i);
turnOnY.add(j);
}
}
else if(boolBoard[i][j]){
fullspace = 0;
if(boolBoard[i + widthT -1][j-1]){
fullspace++;
}
if(boolBoard[i + widthT -1][j]){
fullspace++;
}
if(boolBoard[i][j-1]){
fullspace++;
}
if(boolBoard[i+1][j+1]){
fullspace++;
}
if(boolBoard[i+1][j]){
fullspace++;
}
if(boolBoard[i][j+1]){
fullspace++;
}
if(boolBoard[i+1][j-1]){
fullspace++;
}
if(boolBoard[i + widthT -1][j+1]){
fullspace++;
}
if(fullspace < 2){
turnOffX.add(i);
turnOffY.add(j);
}
else if(fullspace > 3){
turnOffX.add(i);
turnOffY.add(j);
}
}
}
for(int l = 1; l < lengthT - 1; l++){//right bar
int i = widthT -1;
int j = l;
if(!boolBoard[i][j]){//off
fullspace = 0;
if(boolBoard[i-1][j-1]){
fullspace++;
}
if(boolBoard[i-1][j]){
fullspace++;
}
if(boolBoard[i][j-1]){
fullspace++;
}
if(boolBoard[i-widthT+1][j+1]){
fullspace++;
}
if(boolBoard[i-widthT+1][j]){
fullspace++;
}
if(boolBoard[i][j+1]){
fullspace++;
}
if(boolBoard[i-widthT+1][j-1]){
fullspace++;
}
if(boolBoard[i-1][j+1]){
fullspace++;
}
if(fullspace == 3){
turnOnX.add(i);
turnOnY.add(j);
}
}
else if(boolBoard[i][j]){
fullspace = 0;
if(boolBoard[i-1][j-1]){
fullspace++;
}
if(boolBoard[i-1][j]){
fullspace++;
}
if(boolBoard[i][j-1]){
fullspace++;
}
if(boolBoard[i-widthT+1][j+1]){
fullspace++;
}
if(boolBoard[i-widthT+1][j]){
fullspace++;
}
if(boolBoard[i][j+1]){
fullspace++;
}
if(boolBoard[i-widthT+1][j-1]){
fullspace++;
}
if(boolBoard[i-1][j+1]){
fullspace++;
}
if(fullspace < 2){
turnOffX.add(i);
turnOffY.add(j);
}
else if(fullspace > 3){
turnOffX.add(i);
turnOffY.add(j);
}
}
}
for(int i = 1; i < widthT-1; i++)//checking empty spaces *main body*
{
for(int j = 1; j < lengthT-1; j++)
{
if(!boolBoard[i][j]){//off
fullspace = 0;
if(boolBoard[i - 1][j-1]){
fullspace++;
}
if(boolBoard[i - 1][j]){
fullspace++;
}
if(boolBoard[i][j-1]){
fullspace++;
}
if(boolBoard[i+1][j+1]){
fullspace++;
}
if(boolBoard[i+1][j]){
fullspace++;
}
if(boolBoard[i][j+1]){
fullspace++;
}
if(boolBoard[i+1][j-1]){
fullspace++;
}
if(boolBoard[i-1][j+1]){
fullspace++;
}
if(fullspace == 3){
turnOnX.add(i);
turnOnY.add(j);
}
}
else if(boolBoard[i][j]){
fullspace = 0;
if(boolBoard[i - 1][j-1]){
fullspace++;
}
if(boolBoard[i - 1][j]){
fullspace++;
}
if(boolBoard[i][j-1]){
fullspace++;
}
if(boolBoard[i+1][j+1]){
fullspace++;
}
if(boolBoard[i+1][j]){
fullspace++;
}
if(boolBoard[i][j+1]){
fullspace++;
}
if(boolBoard[i+1][j-1]){
fullspace++;
}
if(boolBoard[i-1][j+1]){
fullspace++;
}
if(fullspace < 2){
turnOffX.add(i);
turnOffY.add(j);
}
else if(fullspace > 3){
turnOffX.add(i);
turnOffY.add(j);
}
}
}
}
for (int i = 0; i < turnOnX.size(); i++){
grid[ turnOnX.get(i) ][ turnOnY.get(i) ].setBackground(Color.blue);
boolBoard[turnOnX.get(i)][turnOnY.get(i)] = true;
}
for (int i = 0; i < turnOffX.size(); i++){
grid[ turnOffX.get(i) ][ turnOffY.get(i) ].setBackground(Color.red);
boolBoard[turnOffX.get(i)][turnOffY.get(i)] = false;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T03:54:14.637",
"Id": "68662",
"Score": "2",
"body": "I thought first programs are like System.out.println(\"Hello World\"); When did first programs become games? People must be getting smarter!"
}
] |
[
{
"body": "<p>So there's a lot to go though in here. I think that as a beginner project you can be proud of your code... there are a number of things I would change, but, on the whole, it is systematic, logical, and well-formatted. In my opinion this is far more preferable than 'clever' code that is hard to read and understand...</p>\n\n<p>So, choosing some things that you should work on:</p>\n\n<ul>\n<li>It appears you have used a code-editor to help you (intelliJ maybe, or eclipse?). This is a good thing, because it will help you to debug your programs, and it can help you refactor with fewer errors.</li>\n<li>I would start by renaming some of your J* components... <code>label1</code>, <code>label2</code>, <code>button1</code>, etc. do not help much.</li>\n<li><code>Frame2</code> should have a lower-case 'f', and why do you need two JFrames? Every time you have <code>Frame2</code> you should instead have <code>this</code> (the <code>SettingsBoard</code>)</li>\n<li>Using spaces in Labels to get the justification right, is wrong: <code>value1 = new JLabel(\" Width: \");</code> should be solved by using the correct size and alignment settings in your <code>LayoutManager</code></li>\n<li><p><code>JCheckBox</code> random and <code>JSlider</code> should not be static, should they?</p></li>\n<li><p>in your <code>Board</code> class you have multiple JFrames as well. The Board class itself is a JFrame, so use it.</p></li>\n<li><p>In the Logic method, there is a huge amount of duplicate code.... there's good ways to reduce it... I'll describe a system which I would not expect you (as a beginner) to think of, but it's neat, concise, and really makes things easy...</p></li>\n</ul>\n\n<p>Your goal is to 'wrap' the game of life, so cells on the left margin are impacted by cells on the right, and top and bottom too.... You can use the modulo operator.... and a 'width' (or height) offset. And this way you an eliminate 90% of your code. Consider this function:</p>\n\n<pre><code>private static final int[][] offsets = {\n {-1, -1}, // up left\n {-1, 0}, // left\n {-1, 1}, // dn left\n { 0, -1}, // up \n { 0, 1}, // dn\n { 1, -1}, // up right\n { 1, 0}, // right\n { 1, 1} // dn right\n }\n\nprivate static final int getAliveNeighbors(int x, int y, int width, int height, Boolean[][] boolboard) {\n\n int alive = 0;\n // look around us.... how many cells are alive\n for (int[] offset : offsets) {\n if (boolboard[(x + offset[0] + width) % width][(y + offset[1] + height) % height]) {\n alive++;\n }\n }\n return alive;\n}\n</code></pre>\n\n<p>The above function is 'clever'. It adds the width to the coordinate, and then gets the remainder when dividing by the width. For example, if your grid is 10x10, and you are looking for life at cell 0,0, then you want to check for life in the cell to the left (-1, 0) then you really want to look in cell (9, 0), which is (<code>(0 + 10 - 1) % 10 == 9</code> , 0)</p>\n\n<p>Now we have an 'easy' function for counting the amount of life, you can use that to massively simplify your 'Logic' code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T03:53:15.343",
"Id": "36175",
"ParentId": "36172",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "36175",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T01:28:30.433",
"Id": "36172",
"Score": "8",
"Tags": [
"java",
"beginner",
"game-of-life"
],
"Title": "First Java program critique (Game of Life)"
}
|
36172
|
<p>As shameful as it is to say I wanted to see what all the fuss about was with Tinder, but after downloading it I found I was more interested with its animation effects and started wondering how they did them!</p>
<p>I decided I wanted to see if I could replicate some of them using jQuery so they can be used on web apps and sites and such, but it's always nice to have these snippets lying around if I ever need them.</p>
<p>This seems lightweight enough, and I'm pretty sure I've covered everything, each circle element is targeted individually, the elements are removed after to stop a build up etc. But just out of curiosity, would anyone have approached it differently?</p>
<pre><code>$(document).ready(function () {
var x = 0;
addCircle(x);
setInterval(function () {
if (x === 0) {
x = 1;
}
addCircle(x);
x++;
}, 1200);
});
function addCircle(id) {
$('body').append('<div id="' + id + '" class="circle"></div>');
$('#' + id).animate({
'width': '300px',
'height': '300px',
'margin-top': '-150px',
'margin-left': '-150px',
'opacity': '0'
}, 4000, 'easeOutCirc');
setInterval(function () {
$('#' + id).remove();
}, 4000);
}
</code></pre>
<p><a href="http://jsfiddle.net/HelloJD/Y3r36/" rel="nofollow noreferrer"><strong>Example</strong></a></p>
|
[] |
[
{
"body": "<p><em>Disclaimer: I don't know what Tinder is yet.</em><br>\nShorter version:</p>\n\n<pre><code>$(document).ready(function () {\n function addCircle() {\n var $circle = $('<div class=\"circle\"></div>');\n $circle.animate({\n 'width': '300px',\n 'height': '300px',\n 'margin-top': '-150px',\n 'margin-left': '-150px',\n 'opacity': '0'\n }, 4000, 'easeOutCirc');\n $('body').append($circle);\n\n setTimeout(function __remove() {\n $circle.remove();\n }, 4000);\n }\n addCircle();\n setInterval(addCircle, 1200);\n});\n</code></pre>\n\n<p>I put the <code>addCircle</code> method inside the closure, keeping the <code><div></code> in a variable means there is no need for an ID or counter <code>x</code> and used <code>setTimeout</code> because it only needs to run once.</p>\n\n<p><a href=\"http://jsfiddle.net/Y3r36/9/\" rel=\"nofollow\">http://jsfiddle.net/Y3r36/9/</a></p>\n\n<p>I like it! Might have made the sizes variable but that could be overkill in this situation. Also it might be a good idea to put a wrapping <code><div></code> with <code>position:relative</code> in the case you want multiple of these.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T17:23:35.923",
"Id": "59329",
"Score": "0",
"body": "Ah that's a lot cleaner, I wasn't too sure if it needed the incremental variable or not, since there are multiple elements I wasn't sure if targeting them with animate would of caused problems. Is it necessary to give the timeout function a name like __remove() like you have?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T23:35:31.677",
"Id": "59376",
"Score": "0",
"body": "@Joe No. Its a standard I've developed because trying to debug anonymous functions is hard. If you name the function then debugging becomes easier as the stack shows meaningful names. Totally unneeded 99% of the time."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T04:53:51.740",
"Id": "36177",
"ParentId": "36174",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "36177",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T03:42:44.917",
"Id": "36174",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"animation"
],
"Title": "Tinder-esque location pulse animation effect"
}
|
36174
|
<p>I have an assignment as follows:</p>
<blockquote>
<p>Write a program which reads from the keyboard two integers n and m,
and a character c from the keyboard. This program should define and
call a function:
print rectangle(n, m, c) which prints a rectangle of
size n x m consisting of the character c</p>
</blockquote>
<p>My solution is:</p>
<pre><code>n=int(input("Enter the lenght of the rectangle: "))
m=int(input("Enter the width: "))
c="c"
def print_rect(n, m, c):
for a in range(m):
print (n*c)
print_rect(n, m, c)
input("Press enter to close")
</code></pre>
<p>I am sure there are alternative ways to do this assignment. How would you code this assignment? Do you think my solution is OK?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T08:12:10.847",
"Id": "59204",
"Score": "2",
"body": "\"[...] and a character c from the keyboard\". c should also be input from the user, just like n and m."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T08:23:28.270",
"Id": "59205",
"Score": "0",
"body": "Should the rectangle be solid or should you only print the outline? If it can be solid you would only need to change what I said about the character."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T08:35:42.653",
"Id": "59206",
"Score": "0",
"body": "Thank you. The rectangle should be solid.\nBut you said something important. What should I do if I only want to print the outline?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T09:00:27.300",
"Id": "59207",
"Score": "0",
"body": "I don't have any code of it but I'd made a nested loop over the width and the length of the rectangle and calculate the position of the outline and only print the character when the loop hits that value. Hope I made it clear."
}
] |
[
{
"body": "<pre><code>def print_rect(n, m, c):\n l = (n * c for a in range(m))\n print '\\n'.join(l)\n</code></pre>\n\n<p>I believe this would be slightly faster. I did a test on my computer:) <em>(I'm using Python 2.7.5 so the code is slightly different with Python3)</em></p>\n\n<pre><code>import timeit\nprep = \"\"\"\nn = 10\nm = 7\nc = 'D'\n\"\"\"\n\nold = \"\"\"\n for a in xrange(m):\n print n * c\n \"\"\"\n\nnew = \"\"\"\n l = (n * c for a in xrange(m))\n print \\'\\\\n\\'.join(l)\n \"\"\"\n\n\n\nprint 'Old'\nprint timeit.timeit(old, setup=prep, number=10)\n\nprint 'New'\nprint timeit.timeit(new, setup=prep, number=10)\n</code></pre>\n\n<p>The new implementation is like 10 times faster:)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T09:08:57.257",
"Id": "59208",
"Score": "0",
"body": "n, m, and c, needs to be inputs (but I guess OP can easily modify that:))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T09:19:08.990",
"Id": "59215",
"Score": "0",
"body": "Upvoted because it's an interesting find. But it's also kind of a hack: I would argue it's harder to read, which is way more important than speed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:23:16.733",
"Id": "59291",
"Score": "0",
"body": "I recommend http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html where I got this idea:)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T05:53:55.887",
"Id": "59542",
"Score": "0",
"body": "I ran your code in IDLE and it doesn't make a rectangle."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T08:13:42.447",
"Id": "59550",
"Score": "0",
"body": "»I ran your code in IDLE and it doesn't make a rectangle« that is then a creative solution ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T11:30:33.023",
"Id": "59559",
"Score": "0",
"body": "I double checked, the code works:)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T09:07:34.703",
"Id": "36189",
"ParentId": "36182",
"Score": "2"
}
},
{
"body": "<ol>\n<li>It makes little sense to have a variable c that always contains 'c'.\nSimply replace c by 'c' in your print call.</li>\n<li>Learn about PEP8 and about checking that your code conforms to PEP8. A few things to check here:\n<ol>\n<li>spaces between <code>=</code> when doing an assignment</li>\n<li>new lines between function definitions</li>\n</ol></li>\n<li>no space after <code>print</code>: <code>print(n * c)</code> or <code>print n * c</code> (the former is better since it's Python 3 proof)</li>\n<li>Error checking! What happens if I enter anything else than a number? It's possibly not required by your assignment, but be aware that it can cause issues.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T09:23:48.403",
"Id": "36192",
"ParentId": "36182",
"Score": "4"
}
},
{
"body": "<p>I think the assignment wants you to read the character from input as well. </p>\n\n<p>When you are printing the input you are composing the string m times. More optimal solution is if you do that 1 time and output it m times: </p>\n\n<pre><code>def print_rect(n, m, c):\n row=n*c\n for a in range(m):\n print (row)\n</code></pre>\n\n<p>I would even do it with this oneliner: </p>\n\n<pre><code>print((n * c + '\\n') * m, end=\"\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T12:13:35.617",
"Id": "36203",
"ParentId": "36182",
"Score": "5"
}
},
{
"body": "<p>Here is my implementation for printing hollow rectangles:</p>\n\n<pre><code>import sys\n\n# Python 2/3 compatibility shims\nif sys.hexversion >= 0x3000000:\n inp = input\n rng = range\nelse:\n inp = raw_input\n rng = xrange\n\ndef get_int(prompt):\n while True:\n try:\n return int(inp(prompt))\n except ValueError:\n pass\n\ndef get_ch(prompt):\n while True:\n res = inp(prompt).strip()\n if res:\n return res[:1]\n\ndef make_row(w, edge, center):\n return edge*(w>0) + center*(w-2) + edge*(w>1)\n\ndef print_rectangle(h, w, c):\n top_row = make_row(w, c, c)\n mid_row = make_row(w, c, ' ')\n rows = [top_row]*(h>0) + [mid_row]*(h-2) + [top_row]*(h>1)\n print('\\n'.join(rows))\n\ndef main():\n h = get_int('Rectangle height: ')\n w = get_int('Rectangle width: ')\n c = get_ch('Character to use: ')\n print_rectangle(h, w, c)\n\nif __name__==\"__main__\":\n main()\n</code></pre>\n\n<p>which runs like:</p>\n\n<pre><code>Rectangle height: 4\nRectangle width: 6\nCharacter to use: F\nFFFFFF\nF F\nF F\nFFFFFF\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T21:15:33.960",
"Id": "36379",
"ParentId": "36182",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "36203",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T07:58:15.090",
"Id": "36182",
"Score": "2",
"Tags": [
"python",
"homework",
"python-3.x",
"console"
],
"Title": "Printing a rectangle"
}
|
36182
|
<p>Here is a small library which manages writing into and reading out a byte array. It uses TValue arrays to get and put data, its my first time using them. Its crudely written, and poorly optimized but I tried to make the best solution in the 3 hrs I was given to build and debug it. Right now it only supports Integer, String, TGUID, TBytes and TDateTime as data inputs.</p>
<p>I want your thoughts on it, any areas that may be improved with know how of yours. And for the raging ones, I am not trying to be faster than delphi! </p>
<h2>Library</h2>
<pre><code>unit AgBuffer;
interface
uses System.SysUtils, System.Rtti, Windows;
type
{$SCOPEDENUMS ON}
TAgData = ( Int, Str, GUID, Bytes, Date );
TAgBuffer = class ( TObject )
private
fSize : Int64;
procedure CheckGrowNecessity ( const AElementSize: Int64 );
procedure EmbedInteger ( const AInteger: Integer ); inline;
procedure EmbedString ( const AString: String ); inline;
procedure EmbedGUID ( const AGUID: TGUID ); inline;
procedure EmbedBytes ( const ABytes : TBytes ); inline;
procedure EmbedDateTime ( const ADateTime: TDateTime ); inline;
function ExtractInteger: Integer; inline;
function ExtractString: String; inline;
function ExtractGUID: TGUID; inline;
function ExtractBytes: TBytes; inline;
function ExtractDateTime: TDateTime; inline;
public
Buffer : TBytes;
InitialSize : Int64;
Position : Int64;
Values : TArray <TValue>;
constructor Create ( const ABuffer: TBytes = nil );
procedure Reinitialize ( const ABuffer: TBytes );
procedure Add ( const AData: Array of TValue );
procedure Extract ( const ADataTypes: Array of TAgData );
procedure Clear;
property Size : int64 read fSize;
end;
implementation
constructor TAgBuffer.Create ( const ABuffer: TBytes = nil );
begin
if Assigned ( ABuffer ) then
begin
Buffer := ABuffer;
fSize := Length ( ABuffer );
InitialSize := fSize;
end;
end;
procedure TAgBuffer.Reinitialize ( const ABuffer: TBytes );
begin
Buffer := ABuffer;
fSize := Length ( Buffer );
InitialSize := fSize;
Position := 0;
SetLength ( Values, 0 );
end;
procedure TAgBuffer.CheckGrowNecessity ( const AElementSize: Int64 );
begin
fSize := fSize + AElementSize;
if fSize > InitialSize then
begin
InitialSize := InitialSize + 512;
SetLength ( Buffer, InitialSize );
end;
end;
procedure TAgBuffer.EmbedInteger ( const AInteger: Integer );
begin
CheckGrowNecessity ( 4 );
Move ( AInteger, Buffer [Position], 4 );
Position := Position + 4;
end;
procedure TAgBuffer.EmbedString ( const AString: String );
var
StringLength : DWORD;
StringSize : Int64;
begin
StringLength := Length ( AString );
StringSize := StringLength * 2;
CheckGrowNecessity ( StringSize + 4 );
Move ( StringLength, Buffer [Position], 4 );
Move ( AString [1], Buffer [Position + 4], StringSize );
Position := Position + StringSize + 4;
end;
procedure TAgBuffer.EmbedGUID ( const AGUID: TGUID );
begin
CheckGrowNecessity ( 16 );
Move ( AGUID, Buffer [Position], 16 );
Position := Position + 16;
end;
procedure TAgBuffer.EmbedBytes ( const ABytes : TBytes );
var
StringLength : DWORD;
begin
StringLength := Length ( ABytes );
CheckGrowNecessity ( StringLength + 4 );
Move ( StringLength, Buffer [Position], 4 );
Move ( ABytes [0], Buffer [Position + 4], StringLength );
Position := Position + StringLength + 4;
end;
procedure TAgBuffer.EmbedDateTime ( const ADateTime: TDateTime );
begin
CheckGrowNecessity ( 8 );
Move ( ADateTime, Buffer [Position], 8 );
Position := Position + 8;
end;
procedure TAgBuffer.Add ( const AData: Array of TValue );
var
I : DWORD;
TypeChar : Char;
begin
if Length ( AData ) <> 0 then
begin
// Initialization
Position := fSize;
InitialSize := fSize + 1024;
SetLength ( Buffer, InitialSize );
for I := 0 to Length ( AData ) - 1 do
begin
// Preparation
TypeChar := Char ( AData [I].TypeInfo.Name [2] );
// Type determination
if TypeChar = 'n' then
EmbedInteger ( AData [I].AsInteger )
else if TypeChar = 't' then
EmbedString ( AData [I].AsString )
else if TypeChar = 'G' then
EmbedGUID ( AData [I].AsType <TGUID> )
else if TypeChar = 'A' then
EmbedBytes ( AData [I].AsType <TBytes> )
else if TypeChar = 'D' then
EmbedDateTime ( AData [I].AsType <TDateTime> );
end;
// Freeing left over space
SetLength ( Buffer, fSize );
end;
end;
function TAgBuffer.ExtractInteger: Integer;
begin
Move ( Buffer [Position], Result, 4 );
Position := Position + 4;
end;
function TAgBuffer.ExtractString: String;
var
StrLength : DWORD;
StrSize : int64;
begin
Move ( Buffer [Position], StrLength, 4 );
SetLength ( Result, StrLength );
StrSize := StrLength * 2;
Move ( Buffer [Position + 4], Result [1], StrSize );
Position := Position + 4 + StrSize;
end;
function TAgBuffer.ExtractGUID: TGUID;
begin
Move ( Buffer [Position], Result, 16 );
Position := Position + 16;
end;
function TAgBuffer.ExtractBytes: TBytes;
var
ArrayLength: DWORD;
begin
Move ( Buffer [Position], ArrayLength, 4 );
SetLength ( Result, ArrayLength );
Move ( Buffer [Position + 4], Result [0], ArrayLength );
Position := Position + 4 + ArrayLength;
end;
function TAgBuffer.ExtractDateTime: TDateTime;
begin
Move ( Buffer [Position], Result, 8 );
Position := Position + 8;
end;
procedure TAgBuffer.Extract ( const ADataTypes: Array of TAgData );
var
I : DWORD;
begin
if Length ( ADataTypes ) <> 0 then
begin
SetLength ( Values, Length ( ADataTypes ));
for I := 0 to Length ( ADataTypes ) - 1 do
case ADataTypes [I] of
TAgData.Int : Values [I] := ExtractInteger;
TAgData.Str : Values [I] := ExtractString;
TAgData.GUID : Values [I] := TValue.From <TGUID> ( ExtractGUID );
TAgData.Bytes : Values [I] := TValue.From <TBytes> ( ExtractBytes );
TAgData.Date : Values [I] := TValue.From <TDateTime> ( ExtractDateTime );
end;
end;
end;
procedure TAgBuffer.Clear;
begin
SetLength ( Buffer, 0 );
SetLength ( Values, 0 );
fSize := 0;
InitialSize := 0;
Position := 0;
end;
end.
</code></pre>
<h2>Example</h2>
<p>To use it, I am giving an example which embeds a header of sorts of 2 ints and 2 guids:-</p>
<pre><code>uses
AgBuffer, System.SysUtils, System.Rtti;
---
var
Packet1, Packet2 : TAgBuffer;
Int1, Int2, Int3, Int4 : Integer;
GUID1, GUID2, GUID3, GUID4 : TGUID;
---
// Embedding Data
Int1 := 4;
Int2 := 56000;
CreateGUID ( GUID1 );
CreateGUID ( GUID2 );
Packet1 := TAgBuffer.Create;
Packet1.Add
( [Int1, Int2,
TValue.From <TGUID> ( GUID1 ), TValue.From <TGUID> ( GUID2 )] );
// Packet1.Buffer can now be used for any transmission
// Extracting Data
Packet2 := TAgBuffer.Create ( Packet1.Buffer );
Packet2.Extract ( [AGB_INT, AGB_INT, AGB_GUID, AGB_GUID] );
Int3 := Packet.Values [0].AsInteger;
Int4 := Packet.Values [1].AsInteger;
GUID3 := Packet.Values [2].AsType <TGUID>;
GUID4 := Packet.Values [3].AsType <TGUID>;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T08:53:14.283",
"Id": "59411",
"Score": "0",
"body": "Why do you have all of those commented lines? Is this by convention? Because it's ugly!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T09:00:31.030",
"Id": "59413",
"Score": "0",
"body": "The commenting is done, well for comments sakes, the lines are there only to fragment code. This site is deserted, and people on SO were saying to paste such here, how can they recommend this..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T09:08:32.317",
"Id": "59416",
"Score": "0",
"body": "You asked for our thoughts and that's my thought. You don't \"fragment\" code by adding huge lines in the middle of the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T09:10:34.957",
"Id": "59417",
"Score": "0",
"body": "@UmairAhmed Welcome to Code Review! We have less users than SO indeed, but have a few Delphi programmers around (http://codereview.stackexchange.com/tags/delphi/topusers). Wait and see, sorry! By the way, smaller snippets of code are easier to review, so if you're able to reduce your code to a specific part of the library, it would probably help too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T09:11:27.443",
"Id": "59418",
"Score": "0",
"body": "Sorry, they were not meant for fragmenting code for me, I just put them to emphasize different code parts for people here. I'll remove them if you people don't like them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T09:13:20.797",
"Id": "59419",
"Score": "0",
"body": "@UmairAhmed Removing them won't help per se, it's only a matter of convention. If people do that in Delphi, keep them, otherwise read more Delphi code and see how it's organized and commented."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T09:20:17.987",
"Id": "59421",
"Score": "0",
"body": "Well except for the example, the code part (only the lines) follows our workplace conventions. We have a lot of beginner programmers so this was devised for them to make the code more readable without being commented."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T09:22:52.547",
"Id": "59422",
"Score": "0",
"body": "@QuentinPradet How can I make a concise case in this matter? I wanted some suggestions for the whole library. I have never submitted my code for any peer review, for the 16 months I have been programming in delphi as there are almost no delphi programmers anywhere in my country. Though one may find a php/java programmer underneath every rock."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T09:30:51.650",
"Id": "59423",
"Score": "0",
"body": "Delphi sure is a strange beast, the first reason being that it's a proprietary programming language. But you can certainly find Delphi communities on the web, can't you?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T11:51:44.333",
"Id": "59438",
"Score": "0",
"body": "@QuentinPradet I have found some, yes. I will not go into that, my rage will take the better of me, and the discussion will get off-topic."
}
] |
[
{
"body": "<p>I'm not a Delphi programmer, but here are a two comments based on what I understood.</p>\n\n<p>Use an enumeration type instead of characters ('n', 't'...) to determine the type.</p>\n\n<p>It seems that TArray is a <a href=\"http://en.wikipedia.org/wiki/Dynamic_array\" rel=\"nofollow\">dynamic array</a>, that is, it shrinks and grows automatically and in a smart way based on usage. \"Smart\" here means that the array size does not change too often: when you need more space, the capacity is doubled, avoiding costy reallocations. It guarantees a small cost for such updates. That's a part of TArray that you did not 'emulate'.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T11:43:15.150",
"Id": "59436",
"Score": "0",
"body": "I did to some extent from the CheckGrowNecessity method which allocates 1KB blocks to the array whenever a new element demands more space than the array has already. Due to the packets being sent over the internet, the add method also finally removes any additional free space allocated."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T09:29:00.737",
"Id": "36278",
"ParentId": "36195",
"Score": "0"
}
},
{
"body": "<p>Some suggestions:</p>\n\n<p>Replace this</p>\n\n<pre><code>const\n AGB_INT = 0;\n AGB_STR = 1;\n AGB_GUID = 2;\n AGB_BUFF = 3;\n AGB_DATE = 4;\n</code></pre>\n\n<p>By this</p>\n\n<pre><code>{$SCOPEDENUMS ON} // Enabling scoped enumerations\n\nTDataKind = (\n IntegerData,\n StringData,\n GUIDData,\n BufferData,\n DateData\n);\n</code></pre>\n\n<p>Enumerations are the way in Delphi. It seems you have a background on C or C++, but the use of <code>const</code> in Delphi is kind of rare. In code you will use one of those constants like this: <code>TDataKind.IntegerData</code>, wht is good for code readability.</p>\n\n<p>Replace this</p>\n\n<pre><code>public\n Buffer : TBytes;\n InitialSize : Int64;\n Position : Int64;\n Values : TArray <TValue>;\n</code></pre>\n\n<p>By this</p>\n\n<pre><code>public\n property Buffer: TBytes read FBuffer write SetBuffer;\n property InitialSize: Int64 read FInitialSize write SetInitialSize;\n property Position: Int64 read FPosition write SetPosition;\n property Values[aIndex: Integer]: TValue read GetValues write SetValues;\n property ValuesCount: Integer read GetValuesCount;\n</code></pre>\n\n<p><strong>Never</strong> expose class data directly, rather use properties to control the access outside code has over the class internals.</p>\n\n<p>It seems to me that you are trying to mimic the behavior of a stream. Delphi already has many streaming classes, all subclasses of <code>TStream</code>. In particular, I guess you would like to know <code>TMemoryStream</code> and eventually use it as the ancestor to your class.</p>\n\n<p>I hope it helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T13:49:51.280",
"Id": "59452",
"Score": "0",
"body": "(+1) ...just a thought about Delphi streaming: it does a good job, but it's not neutral to the platform/tools you use."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T15:01:48.467",
"Id": "59459",
"Score": "0",
"body": "I have used Memory Stream many times before but the issue with it is that it extends itself on every new element add. Also a lot functionality comes along with it which is not necessary for making packets. I want as much less going on as possible. With this one can extend TValue fields to accommodate any type of classes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T15:07:33.087",
"Id": "59461",
"Score": "0",
"body": "Thanks for the suggestions, and yes I have lived with C/C++ far more than delphi."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T13:43:28.160",
"Id": "36288",
"ParentId": "36195",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "36288",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T09:57:31.853",
"Id": "36195",
"Score": "2",
"Tags": [
"performance",
"delphi",
"object-pascal"
],
"Title": "Thoughts on my byte array library"
}
|
36195
|
<p>I found myself writing code of the form...</p>
<pre><code>val foo : Foo = ???
val step1 : Foo = {
if ( someCharacteristic( foo ) )
someTransformation( foo )
else
foo
}
val step2 : Foo = {
if ( otherCharacteristic( foo ) )
otherTransformation( foo )
else
foo
}
val result = step2;
</code></pre>
<p>That seemed awkward, and it seemed like this sort of ugly stepwise processing could be monadified. I've used but not written Scala monads; I thought I'd give it a shot. What I have seems to work, but I found proving the monad laws surprisingly challenging. I'm not sure I've got a valid monad, and wonder whether there is some subtle problem that would bite me someday if I haven't. FWIW, here's the code, any comments would be very welcome.</p>
<pre><code>package dumbmonad;
import scala.language.implicitConversions;
object If {
implicit def unwrap[T]( ift : If[T] ) = ift.value;
def evaluate[T]( ift : If[T] ) : T = if ( ift.condition( ift.value ) ) ift.transformation( ift.value ) else ift.value;
def flatten[T]( outer : If[If[T]] ) : If[T] = evaluate( outer );
def apply[T]( value : T ) : If[T] = apply( value, _ => false, identity );
}
case class If[T]( val value : T, val condition : (T)=>Boolean, val transformation : (T)=>T ) {
lazy val evaluate : T = If.evaluate( this );
def map[S]( f : (T) => S ) : If[S] = If( f( this.evaluate ) )
def flatMap[S]( f : (T) => If[S] ) : If[S] = If.flatten( this.map( f ) )
}
</code></pre>
<p>I use it like this:</p>
<pre><code>import dumbmonad._;
import dumbmonad.If._;
val foo : Foo = ???
for {
a <- If( foo, someCharacteristic, someTransformation )
b <- If( a, otherCharacteristic, otherTransformation )
} yield b;
val result : Foo = b; // implicit call to If.unwrap( ... )
</code></pre>
<p>Is this terrible? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T12:50:24.863",
"Id": "59251",
"Score": "0",
"body": "Umm... I think you could easily solve the problem above with a `Map` (or even just a sequence of tuples) and two basic operations: `filter` and `foldLeft`. :) Although it doesn't really answer the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T23:26:44.827",
"Id": "59375",
"Score": "0",
"body": "I wanted to suggest the ternary operator (x ? y : z) instead, but I just realized it does not exist in Scala. [Here](http://stackoverflow.com/questions/4947535) is link about this topic. It is not an answer to your question, but related."
}
] |
[
{
"body": "<p>What you are describing are simply functions.</p>\n\n<p>To take a related example from mathematics, </p>\n\n<pre><code> / x, if x >= 0\nabs(x) = |\n \\ -x, otherwise\n</code></pre>\n\n<p>And you are just composing functions: <code>f(g(x))</code>.</p>\n\n<p>You can somewhat make the correspondence to monads, but it is a bit of a stretch. I think it is more that monads are extensions of functions rather than the other way around.</p>\n\n<p><code>flatMap</code> would be the composition operator: <code>o</code> , ie <code>(f o g)(x) = f(g(x))</code>. And <code>unit</code> would just be the identity operation: <code>I(x) = x</code>.</p>\n\n<p>The three monad laws:</p>\n\n<ul>\n<li>Associativity: <code>f o (g o h) = (f o g) o h</code></li>\n<li>Left unit: <code>I o f = f</code></li>\n<li>Right unit: <code>f o I = f</code></li>\n</ul>\n\n<p>So instead of defining your <code>If</code> class, you can just stick to <code>def</code>, the usual function definition. Functional programming!!! In your case you can compose all your functions in any order since they always input/output <code>Foo</code> type. You can compose functions in Scala with <code>val h = f _ compose h _</code>, or using <code>andThen</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T01:58:54.083",
"Id": "36260",
"ParentId": "36197",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T10:13:07.407",
"Id": "36197",
"Score": "1",
"Tags": [
"scala",
"monads"
],
"Title": "Is this a reasonable Scala monad?"
}
|
36197
|
<p>We have a large directed acyclic graph and a requirement to filter it by allowing a user to select certain nodes and then we remove all nodes that are not selected nodes, ancestors of those nodes, or descendants of those nodes.</p>
<p><img src="https://i.stack.imgur.com/Ec8Fg.png" alt="graph removal"></p>
<p>As you can see in the above image nodes 6 and 9 have been selected and so nodes which do not route to those nodes are removed.</p>
<p>We are trying to build the closures (transitive closures?) of the graph so we can quickly filter it. We used the below code which was very slow. Profiling it shows around half of the time is spent in garbage collection.</p>
<pre><code>public static class NodeClosureAnalyser
{
public static NodeClosures Analyse(Node root)
{
var results = new NodeClosures
{
AncestorClosures = new Dictionary<int, HashSet<int>>(),
DescendantClosures = new Dictionary<int, HashSet<int>>()
};
//walk the tree and build the closures lists
var stack = new Stack<Node>();
stack.Push(root);
var route = new Stack<Node>();
while (stack.Count != 0)
{
var current = stack.Pop();
//keep track of the route to root
while (route.Any() && !route.Peek().Children.Any(n => n.Id == current.Id))
{
route.Pop();
}
route.Push(current);
AddNodeRelationships(results, current, route);
foreach (var child in current.Children)
{
stack.Push(child);
}
}
return results;
}
private static void AddNodeRelationships(NodeClosures results, Node current, IEnumerable<Node> route)
{
foreach (var node in route)
{
results.AncestorClosures.GetOrCreateValuesList(current.Id).Add(node.Id);
results.DescendantClosures.GetOrCreateValuesList(node.Id).Add(current.Id);
}
}
}
public struct NodeClosures
{
public Dictionary<int, HashSet<int>> AncestorClosures { get; set; }
public Dictionary<int, HashSet<int>> DescendantClosures { get; set; }
}
public static class DictionaryExtension
{
public static HashSet<int> GetOrCreateValuesList(
this IDictionary<int, HashSet<int>> dictionary, int key)
{
HashSet<int> ret;
if (!dictionary.TryGetValue(key, out ret))
{
ret = new HashSet<int>(new List<int>());
dictionary[key] = ret;
}
return ret;
}
}
</code></pre>
<p>A program with tests to demonstrate the issue is <a href="https://github.com/pauldambra/treeFilter" rel="nofollow noreferrer">available on Github</a></p>
<p>Many thanks for any input!</p>
|
[] |
[
{
"body": "<p>Since your nodes are double-linked (i.e. each has a list of all parents and children), creating the list of closures for all children of a certain node (especially the root node) seems like an overkill, especially if you're doing that whenever you start to filter. If you have a doubly linked graph, descendant and ancestor lists seem pretty cheap to get for each node, and for a large graph you will have to waste an awful lot of memory to keep them around.</p>\n\n<p>If I am not mistaken, for each \"chosen\" node, you need to mark that node as safe, mark its children as safe, then traverse back to the root and mark all nodes you encounter as safe, and finally remove all non marked nodes. That should be much less work than you're doing now, if I didn't misunderstand the problem completely.</p>\n\n<p>Some minor issues:</p>\n\n<ol>\n<li><p>To merge two <code>HashSet</code>s, it's much cheaper to use <code>HashSet.UnionWith</code>, than to create a new <code>HastSet</code> each time (like you're doing in your <code>Filter</code> method).</p></li>\n<li><p>Btw, by looking at your code, it seems that <code>Node.AnyDescendant</code> should iterate through <code>Children</code>, not <code>Parents</code>.</p></li>\n</ol>\n\n<p>I.e. wouldn't this work:</p>\n\n<pre><code>public static Node Filter(Node startNode, IEnumerable<int> includedNodes)\n{\n var explicitlyIncludedNodes = startNode\n .Descendants()\n .Where(n => includedNodes.Contains(n.Id));\n\n var nodesToKeep = new HashSet<int>();\n foreach (var node in explicitlyIncludedNodes)\n {\n nodesToKeep.UnionWith(node.Ancestors().Select(n => n.Id));\n nodesToKeep.UnionWith(node.Descendants().Select(n => n.Id));\n }\n\n return BreadthFirstDeletion(startNode, nodesToKeep, includedNodes.ToArray());\n}\n</code></pre>\n\n<p><code>Ancestors()</code> should simply return all ancestors all the way to the root:</p>\n\n<pre><code>public IEnumerable<Node> Ancestors()\n{\n var stack = new Stack<Node>();\n stack.Push(this);\n while (stack.Count != 0)\n {\n var current = stack.Pop();\n yield return current;\n\n foreach (var child in current.Parents)\n stack.Push(child);\n }\n}\n</code></pre>\n\n<p>(<code>Descendants</code> the same way but for <code>Children</code> instead of <code>Parents</code>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T18:17:39.077",
"Id": "36234",
"ParentId": "36198",
"Score": "2"
}
},
{
"body": "<p>Expanding on Groo's answer a bit. One classic solution to this problem which avoids building temporary node sets is to add a <code>Tag</code> to your <code>Node</code> class. For simplicities sake lets say we make it a <code>Guid</code></p>\n\n<pre><code>class Node\n{\n ...\n public Guid Tag { get; set; }\n ...\n}\n</code></pre>\n\n<p>Then your problem can be solved by traversing the graph and tagging interesting nodes:</p>\n\n<pre><code>private Guid TagReachableNodes(IEnumerable<Node> selectedNodes)\n{\n var tag = Guid.NewGuid();\n foreach (var node in selectedNodes)\n {\n node.Tag = tag;\n TagChildren(node, tag);\n TagParents(node, tag);\n }\n return tag;\n}\n\nprivate void TagChildren(Node node, Guid tag)\n{\n foreach (var child in node.Children)\n {\n child.Tag = tag;\n TagChildren(child, tag);\n }\n}\n\nprivate void TagParents(Node node, Guid tag)\n{\n // assuming root has an empty Parents list\n foreach (var parent in node.Parents)\n {\n parent.Tag = tag;\n TagParents(parent, tag);\n }\n}\n</code></pre>\n\n<p>And then you can simply remove all nodes which don't match the tag. That said I didn;t fully comprehend the <code>BreadthFirstDeletion</code> algorithm you have implemented. From what I understand removing a node is:</p>\n\n<ul>\n<li>Removing it from the <code>Children</code> collection of all it's parent AND</li>\n<li>Removing it from the <code>Parents</code> collection of all its children</li>\n</ul>\n\n<p>Should be something like this:</p>\n\n<pre><code>void RemoveUntaggedNodes(Node root, Guid tag)\n{\n var stack = new Stack<Node>();\n stack.Push(root);\n while (stack.Count > 0)\n {\n var current = stack.Pop();\n foreach (var child in current.Children)\n {\n stack.Push(child);\n }\n if (current.Tag != tag)\n {\n foreach (var parent in current.Parents)\n {\n parent.RemoveChild(current);\n }\n foreach (var child in current.Children)\n {\n child.RemoveParent(current);\n }\n }\n }\n}\n</code></pre>\n\n<p>In total your removal algorithm would then be:</p>\n\n<pre><code>void RemoveUnreachableNodes(IEnumerable<Node> selectedNodes)\n{\n var tag = TagUnreachableNodes(selectedNodes);\n RemoveUntaggedNodes(root, tag);\n}\n</code></pre>\n\n<p>Note that with the tagging approach you can't have multiple traversals running in parallel (although you could parallelize the tagging traversal itself)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-19T08:12:16.400",
"Id": "277193",
"Score": "0",
"body": "This approach has a persistent overhead (16 bytes per node in your case) besides the problems you have already mentioned. You can achieve the same with `ConditionalWeakTable'2`, but I'm not sure about performance in this case."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T11:03:36.053",
"Id": "36282",
"ParentId": "36198",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "36234",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T10:40:21.270",
"Id": "36198",
"Score": "6",
"Tags": [
"c#",
"algorithm",
"performance",
"graph"
],
"Title": "How to improve this algorithm for building a graphs closures"
}
|
36198
|
<p>I have this code which will store user session credentials:</p>
<pre><code>import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class SessionCache
{
/**
* Default Constructor
*/
public SessionCache()
{
}
/**
* Map which which will store Connections Objects by connection_id
*/
private static final Map<String, ActiveConnections> cache = new LinkedHashMap<>();
/**
* Object which will store connection credentials
*/
public class ActiveConnections
{
private int one;
private int two;
private int three;
public ActiveConnections(int one, int two, int three)
{
this.one = one;
this.two = two;
this.three = three;
}
public int getOne()
{
return one;
}
public void setOne(int one)
{
this.one = one;
}
public int getTwo()
{
return two;
}
public void setTwo(int two)
{
this.two = two;
}
public int getThree()
{
return three;
}
public void setThree(int three)
{
this.three = three;
}
}
/**
* Get Connection credentials by connection_id
*
* @param connection_id
* @return
*/
public Object getCache(String connection_id)
{
return cache.get(connection_id);
}
/**
* Insert new Connection Object into the cache
*
* @param connection_id
* @param one
* @param two
* @param three
*/
public void addCache(String connection_id, int one, int two, int three)
{
/**
* @ You may want to check if entry already exists for connection depends on logic in your application.
* @ Otherwise this will replace any previous entry for connection_id
*/
if (!cache.containsKey(connection_id))
{
cache.put(connection_id, new ActiveConnections(one, two, three));
}
}
/**
* Remove Connection from the cache based on connection_id
*
* @param connection_id
*/
public void removeCache(String connection_id)
{
cache.remove(connection_id);
}
/**
* Get the number of all connections
*
* @return
*/
public int countCacheSize()
{
return cache.size();
}
/**
* Clear all cache
*/
public void flushCache()
{
cache.clear();
}
public List<String> sendAllKeys()
{
List<String> list = new ArrayList<>(cache.keySet());
return list;
}
public Object sendKeyValue(int key)
{
Object mapKey = cache.keySet().toArray()[key];
return mapKey;
}
}
</code></pre>
<p>Can you help me to improve this code?
I would like to make a while cycle which searches for a value into the Map every 5 seconds for example expired session. Could you please help me to improve the code and make it lightweight as much as possible.</p>
|
[] |
[
{
"body": "<ol>\n<li>First you should rename your instance members in ActiveConnections class - having methods and variables named getOne(), getTwo(), etc, are horrible because at first you'd expect them to return the int value of one, two, three (e.g., returning 1, 2, 3) but in reality they most likely won't.</li>\n<li>You should either put a lock on your cache or use a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentMap.html\" rel=\"nofollow\"><code>ConcurrentMap</code></a> or you will sooner or later experience race condition errors.</li>\n<li>Your <code>send</code> methods should be renamed to <code>get</code> because you are not sending them anywhere, you are returning them.</li>\n<li>You should consider setting a memory/element limit on your cache; ex. it should only hold 101 cached items and when this limit is reached you apply a Least Recently Used policy and remove the X amount of LRU cache items.</li>\n<li>Your <code>getCache(..)</code> and <code>addCache(..)</code> should be renamed because you are not getting nor adding a cache, but rather a cache item. </li>\n<li>Your <code>getCache(..)</code> should have ActiveConnection as the return type</li>\n</ol>\n\n<p>If you want a kind of Sliding Expiration policy where you remove items that are older than 5 seconds there are a few things to keep in mind:</p>\n\n<ul>\n<li>5 seconds are a very short period of time; and</li>\n<li>You need a way to map a timestamp to a cache item. A very simple way of doing this is making a nested class, e.g., CacheItem, which only holds a timestamp and a value and your map will consist of a <code><string key, CacheItem value></code></li>\n</ul>\n\n<p><strong>edit</strong></p>\n\n<p>Here is an example of a very simple cache class I wrote in C# (just for reference). For the test cases I've ran it through it works fine, but you might want to check into existing cache libraries.</p>\n\n<pre><code>public class SimpleCache\n{\n public const int MAX_CACHE_SIZE = 101;\n public long CacheExpirationTicks { get; set; }\n private ConcurrentDictionary<string, CacheItem> _cache = new ConcurrentDictionary<string, CacheItem>();\n\n public SimpleCache() { CacheExpirationTicks = 30000; /*default*/ }\n\n public void Add(string key, object value)\n {\n //if the cache limit is reached we apply a LRU policy on the cache and remove half of the cache ( MAX_CACHE_SIZE / 2 ) least recently used\n if (_cache.Count == MAX_CACHE_SIZE)\n {\n foreach (var cacheItem in _cache\n .OrderByDescending(x => x.Value.LastAccessed)\n .Skip(MAX_CACHE_SIZE / 2))\n {\n CacheItem ignored;\n _cache.TryRemove(cacheItem.Key, out ignored);\n }\n\n }\n _cache.TryAdd(key, new CacheItem() { Value = value, LastAccessed = DateTime.Now.Ticks });\n }\n\n public object this[string key]\n {\n get\n {\n if (_cache.ContainsKey(key))\n {\n if ((_cache[key].LastAccessed + CacheExpirationTicks) > DateTime.Now.Ticks)\n {\n return _cache[key].Value;\n }\n CacheItem ignored;\n _cache.TryRemove(key, out ignored);\n }\n return null;\n }\n }\n\n internal sealed class CacheItem\n {\n //despite of it's name, LastAccess will *AND SHOULD* only be set once. The cache will validate its item in the get and add function and remove them by itself\n public long LastAccessed { get; set; }\n public object Value { get; set; }\n }\n}\n</code></pre>\n\n<p>And you would implement it like this</p>\n\n<pre><code>public class Program\n{\n public static SimpleCache simpleCache = new SimpleCache();\n\n static void Main(string[] args)\n {\n DataTable dt = GetDataTableFromCSVFile(\"myCSV.csv\");\n }\n\n private static DataTable GetDataTableFromCSVFile(string csv_file_path)\n {\n object obj;\n if ((obj = simpleCache[csv_file_path]) != null)\n {\n return (DataTable)obj;\n }\n else\n {\n var csvData = ExpensiveOperation();\n var key = csv_file_path;\n\n simpleCache.Add(key, csvData);\n\n return csvData;\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T14:09:04.937",
"Id": "59256",
"Score": "0",
"body": "Any code example please?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T06:59:07.743",
"Id": "59396",
"Score": "0",
"body": "Point (4) has caught me out before."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T07:47:47.917",
"Id": "59402",
"Score": "0",
"body": "@PeterPenzov I have a working example in C# if thats acceptable? Other than that I'd suggest looking into existing cache-libraries as they will most likely be thoroughly tested."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T08:12:39.620",
"Id": "59406",
"Score": "0",
"body": "Yes it will be very valuable for me to see it. Could you please paste the code here please?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T13:34:23.770",
"Id": "36206",
"ParentId": "36200",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "36206",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T11:35:57.617",
"Id": "36200",
"Score": "3",
"Tags": [
"java",
"search",
"cache"
],
"Title": "How to improve this session cache to search faster"
}
|
36200
|
<p>just wanted to check with you could this be done better:</p>
<pre><code>awk -F"\t" '{
for (i = 1; i <= NF; i++) {
if ($i != "NULL") {
printf("%s%s", $i, FS);
}
}
printf("\n");
}' file1
</code></pre>
<p>The goal is to print only non-<code>NULL</code> fields. For example:</p>
<pre><code>echo "TestRecord001 NULL NULL Age 29 NULL NULL Name John" | awk -F"\t" '{
for (i = 1; i <= NF; i++) {
if ($i != "NULL") {
printf("%s%s", $i, FS);
}
}
printf("\n");
}'
</code></pre>
<p>will print out: <code>TestRecord001 Age 29 Name John</code></p>
|
[] |
[
{
"body": "<p>The same behaviour can be achieved using <code>sed</code> as follows:</p>\n\n<pre><code>echo -e 'TestRecord001\\tNULL\\tNULL\\tAge\\t29\\tNULL\\tNULL\\tName\\tJohn' | sed '\ns/$/\\t/;\ns/\\(\\tNULL\\)\\+\\t/\\t/g;\ns/^NULL\\t//';\n</code></pre>\n\n<p>Explanation:</p>\n\n<p><code>sed s/SearchPattern/Replacement/g</code>. Here <code>s</code> indicates that replacement operation is to be done. Strings matching <code>SearchPattern</code> will be replaced by <code>Replacement</code>. <code>g</code> indicates that the operation will have to be performed on every match and not just on the first occurrence in a line.</p>\n\n<ol>\n<li><p><code>s/$/\\t/</code> adds a tab to the end of each line. [<code>$</code> matches the end of a line]</p></li>\n<li><p><code>\\(\\tNULL\\)\\+\\t</code> matches a string of the form <code>\\tNULL\\tNULL...NULL\\t</code>. This is replaced with <code>\\t</code>.</p></li>\n<li><p>After this the only remaining NULL is the one at the beginning of a line (without <code>\\t</code> to its left). This is matched by <code>^NULL\\t</code> and replaced with the empty string. [<code>^</code> matches the beginning of a line]</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T14:48:17.520",
"Id": "59268",
"Score": "0",
"body": "My previous answer was incorrect because NULL\\(\\t\\|$\\) matches with the ending portion of This-entry-is-not-NULL\\t (which it shouldn't)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T13:20:19.367",
"Id": "36205",
"ParentId": "36201",
"Score": "2"
}
},
{
"body": "<h2>Your code is good.</h2>\n\n<p>I can't see anything to improve upon in your original code.</p>\n\n<h2>awk vs other tools (e.g sed)</h2>\n\n<p>I think awk is a good tool for this as you are dealing with input that has clearly defined fields and field separators. The code seems more readable in awk.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:31:00.057",
"Id": "36217",
"ParentId": "36201",
"Score": "2"
}
},
{
"body": "<p>You can print only non <code>NULL</code> values by using this simple <code>awk</code> command:</p>\n\n<pre><code>echo -e 'TestRecord001\\tNULL\\tNULL\\tAge\\t29\\tNULL\\tNULL\\tName\\tJohn' | awk -F\"\\t\" '{gsub(\"NULL\\t*\",\"\")}1'\n</code></pre>\n\n<p><code>gsub</code> changes the record such that any occurence with NULL followed by a tab is deleted.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-05-24T08:09:55.373",
"Id": "195069",
"ParentId": "36201",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "36205",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T11:49:47.723",
"Id": "36201",
"Score": "4",
"Tags": [
"shell",
"null",
"unix",
"awk"
],
"Title": "Removing NULL / empty fields"
}
|
36201
|
<p>I have implemented several lock-free algorithms to maximise throughput but have always baulked when performing a spin-lock. I can usually convince myself that this is the only way but it still nags at me that a spin-lock is a terribly bad idea.</p>
<p>I recently came across a <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/LockSupport.html" rel="nofollow">FIFOMutex</a> code fragment and thought perhaps that would be a solution. I have hacked it around a bit because I don't want mine to consume interrupt exceptions but essentially it looks like this:</p>
<pre><code>/**
* Queue of blocked writers.
*/
private static class BlockedQueue {
// Everyone who is waiting.
private final Queue<Thread> waiting = new ConcurrentLinkedQueue<>();
// Ensure only one thread unlocks at a time.
private final AtomicBoolean lock = new AtomicBoolean(false);
public void sleep() {
Thread me = Thread.currentThread();
// Put me in the queue.
waiting.add(me);
try {
do {
// Park until I am head of the queue and I hold the lock
LockSupport.park(this);
/*
* If I am not at the head of the queue - go back to sleep.
*
* If I am at the head of the queue - grab the lock and get out of the loop.
*
* If I was at the head and I couldn't get the lock - go back to sleep -
* someone else is still in the process of exiting.
*/
} while (!(waiting.peek() == me && lock.compareAndSet(false, true)));
} finally {
// Take me from the queue - it must be me because I locked everyone else out.
waiting.remove();
// Done with the lock.
lock.set(false);
}
}
public void wakeup() {
// Wake the first in the queue ... unpark does nothing with a null parameter.
LockSupport.unpark(waiting.peek());
}
}
// Use this to block for a while.
private final BlockedQueue block = new BlockedQueue();
/**
* Wait for a time when it is likely that a free slot is available.
*/
private void waitForFree() {
// Still full?
while (isFull()) {
// Park me 'till something is removed.
block.sleep();
}
}
/**
* A slot has been freed up. If anyone is waiting, let the next one know.
*/
private void signalFree() {
block.wakeup();
}
</code></pre>
<p>See how I can now call <code>block.sleep()</code> in what used to be a spin-lock around <code>while(isFull())</code>. </p>
<p>What I like most about this is that the <code>wakeup</code> method is truly simple and that it will only wake up the thread that has been waiting longest.</p>
<p>I have some questions though:</p>
<ol>
<li>Will this do what I want it to do - i.e. handle multiple threads waiting for a resource without consuming unnecessary CPU.</li>
<li>Is the <code>while ((removed = waiting.remove()) != me)</code> necessary? Logic suggests that the head of the queue at that point <strong>must</strong> be me but is there a scenario where it may not be?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T14:34:27.900",
"Id": "59262",
"Score": "0",
"body": "Note - I have tinkered with it a bit since first post so if you have taken a copy to test, please recopy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T14:36:05.367",
"Id": "59264",
"Score": "0",
"body": "also I am adding an answer ... just takes some time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:26:28.880",
"Id": "59292",
"Score": "0",
"body": "Tweaked again - please take a new copy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:30:35.823",
"Id": "59296",
"Score": "0",
"body": "I think the problem with the current/latest revision is that the first thread in to your system will need a wakeup() to work"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:39:45.703",
"Id": "59298",
"Score": "0",
"body": "@rolfl - that was the intent because of `private void waitForFree() { while (isFull()) { block.sleep(); } }`. It will **only** sleep if the queue was full at one point. Note that `LockSupport.unpark` *... Otherwise, its next call to park is guaranteed not to block.*. Or am I wrong?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T16:31:57.353",
"Id": "59310",
"Score": "0",
"body": "Just to be clear, do you need the order in which the threads 'queue' to be 'fair'? (i.e. it has to be FIFO?)"
}
] |
[
{
"body": "<p>I believe there's race conditions in your code, Specifically, if you call <code>wakeup()</code> asymettrically (more times than you call <code>sleep()</code>) then you run the risk of a few things:</p>\n\n<ol>\n<li>you could have multiple running threads (i.e. there's not just one thread using the resource)</li>\n<li>you may possibly trigger a condition where calling wakeup() twice, very fast, will cause the <strong>same</strong> thread to be unparked (i.e. <code>waiting.peek()</code> in <code>wakeup()</code>) will return the same value twice....).</li>\n<li>it is possible that the queue does not contain a value when the wakeup is called because the 'active' thread is in the process of looking for itself (and removing other content from the queue) as it goes.</li>\n</ol>\n\n<p>I have tried to find a way to make it work to my satisfaction below, but, frankly, I don't think it is possible without changing the code so much it is no longer 'yours'.</p>\n\n<p>I think the reality is that a secure mechanism for this will necessarily rely on having a lock that contains both the unpark and the queue management.... at which point, using the park/unpark is no longer the right tool, so it defeats this process...</p>\n\n<p>Feel free to read through what I was about to write, but, I am essentially abandoning it....</p>\n\n<hr>\n\n<p>DISREGARD BELOW HERE</p>\n\n<p>Right, you'll have to work with me on this one.... (it takes multiple 'heads' to work around 'threads'....)...</p>\n\n<p>First, let me restate the problem I think you are trying to solve:</p>\n\n<ul>\n<li>you have a resource that only one thread can access at a time</li>\n<li>you want the 'waiting' threads to be queued (essentially in FIFO order) until the resource is available.</li>\n<li>you want the waiting threads to be (b)locked rather than spinning.</li>\n</ul>\n\n<p>You want the 'outside' code to look something like (this code will be in the resource-using threads):</p>\n\n<pre><code>try {\n blockedqueue.sleep(); // wait for my turn to use the resource\n doSomethingWith(resource);\n} finally {\n blockedqueue.wakeup(); // indicate that another thread can use the resource.\n}\n</code></pre>\n\n<p>I see that you start the BlockedQueue off in an 'unblocked' state, so the first thread in will immediately return. Only 'subsequent' threads will wait.</p>\n\n<p>There is a gap in your logic though.... (hate to be the bearer of bad news....)...</p>\n\n<p>It is possible for the queue to be empty when <code>wakeup()</code> is called <strong>even though there are blocked threads</strong>. This is because you may be removing() items in your loop at the same time as when the wake-up is called.</p>\n\n<p>Also, I think that you should be more precise about what threads can re-awaken the queue. I like the try-finally concept which will assure that the same thread that calls <code>sleep()</code> will also call <code>wakeup()</code>.</p>\n\n<p>Consider the following alteration. Instead of using an AtomicBoolean to lock the thread, use an AtomicReference (and I have renamed it to 'active' instead of 'lock'....</p>\n\n<pre><code>public void wakeup() {\n // Unlock.\n if (active.compareAndSet(this, null)) {\n // Wake the first in the queue (and remove it too) ... unpark does nothing with a null parameter.\n LockSupport.unpark(waiting.poll());\n } else {\n throw new IllegalMonitorStateException(\"Cannot unlock a thread unless you are the owner of the lock\");\n }\n}\n</code></pre>\n\n<p>This will prevent spurious wake-ups, but if you have asymmetrical code (more <code>wakeup()</code> than <code>sleep()</code>) you will get exceptions (I think that's a good thing).</p>\n\n<p>In your <code>sleep()</code> method you can also gain some efficiency by not using the queue at all if you're the only active thread...</p>\n\n<pre><code>public void sleep() {\n final Thread me = Thread.currentThread();\n if (blocked.compareAndSet(null, me) {\n // nothing is waiting, next threads will, but we can just keep going\n // there is a slight possibility that we can 'jump the queue'\n // if sleep() is called at **just** the right time...\n return;\n }\n\n // here we know that some other thread is active....\n // Put me in the queue.\n waiting.add(me);\n try {\n // Block while not first in queue or we're blocked\n // wait till we are at the front of the queue and we are also\n // not blocked by anything. If we are blocked, then park.\n // If not, we immediately block the next front-of-queue as well.\n while (waiting.peek() != me || !blocked.compareAndSet(false, true)) {\n LockSupport.park(this);\n }\n } finally {\n // Take me from the queue.\n Thread removed;\n while ((removed = waiting.remove()) != me) {\n // Put it back! It wasn't me!\n waiting.add(removed);\n }\n }\n}\n</code></pre>\n\n<p>I think you may have a problem with initial state, and spurious wake-ups.... Consider the following</p>\n\n<p>You have multiple instances of a Runnable (<code>ta</code> and <code>tb</code> for thread A and thread B), each of them does <code>blockingqueue.sleep()</code>. The expectation is that they will be woken up in turn when the queue's <code>wakup()</code> method is called (wake up both <code>ta</code> and <code>tb</code> by calling <code>wakeup()</code> twice).</p>\n\n<p>So, both threads are asleep, the queue contains <code>[ta, tb]</code> and the atomic boolean <code>blocked</code> is false (the</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:07:49.563",
"Id": "59280",
"Score": "0",
"body": "Thanks for the attention. I think I picked up on your point about the initial condition problem and tweaked the code to deal with that - see the `do { ... } while ...` rather than the `while ... {...}`. Still thinking about your other points ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:10:11.410",
"Id": "59281",
"Score": "0",
"body": "I know my answer is a mess... and any threading problem is hard to describe. If you have any questions, feel free to discuss."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:13:44.737",
"Id": "59285",
"Score": "0",
"body": "Of your points 1, 2 and 3 - I think the `while ((removed = ...` loop can be replaced completely by just `waiting.remove()` like in the original code because the logic dictates that the head of the queue **must** be `me` at this point. If that is the case then I suspect your concerns are unfounded. I think there **is** an issue in that area but I cannot define it at this time and I am still not certain you are wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:28:11.453",
"Id": "59293",
"Score": "0",
"body": "I've tweaked it again and added some more comments - mostly to clarify my own thoughts. It seems to still work but I haven't managed to work out an effective test for it yet."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:00:02.787",
"Id": "36213",
"ParentId": "36204",
"Score": "2"
}
},
{
"body": "<p>Posting a second answer to keep things clean.</p>\n\n<p>I think I missed one of the important concepts in your use-case, that you are 'gating' the access to the resource from the resource-side of things, not the thread side of things....</p>\n\n<p>If I were to suggest the following code, I think it would add to this 'conversation':</p>\n\n<pre><code>import java.util.concurrent.locks.Condition;\nimport java.util.concurrent.locks.ReentrantLock;\n\n\npublic class ResourceWaitQueue {\n\n private final ReentrantLock lock = new ReentrantLock(true); // use a FIFO lock.\n private final Condition goodtogo = lock.newCondition();\n private int releasecount = 0; // how many threads should be released.\n\n public final void await() throws InterruptedException {\n lock.lock();\n try {\n while (releasecount == 0) {\n goodtogo.await();\n }\n // releasecount > 0 and we were signalled.\n if (--releasecount > 0) {\n // reduce the releasdecount, but there's still another\n // thread that should be released.\n goodtogo.signal();\n // when that other thread releases, if there's still more\n // to be released, it can do that for us.\n };\n } finally {\n lock.unlock();\n }\n }\n\n public final void release() {\n lock.lock();\n try {\n // indicate there is work to do\n releasecount++;\n // signal the condition is true.... (only signal, not signalAll())\n goodtogo.signal();\n } finally {\n lock.unlock();\n }\n }\n\n\n}\n</code></pre>\n\n<p>The above will queue threads up, using the 'fair' (FIFO) nature of the Re-Entrant Lock (or you can use the faster 'unfair' version too). It uses the lock to queue up threads, and it will release as many threads as times you call <code>release</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T09:02:45.310",
"Id": "59414",
"Score": "0",
"body": "You are right - I should have gone for a `Condition` in the first place and this is certainly the correct approach. It just seems strange to write a lock-free high-performace mechanism and then make use of locks and blocks when really all I want is a reliable and lightweight `Thread.yield()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T08:34:39.640",
"Id": "75871",
"Score": "0",
"body": "@OldCurmudgeon: I may have missed something but what about a fair Semaphore? Wouldn't it good?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T16:45:56.147",
"Id": "36228",
"ParentId": "36204",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "36228",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T12:44:56.233",
"Id": "36204",
"Score": "5",
"Tags": [
"java",
"lock-free"
],
"Title": "Block a thread - spin-lock replacement"
}
|
36204
|
<p>I'd like to have this code looked over because I feel my approach might be very novice and there has to be a more elegant or at least less "grunt-work" way of doing it.</p>
<p>I have to write a small TCP client in my application which can send an object to a server for it to be stored in a Database. Before I send the object I remember that I was once told sending custom objects is generally bad practice unless you have a custom Stream Class (Which I don't have). So I am dissecting my objects before I send them into their respective Strings/ints/whatever else objects. I just feel my approach might not be very efficient.</p>
<p>The end result will be that the server can put together a Query to be executed in the database for storage.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Smart_Journal.Familie;
using System.Net.Sockets;
using System.IO;
namespace Smart_Journal
{
/// <summary>
/// DBM is our Database Manager. It will handle sending and receiving data from the server.
/// You should NOT call these functions directly. Instead, call the functions in the Utility Class.
/// </summary>
public static class DBM
{
private static TcpClient _client;
private static StreamReader _sReader;
private static StreamWriter _sWriter;
private static bool _isConnected;
private static int portNum;
private static String ipAddress;
private static void InitConnection()
{
_client = new TcpClient();
_client.Connect(ipAddress, portNum);
_sReader = new StreamReader(_client.GetStream(), Encoding.ASCII);
_sWriter = new StreamWriter(_client.GetStream(), Encoding.ASCII);
_isConnected = true;
}
private static void EndConnection()
{
_sWriter.WriteLine("END");
_sWriter.Flush();
_sReader.Close();
_sWriter.Close();
_client.Close();
_isConnected = false;
}
// Basically means: SendSupportFamilyObject
public static void SendPlejeFamilieObjekt(PlejeFamilie pfamilie)
{
InitConnection();
if (_isConnected)
{
_sWriter.WriteLine("SEND_PLEJEFAMILIE");
_sWriter.Flush();
if (_sReader.ReadLine().Equals("AUTH_GIVEN"))
{
#region Send Plejefamilie Objekt
_sWriter.WriteLine(pfamilie.CPRKvinde);
_sWriter.Flush();
_sWriter.WriteLine(pfamilie.CPRMand);
_sWriter.Flush();
_sWriter.WriteLine(pfamilie.NavnKvinde);
_sWriter.Flush();
_sWriter.WriteLine(pfamilie.NavnMand);
_sWriter.Flush();
_sWriter.WriteLine(pfamilie.Addresse);
_sWriter.Flush();
_sWriter.WriteLine(pfamilie.MobilKvinde);
_sWriter.Flush();
_sWriter.WriteLine(pfamilie.MobilMand);
_sWriter.Flush();
_sWriter.WriteLine(pfamilie.HjemmeTelefon);
_sWriter.Flush();
_sWriter.WriteLine(pfamilie.StillingKvinde);
_sWriter.Flush();
_sWriter.WriteLine(pfamilie.StillingMand);
_sWriter.Flush();
_sWriter.WriteLine(pfamilie.EmailKvinde);
_sWriter.Flush();
_sWriter.WriteLine(pfamilie.EmailMand);
_sWriter.Flush();
_sWriter.WriteLine(pfamilie.EmailFaelles);
_sWriter.Flush();
_sWriter.WriteLine(pfamilie.GodkendtDato);
_sWriter.Flush();
_sWriter.WriteLine(pfamilie.PlejeForaeldreUdd);
_sWriter.Flush();
_sWriter.WriteLine(pfamilie.AntalKurserIAar);
_sWriter.Flush();
_sWriter.WriteLine(pfamilie.AntalBoernGodkendt);
_sWriter.Flush();
_sWriter.WriteLine(pfamilie.Vilkaar);
_sWriter.Flush();
_sWriter.WriteLine(pfamilie.Status);
_sWriter.Flush();
#endregion Send Plejefamilie Objekt
}
}
EndConnection();
}
// Basically means: SendSpecialNeedsChildObject
public static void SendPlejeBarnObjekt(PlejeBarn pbarn)
{
InitConnection();
if (_isConnected)
{
_sWriter.WriteLine("SEND_PLEJEBARN");
_sWriter.Flush();
if (_sReader.ReadLine().Equals("AUTH_GIVEN"))
{
#region Send Plejebarn Objekt
_sWriter.WriteLine(pbarn.CPR);
_sWriter.Flush();
_sWriter.WriteLine(pbarn.Navn);
_sWriter.Flush();
_sWriter.WriteLine(pbarn.FolkeregisterAdresse);
_sWriter.Flush();
_sWriter.WriteLine(pbarn.Email);
_sWriter.Flush();
_sWriter.WriteLine(pbarn.Telefon);
_sWriter.Flush();
_sWriter.WriteLine(pbarn.Sagsbehandler);
_sWriter.Flush();
_sWriter.WriteLine(pbarn.Konsulent);
_sWriter.Flush();
_sWriter.WriteLine(pbarn.Aflastning);
_sWriter.Flush();
_sWriter.WriteLine(pbarn.NuvaerendeForanstaltning);
_sWriter.Flush();
_sWriter.WriteLine(pbarn.AnbringelsesDato);
_sWriter.Flush();
_sWriter.WriteLine(pbarn.UdskrivningsDato);
_sWriter.Flush();
_sWriter.WriteLine("PLEJEBARN_B");
_sWriter.Flush();
foreach(Note n in pbarn.Bemaerkninger)
{
_sWriter.WriteLine(n.Dato);
_sWriter.Flush();
_sWriter.WriteLine(n.Navn);
_sWriter.Flush();
_sWriter.WriteLine(n.Tekst);
_sWriter.Flush();
}
_sWriter.WriteLine("END_PLEJEBARN_B");
_sWriter.Flush();
_sWriter.WriteLine("PLEJEBARN_TF");
_sWriter.Flush();
foreach (Note n in pbarn.TideligereForanstaltninger)
{
_sWriter.WriteLine(n.Dato);
_sWriter.Flush();
_sWriter.WriteLine(n.Navn);
_sWriter.Flush();
_sWriter.WriteLine(n.Tekst);
_sWriter.Flush();
}
_sWriter.WriteLine("END_PLEJEBARN_TF");
#endregion Send Plejebarn Objekt
}
}
EndConnection();
}
// Basically means: SendBiologicalFamilyObject
public static void SendBiologiskFamilieObjekt(BiologiskFamilie bfamilie)
{
InitConnection();
if (_isConnected)
{
if (_sReader.ReadLine().Equals("AUTH_GIVEN"))
{
#region Send Biologiskfamilie Objekt
_sWriter.WriteLine(bfamilie.CPRMor);
_sWriter.Flush();
_sWriter.WriteLine(bfamilie.CPRFar);
_sWriter.Flush();
_sWriter.WriteLine(bfamilie.NavnMor);
_sWriter.Flush();
_sWriter.WriteLine(bfamilie.NavnFar);
_sWriter.Flush();
_sWriter.WriteLine(bfamilie.Addresse);
_sWriter.Flush();
_sWriter.WriteLine(bfamilie.MobilMor);
_sWriter.Flush();
_sWriter.WriteLine(bfamilie.MobilFar);
_sWriter.Flush();
_sWriter.WriteLine(bfamilie.HjemmeTelefon);
_sWriter.Flush();
_sWriter.WriteLine(bfamilie.EmailMor);
_sWriter.Flush();
_sWriter.WriteLine(bfamilie.EmailFar);
_sWriter.Flush();
_sWriter.WriteLine(bfamilie.EmailFaelles);
_sWriter.Flush();
_sWriter.WriteLine(bfamilie.ForaeldreMyndighed);
_sWriter.Flush();
#endregion Send Biologiskfamilie Objekt
}
}
EndConnection();
}
public static PlejeFamilie HentPlejeFamilieObjekt(String s)
{
return null;
}
public static PlejeBarn HentPlejeBarnObjekt(String s)
{
return null;
}
public static BiologiskFamilie HentBiologiskFamilie(String s)
{
return null;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:07:39.600",
"Id": "59279",
"Score": "1",
"body": "are you worried about thread safety or not because currently it's not thread safe"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:10:26.000",
"Id": "59282",
"Score": "0",
"body": "@ratchetfreak A client should only send one object at a time so it shouldn't be an issue, right? The server that it sends to will be able to handle multiple clients at once however."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:10:55.063",
"Id": "59283",
"Score": "0",
"body": "I know this is asking a lot but `_sWriter.WriteLine(pfamilie.CPRKvinde);` can you translate everything to English? if not that is cool. it just helps to understand what is really going where."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:14:27.110",
"Id": "59286",
"Score": "0",
"body": "if you have multiple thread somewhere it may be possible that you need thread safety on this, at least document it as not thread safe"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:14:28.910",
"Id": "59287",
"Score": "0",
"body": "@Malachi It is a lot of strings, some date time objects and one or two ints. It would really take a lot to translate. The thing is that I am making an application to manage Children with Special Needs, their associations and their biological family. What you pulled out there is \"CPRKvinde\" which means \"Social Security Number Woman\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:52:08.613",
"Id": "59300",
"Score": "0",
"body": "lol, I kind of figured these were labels for basic information that gets passed in. what are you writing to, is it a database, textfile, xml? because that could change your code altogether"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:58:08.293",
"Id": "59301",
"Score": "0",
"body": "I state that I write to a database :P But I send the info to a server first which will take care of reading/writing to the database."
}
] |
[
{
"body": "<p>I find whenever I <em>feel the need</em> to use a <code>#region</code>, there's something fishy going on with my code; I see the same in your <code>SendPlejeFamilieObjekt</code> method: all those <code>WriteLine</code>/<code>Flush</code> calls look very suspicious. Why do you flush at every single line written?</p>\n\n<p>Have you considered overriding <code>PlejeFamilie.ToString()</code> to return the equivalent string? You could do <code>_sWriter.WriteLine(pfamilie.ToString()</code>; and have no code to modify in that method the day <code>PlejeFamilie</code> needs a new member.</p>\n\n<p>[scrolls down]</p>\n\n<p>The same applies to <code>BiologiskFamilie</code>; whenever something changes in these classes, you have multiple places that <em>must</em> change. I would refactor this code so as to minimize the amount of code that needs to be written (therefore possible omissions and bugs) when a change becomes required.</p>\n\n<p>Why is everything <code>static</code>? This class has <em>disposable</em> private fields, I think it should be an instance, and should implement <code>IDisposable</code> so it could be used in a <code>using</code> block and then the client code doesn't need to \"remember\" to call <code>EndConnection</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T14:41:37.547",
"Id": "59266",
"Score": "0",
"body": "The method is in the DBM class (Database Manager). You send an object to the \"Utility\" class, it will call one of the DBM methods. To do this, I decided to make the class and it's methods Static since then I won't have to instantiate the DBM in my Utility class. I flush because if I don't the buffer might be filled up with more lines and I need to read the object attribute by attribute."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T14:48:01.913",
"Id": "59267",
"Score": "0",
"body": "@Vipar the buffer will auto flush itself when it gets full, don't worry about that"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T14:50:09.780",
"Id": "59270",
"Score": "0",
"body": "@ratchetfreak The I might misunderstand how the buffer works. I thought it only sent what I wrote when it was flushed or full."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T17:58:55.510",
"Id": "59340",
"Score": "0",
"body": "@Vipar: It's OK for the buffer to have more than one line in it at a time. The TCP/IP stack will by default bunch the lines up anyway and send the info in bigger chunks to save bandwidth (see [Nagle's algorithm](http://en.wikipedia.org/wiki/Nagle's_algorithm)), whether you flush or not. In fact, TCP on both ends does its best to maintain the illusion of a continuous stream of bytes; at that level, there's no such thing as a discrete packet/datagram/frame/whatever anyway. Just make sure each line has a CRLF or whatever at the end, and the other end will know they're separate."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T14:34:59.963",
"Id": "36208",
"ParentId": "36207",
"Score": "3"
}
},
{
"body": "<p>you have the connection cleanup just at the bottom of the method, so when an early return sneaks in there or an exception occurs the connection won't be cleaned up </p>\n\n<p>either wrap it in a <code>try</code>-<code>finally</code>:</p>\n\n<pre><code>public static void SendPlejeFamilieObjekt(PlejeFamilie pfamilie)\n{\n\n try{\n InitConnection();\n\n }\n finally{\n EndConnection();\n }\n }\n</code></pre>\n\n<p>or create a <code>IDisposable</code> that does the cleanup in its Dispose and use the <code>using</code> statement</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T14:55:29.210",
"Id": "36212",
"ParentId": "36207",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T14:20:11.197",
"Id": "36207",
"Score": "4",
"Tags": [
"c#",
"tcp",
"client"
],
"Title": "Objects sending TCP Client"
}
|
36207
|
<p>I am trying to implement a function below:</p>
<blockquote>
<p>Given a target sum, populate all subsets, whose sum is equal to the target sum, from an <code>int</code> array.</p>
</blockquote>
<p>For example:</p>
<p>Target sum is 15.</p>
<p>An <code>int</code> array is <code>{ 1, 3, 4, 5, 6, 15 }</code>.</p>
<p>Then all satisfied subsets whose sum is 15 are as follows:</p>
<pre><code>15 = 1+3+5+6
15 = 4+5+6
15 = 15
</code></pre>
<p>I am using <code>java.util.Stack</code> class to implement this function, along with recursion.</p>
<p><strong>GetAllSubsetByStack</strong> class</p>
<pre><code>import java.util.Stack;
public class GetAllSubsetByStack {
/** Set a value for target sum */
public static final int TARGET_SUM = 15;
private Stack<Integer> stack = new Stack<Integer>();
/** Store the sum of current elements stored in stack */
private int sumInStack = 0;
public void populateSubset(int[] data, int fromIndex, int endIndex) {
/*
* Check if sum of elements stored in Stack is equal to the expected
* target sum.
*
* If so, call print method to print the candidate satisfied result.
*/
if (sumInStack == TARGET_SUM) {
print(stack);
}
for (int currentIndex = fromIndex; currentIndex < endIndex; currentIndex++) {
if (sumInStack + data[currentIndex] <= TARGET_SUM) {
stack.push(data[currentIndex]);
sumInStack += data[currentIndex];
/*
* Make the currentIndex +1, and then use recursion to proceed
* further.
*/
populateSubset(data, currentIndex + 1, endIndex);
sumInStack -= (Integer) stack.pop();
}
}
}
/**
* Print satisfied result. i.e. 15 = 4+6+5
*/
private void print(Stack<Integer> stack) {
StringBuilder sb = new StringBuilder();
sb.append(TARGET_SUM).append(" = ");
for (Integer i : stack) {
sb.append(i).append("+");
}
System.out.println(sb.deleteCharAt(sb.length() - 1).toString());
}
}
</code></pre>
<p><strong>Main class</strong></p>
<pre><code>public class Main {
private static final int[] DATA = { 1, 3, 4, 5, 6, 2, 7, 8, 9, 10, 11, 13,
14, 15 };
public static void main(String[] args) {
GetAllSubsetByStack get = new GetAllSubsetByStack();
get.populateSubset(DATA, 0, DATA.length);
}
}
</code></pre>
<p>Output in Console is as follows:</p>
<pre><code>15 = 1+3+4+5+2
15 = 1+3+4+7
15 = 1+3+5+6
15 = 1+3+2+9
15 = 1+3+11
15 = 1+4+2+8
15 = 1+4+10
15 = 1+5+2+7
15 = 1+5+9
15 = 1+6+8
15 = 1+14
15 = 3+4+6+2
15 = 3+4+8
15 = 3+5+7
15 = 3+2+10
15 = 4+5+6
15 = 4+2+9
15 = 4+11
15 = 5+2+8
15 = 5+10
15 = 6+2+7
15 = 6+9
15 = 2+13
15 = 7+8
15 = 15
</code></pre>
<p>Please help me with the following 2 things:</p>
<ol>
<li><p>How can I improve this code to reduce the times for recursion? Is sorting the <code>int</code> array (from high to low) before recursion a better way?</p></li>
<li><p>Is there a way to improve the code without using recursion?</p></li>
</ol>
|
[] |
[
{
"body": "<p>There are three reasonable responses here:</p>\n\n<ul>\n<li>yes, your recursion code can be improved for performance.</li>\n<li>yes, part of that improvement can come from sorting the data.</li>\n<li>yes, there's a way to refactor the code to not use recursion, and it may even be faster.</li>\n</ul>\n\n<p>Bearing that in mind, this answer becomes 'complicated'.</p>\n\n<p>Basic performance improvements for current code:</p>\n\n<pre><code>if (sumInStack == TARGET_SUM) {\n print(stack);\n}\n</code></pre>\n\n<p>can easily be:</p>\n\n<pre><code>if (sumInStack >= TARGET_SUM) {\n if (sumInStack == TARGET_SUM) {\n print(stack);\n }\n // there is no need to continue when we have an answer\n // because nothing we add from here on in will make it\n // add to anything less than what we have...\n return;\n}\n</code></pre>\n\n<p>I dislike any recursive function which rely on external (outside-the-method) values. In your case, the <code>sumInStack</code> is external. This makes the target hard to 'see'.</p>\n\n<p>Additionally, if we do sort the data, there are some benefits we can have, and a way to restructure the recursion to make it do less work (since we can guarantee that all values after a point have certain properties...):</p>\n\n<p>consider the method (assuming sorted <code>data</code>):</p>\n\n<pre><code>public void populateSubset(final int[] data, int fromIndex, \n final int[] stack, final int stacklen,\n final int target) {\n if (target == 0) {\n // exact match of our target. Success!\n printResult(Arrays.copyOf(stack, stacklen));\n return;\n }\n\n while (fromIndex < data.length && data[fromIndex] > target) {\n // take advantage of sorted data.\n // we can skip all values that are too large.\n fromIndex++;\n }\n\n while (fromIndex < data.length && data[fromIndex] <= target) {\n // stop looping when we run out of data, or when we overflow our target.\n stack[stacklen] = data[fromIndex];\n populateSubset(data, fromIndex + 1, stack, stacklen + 1, target - data[fromIndex]);\n fromIndex++;\n }\n}\n</code></pre>\n\n<p>You would call this function with:</p>\n\n<pre><code>Arrays.sort(data); \npopulateSubSet(data, 0, new int[data.length], 0, 15);\n</code></pre>\n\n<p>So, that is 'can the code be improved?' and 'will sorting help'</p>\n\n<p>As for the 'unrolled' (no recursion) version of the system, it can be done. It would require three int[] arrays:</p>\n\n<pre><code>int[] data = {....}\nint[] sum = new int[data.length];\nint[] indices = new int[data.length];\nint depth = 0;\nint lastindex = -1;\n</code></pre>\n\n<p>The sum gives and indices act like a stack, and the depth is how deep the stack is (again, assume sorted data):</p>\n\n<pre><code>Arrays.sort(data);\nwhile (depth >= 0) {\n lastindex++;\n if (lastindex == data.length) {\n // we have run out of data.\n do {\n // walk up the stack till we find some data.\n depth--;\n while (depth >= 0 && (lastindex = indices[depth] + 1) < data.length);\n }\n if (depth >= 0) {\n .....\n you then add your code in here to check the target,\n keep it updated in your 'stack'.\n go down a level and move on....\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-03T08:22:04.133",
"Id": "168056",
"Score": "0",
"body": "I can think of so many awesome things to do with memoization! We can store all the solutions in ArrayList<ArrayList<Integer>> for a particular (fromIndex, target) pair"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T20:28:21.993",
"Id": "36247",
"ParentId": "36214",
"Score": "18"
}
},
{
"body": "<p>Another way to do problems like this — investigating properties of all subsets (that is, members of the \"power set\") — is to think of the main set as a list of cells, and each cell as a binary digit position. A member of the power set can therefore be described by a binary number, such that the subset contains only those elements of the set corresponding to a 1 in the binary value.</p>\n\n<p>By doing that, you can generate the power set just by counting. Of course this gets a little complicated when the original set has more values in it that can be comfortably dealt with by the native integer type in a given programming language, but Java has <code>BigInteger</code>. (Enumerating a power set for <em>any</em> purpose is going to be a little painful for original sets that big anyway.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-27T15:08:15.337",
"Id": "105837",
"ParentId": "36214",
"Score": "-1"
}
},
{
"body": "<p>I have not fully worked it out, but the best algorithm here is probably <a href=\"https://en.wikipedia.org/wiki/Dynamic_programming\" rel=\"nofollow\">dynamic programming</a>. Basically, I would order the values and at each one keep all possible sums, considering earlier sums. </p>\n\n<p>For example, for input {1, 2, 3, 4, 6}:</p>\n\n<pre><code>Value : possible sums considering earlier sums and current value\n1 : 0, 1\n2 : 0, 1, 2, 3 (that is: 1 + 0 * 2, 0 * 1 + 2, 1 + 2)\n3 : 0, 1, 2, 3, 4, 5, 6\n4 : 0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11\n6 : 0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 8, 12, 13, 15, 16\n</code></pre>\n\n<p>Note that there is some efficiency above because some combinations are repeated many times. For example, at item 3, the output value 3 can be obtained from either (1 * 3_from_previous_sum + 0 * 3) or (0 * 3_from_previous_sum + 1 * 3). The further you go, the more such redundant values happen.</p>\n\n<p>I have not worked out is if this would clearly be more efficient than using brute force search, but I am pretty sure it would. Dynamic programming should increase the memory requirement of the algorithm, but decrease the compute time.</p>\n\n<p>The example table I made would be useful to answer whether a given sum can be attained or not, but not to give all combinations that can produce a sum, if it exists. To answer that second question, the table would have to be modified to also associate with each output sum value all the combinations which can produce it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-28T03:12:43.900",
"Id": "105875",
"ParentId": "36214",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "36247",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:04:51.970",
"Id": "36214",
"Score": "30",
"Tags": [
"java",
"array",
"recursion",
"mathematics",
"combinatorics"
],
"Title": "Find all subsets of an int array whose sums equal a given target"
}
|
36214
|
<p>I have an assignment as follows:</p>
<blockquote>
<p>Write a program where you can enter from the keyboard up to 10
integers. If the number entered is equal to -99, stop reading numbers
from the keyboard and compute the average and sum of all values
(excluding -99). Print the average on the screen. Make sure you
consider all the cases: less than 10 or exactly 10 numbers can be
entered. After the numbers have been entered you need to make sure
that the average is computed then.</p>
</blockquote>
<p>I came up with the program below. Do you think my program is fine? What could be alternative solutions?</p>
<pre><code>s = 0
for i in range(1, 11):
a=int(input("Enter a number: "))
if a==-99:
s = s+a
print("The sum of the numbers that you've entered excluding -99:",s-a) # minus a because we want to exclude -99
print("The average of the numbers that you've entered excluding -99:",(s-a)/(i-1)) # minus a because we want to exclude -99. i-1 in denominator because we excluded -99 from the sum.
break
else:
s = s+a
print("The sum of the number(s) that you've entered:",s)
print("The average of the number(s) that you've entered:",s/i)
continue
input("Press enter to close")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T16:30:03.500",
"Id": "59309",
"Score": "1",
"body": "have you read the assignment? `excluding -99`. Also you are displaying results after every input."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-05T10:39:30.013",
"Id": "60313",
"Score": "1",
"body": "You should mark an answer as accepted if you think it answers your question :)"
}
] |
[
{
"body": "<p>A few things:</p>\n\n<p>The application should do 2 things.</p>\n\n<blockquote>\n <ol>\n <li><p>Collect up to 10 different integers, or until the entered value is -99</p></li>\n <li><p>Sum and Average the values</p></li>\n </ol>\n</blockquote>\n\n<pre><code># so lets start by creating a list and fill it with all the numbers we need\nnumbers = list() \nfor i in range(0, 10): \n inputNr = int(input(\"Enter a number: \"))\n if(inputNr == -99):\n break;\n\n numbers.append(inputNr)\n\n#Then we take all of the numbers and calculate the sum and avg on them\nsum = 0\nfor j, val in enumerate(numbers):\n sum += val\n\nprint(\"The total sum is: \" + str(sum))\nprint(\"The avg is: \" + str(sum / len(numbers)))\n</code></pre>\n\n<p>A few pointers about your code:</p>\n\n<ul>\n<li>Use a whitespace (a single space) between variable declaration and assignment. Where you did <code>a=1</code> you want to do <code>a = 1</code></li>\n<li>You usually iterate an array (or in Pythons case a list) from <code>0 to N</code>, and not <code>1 to N</code></li>\n<li>Create variables which you can reuse. As you can see in my example I create a <code>inputNr</code> variable which holds the input. I later reuse this to check if it's <code>-99</code> and I reuse it by adding it to my list</li>\n<li>variable names, function names, and everything else should have a descriptive and concise name. Where you named your input variable to <code>a</code> I named mine to <code>inputNr</code>. This means that when we later reuse this variable in the code it will be clear to us what it is and what it holds.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T02:56:18.587",
"Id": "59383",
"Score": "2",
"body": "I would remove the unused `j` and `enumerate`, leaving just `for val in numbers: sum += val`. Or, better, use `sum()` for the whole thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T07:51:43.120",
"Id": "59403",
"Score": "0",
"body": "@MichaelUrman Good point! I'm still new to Python..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:39:43.440",
"Id": "36219",
"ParentId": "36216",
"Score": "4"
}
},
{
"body": "<p>A few things that spring to mind:</p>\n\n<blockquote>\n <ol>\n <li>Keeping a running total is a good idea but take care to catch the <code>-99</code> case - there's no need to add it to the total at all.</li>\n <li>I like how you're using range to count the inputs. This, plus the first point means you don't have to store the actual inputs anywhere.</li>\n <li>My personal oppinion: Your division is fine but would not work in python 2.x. I prefer explicit integer/float division to avoid this ambiguity. You could start with <code>s</code> as a float, <code>s = 0.</code> or force float division <code>s * 1. / i</code> .</li>\n <li>You could use string substitution to format your output in a nice way. <a href=\"http://docs.python.org/3/library/string.html#format-examples\" rel=\"nofollow\">See here in the docs.</a></li>\n <li><code>break</code> is required but <code>continue</code> is not. You should read <code>continue</code> as \"continue to next loop iteration, do not execute any more code until you get there\". As there is no more code in the loop after <code>continue</code>, it is not needed.</li>\n </ol>\n</blockquote>\n\n<p>Here's my version:</p>\n\n<pre><code>s = 0 # Ok in python 3, for 2.x explicitly use a float s = 0.\nfor i in range(1, 11):\n n = int(input()) # Careful to only enter numbers here\n if n == -99:\n i -= 1\n break\n s += n\ni = i if i else 1 # Avoids ZeroDivisionError\nprint 'The sum was: {}\\nThe average was: {}'.format(s, s/i)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T14:19:01.517",
"Id": "59455",
"Score": "1",
"body": "Given the `python3` tag, points 3 and 4 are not necessary here. Still they're good reference for `python2` users."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T15:38:19.840",
"Id": "59469",
"Score": "1",
"body": "thanks MichaelUrman, I didn't notice that tag. I'll edit the post to take it into account"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T04:51:14.127",
"Id": "59537",
"Score": "2",
"body": "your code doesn't properly return the average"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-05T10:33:51.000",
"Id": "60312",
"Score": "1",
"body": "@Malachi - Apologies, the -99 case should have subtracted 1 from i. Fixed now."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T13:52:03.363",
"Id": "36289",
"ParentId": "36216",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "36219",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:19:23.240",
"Id": "36216",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"mathematics"
],
"Title": "Taking the sum and average of the keyboard inputs"
}
|
36216
|
<p>I am developing a GUI using Swing, but before my project gets too complex. I would like to have a good design structure. I have a few ideas and will use a simple example to illustrate. Some feedback on whether or not this is a good approach would be great. </p>
<p>This is what my GUI looks like:</p>
<p><img src="https://i.stack.imgur.com/gE6FA.png" alt="enter image description here"></p>
<p>There are 2 Jpanels <code>LeftPanel</code> and <code>RightPanel</code>. When Show Name is clicked the name in that panel pops up.</p>
<p>My approach for this is:</p>
<ol>
<li><p>If a component is used more than once, I write a class(<code>GetNameButton</code>,<code>NameLabel</code>).</p></li>
<li><p>I write a class for each panel. As the project gets bigger, the JFrame class won't get too cluttered and changes to a panel won't affect the JFrame class.</p></li>
</ol>
<p>Here is the code:</p>
<pre><code>public class MyFrame extends JFrame{
public MyFrame(){
this.setLayout(null);
this.setBounds(100,100,400,400);
this.add(new LeftPanel());
this.add(new RightPanel());
this.setVisible(true);
}
public static void main(String[] args) {
new MyFrame();
}
}
</code></pre>
<p><strong>LeftPanel</strong></p>
<pre><code>public class LeftPanel extends JPanel implements ActionListener{
CloseButton cb = new CloseButton();
JLabel name = new JLabel("foo");
GetNameButton gnb = new GetNameButton();
public LeftPanel(){
this.setLayout(null);
this.setBounds(20, 20, 160, 320);
this.setBorder(new SoftBevelBorder(BevelBorder.RAISED, null, null, null, null));
this.add(new NameLabel());
name.setBounds(50,10,40,10);
this.add(name);
this.add(cb);
this.add(gnb);
gnb.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==gnb){
JOptionPane.showMessageDialog(null, name.getText());
}
}
}
</code></pre>
<p><strong>RightPanel</strong></p>
<pre><code>public class RightPanel extends JPanel implements ActionListener{
JLabel name = new JLabel("bar");
GetNameButton gnb = new GetNameButton();
public RightPanel(){
this.setLayout(null);
this.setBounds(200, 20, 160, 320);
this.setBorder(new SoftBevelBorder(BevelBorder.RAISED, null, null, null, null));
this.add(new NameLabel());
JLabel name = new JLabel("bar");
name.setBounds(50,10,40,10);
this.add(name);
this.add(gnb);
gnb.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==gnb){
JOptionPane.showMessageDialog(null, name.getText());
}
}
}
</code></pre>
<p><strong>GetNameButton</strong></p>
<pre><code>public class GetNameButton extends JButton{
public GetNameButton(){
this.setText("Show Name");
this.setBounds(20,100,120,20);
}
}
</code></pre>
<p><strong>NameLabel</strong></p>
<pre><code>public class NameLabel extends JLabel{
public NameLabel(){
this.setBounds(10,10,40,10);
this.setText("NAME: ");
}
}
</code></pre>
<p><strong>CloseButton</strong></p>
<pre><code>public class CloseButton extends JButton implements ActionListener{
public CloseButton(){
this.setText("Close");
this.setBounds(20,50,100,20);
this.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==this){
System.exit(8);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:51:19.030",
"Id": "59299",
"Score": "1",
"body": "I haven't done Java in years, but both panels seem to have a lot in common. Perhaps you can reduce duplicate code by putting all of the common features into a base class that extends `JPanel`."
}
] |
[
{
"body": "<ul>\n<li><p>Variable names. Imagine yourself a couple of months from now on, when you look back at the code. Will you remember without looking at the variable declaration what <code>gnb</code> is short for? I suggest you use longer variable names so that you even won't have to try to remember it. <code>getNameBtn</code> would be a better name, and it's still not too long. Using <code>closeBtn</code> instead of <code>cb</code> is also better. <code>cb</code> could just as well mean <code>clearbright</code> or something else totally irrelevant.</p></li>\n<li><p>You seem to use <code>setBounds</code> to set the exact layout positions in pixels for your components. This is not recommended as this will not be flexible for resizing the windows. Instead use a proper <code>LayoutManager</code> such as <code>BorderLayout</code> and add some margins to make your buttons be placed approximately where they belong and still be flexible for if someone wants to resize the window. (Trust me, this can be more important than you think).</p></li>\n<li><p>You seem to <code>extend</code> a lot of <code>JButton</code>s and other things. Technically, what's different between a <code>CloseButton</code> and a <code>GetNameButton</code>? The only differences are their positions, labels and I suppose there will be a difference in what happens when you click them. All these things are <strong>properties</strong>, it does not warrant <strong>extension</strong> of the original class. Instead you can use a <code>public static</code> method that <strong>creates</strong> a <code>JButton</code> with the initialized properties of a \"close-button\" or a \"get-name-button\". (The same goes for <code>NameLabel</code>, it does not need to extend <code>JLabel</code>)</p>\n\n<p>Here's code for such a <code>public static</code> method:</p>\n\n<pre><code>public static JButton createGetNameButton() {\n JButton btn = new JButton();\n btn.setText(\"Show Name\");\n btn.setBounds(20,100,120,20);\n return btn;\n}\n</code></pre></li>\n<li><p>jliv902 has a good point in his comment of putting common features into a base class for your panels. However, think about whether or not you really should extend them or not. Personally I think that extending a <code>JPanel</code> or a <code>JFrame</code> is more OK than extending a button, but I want you to know that there are even <a href=\"https://stackoverflow.com/questions/1143923/why-shouldnt-you-extend-jframe-and-other-components\">reasons for why a JFrame shouldn't be extended</a>. Instead of extending, consider this:</p>\n\n<pre><code>public class MyJPanelContainer implements ActionListener {\n private final JPanel panel;\n public MyJPanelContainer() {\n this.panel = new JPanel();\n // code to setup the panel the way you want it\n someComponent.addActionListener(this);\n }\n\n @Override\n public void actionPerformed(ActionEvent e) {\n // ...\n }\n public JPanel getPanel() { \n // Technically, in another approach, you might not even need this getter, but that's a whole other story.\n return this.panel;\n }\n}\n</code></pre>\n\n<p>If you would write a class like that, it will encapsulate the <code>JPanel</code> and thus hide several methods. The easiest effect to describe for using this approach is that it will drastically decrease the number of visible elements when you press Ctrl + Space, which will make it easier to see the method you are looking for.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T15:34:06.603",
"Id": "59468",
"Score": "0",
"body": "While I agree with all your remarks, and specifically, with the first one as a general rule, I think in this particular case it's sensible to use a variable name of \"cb\" for a variable that's of type \"CloseButton\". From its type it's pretty clear what it does, replacing that by \"CloseButton closeButton = new CloseButton()\" looks kind of cluttery to me..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T15:42:23.037",
"Id": "59471",
"Score": "0",
"body": "@ShivanDragon Sure, you would know what the button does if you know the type (as long as it's only one of them, what would you do if there were two?). However, you would only know the type if you *read the line where it is declared*. Also, I propose to **not** use a `CloseButton` type, therefore it would become `JButton cb = createCloseButton();` which would make the variable name \"cb\" even worse."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T16:36:32.850",
"Id": "36225",
"ParentId": "36220",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "36225",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T15:43:27.193",
"Id": "36220",
"Score": "5",
"Tags": [
"java",
"swing",
"gui"
],
"Title": "GUI design in Java Swing"
}
|
36220
|
<p>I have written a method that uses binary search to insert a value into an array.</p>
<p>It is working, but i would like to get a second opinion to see if i didn't write too much code for it. aka doing same thing twice for example.</p>
<p>The code looks for the right index for insertion and is called by an insert method that uses that index value to insert.</p>
<p>Here is the code:</p>
<pre><code>public class OrdArray {
final private long[] a; // ref to array
int nElems; // number of dataitems
int curIn;
//----------------------------------------------------------------------
public OrdArray(int max) { // constructor
a = new long[max]; // create array
nElems = 0;
}
public int binaryInsert(long insertKey) {
int lowerBound = 0;
int upperBound = nElems - 1;
while (true) {
curIn = (upperBound + lowerBound) / 2;
if (nElems == 0) {
return curIn = 0;
}
if (lowerBound == curIn) {
if (a[curIn] > insertKey) {
return curIn;
}
}
if (a[curIn] < insertKey) {
lowerBound = curIn + 1; // its in the upper
if (lowerBound > upperBound) {
return curIn += 1;
}
} else if (lowerBound > upperBound) {
return curIn;
} else {
upperBound = curIn - 1; // its in the lower
}
}
}
public void display() { // display array contents
for (int j = 0; j < nElems; j++) { // for each element,
System.out.print(a[j] + " "); // display it
}
System.out.println("");
}
public void insert(long value) { // put element into array
binaryInsert(value);
int j = curIn;
int k;
for (k = nElems; k > j; k--) { // move bigger ones one up.
a[k] = a[k - 1];
}
a[j] = value; // insert value
nElems++; // increment size.
}
}
public static void main(String[] args) {
// TODO code application logic here
int maxSize = 100; // array size
OrdArray arr; // reference to array
arr = new OrdArray(maxSize); // create array
arr.insert(77); // insert 10 items
arr.insert(99);
arr.insert(44);
arr.insert(55);
arr.insert(22);
arr.insert(88);
arr.insert(11);
arr.insert(00);
arr.insert(66);
arr.insert(33);
arr.display();
}
</code></pre>
<p>Feedback appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T16:05:51.693",
"Id": "59303",
"Score": "0",
"body": "Can you also post the other variables that aren't mentioned in this function? It will help with the code review :) `nElems`, data type of `curIn`, declaration of `a[]` and whatever else you think is necessary. Also, this function is just supposed to return the index where the element should be inserted, correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T16:06:46.567",
"Id": "59304",
"Score": "0",
"body": "Yes ofc. Hold on. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T16:26:20.747",
"Id": "59308",
"Score": "0",
"body": "Yes that is correct. It's for returning the index to insert. It's a modified one for searching for a particular value, from the book i'm reading."
}
] |
[
{
"body": "<p>Here is my version of your code.</p>\n\n<ol>\n<li>You never use \"max\" so I used it by throwing an exception if you are trying to insert too many elements.</li>\n<li>You should make everything that shouldn't be public; private. </li>\n<li>In your <code>binaryInsert()</code> you should move your base case to the begining. </li>\n<li><p>Your <code>binaryInsert()</code> is a bit wonky but it works. I think this would do but I haven't checked it. Looks a bit neater and has one unnecessary if removed.</p>\n\n<blockquote>\n<pre><code>public int binaryInsert(long insertKey) {\n if (nElems == 0)\n return 0;\n int lowerBound = 0;\n int upperBound = nElems - 1;\n int curIn = 0;\n while (true) {\n curIn = (upperBound + lowerBound) / 2;\n if (a[curIn] == insertKey) {\n return curIn;\n } else if (a[curIn] < insertKey) {\n lowerBound = curIn + 1; // its in the upper\n if (lowerBound > upperBound)\n return curIn + 1;\n } else {\n upperBound = curIn - 1; // its in the lower\n if (lowerBound > upperBound)\n return curIn;\n }\n }\n }\n</code></pre>\n</blockquote></li>\n<li><p>Just use methods that return things directly. Don't need to store them in a temporary variable first. Talking about <code>curIn</code> here in your <code>insert</code> function.</p></li>\n<li><p>If you want to return something (like an object) as a String or print something out. You should override the toString() method as I have done. Then you can just call <code>System.out.println(arr.toString())</code> whenever you want to print the Object.</p></li>\n<li><p>The whole point of doing a binary insert would be to quickly find out where to insert an element. Your implementation does this, however your implementation isn't super useful because you have to move each and every element foward by one. A double linked list (as usually taught in C++ classes) is ideal for your implementation of this better version of insertion sort. The java equivalent of a doubly linked list is a <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html\" rel=\"nofollow\"><code>LinkedList</code></a>. Which will give you much better performance as you will not need to move elements forward by one.</p></li>\n</ol>\n\n<p>.</p>\n\n<pre><code>public class OrdArray {\n\n final private long[] a; // ref to array\n private int nElems; // number of dataitems\n private final int MAX;\n\n // ----------------------------------------------------------------------\n\n public OrdArray(int max) { // constructor\n this.MAX = max;\n a = new long[MAX]; // create array\n nElems = 0;\n }\n\n private int binaryInsert(long insertKey) {\n if (nElems == 0) {\n return 0;\n }\n\n int lowerBound = 0;\n int upperBound = nElems - 1;\n\n while (true) {\n int curIn = (upperBound + lowerBound) / 2;\n if (lowerBound == curIn) {\n if (a[curIn] > insertKey) {\n return curIn;\n }\n }\n if (a[curIn] < insertKey) {\n lowerBound = curIn + 1; // its in the upper\n if (lowerBound > upperBound) {\n return curIn += 1;\n }\n } else if (lowerBound > upperBound) {\n return curIn;\n } else {\n upperBound = curIn - 1; // its in the lower\n }\n }\n }\n\n @Override\n public String toString() { // display array contents\n StringBuffer sb = new StringBuffer();\n for (int j = 0; j < nElems; j++) { // for each element,\n sb.append(a[j] + \" \"); // display it\n }\n sb.append(System.lineSeparator());\n return sb.toString();\n }\n\n public void insert(long value) throws Exception { // put element into array\n if (nElems == MAX)\n throw new Exception(\"Can not add more elements.\");\n int j = binaryInsert(value);\n int k;\n for (k = nElems; k > j; k--) { // move bigger ones one up.\n a[k] = a[k - 1];\n }\n a[j] = value; // insert value\n nElems++; // increment size.\n }\n}\n</code></pre>\n\n<p>I'm sure I didn't get everything you need to improve on but hopefully that is atleast one step forward in the right direction. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T18:43:47.640",
"Id": "59346",
"Score": "0",
"body": "It looked a lot more wonkier when i saw it this morning. :) Your corrections work fine, except when there are no elements in the array, it starts inserting at index 1; Not sure how to fix that without an extra if statement saying if nElements == 0 --> return curIn; What do you mean at point 3 moving base case to beginning?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T19:22:11.047",
"Id": "59351",
"Score": "0",
"body": "Base case sort of means stuff that you can use to immediately exit the function. It's stuff you know to be true / the basis for the rest of your fuction to work. Like for fibonacci numbers base case is fib(0) = 0 and fib(1) = 1. You hardcode this in so that the rest of your function works."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T18:07:02.163",
"Id": "36233",
"ParentId": "36221",
"Score": "8"
}
},
{
"body": "<p>There are a couple of things I think you should consider, on top of what Sanchit has pointed out.</p>\n\n<p>The two things I can see are:</p>\n\n<ul>\n<li>why are you 'reinventing the wheel'</li>\n<li>if you <em>have</em> to do your own binary search, there are some things you should do right</li>\n</ul>\n\n<h1>Not-Reinventing-the-wheel</h1>\n\n<p>The 'right' way to do this is (and throw away your binary search code):</p>\n\n<pre><code>public void insert(long value) throws Exception { // put element into array\n if (nElems == MAX)\n throw new IllegalStateException(\"Can not add more elements.\");\n int j = Arrays.binarySearch(a, 0, nElems, value);\n if (j < 0) {\n // this is a new value to insert (not a duplicate).\n j = - j - 1;\n }\n System.arraycopy(a, j, a, j+1, nElems - j);\n a[j] = value;\n nElems++;\n}\n</code></pre>\n\n<h1>Re-inventing the wheel</h1>\n\n<p>If you <strong>have</strong> to reinvent this wheel (it's homework, or something), then consider this:</p>\n\n<ul>\n<li>curIn is redundant, and should be the return value of your binarySearch function.</li>\n<li>the 'standard' in Java is to return the position of the value in the array, or, if the value does not exist in the array, return <code>- ip - 1</code> where 'ip' is the 'insertion point' or where the new value <em>should</em> be. i.e. in the array [1, 2, 4, 5] a binary search for '4' should return '2' (4 is at position 2). A search for '3' should return '-3' because <code>- (-3) - 1</code> is <code>+3 - 1</code> or <code>2</code> which is the place the 3 should go if it is inserted. This allows a single binary search to produce the answer to two questions: <code>is it in the array, and if it is, where is it?</code> and also <code>if it isn't, where should it go?</code></li>\n<li>technically your code has a slight bug for large values of MAX.... your binary search should do <code>upperbound + lowerbound >>> 1</code> because that will give the right values if/when <code>upperbound + lowerbound</code> overflows.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T19:16:29.350",
"Id": "59349",
"Score": "0",
"body": "It's about Re-inventing the wheel. :) The book i am reading states: \"The techniques used in this chapter, while unsophisticated and comparatively slow are nevertheless worth examining.\" The code i have written is just as an exercise. With curIn is redundant and should be the return value. I thought it is the return value of my function? I don't understand how a search for 3 can return -3."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T19:25:32.093",
"Id": "59352",
"Score": "0",
"body": "@Xbit This link has a pretty good description of wht Arrays.binary search is good: http://www.htmlgoodies.com/beyond/java/using-the-java-arrays-binary-search-methods.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T19:45:47.623",
"Id": "59353",
"Score": "0",
"body": "A note I'm not sure how relevant it is, but it is a better practice to throw an `IllegalStateException` instead of declaring `throw Exception`. You should be [as specific as possible in \"throws\" declarations](http://codereview.stackexchange.com/questions/28809/toggling-actionbar-visibility-for-sherlockfragmentactivity/35881#35881)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T20:21:39.890",
"Id": "59358",
"Score": "0",
"body": "Copy-paste problem.... hmmm."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T18:59:09.627",
"Id": "36239",
"ParentId": "36221",
"Score": "7"
}
},
{
"body": "<p>This is a simpler way. </p>\n\n<p>EDIT: \nThe original way works fine. With regards to my solution, it's just with less code. The algorithm itself covers all the cases and we don't need to put if-else conditions to catch edge cases.</p>\n\n<pre><code>fun searchInsert(array: IntArray, num: Int): Int {\n var head = 0\n var tail = array.lastIndex\n\n while (head <= tail) {\n var mid = (head + tail) / 2\n if (num == array[mid])\n return mid\n else if (num > array[mid]) {\n head = mid + 1\n } else {\n tail = mid - 1\n }\n }\n\n return head\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T04:32:49.503",
"Id": "433312",
"Score": "3",
"body": "Could you also explain why this is better and how the original code fails to meet this level of optimization?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T04:44:27.200",
"Id": "433313",
"Score": "0",
"body": "Hi @dfhwze. Thanks for the reminder and I'm sorry I didn't explain it in the first place. I have added more explanation to it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T04:26:30.180",
"Id": "223539",
"ParentId": "36221",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "36233",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T16:01:28.400",
"Id": "36221",
"Score": "9",
"Tags": [
"java",
"array",
"binary-search",
"reinventing-the-wheel"
],
"Title": "Binary search for inserting in array"
}
|
36221
|
<p>I have a <code>List</code> of objects, <code>List<myObject> objectList</code>, and each object contains a <code>List</code> of strings like so:</p>
<pre><code>myObject: StringList( "A_1", "B_1", "C_1", "D_1", "E_1", "F_1" )
myObject: StringList( "A_2", "B_2", "C_1", "D_2", "E_2", "F_1" )
myObject: StringList( "A_2", "B_3", "C_1", "D_3", "E_2", "F_1" )
</code></pre>
<p>I'm trying to merge the lists into a dictionary of: <code>Dictionary<string, List<string>></code>, where the final results will look like so:</p>
<pre><code>Dictionary: { [A:1,2] [B:1,2,3] [C:1] [D:1,2,3] [E:1,2] [F:1] }
</code></pre>
<p>Here is what I have done, and it does work:</p>
<pre><code>Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
foreach (myObject result in objectList)
{
foreach (var item in result.StringList)
{
string Key = item.Split('_')[0];
string Value = item.Split('_')[1];
List<string> sValue = new List<string>();
bool exists = dict.TryGetValue(Key, out sValue);
if (exists && !sValue.Contains(Value))
{
sValue.Add(Value);
dict[Key] = sValue;
}
else if (!exists)
{
sValue = sValue ?? new List<string>();
sValue.Add(Value);
dict.Add(Key, sValue);
}
}
}
</code></pre>
<p>Is there a better way to do this, where I don't have to use two <code>foreach</code> loops? Is there a way to do it without using any <code>foreach</code> loops?</p>
<p>I have tried using lambda but this is as far as I got:</p>
<pre><code>Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
foreach (myObject result in objectList)
{
dict = result.StringList.Select(x => x.Split('_'))
.GroupBy(x => x[0])
.ToDictionary(x => x.Key, x => x.Select(g => g[1]).ToList());
}
</code></pre>
<p>The problem is that the expression keeps overwriting any existing entries in the dictionary each time I iterate through the loop.</p>
<p>Is there a way to keep the existing entries, groupby the Key and add to the existing list of values but don't duplicate any values?</p>
<p>I think the answer lies in this part of the expression:</p>
<pre><code>x => x.Select(g => g[1]).ToList()
</code></pre>
<p>but I'm not 100% sure.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T16:28:38.343",
"Id": "59311",
"Score": "1",
"body": "Did you try SelectMany?"
}
] |
[
{
"body": "<p>Just get rid of the outer <code>foreach</code> as well:</p>\n\n<pre><code>dict = objectList.SelectMany(x => x.StringList)\n .Select(x => x.Split('_'))\n .GroupBy(x => x[0])\n .ToDictionary(x => x.Key, x => x.Select(g => g[1]).Distinct().ToList());\n</code></pre>\n\n<p>SelectMany retrieves all the <code>StringList</code>s and flattens them into one single list:</p>\n\n<pre><code>\"A_1\", \"B_1\", ..., \"F_1\", \"A_2\", \"B_2\", ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T16:39:51.900",
"Id": "59312",
"Score": "0",
"body": "I think you want a distinct in there as well so that A is `1,2` rather than `1,2,2`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T16:40:02.543",
"Id": "59313",
"Score": "1",
"body": "`x => x.Select(g => g[1]).Distinct().ToList()`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T16:48:17.090",
"Id": "59317",
"Score": "1",
"body": "Note that [`Distinct` destroys order](http://stackoverflow.com/questions/204505/preserving-order-with-linq), so it might be `1,2` or `2,1`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T16:59:17.890",
"Id": "59320",
"Score": "0",
"body": "@Heinzi - Thanks so much! This works perfectly! Much simpler and more elegant. For the life of me, I couldn't figure this out...a million times thank you!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T17:00:12.160",
"Id": "59321",
"Score": "0",
"body": "@TimS. - Yes, you are right. I added a quick .OrderBy() after the .Distinct and it fixed things right up. Thank you for your help!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T17:04:17.777",
"Id": "59322",
"Score": "0",
"body": "@Tim: it probably doesn't guarantee to preserve order for all LINQ providers, but in LINQ to objects (i.e. `IEnumerable` extensions) it should preserve order (it seems like the most logical way to implement it: *for each item in input sequence, yield return it unless it's already present in a hashset*.)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T17:07:53.683",
"Id": "59324",
"Score": "1",
"body": "@Groo Like a comment at my link says, \"what you say could be true [that it preserves first-found order], but it would be a bad idea to rely on that behavior\" (because it is documented as being an *unordered* sequence, you should treat it as such). Also, I don't know that `objectList` had it sorted to begin with, the example just happens to have it so (I think)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T17:13:49.503",
"Id": "59327",
"Score": "0",
"body": "@Tim: that's news for me, I must admit, but that's probably the safest bet if they say so (even though I don't see how and why would one implement an unordered `Distinct` without some extra effort). The puzzling thing, however, was that OP wrote that it *fixed things right up*, even though I am pretty sure it didn't change anything. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T17:20:47.357",
"Id": "59328",
"Score": "0",
"body": "@Groo I could write it with the least possible effort, in a way that destroys the order: `return new HashSet<T>(source);`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T17:27:37.413",
"Id": "59332",
"Score": "0",
"body": "Hm, actually, that does seem to retain the insertion order (again, just as an implementation detail)."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T16:32:18.967",
"Id": "36224",
"ParentId": "36223",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "36224",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T16:25:26.127",
"Id": "36223",
"Score": "7",
"Tags": [
"c#",
"strings",
"linq",
"hash-map"
],
"Title": "Creating a dictionary of strings and list of strings"
}
|
36223
|
<p>Whenever I create a Javascript "class" I do something like this:</p>
<pre><code>// Definition
function MyObject() {
this.id = 0;
this.legs = 2;
}
MyObject.prototype = {
walk: function() {
// Do stepping
},
stop: function() {
// Stop stepping
}
};
// Instanciation
var TestMyObject = new MyObject();
TestMyObject.id = 1;
TestMyObject.legs = 3;
</code></pre>
<p>However, as I was trying to find a way to do fixed time step timers, I found another way to construct objects by passing in a key value pair object. That got me thinking that it could be convenient to construct MY objects in a similar fashion. So is there a problem with creating an object like this:</p>
<pre><code>// Definition
function MyObject(objectSettings) {
// Essentially acts as default constructor
objectSettings = objectSettings || {};
// Without a given parameter, use default
this.id = objectSettings.id || 0;
this.legs = objectSettings.legs || 2;
// Make sure the reference is gone
objectSettings = null; // Do I even need this?
}
MyObject.prototype = {
walk: function() {
},
stop: function() {
}
};
// Instanciation
// Use all defaults
var TestMyObject01 = new MyObject();
// Set only id
var TestMyObject02 = new MyObject({
id: 1
});
// Set everything
var TestMyObject02 = new MyObject({
id: 1,
legs: 3
});
</code></pre>
<p>My question is, <code>objectSettings</code> doesn't stick around after instantiating the new object right? Maybe I'm being paranoid. I'm still trying to wrap my head around closures and initially I had a <code>var</code> inside the definition that referenced the passed <code>objectSettings</code> but I figured that was a bad choice because that would be a private immutable reference to a hunk of memory that was just used to copy into an object and that memory wouldn't go away as long as the created object was around.</p>
<p>I realize it would probably be even easier to pass values in individually to the constructor, but I thought maybe this would be a way to overcome the limitation of not being able to overload a function based on parameter type. I would pass what I want to set specifically and if it isn't in the passed object (or if there is no passed object at all) the parameter would be set to a default value. Is there a better way to construct objects in a similar fashion?</p>
<p>I can't find the link to the timer object that got me on this but If I do find it, I'll link it here.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T18:11:15.313",
"Id": "59342",
"Score": "0",
"body": "Welcome! Yes, it certainly looks like you have come to the right place!"
}
] |
[
{
"body": "<p>Correct, the lifetime of <code>objectSettings</code> is only for the <code>MyObject</code> function, so you don't need the assignment to <code>null</code> at the end.</p>\n\n<p>Passing in an object to the constructor is a common pattern to set its properties, and if you don't want to add specific assignment statements for each property, you can do something like this:</p>\n\n<pre><code>Utils = {\n // Taken from the ExtJS library\n apply: function(o, c, defaults) {\n if(defaults) {\n Utils.apply(o, defaults);\n }\n if(o && c && typeof c == 'object') {\n for(var p in c) {\n o[p] = c[p];\n }\n }\n return o;\n }\n};\n\nfunction MyObject(cfg) {\n Utils.apply(this, cfg, {\n id: 0,\n legs: 2,\n ...\n });\n\n // You now have access to this.id, etc.\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T20:03:26.593",
"Id": "59357",
"Score": "0",
"body": "Awesome, thanks. It occurred to me while I was testing that you define a ton of objects in JQuery using this method so I should have taken that as a cue that this was safe. Still though, good to be assured that I'm not leaking memory."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T18:55:32.697",
"Id": "36237",
"ParentId": "36231",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "36237",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T18:02:37.120",
"Id": "36231",
"Score": "5",
"Tags": [
"javascript",
"object-oriented"
],
"Title": "Object construction differences"
}
|
36231
|
<p>Should I leave the Default Route in if it's not adding any benefit?</p>
<p>I have a RouteConfig.cs file that looks like this:</p>
<pre><code>public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Dashboard",
url: "{controller}/{action}",
defaults: new { controller = "JobDashboard", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "JobDashboard", action = "Index", enumDigit = UrlParameter.Optional }
);
routes.MapRoute(
name: "Login",
url: "{controller}/{action}",
defaults: new { controller = "Account", action = "Login" }
);
}
</code></pre>
<p>If I only have the Default and Login Routes and the user goes to the root of the site (eg www.sitename.com), then the user always goes to the Login page. I don't want them going to the Login page after they've logged in, and after a little bit of digging I discovered that MVC4 always sorts Route Order Importance by Custom Route first, and then the Default Route. </p>
<p>I created the Dashboard route, and everything is working fine. I then took out the Default route because it didn't seem needed. Nothing seems to be affected by removing the Default Route, and that leads me to the question, should I leave the Default Route in there? </p>
<p>I seem to recall that having a Default Route is good practice, but if it's not adding anything to the solution, is there a good reason to keep it around?</p>
|
[] |
[
{
"body": "<p>I am thinking that you would want to keep that default route in there in the case that something happens to the other routes, then there is something to route to if your custom routes get hosed up for some reason.</p>\n\n<p>Defaults are there for a reason, don't get rid of them</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T00:45:13.103",
"Id": "59522",
"Score": "0",
"body": "What kind of “something” could happen to the other routes that would leave the default route unaffected?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T01:39:34.823",
"Id": "59527",
"Score": "0",
"body": "Errors, Exceptions, someone trying to hack the site by putting things in there that aren't supposed to be there. I am not overly familiar with MVC structure, I just know that Defaults are there for a reason"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T20:56:05.633",
"Id": "36313",
"ParentId": "36236",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "36313",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T18:41:18.497",
"Id": "36236",
"Score": "5",
"Tags": [
"c#",
"asp.net-mvc-4",
"url-routing"
],
"Title": "MVC4 Routes, using Default"
}
|
36236
|
<p>I need to build the following XML document</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0"?>
<SFDocument>
<TableID>5415</TableID>
<PageSize>1</PageSize>
<PageIndex>1</PageIndex>
<MultiCompany>No</MultiCompany>
<Language>1033</Language>
<Fields>
<Field>Operation No.</Field>
<Field>Line No.</Field>
<Field>Date</Field>
<Field>Comment</Field>
</Fields>
<TableFilters>
<TableFilter>
<Field>Status</Field>
<Filter>3</Filter>
</TableFilter>
<TableFilter>
<Field>Prod. Order No.</Field>
<Filter>101006</Filter>
</TableFilter>
</TableFilters>
<Key>
<Field>Routing Reference No</Field>
<Field>10000</Field>
</Key>
</SFDocument>
</code></pre>
<p>using the following code, it works but is it the proper way of doing it.</p>
<pre><code>internal class Field
{
public string Name { get; set; }
public const string FieldName = "Field";
}
internal class Key
{
public string Field { get; set; }
public const string FieldName = "Field";
}
internal class TableFilter
{
public string Field { get; set; }
public string Filter { get; set; }
public const string FieldName = "Field";
public const string FilterName = "FilterName";
}
void Main()
{
//this part is just for the example, obviously, this would be passed as parameter
var tableId = 5415;
var pageSize = 1;
var pageIndex = 1;
var multiCompany = "No";
var language = 1033;
var fields = new List<Field>();
fields.Add(new Field() {Name = "Operation No."});
fields.Add(new Field() {Name = "Line No."});
fields.Add(new Field() {Name = "Date"});
fields.Add(new Field() {Name = "Comment"});
var tableFilters = new List<TableFilter>();
tableFilters.Add(new TableFilter() {Field = "Status", Filter = "3"});
tableFilters.Add(new TableFilter() {Field = "Prod. Order No.", Filter = "101006"});
var keys = new List<Key>();
keys.Add(new Key() {Field = "Routing Reference No"});
keys.Add(new Key() {Field = "10000"});
//End of setup
XDocument doc = new XDocument(new XElement("SFDocument",
new XElement("TableId", tableId),
new XElement("PageSize", pageSize),
new XElement("PageIndex", pageIndex),
new XElement("MultiCompany", multiCompany),
new XElement("Language", language),
new XElement("Fields"),
new XElement("TableFilters"),
new XElement("Key")
)
);
var xFields = doc.Element("SFDocument").Element("Fields");
foreach (Field field in fields)
{
xFields.Add(new XElement(Field.FieldName, field.Name));
}
var xTableFilters = doc.Element("SFDocument").Element("TableFilters");
foreach (TableFilter tableFilter in tableFilters)
{
var tf = new XElement("TableFilter");
tf.Add(new XElement(TableFilter.FieldName, tableFilter.Field));
tf.Add(new XElement(TableFilter.FilterName, tableFilter.Filter ));
xTableFilters.Add(tf);
}
var xKey = doc.Element("SFDocument").Element("Key");
foreach (Key key in keys)
{
xKey.Add(new XElement(Key.FieldName, key.Field));
}
doc.Dump(); //Using LinqPad
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T21:25:16.630",
"Id": "59365",
"Score": "2",
"body": "Recently i have started using serializable classes for these kinds of things, the advantage being that i can easily read the XML document back into the same structure, by deserializing it. And if you ever what the change the format of the XML, you don't have update your logic, just add the attribute the the serializable class, and the serializer will handle the rest. Just found this article over at code project: http://www.codeproject.com/Articles/483055/XML-Serialization-and-Deserialization-Part-1 that might be of help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T19:58:30.617",
"Id": "59506",
"Score": "0",
"body": "I tried and loved that way... I will post how i did it below"
}
] |
[
{
"body": "<p>Back when using .NET 2.0, I wrote a <code>Tag</code> class which inherited from <code>XmlElement</code>, and a <code>XmlBuilder</code> which inherited from <code>XmlDocument</code>. For legacy reasons we still use it, but I'm pretty sure it could be rewritten in half the code as a few extension methods.</p>\n\n<p>Here's a small sample:</p>\n\n<pre><code>XmlBuilder xml = new XmlBuilder(\"AmazonEnvelope\");\nxml.AddNamespace(\"noNamespaceSchemaLocation\", \"amzn-envelope.xsd\");\nXmlBuilder.Tag message = xml.FirstTag.AddTag(\"Message\");\nmessage.AddTag(\"MessageID\", messageID++);\nmessage.AddTag(\"OperationType\", \"PartialUpdate\");\n\nXmlBuilder.Tag product = message.AddTag(\"Product\");\nproduct.AddTag(\"SKU\", part.ID);\n\nif (part.upcCode.Length == 12)\n{\n XmlBuilder.Tag UPC = product.AddTag(\"StandardProductID\");\n UPC.AddTag(\"Type\", \"UPC\");\n UPC.AddTag(\"Value\", part.upcCode);\n}\nelse if (part.upcCode.Length == 13)\n{\n XmlBuilder.Tag UPC = product.AddTag(\"StandardProductID\");\n UPC.AddTag(\"Type\", \"EAN\");\n UPC.AddTag(\"Value\", part.upcCode);\n}\n\nproduct.AddTag(\"ProductTaxCode\", \"A_GEN_TAX\");\nreturn xml.OuterXml\n</code></pre>\n\n<p>The <code>XmlBuilder</code> constructor just takes the string and uses that to create the first node: </p>\n\n<pre><code>_outerNode = new Tag(qualifiedName, this);\nAppendChild(_outerNode);\n</code></pre>\n\n<p><code>xml.FirstTag</code> is just a call to get <code>_outerNode</code> as a <code>Tag</code> (instead of an <code>XmlElement</code>).</p>\n\n<p>And so on...</p>\n\n<p>This lets you easily add a lot of logic (\"Do I add this set of tags?\"), doesn't require a multitude of <code>new</code>s, and you can go back and add more things to a tag later.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T22:58:30.367",
"Id": "36254",
"ParentId": "36238",
"Score": "1"
}
},
{
"body": "<p>I ended up changing my approach and went with a serialize method:</p>\n\n<pre><code>public static class SerializationHelper\n{\n internal static string SerializeObject<T>(this T toSerialize)\n {\n var xmlSerializer = new XmlSerializer(toSerialize.GetType());\n var textWriter = new StringWriter();\n xmlSerializer.Serialize(textWriter, toSerialize);\n return textWriter.ToString();\n }\n}\n[Serializable]\npublic class SFDocument\n{\n public int TableId { get; set; }\n public int PageSize { get; set; }\n public int PageIndex { get; set; }\n public string MultiCompany { get; set; }\n public int Language { get; set; }\n\n [XmlArrayItem(\"Field\")]\n public List<string> Fields { get; set; }\n\n public List<TableFilter> TableFilters { get; set; }\n\n [XmlArrayItem(\"Field\")]\n public List<string> Key { get; set; }\n public SFDocument(): this(5415, 1, 1, \"No\", 1033){}\n\n public SFDocument(int tableId, int pageSize, int pageIndex, string multiCompany, int language)\n {\n TableId = tableId;\n PageSize = pageSize;\n PageIndex = pageIndex;\n MultiCompany = multiCompany;\n Language = language;\n\n Fields = new List<string>();\n Key = new List<string>();\n TableFilters = new List<TableFilter>();\n }\n} \n\n[Serializable]\npublic class TableFilter\n{\n public string Field { get; set; }\n public string Filter { get; set; }\n\n public TableFilter() {}\n\n public TableFilter(string field, string filter)\n {\n Field = field;\n Filter = filter;\n }\n}\n\nvoid Main()\n{\n var sfd = new SFDocument();\n sfd.Fields.Add(\"Field1\");\n sfd.Fields.Add(\"Field2\");\n sfd.Fields.Add(\"Field3\");\n sfd.Fields.Add(\"Field4\");\n\n sfd.Key.Add(\"Key1\");\n sfd.Key.Add(\"Key2\");\n sfd.Key.Add(\"Key3\");\n\n sfd.TableFilters.Add(new TableFilter(\"field1\", \"filter1\"));\n sfd.TableFilters.Add(new TableFilter(\"field2\", \"filter2\"));\n sfd.TableFilters.Add(new TableFilter(\"field3\", \"filter3\"));\n sfd.SerializeObject().Dump();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T20:52:03.590",
"Id": "59510",
"Score": "0",
"body": "Feel free to *accept* an answer, doing so will remove this question from the stack of [unanswered zombies](http://meta.codereview.stackexchange.com/questions/999/call-of-duty-were-on-a-mission) and help bring up the site's metrics (we're a beta site!)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T20:14:41.207",
"Id": "36312",
"ParentId": "36238",
"Score": "4"
}
},
{
"body": "<p>Using XML serialization is certainly a valid approach. But if you wanted to keep using LINQ to XML, I would change the code to be more declarative. This way, the structure of the code would closely resemble the structure of the XML, so it would be clearer to see what's going on:</p>\n\n<pre><code>XDocument doc = new XDocument(\n new XElement(\n \"SFDocument\",\n new XElement(\"TableId\", tableId),\n new XElement(\"PageSize\", pageSize),\n new XElement(\"PageIndex\", pageIndex),\n new XElement(\"MultiCompany\", multiCompany),\n new XElement(\"Language\", language),\n new XElement(\n \"Fields\", fields.Select(field => new XElement(Field.FieldName, field.Name))),\n new XElement(\n \"TableFilters\",\n tableFilters.Select(\n tableFilter =>\n new XElement(\n \"TableFilter\",\n new XElement(TableFilter.FieldName, tableFilter.Field),\n new XElement(TableFilter.FilterName, tableFilter.Filter)))),\n new XElement(\"Key\", keys.Select(key => new XElement(Key.FieldName, key.Field)))));\n</code></pre>\n\n<p>Though the <code>TableFilters</code> element is probably too complicated for this approach. But you can easily refactor that to another method:</p>\n\n<pre><code>private static XElement CreateTableFilters(IEnumerable<TableFilter> tableFilters)\n{\n return new XElement(\n \"TableFilters\",\n tableFilters.Select(\n tableFilter =>\n new XElement(\n \"TableFilter\",\n new XElement(TableFilter.FieldName, tableFilter.Field),\n new XElement(TableFilter.FilterName, tableFilter.Filter))));\n}\n\n…\n\nXDocument doc = new XDocument(\n new XElement(\n \"SFDocument\",\n new XElement(\"TableId\", tableId),\n new XElement(\"PageSize\", pageSize),\n new XElement(\"PageIndex\", pageIndex),\n new XElement(\"MultiCompany\", multiCompany),\n new XElement(\"Language\", language),\n new XElement(\n \"Fields\", fields.Select(field => new XElement(Field.FieldName, field.Name))),\n CreateTableFilters(tableFilters),\n new XElement(\"Key\", keys.Select(key => new XElement(Key.FieldName, key.Field)))));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T14:06:34.157",
"Id": "59572",
"Score": "0",
"body": "I like how you made it much more readable. However, I didn't want to necessarily stick to Linq to XML."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T01:05:27.187",
"Id": "36319",
"ParentId": "36238",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "36312",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T18:58:55.747",
"Id": "36238",
"Score": "5",
"Tags": [
"c#",
"linq",
"xml"
],
"Title": "Proper and elegant way of Building a XML Document"
}
|
36238
|
<p>How can I rewrite this code to make it more readable and, if possible, more efficient? The conditions are entirely necessary in this problem, but how could I rewrite those <code>if(a != 1)</code> and such?</p>
<pre><code>celula ** verificaNo(celula ** matriz, int linhas, int colunas){
celula ** aux = matriz;
int i, j, k;
int node = 1;
int a = 0;
int b = 0;
int c = 0;
for(i = 0; i < linhas; i++){
for(j = 0; j < colunas; j++){
if((i == 0) && (j == 0)){
aux[i][j].no = node;
}
else if((i == 0) && (j != 0)){
if(aux[i][j-1].peso == 0 && aux[i][j].peso == 0){
aux[i][j].no = aux[i][j-1].no;
}
else if(aux[i][j-1].peso != 0 && aux[i][j].peso == 0){
for(k = j; aux[i+1][k].peso == 0 && k > 0; k--){
if(aux[i][k-1].peso == 0){
aux[i][j].no = aux[i][k-1].no;
a = 1;
}
}
if(a != 1){
node++;
aux[i][j].no = node;
}
}
}
else if((j == 0) && (i != 0)){
if(aux[i-1][j].peso == 0 && aux[i][j].peso == 0){
aux[i][j].no = aux[i-1][j].no;
}
else if(aux[i-1][j].peso != 0 && aux[i][j].peso == 0){
for(k = j; aux[i][k].peso == 0 && k < colunas; k++){
if(aux[i-1][k+1].peso == 0){
aux[i][j].no = aux[i-1][k+1].no;
b = 1;
}
}
if(b != 1){
node++;
aux[i][j].no = node;
}
}
}
else if(aux[i][j].peso == 0 && aux[i-1][j].peso == 0 && i != 0){
aux[i][j].no = aux[i-1][j].no;
}
else if(aux[i][j].peso == 0 && aux[i][j-1].peso == 0 && j != 0){
aux[i][j].no = aux[i][j-1].no;
}
else if(aux[i][j].peso == 0){
for(k = j; aux[i][k].peso == 0 && k < colunas; k++){
if(i != 0){
if(aux[i-1][k].peso == 0){
aux[i][j].no = aux[i-1][k].no;
c = 1;
}
}
}
if(c != 1){
node++;
aux[i][j].no = node;
}
}
}
}
return aux;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T15:06:49.943",
"Id": "59460",
"Score": "1",
"body": "As to discuss the readability, would you explain a little bit more about its function? So no one has to guess."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-09T23:07:30.823",
"Id": "60932",
"Score": "0",
"body": "If you wrote it in English, it would be more readable to me. ;-)"
}
] |
[
{
"body": "<p>This would become instantly more understandable if you gave a description (a comment at the start of the function) of what it was supposed to do. You could also give the structure <code>celula</code>, which I'm assuming is at least:</p>\n\n<pre><code>struct celula\n{\n int no; // number of something?\n int peso; // weight, perhaps?\n};\n</code></pre>\n\n<p>Also you use <code>i</code> for line (linhas) and <code>j</code> for column (colunas). But <code>l</code> and <code>c</code> would be more logical and readable (but <code>l</code> looks like <code>1</code>, so in English I'd use <code>r</code> for \"row\"). I'm generally ok with short variable names, but in such a long function <code>i</code> and <code>j</code> don't work for me. In English I would probably use <code>row</code> and <code>col</code>.</p>\n\n<p>As your function has nested loops with the outer loop doing nothing but enclosing the inner loop, I would if possible extract the whole inner loop to a separate function. But I can see that this might not be easy if those <strong>badly named</strong> variables <code>a</code>, <code>b</code>, <code>c</code>, <code>loop</code> accumulate across rows. It is difficult to tell whether they do from a short look - I might take a longer look later...</p>\n\n<p>Later...</p>\n\n<p>Returning to variables <code>a</code>, <code>b</code>, <code>c</code>: they are never reset once set. \nIs that correct? These variables names are meaningless and need changing. And what does <code>node</code> mean - again the name needs improving.</p>\n\n<p>A bigger observation is that everything below the first <code>else</code> contains the term <code>aux[i][j].peso == 0</code>. I think these can all be factored out (so that the condition is tested at the top of the loop. </p>\n\n<pre><code>for(i = 0; i < linhas; i++){\n for(j = 0; j < colunas; j++){\n if((i == 0) && (j == 0)){\n aux[i][j].no = node;\n }\n else if(aux[i][j].peso == 0) { // moved to here\n if((i == 0) && (j != 0)){\n</code></pre>\n\n<p>And also the <code>i != 0</code> and <code>j != 0</code> in the following lines are unnecessary, as they have been handled further up:</p>\n\n<pre><code>else if(aux[i-1][j].peso == 0 && i != 0){ // here\n aux[i][j].no = aux[i-1][j].no;\n}\nelse if(aux[i][j-1].peso == 0 && j != 0){ //here\n aux[i][j].no = aux[i][j-1].no;\n}\nelse{\n for(k = j; aux[i][k].peso == 0 && k < colunas; k++){\n if(i != 0){ // here\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T14:45:49.323",
"Id": "59458",
"Score": "0",
"body": "I'm guessing `peso` is the former Spanish currency, and `no` could either be Spanish for no (and use it as a kind of boolean) or it could be number of."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T17:00:46.750",
"Id": "59482",
"Score": "0",
"body": "Maybe peso is weight?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T14:23:16.367",
"Id": "36291",
"ParentId": "36241",
"Score": "6"
}
},
{
"body": "<p>For readability this can help:</p>\n\n<ul>\n<li>use the usual C-style short forms for 0-check <code>if (i)</code> and if <code>if (!i)</code>, so the non-trivial comparisons get weight</li>\n<li>add a space between keywords like <code>if</code>, <code>for</code> and the following opening parenthesis</li>\n</ul>\n\n<hr>\n\n<p><em>Edit:</em> [as usual] <strong>Use meaningful names, and, where not applicable (only!), comments.</strong></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T15:10:30.243",
"Id": "36295",
"ParentId": "36241",
"Score": "4"
}
},
{
"body": "<p>Since you are passing matriz as a pointer, I don't think you need to create a local copy. This also means that your function doesn't need a return value. The matrix being passed in is the one being operated on.</p>\n\n<p>There are 3 special cases here around the zero index, I would break them out into separate loops. There is also a repeated inner loop that can be extracted to a separate function,so I would do that. The first iteration counts down instead of up, though. I've preserved that as an option, but maybe its a typo?</p>\n\n<p>Once you make those 2 changes there are a few simplifications that can be made. I used the boolean tests to get rid of all the ==0 and !=0, which cleans things up a bit.</p>\n\n<p>EDIT: I've implemented @Roddy's suggestions</p>\n\n<pre><code>bool test(celula * *matriz, int &i, int &k, int incrementor int limit) {\n bool result = false;\n for (; !matriz[i + 1][k].peso && k > 0 && k<limit; k + incrementor) {\n if (!matriz[i][k - 1].peso ) {\n matriz[i][j].no = matriz[0][k - 1].no;\n result = true;\n }\n }\n}\n\n void verificaNo(celula * *matriz, int linhas, int colunas) {\n int node = 1;\n\n // i, j == 0\n matriz[0][0].no = node;\n\n // i==0, j != 0\n for (int j = 1; j < colunas; ++j) {\n if (!matriz[0][j - 1].peso && !matriz[0][j].peso) {\n matriz[0][j].no = matriz[0][j - 1].no;\n } else if (matriz[0][j - 1].peso && !matriz[0][j].peso && !test(matriz, 0, j, -1, colunas)) {\n matriz[0][j].no = ++node;\n }\n }\n\n // j == 0, i != 0\n for (int i = 1; i < linhas; ++i) {\n if (!matriz[i - 1][0].peso && !matriz[i][0].peso) {\n matriz[i][0].no = matriz[i - 1][0].no;\n } else if (matriz[i - 1][0].peso && !matriz[i][0].peso == 0 && !test(matriz, i, 0, 1, colunas)) {\n matriz[i][0].no = ++node;\n }\n }\n\n // i > 0, j> 0\n for (int i = 1; i < linhas; ++i) {\n for (int j = 1; j < colunas; ++j) {\n if (!matriz[i][j].peso) {\n if (!matriz[i - 1][j].peso) {\n matriz[i][j].no = matriz[i - 1][j].no;\n } else if (!matriz[i][j - 1].peso) {\n matriz[i][j].no = matriz[i][j - 1].no;\n }\n } else if (!matriz[i][j].peso && test(matriz, i, j, +1, colunas)) {\n matriz[i][j].no = ++node;\n }\n }\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T16:36:41.227",
"Id": "36299",
"ParentId": "36241",
"Score": "3"
}
},
{
"body": "<p>Readability:</p>\n\n<p><code>a</code>, <code>b</code>, and <code>c</code> are not meaningful names, unless you have a very specific problem space.</p>\n\n<p>Replace these</p>\n\n<pre><code> node++;\n aux[i][j].no = node;\n</code></pre>\n\n<p>...with these</p>\n\n<pre><code> aux[i][j].no = ++node;\n</code></pre>\n\n<hr>\n\n<p>And for C99 or later, use local for loop variables</p>\n\n<pre><code> for (int j = 1; j < colunas; ++j) \n</code></pre>\n\n<p>It's also good to get in the habit of using preincrement on loop variable (as above), as this can give greater efficiency particularly if you move to C++.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T13:45:00.947",
"Id": "59569",
"Score": "0",
"body": "It's C, not C++."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T16:59:30.133",
"Id": "59594",
"Score": "0",
"body": "@Wolf Yes: `for` loop with declaration is valid C99. Or did you mean something else?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T17:37:12.543",
"Id": "59599",
"Score": "0",
"body": "Yes, and even [const](http://stackoverflow.com/a/5250078/2932052). But the OP didn't state that used C99. And since you mentioned also the performance preincrement, I wanted remind you about this. Is I read it again now, your have formulated this quite good. Maybe you could explicitly add the C99 vs. C89 distinction. There are people who are in the sad position to have to use non-standard compiler..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T18:02:58.890",
"Id": "59603",
"Score": "2",
"body": "@wolf : \"the OP didn't state that used C99\". No, but he didn't say \"K&R C\" either ;-) It's a reasonable to assume the most recent ratified standard unless otherwise specified."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-09T02:58:27.190",
"Id": "60792",
"Score": "0",
"body": "@Roddy \"most recent ratified standard\" meaning C11?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-09T10:07:12.747",
"Id": "60800",
"Score": "2",
"body": "@chux : Yes. http://en.wikipedia.org/wiki/C11_(C_standard_revision)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T17:20:11.983",
"Id": "36305",
"ParentId": "36241",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T20:07:58.693",
"Id": "36241",
"Score": "1",
"Tags": [
"optimization",
"c",
"matrix"
],
"Title": "How can I make this code more readable and efficient?"
}
|
36241
|
<p>This code basically connects to a database, sets login success and failure pages, queries the database for user details, checks if user is active, sets session value and redirects accordingly.</p>
<p>Can you have a look? What do you think of it? Any suggestions?</p>
<pre><code><?php
session_start();
// Connect to the database
try {
$db = new PDO('mysql:host=localhost; dbname=database', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch(Exception $e) {
exit;
}
// Set URL for successful login and unsuccessful login
if($_POST['page']) {
$success = $_POST['page'];
} else {
$success = 'http://website.com/members';
}
$fail = 'http://website.com/login';
// Check if login came from my server
if($_SERVER['SERVER_NAME'] != 'website.com') {
header('Location: ' . $fail);
}
// Check if a user is trying to login
if($_POST) {
// Query the users details
try {
$user_query = $db->prepare('SELECT * FROM users LEFT JOIN zones ON user_timezone = zone_id WHERE user_email = ? AND user_pass = ?');
$user_query->bindParam(1, $_POST['username'], PDO::PARAM_STR, 50);
$user_query->bindParam(2, $_POST['password'], PDO::PARAM_STR, 15);
$user = $user_query->execute();
$user = $user_query->fetch(PDO::FETCH_ASSOC);
} catch(Exception $e) {
exit;
}
// Make sure account is active
if($user['user_active'] != 1) {
header('Location: ' . $fail . '?error=2');
exit;
}
// Make sure user exists
if($user != FALSE) {
$_SESSION['uid'] = $user['user_id'];
$_SESSION['utz'] = $user['zone_name'];
header('Location: ' . $success);
} else {
header('Location: ' . $fail . '?error=1');
exit;
}
} else {
header('Location: ' . $fail . '?error=4');
exit;
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T20:29:36.433",
"Id": "59359",
"Score": "1",
"body": "You mean *improve* a piece of code right? Or you're a code jazzman?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T20:40:53.577",
"Id": "59361",
"Score": "0",
"body": "where did you get this code at?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-01T18:42:50.373",
"Id": "59766",
"Score": "1",
"body": "Are you trying to improve someone else's code or this is the code which you implemented ?"
}
] |
[
{
"body": "<p>Just few quick things come to my mind:</p>\n\n<ul>\n<li><p>The way try/catch is used is to exit on error, which would happen anyway. Maybe you need to send some info to the user here instead.</p></li>\n<li><p>Are you passing raw user input to the database, without validation? This would be clear security issue.</p></li>\n<li><p>Why not <code>if($user)</code> instead of <code>if($user != FALSE)</code>?</p></li>\n<li><p>What is the purpose to set headers and then exit without any request?</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-01T20:26:08.937",
"Id": "59780",
"Score": "1",
"body": "Prepared statements mean sql injection is already accounted for. Setting location headers and exiting is the normal way to redirect a user. Wrapping the header-and-exit lines in a function is a simple example how the code could be improved."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-01T17:47:15.723",
"Id": "36461",
"ParentId": "36242",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T20:17:43.077",
"Id": "36242",
"Score": "1",
"Tags": [
"php",
"mysql",
"session"
],
"Title": "Login and User Information Requests"
}
|
36242
|
<blockquote>
<p>Open-source programming language and integrated development environment (IDE) built for the electronic arts, new media art, and visual design communities with the purpose of teaching the fundamentals of computer programming in a visual context, and to serve as the foundation for electronic sketchbooks.
- <a href="http://processing.org/" rel="nofollow noreferrer">Processing.org</a></p>
</blockquote>
<p>Processing programs (known as sketches) can be exported as Java applications. Processing is also available for developing in a Java-only environment through use of a <code>core.jar</code></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-11-27T20:19:28.280",
"Id": "36243",
"Score": "0",
"Tags": null,
"Title": null
}
|
36243
|
Open-source programming language and IDE built to teach the fundamentals of computer programming in a visual context, and to serve as the foundation for electronic sketchbooks.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-11-27T20:19:28.280",
"Id": "36244",
"Score": "0",
"Tags": null,
"Title": null
}
|
36244
|
<p>A Session refers to all the requests that a single client makes to a server.</p>
<p>From <a href="http://en.wikipedia.org/wiki/Session_%28computer_science%29" rel="nofollow">Wikipedia</a>: </p>
<p>A session is a semi-permanent interactive information interchange, also known as a dialogue, a conversation or a meeting, between two or more communicating devices, or between a computer and user (see <a href="http://en.wikipedia.org/wiki/Login_session" rel="nofollow">Login session</a>). A session is set up or established at a certain point in time, and torn down at a later point in time. An established communication session may involve more than one message in each direction. A session is typically, but not always, <a href="http://en.wikipedia.org/wiki/Stateful" rel="nofollow">stateful</a>, meaning that at least one of the communicating parts needs to save information about the session history in order to be able to communicate, as opposed to <a href="http://en.wikipedia.org/wiki/Stateless_server" rel="nofollow">stateless</a> communication, where the communication consists of independent requests with responses.</p>
<p>An established session is the basic requirement to perform a <a href="http://en.wikipedia.org/wiki/Connection-oriented_communication" rel="nofollow">connection-oriented communication</a>. A session also is the basic step to transmit in <a href="http://en.wikipedia.org/wiki/Connectionless_communication" rel="nofollow">connectionless communication</a> modes. However any unidirectional transmission does not define a session.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T20:38:37.470",
"Id": "36248",
"Score": "0",
"Tags": null,
"Title": null
}
|
36248
|
<p>I am trying to simplify the below <code>if</code> <code>else</code> statement, and I think it can be done.</p>
<p>Algorithm is like this - </p>
<blockquote>
<p>If <code>user_ptr</code> exists, then <code>lock attrmap</code>, find <code>user_ptr</code>. And if it
is a <code>batch</code>, then don't ping. And else if <code>user_ptr</code> doesn't exists
and if it is not a <code>batch</code>, then do other stuff. But if it is a
<code>batch</code> and <code>user_ptr</code> doesn't exists, then don't do anything.</p>
</blockquote>
<p>With the above algorithm, this is what I've came up with, but I'm not sure whether it can be simplified or not.</p>
<pre><code>if (user_ptr) {
if(batchOrTimestamp != "batch") {
user_ptr->ping(); // dont ping it if its a batch update
}
// lock attribute map from outside access and modification
AttributeMap::GuardSPtr guard = user_ptr->m_attrMap.get_guard();
user_ptr->m_attrMap.find(column_key.c_str(), actual_binary_value, attributeLength, schemaId, lastModifiedDate);
} else if(!user_ptr && batchOrTimestamp != "batch") {
user_ptr = User::MakeUser(user_id);
user_ptr->m_attrMap.find(column_key.c_str(), actual_binary_value, attributeLength, schemaId, lastModifiedDate);
User::Find(user_ptr);
}
</code></pre>
<p>Any thoughts on this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T21:09:49.403",
"Id": "59364",
"Score": "0",
"body": "You *could* technically simplify it by expressing results in values and run the values through a 'switch' block."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T22:04:01.343",
"Id": "59371",
"Score": "2",
"body": "*else if(!user_ptr* <-- the !user_ptr check is redundant in this case. That branch won't be reached if user_ptr is not 0 anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T20:42:11.743",
"Id": "61688",
"Score": "0",
"body": "@AlexM. so in that case, this is sufficient - `else if(batchOrTimestamp != \"batch\") {` right?"
}
] |
[
{
"body": "<p>What you have is essentially:</p>\n\n<pre><code>if (a) {\n if (b) c();\n d();\n}\nelse if (b) e();\n</code></pre>\n\n<p>Where:</p>\n\n<pre><code>a = user_ptr\nb = batchOrTimestamp != \"batch\"\nc = user_ptr->ping();\nd = 2 lines, starting with `AttributeMap::GuardSPtr guard = user_ptr->m_attrMap.get_guard();`\ne = 3 lines, starting with `user_ptr = User::MakeUser(user_id);`\n</code></pre>\n\n<p>One way to rewrite this is:</p>\n\n<pre><code>if (a && b) c();\nif (a) d();\nelse if (b) e();\n</code></pre>\n\n<p>And another way is:</p>\n\n<pre><code>if (b) {\n if (a) c();\n else e();\n}\nif (a) d();\n</code></pre>\n\n<p>Which of these ways you prefer is up to you. The problem is that you have a total of three branches. One for <code>a</code>, one for <code>b && !a</code> and one for <code>a && b</code>.</p>\n\n<p>I don't believe it's possible to <strong>simplify</strong> this in a better way (I would gladly be proven wrong).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T20:47:22.327",
"Id": "61690",
"Score": "0",
"body": "Thanks Simon a lot. And apart from this, whatever I have in my updated code in my question is also right? Correct? And we can rewrite this in two ways as well as you have suggested?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T23:48:16.620",
"Id": "36257",
"ParentId": "36250",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "36257",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T21:07:35.360",
"Id": "36250",
"Score": "2",
"Tags": [
"c++"
],
"Title": "Simplifying the if else statement"
}
|
36250
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.