body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>Having scoured the web and found little helpful information regarding the implementation of an overridable <code>compareTo()</code> method, I determined myself to find a solution. In another thread I was pointed to some information pertaining to an overridable <code>equals()</code> method, however <code>compareTo()</code> has some pretty unique issues which must be overcome (namely, how to deal with objects of a related supertype, but each existing in a separate hierarchical branch). I've considered many possible scenarios and believe that I've implemented a type which allows for the modification of relational behavior by subtypes, however I'd like external verification that I'm not breaking the <code>compareTo()</code> contract.</p>
<pre><code>public abstract class RelationalObject
implements Comparable<RelationalObject>
{
/*
* Compares two RelationalObjects for semantic ordering.
*
* @param other The RelationalObject to be compared.
*
* @return An int value representing the semantic relationship between the
* two RelationalObjects. A value of 0 is returned if the two
* objects are determined to be equal. A negative value is
* returned if "this" object is determined to have a
* lower semantic ordering than the "other" object. A positive
* value is returned if "this" object is determined to have a
* highter semantic ordering than the "other" object.
*/
public final int compareTo(RelationalObject other)
throws ClassCastException, NullPointerException
{
if (other == null)
throw new NullPointerException("other: Cannot be null.");
int relation = 0;
if (!this.equals(other))
{
if (this.getClass().isAssignableFrom(other.getClass()))
{
if (this.getClass() == other.getClass())
relation = this.compareToExactType(other);
else
/*
* Defer comparison to subtype, thereby allowing an
* optional override of compareToSuperType().
*/
relation = -1 * other.compareTo(this);
}
else
{
if (other.getClass().isInstance(this))
relation = this.compareToSuperType(other);
else
relation = this.compareToForeignType(other);
}
}
return relation;
}
/*
* Compares two RelationalObjects with the exact same class type for
* semantic ordering. The comparison may be based upon any of the class
* state elements so long as the compareTo() method contract is not
* broken.
*
* @param exact The RelationalObject with exactly matching type to be
* compared.
*
* @return An int value representing the semantic relationship between the
* two RelationalObjects.
*/
protected abstract int compareToExactType(RelationalObject exact);
/*
* Compares two RelationalObjects not within the same hierarchical branch
* for semantic ordering. The comparison may be based upon only those
* state elements common to both objects (i.e. A comparison must be made
* between each element and the pair's common ancestor). Should the two
* results be equal, a ClassCastException must be thrown as the objects do
* not contain enough distinct information to be further compared.
*
* As only one implementation exists, this should be finalized by the first
* derivative of RelationalObject.
*
* @param foreign The RelationalObject from a foreign hierarchical branch
* to be compared.
*
* @return An int value representing the semantic relationship between the
* two RelationalObjects.
*/
protected abstract int compareToForeignType(RelationalObject foreign);
/*
* Compares two RelationalObjects within the same class hierarchical
* branch for semantic ordering. The comparison may be based upon any of
* the class state elements so long as the compareTo() method contract is
* not broken.
*
* @param upper The RelationalObject within the same heirarchical branch
* and with lesser definition to be compared.
*
* @return An int value representing the semantic relationship between the
* two RelationalObjects.
*/
protected abstract int compareToSuperType(RelationalObject upper);
}
</code></pre>
|
[] |
[
{
"body": "<p>Nice question! Some thoughts about it:</p>\n\n<p>If <code>B</code> and <code>C</code> are subclasses of <code>A</code> (in separate hierarchical branches) they usually should not know about each other even in the <code>compareToExactType</code> method. It leads to tight coupling which we try to avoid in OOP.</p>\n\n<p>Here the <code>other.compareTo(this)</code> and similar calls seems hard to follow, though ones which would not be the easiest to debug, maintain or to figure out what is the order that it provides in a complex case.</p>\n\n<p>I'd try to use a separate <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html\" rel=\"nofollow noreferrer\"><code>Comparator</code></a> class which knows all the necessary information about <code>A</code>, <code>B</code>, <code>C</code> and the ordering. You may could use something like that was mentioned in my former answer in the <a href=\"https://codereview.stackexchange.com/a/12273/7076\">Multi-tiered sorting using custom IComparer</a> question.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T16:20:33.300",
"Id": "23001",
"Score": "0",
"body": "Thanks for the suggestions. I'll give the Comparator idea some thought, however I must ensure that subclasses are able to cleanly (without modification) inherit the relational behavior of their parent while also being able to change this behavior without breaking the compareTo() contract."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T16:26:46.943",
"Id": "23002",
"Score": "0",
"body": "I can agree that the various sub-comparisons are at times a little difficult to follow, however I found this to be necessary in order to allow clean (no modification) inheritance while at the same time allowing for modifiable inheritance. (i.e.: -1 * other.compareTo(this) says to defer all actual comparisons to the subtype which should be able to make a more informed decision, while other.compareToForeignType(this) is basically a clever way of allowing the other object to override the compareToForeignType() method so that this instance will not automatically throw ClassCastException."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T05:18:46.430",
"Id": "23028",
"Score": "0",
"body": "I'm glad you spurred me to take another look. I was considering the Foreign Type comparison somewhat incorrectly. There will only ever be one such comparison to be made. I've updated the code segment and comments to reflect accordingly."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T10:17:55.860",
"Id": "14193",
"ParentId": "14189",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T06:52:29.483",
"Id": "14189",
"Score": "4",
"Tags": [
"java"
],
"Title": "Cleanly overridable/modifiable compareTo() method?"
}
|
14189
|
<p>I have two Java classes with very similar code. Basically they are almost the same except for a few method calls etc, i.e. replace <code>ip</code> with <code>msisdn</code> in the classes and they would be identical.</p>
<p>How can I refactor them to remove the duplication? Or maybe if there is a Design Pattern I should be using?</p>
<pre><code>public class IpQuery {
private final CommandLineInterface commandLineInterface;
private final CSVFileReader csvFileReader;
private final XMLFileReader xmlFileReader;
private final CacheQueryRequester cacheQueryRequester;
private final CacheQueryResponseParser cacheQueryResponseParser;
/**
* Invokes a cache query using the ip as a key into the session cache, displaying the result on the command line.
* <p>
* @param ipToQueryCacheFor the ip to query the PCC-A session cache for.
* @param commandLineInterface object used to display error/warning/info messages on the command line.
*/
public IpQuery(String ipToQueryCacheFor, CommandLineInterface commandLineInterface) {
this.commandLineInterface = commandLineInterface;
this.csvFileReader = new CSVFileReader(commandLineInterface);
this.xmlFileReader = new XMLFileReader(commandLineInterface);
this.cacheQueryRequester = new CacheQueryRequester();
this.cacheQueryResponseParser = new CacheQueryResponseParser();
queryCacheForSessionWithIp(ipToQueryCacheFor);
}
private void queryCacheForSessionWithIp(String ipToQueryCacheFor) {
final String configFile = commandLineInterface.getConfigFileArgValue();
if (configFile != null) {
if (configFile.endsWith(".xml")) {
final ArrayList<String> pccaPoolHosts = xmlFileReader.read(configFile);
queryPrimaryAndSecondaryPCCAForIp(ipToQueryCacheFor, pccaPoolHosts);
} else {
final ArrayList<String> pccaPoolHosts = csvFileReader.read(configFile);
queryPrimaryAndSecondaryPCCAForIp(ipToQueryCacheFor, pccaPoolHosts);
}
} else {
commandLineInterface.displayMessage(
"Warning: No CSV or XML config file entered, defaulting to querying localhost [::1].");
invokeCacheQueryForIp(ipToQueryCacheFor, "::1");
}
}
private void queryPrimaryAndSecondaryPCCAForIp(String ipToQueryCacheFor, ArrayList<String> pccaPoolHosts) {
final PCCAServerSelector pccaServerSelector = new PCCAServerSelector(pccaPoolHosts, ipToQueryCacheFor);
commandLineInterface.displayMessage(
"Info: Querying primary PCC-A [" + pccaServerSelector.getPrimaryEndpoint().getIPAddress() +"]");
invokeCacheQueryForIp(ipToQueryCacheFor, pccaServerSelector.getPrimaryEndpoint().getIPAddress());
commandLineInterface.displayMessage(
"Info: Querying secondary PCC-A [" + pccaServerSelector.getSecondaryEndpoint().getIPAddress() +"]");
invokeCacheQueryForIp(ipToQueryCacheFor, pccaServerSelector.getSecondaryEndpoint().getIPAddress());
}
private void invokeCacheQueryForIp(String ipToQueryCacheFor, String pccaHostToQuery) {
final PayLoad cacheQueryResponsePayLoad = cacheQueryRequester.queryCacheForSessionWithIp(ipToQueryCacheFor, pccaHostToQuery);
final String cacheQueryResponseAsString = cacheQueryResponseParser.parse(cacheQueryResponsePayLoad);
commandLineInterface.displayMessage(cacheQueryResponseAsString);
}
}
</code></pre>
<pre><code>public class MsisdnQuery {
private final CommandLineInterface commandLineInterface;
private final CSVFileReader csvFileReader;
private final XMLFileReader xmlFileReader;
private final CacheQueryRequester cacheQueryRequester;
private final CacheQueryResponseParser cacheQueryResponseParser;
/**
* Invokes a cache query using the msisdn as a key into the session cache, displaying the result on the command line.
* <p>
* @param msisdnToQueryCacheFor the msisdn to query the PCC-A session cache for.
* @param commandLineInterface object used to display error/warning/info messages on the command line.
*/
public MsisdnQuery(String msisdnToQueryCacheFor, CommandLineInterface commandLineInterface) {
this.commandLineInterface = commandLineInterface;
this.csvFileReader = new CSVFileReader(commandLineInterface);
this.xmlFileReader = new XMLFileReader(commandLineInterface);
this.cacheQueryRequester = new CacheQueryRequester();
this.cacheQueryResponseParser = new CacheQueryResponseParser();
queryCacheForSessionWithMsisdn(msisdnToQueryCacheFor);
}
private void queryCacheForSessionWithMsisdn(String msisdnToQueryCacheFor) {
final String configFile = commandLineInterface.getConfigFileArgValue();
if (configFile != null) {
if (configFile.endsWith(".xml")) {
final ArrayList<String> pccaPoolHosts = xmlFileReader.read(configFile);
queryPrimaryAndSecondaryPCCAForMsisdn(msisdnToQueryCacheFor, pccaPoolHosts);
} else {
final ArrayList<String> pccaPoolHosts = csvFileReader.read(configFile);
queryPrimaryAndSecondaryPCCAForMsisdn(msisdnToQueryCacheFor, pccaPoolHosts);
}
} else {
commandLineInterface.displayMessage(
"Warning: No CSV or XML config file entered, defaulting to querying localhost [::1].");
invokeCacheQueryForMsisdn(msisdnToQueryCacheFor, "::1");
}
}
private void queryPrimaryAndSecondaryPCCAForMsisdn(String msisdnToQueryCacheFor, ArrayList<String> pccaPoolHosts) {
final PCCAServerSelector pccaServerSelector = new PCCAServerSelector(pccaPoolHosts, msisdnToQueryCacheFor);
commandLineInterface.displayMessage(
"Info: Querying primary PCC-A [" + pccaServerSelector.getPrimaryEndpoint().getIPAddress() +"]");
invokeCacheQueryForMsisdn(msisdnToQueryCacheFor, pccaServerSelector.getPrimaryEndpoint().getIPAddress());
commandLineInterface.displayMessage(
"Info: Querying secondary PCC-A [" + pccaServerSelector.getSecondaryEndpoint().getIPAddress() +"]");
invokeCacheQueryForMsisdn(msisdnToQueryCacheFor, pccaServerSelector.getSecondaryEndpoint().getIPAddress());
}
private void invokeCacheQueryForMsisdn(String msisdnToQueryCacheFor, String pccaHostToQuery) {
final PayLoad cacheQueryResponsePayLoad
= cacheQueryRequester.queryCacheForSessionWithMsisdn(msisdnToQueryCacheFor, pccaHostToQuery);
final String cacheQueryResponseAsString = cacheQueryResponseParser.parse(cacheQueryResponsePayLoad);
commandLineInterface.displayMessage(cacheQueryResponseAsString);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T13:00:11.907",
"Id": "22971",
"Score": "0",
"body": "I think it would be useful to remove the multiple blank lines from the above"
}
] |
[
{
"body": "<p>If I'm right the only difference is this line:</p>\n\n<pre><code>final PayLoad cacheQueryResponsePayLoad \n = cacheQueryRequester.queryCacheForSessionWithMsisdn(msisdnToQueryCacheFor, \n pccaHostToQuery);\n</code></pre>\n\n<p>ant the <code>CacheQueryRequester</code> class could be similar to the following:</p>\n\n<pre><code>public class CacheQueryRequester {\n\n public PayLoad queryCacheForSessionWithMsisdn(final String msisdnToQueryCacheFor, \n final String pccaHostToQuery) {\n ...\n }\n\n public PayLoad queryCacheForSessionWithIp(final String ipToQueryCacheFor, \n final String pccaHostToQuery) {\n ...\n }\n\n}\n</code></pre>\n\n<p>To remove the duplication I'd change the <code>CacheQueryRequester</code> to an interface with only one method:</p>\n\n<pre><code>public interface CacheQueryRequester {\n\n public PayLoad queryCacheForSession(final String queryCacheFor, \n final String pccaHostToQuery);\n}\n</code></pre>\n\n<p>And create two implementations: <code>IpCacheQueryRequester</code> and <code>MsisdnCacheQueryRequester</code>. Finally, rename one of the original query classes simply to <code>Query</code> and modify its constructor to the following:</p>\n\n<pre><code>public Query(final String queryCacheFor, final CommandLineInterface commandLineInterface, \n final CacheQueryRequester cacheQueryRequester) {\n ...\n this.cacheQueryRequester = cacheQueryRequester;\n ...\n}\n</code></pre>\n\n<p>Now, you can pass an <code>IpCacheQueryRequester</code> or an <code>MsisdnCacheQueryRequester</code> instance to the constructor and get rid of the other query class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T12:43:10.087",
"Id": "14198",
"ParentId": "14191",
"Score": "3"
}
},
{
"body": "<p>From memory I think Eclipse does an \"Extract Supertype\" which might help you pull out a base class. Using inheritance may not be the best way of solving this but it will at least give you the common code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T15:24:52.987",
"Id": "14208",
"ParentId": "14191",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "14198",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T09:44:27.817",
"Id": "14191",
"Score": "1",
"Tags": [
"java"
],
"Title": "Two Java classes to perform similar queries with caching"
}
|
14191
|
<p>Since I don't know how LINQ works under the hood, I can't decide what version is best to use in term of <strong>rapidity of execution</strong>. I've done some testing with my testing data (Point Cloud) but I can't see a clear difference between the 2. The only thing I know is that the real life data will be a larger Point Cloud so my guess is that the LINQ would be faster but this is only if LINQ doesn't do a for each under the hood. If it's the case, the 2 functions would be the same. What is your advice?</p>
<p>By the way, <code>cylindre</code> is a 3D cylinder and I want to know which point are inside.</p>
<p>Version 1 without LINQ</p>
<pre><code>for (int i = 0; i < fpc.Vertices.Length; i++)
{
if (cylindre.IsPointInside(fpc.Vertices[i]))
listPoint.Add(fpc.Vertices[i]);
}
</code></pre>
<p>Version 2, with LINQ</p>
<pre><code>var insidePoint =
from pt1 in fpc.Vertices
where cylindre.IsPointInside(pt1)
select pt1;
foreach (Point3D pt2 in insidePoint)
{
listPoint.Add(pt2);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T12:44:50.630",
"Id": "22970",
"Score": "4",
"body": "This might help: http://programmers.stackexchange.com/questions/80084/is-premature-optimization-really-the-root-of-all-evil"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T13:06:29.303",
"Id": "22972",
"Score": "0",
"body": "@ANeves Interesting article. I don't think my question in premature since this is in the requirement and very important because it will be done like 500 times a day by each user. And the only reason I don't have real data is that the final product isn't ready but I know for sure that it will be larger so optimization at this moment is very important. I'm also considering other way of improving the function but the difference between linq and the foreach was something that interest me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T15:49:46.250",
"Id": "22998",
"Score": "3",
"body": "Have you squeezed every bit of performance algorithmically? Which data structures and algorithms you use matters. Some highly optimized libraries for .Net will perform some computations faster. Also, perhaps it is possible to use PLINQ and utilize multiple cores at once? I would measure that too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T17:09:31.237",
"Id": "23004",
"Score": "0",
"body": "Thanks for the info. In fact, we have created a very small subset to run the foreach now it runs super fast, with LINQ and the foreach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T09:06:27.493",
"Id": "23043",
"Score": "1",
"body": "In the LINQ version, you might consider using `AddRange()` instead of `foreach`. It won't increase performance, but it will make your code more readable. Also, using `Where()` directly will be shorter than `from`/`where`/`select`."
}
] |
[
{
"body": "<p>I don't think it will run faster on LINQ. The function <code>cylindre.IsPointInside</code> would still have to be called on each item of Vertices.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T13:00:14.143",
"Id": "14199",
"ParentId": "14197",
"Score": "0"
}
},
{
"body": "<p>Under the hood LINQ will iterate over the collection, just as <code>foreach</code> will. The difference between LINQ and foreach is that LINQ will defer execution until the iteration begins.</p>\n\n<p>Performance wise take a look at <a href=\"http://www.schnieds.com/2009/03/linq-vs-foreach-vs-for-loop-performance.html\" rel=\"nofollow\">this blog post</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T13:40:15.987",
"Id": "23527",
"Score": "1",
"body": "Just a note about that link. The link is dealing with deleting elements from a list. It uses a for loop, then contrasts that with a double foreach loop and a LINQ/foreach combo. Not really a fair comparison."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T06:59:57.900",
"Id": "484127",
"Score": "0",
"body": "Also that link was three years old when this answer was posted, and is now over 11 years old."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T15:34:22.730",
"Id": "489141",
"Score": "0",
"body": "link is no longer valid"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T05:35:44.393",
"Id": "521902",
"Score": "0",
"body": "Link is dead, please correct"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T13:32:10.180",
"Id": "14200",
"ParentId": "14197",
"Score": "5"
}
},
{
"body": "<p>As has been said, the for loop will most likely be more performant, but you can still clean the code up a bit more:</p>\n\n<pre><code>for (int i = 0; i < fpc.Vertices.Length; i++)\n{\n if (cylindre.IsPointInside(fpc.Vertices[i]))\n listPoint.Add(fpc.Vertices[i]);\n}\n</code></pre>\n\n<p>Can become:</p>\n\n<pre><code>foreach (var vertice in fpc.Vertices)\n{\n if (cylindre.IsPointInside(vertice))\n listPoint.Add(vertice);\n}\n</code></pre>\n\n<p>EDIT: As per the performance question. This code will run in LINQPad. I found that the foreach version performs a few milliseconds better than the for loop.</p>\n\n<pre><code>var elements = Enumerable.Range(0, 4000000).Select(x => true).ToArray();\n\n\nvar sw = new Stopwatch();\nvar result = new List<bool>();\nint trueCount = 0;\nsw.Start();\nfor(int i=0; i < elements.Length; ++i)\n{\n if (elements[i])\n {\n ++trueCount;\n result.Add(elements[i]);\n }\n}\n\nsw.Stop();\nsw.ElapsedMilliseconds.Dump();\n\nsw.Reset();\ntrueCount = 0;\nresult = new List<bool>();\nsw.Start();\nforeach(var element in elements)\n{\n if (element)\n {\n ++trueCount;\n result.Add(element);\n }\n}\nsw.Stop();\nsw.ElapsedMilliseconds.Dump();\n</code></pre>\n\n<p>EDIT2 - Regarding the link that seems to indicate such drastically poor performance in a foreach loop</p>\n\n<p>The link (http://www.schnieds.com/2009/03/linq-vs-foreach-vs-for-loop-performance.html) is dealing with removing elements from a list. In the case that you have a generic list, removing elements via a for loop is not normally the best approach. A better approach is to use the <a href=\"http://msdn.microsoft.com/en-us/library/wdka673a\" rel=\"noreferrer\">RemoveAll</a> method. RemoveAll will remove all elements matching the predicate and then consolidate the list as opposed to RemoveAt which will require moving all elements above the removed element. For performance comparison of the removal please see the below code (once again, this can be run in LINQPad). In my testing the RemoveAll ran roughly 250x faster.</p>\n\n<pre><code>var elements = Enumerable.Range(0, 100000).Select(x => x % 2 == 0).ToArray();\n\nvar sw = new Stopwatch();\nvar source = new List<bool>(elements);\nsw.Start();\nfor(int i=0; i < source.Count; ++i)\n{\n if (!source[i])\n {\n source.RemoveAt(i);\n --i;\n }\n}\n\nsw.Stop();\nsw.ElapsedMilliseconds.Dump();\nint count = source.Count;\n\nsw.Reset();\nsource = new List<bool>(elements);\n\nsw.Start();\nsource.RemoveAll((bool x) => {return x;});\nsw.Stop();\nsw.ElapsedMilliseconds.Dump();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T13:09:58.493",
"Id": "23525",
"Score": "0",
"body": "Replacing the for loop by a foreach will decrease the performance, as stated in Xharze's link http://www.schnieds.com/2009/03/linq-vs-foreach-vs-for-loop-performance.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T13:29:59.290",
"Id": "23526",
"Score": "2",
"body": "@Goldorak84 - If you look at the code sample for that link, you will see that in both the foreach and LINQ case the code walked the list twice as compared to the for case that only walked the list once. That link was dealing with removing items from a list, and could have been written without a loop using [RemoveAll](http://msdn.microsoft.com/en-us/library/wdka673a) which would be faster than even the for loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T14:51:21.847",
"Id": "23529",
"Score": "0",
"body": "@pstrjds - I'm sorry, you are totally right. I adapted the code sample to apply the foreach and linq list removing mechanism on the for loop. The difference between the for and the foreach is barely noticeable."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T18:06:07.777",
"Id": "14270",
"ParentId": "14197",
"Score": "8"
}
},
{
"body": "<p>Update:</p>\n\n<p>If you're targeting .net 4 or later, you could use:</p>\n\n<pre><code>Parallel.ForEach()\n</code></pre>\n\n<p>or </p>\n\n<pre><code>RemoveAll().Parallel();\n</code></pre>\n\n<p>They should be faster than other methods.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T22:13:28.840",
"Id": "82836",
"Score": "1",
"body": "`List<T>.RemoveAll()` returns an `int` representing the number of elements removed from the list. Did you mean `List<T>.AsParallel()`?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T21:01:41.617",
"Id": "47290",
"ParentId": "14197",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "14200",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T12:23:39.227",
"Id": "14197",
"Score": "27",
"Tags": [
"c#",
"performance",
"linq",
"comparative-review"
],
"Title": "Is the LINQ version faster than the foreach one?"
}
|
14197
|
<p>I am working on a Rails 3 application, and am having some trouble with my user/edit view. In this application, Users can subscribe to Categories. Users and Categories have a <code>has_and_belongs_to_many</code> relationship through a join table (<code>categories_users</code>).</p>
<p>In my user/edit view, I need to display a list of checkboxes for the various categories so the user can edit his subscriptions. I am using the following code to achieve this:</p>
<pre><code><div id="category-checklist">
<% Category.roots.order('name ASC').each do |category| %>
<ul>
<li class="parent <%= category.name %>">
<%= check_box_tag "user[category_ids][]", category.id, @user.categories.include?(category) %> <span><%= category.name %></span>
</li>
<ul id="children-<%= category.id %>" class="children-list">
<% category.children.order('name ASC').each do |child| %>
<li class="child <%= child.name %>">
<%= check_box_tag "user[category_ids][]", child.id, @user.categories.include?(child) %> <span><%= child.name %></span>
</li>
<% end %>
</ul>
</ul>
<% end %>
</div>
</code></pre>
<p>The <code>Category</code> model uses the ancestry gem for hierarchy, which is there the <code>roots</code> and <code>children</code> methods come from. Roots returns all the parent categories, and children returns all of the sub-categories for a given parent.</p>
<p>The really problematic part of this code seems to be <code>@user.categories.include?(child)</code> which is running 81 separate queries (one for each child category). This line is used to check if the category is currently subscribed to by the user -- if so, the checkbox is marked checked. Is there a better/faster way to accomplish this?</p>
<p>For reference, here is the join table's schema definition - I tried to put an index on the foreign keys thinking it would speed things up, but this is still very slow compared to the rest of my app.</p>
<pre class="lang-ruby prettyprint-override"><code>create_table "categories_users", :id => false, :force => true do |t|
t.integer "category_id"
t.integer "user_id"
end
add_index "categories_users", ["category_id"], :name => "index_categories_users_on_category_id"
add_index "categories_users", ["user_id"], :name => "index_categories_users_on_user_id"
</code></pre>
|
[] |
[
{
"body": "<p>When you load the user, you can include the categories using eager loading. </p>\n\n<pre><code>@user = User.includes(:categories).find(params[:id])\n</code></pre>\n\n<p>or </p>\n\n<pre><code>@user = User.find(params[:id])\n@categories = @user.categories.all\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T15:52:46.453",
"Id": "23060",
"Score": "0",
"body": "Thanks - you know, I had it setup this way in my users controller and I didn't realize that Devise moves everything to use their registrations_controller. I added \"@categories = @user.categories.all\" to the Devise controller's edit method and page load dropped exponentially! Thanks for pointing me in the right direction."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T07:17:02.043",
"Id": "14247",
"ParentId": "14201",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "14247",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T13:40:40.827",
"Id": "14201",
"Score": "1",
"Tags": [
"performance",
"html",
"mysql",
"ruby-on-rails"
],
"Title": "Allowing users to subscribe to categories"
}
|
14201
|
<p>I’m trying to learn as much as I can on my own by reading lots of examples, documentations, and asking here. I would like to improve my style to write efficient code and adhere to Java standards.</p>
<p>In this small sample of code I would like to get feedback on a few things:</p>
<ul>
<li>Exception throwing</li>
<li>Opening/closing database connection</li>
<li>Any other comments in general style</li>
</ul>
<p>There are two classes, Database and Main.</p>
<p>My Database class:</p>
<pre><code>public class Database {
private String dbName = "";
private SqlJetDb db = null;
public Database(String dbName) {
this.dbName = dbName;
}
public void CreateDatabase() throws SqlJetException {...}
public void OpenDatabaseConnection() throws SqlJetException {...}
public void CloseDatabaseConnection() throws SqlJetException {...}
private void InsertRecord(String file) throws SqlJetException {...}
public void GetDirectoryContent(String dir) {
File directory = new File(dir);
if (directory.isDirectory()) {
String[] content = directory.list();
for (String s : content) {
GetDirectoryContent(dir + "\\" + s);
}
} else {
String file = directory.toString();
String extension = file.substring(file.lastIndexOf("."));
if (extension.equals(".h")) {
try {
InsertRecord(file);
} catch (SqlJetException e) {
e.printStackTrace();
}
}
}
}
}
</code></pre>
<p>Call in main:</p>
<pre><code>Database db = new Database("test.db");
try {
db.CreateDatabase();
db.OpenDatabaseConnection();
db.GetDirectoryContent("C:\\test");
} catch (SqlJetException e) {
e.printStackTrace();
} finally {
try {
db.CloseDatabaseConnection();
} catch (SqlJetException e) {
e.printStackTrace();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T07:51:13.127",
"Id": "22976",
"Score": "0",
"body": "You code is Ok but do you use java 6 or java 7 ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T07:53:09.160",
"Id": "22977",
"Score": "5",
"body": "Besides the logik: Clean code also involves adherence to the coding guidelines. So please name your methods according to the Java standards."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T07:56:21.723",
"Id": "22979",
"Score": "1",
"body": "There is one problem in your code.\nYou should read this http://en.wikipedia.org/wiki/Single_responsibility_principle Class Database shouldn't have file operations. It should be another class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T08:01:59.393",
"Id": "22980",
"Score": "0",
"body": "I think you mean to swap the `GetDirectoryContent` function to a own class, right? I always use `File dbFile = new File(\"test.db\");` in the create and open function, because I use SQLJet to store the records. That one line is ok or should swap this too?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T08:09:27.140",
"Id": "22981",
"Score": "0",
"body": "Yes, database class should only use CRUD operations and execute various sql queries, if you need operations with file system - create special class for it. in main class you can write code to deliver data from one class to another"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T12:15:10.927",
"Id": "22982",
"Score": "0",
"body": "Please see my **Edit**, is this better? I created a new class for the Fileaccess and a method to search and append the files to a `ArrayList` and a getter which `returns` the `ArrayList`. Greetz"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T12:32:24.737",
"Id": "22983",
"Score": "0",
"body": "so now you have separated logic for database and file system, it looks better of course."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T08:13:21.123",
"Id": "22984",
"Score": "0",
"body": "I noticed about your method naming. Perhaps you may want to adhere to the coding convention that sun had defined . You can get the pdf version the copy [here](http://java.sun.com/docs/codeconv/CodeConventions.pdf)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T11:39:08.183",
"Id": "22985",
"Score": "0",
"body": "I read the conding convention, I’m sorry but whats wrong with them? I used verbs which gives a little description about the function. Ok, I missed the first letter lowercase convention , did you mean this? Greetz."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T12:33:39.353",
"Id": "22986",
"Score": "0",
"body": "Yes. Also I thought reading that would be useful in naming conventions and coding conventions in your future programs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T12:38:52.517",
"Id": "22987",
"Score": "0",
"body": "Yep, this pdf is quit nice! I found few new things. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T12:43:38.453",
"Id": "22988",
"Score": "0",
"body": "Great. Happy learning. God bless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T07:54:06.140",
"Id": "22989",
"Score": "1",
"body": "Your exception handling could be improved. Remove the try-catch from the `GetDirectoryContent` method and let that exception bubble up into your `Main` class. Take this as a general guideline—catch as late as possible. But, even before you start entering such details, you must first study the Java Naming Conventions and adhere to them religiously."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T11:00:15.580",
"Id": "23318",
"Score": "2",
"body": "Use a Static Code Review tool like CheckStyle or PMD, which will cover most of the best practices. That way you can learn faster."
}
] |
[
{
"body": "<p>Consider in the following:</p>\n\n<pre><code>public Database(String dbName) {\n this.dbName = dbName;\n}\n</code></pre>\n\n<ol>\n<li>I would check for a null <code>dbName</code> being passed in. Note that you pass this reference and then simply store it. Consequently, if it's null, you won't find out until later (perhaps, <em>much</em> later). You then have to work out at what point that was set to <code>null</code>.</li>\n<li>Will you change <code>dbName</code> ? If not, make it <code>final</code>. It'll stop you changing it inadvertently later on. Immutability is often a good idea. It makes the class more robust and thread-safety easier to achieve. Perhaps not a requirement here, but who knows ? It's easier to relax a restriction rather than apply it after-the-fact.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T08:04:32.560",
"Id": "22990",
"Score": "0",
"body": "Yea, I missing to check if the vaule is `null`. No I will not change, so `final` is better. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T13:45:52.173",
"Id": "22991",
"Score": "0",
"body": "if you are checking for null then I would recommend constructing and IllegalArgumentException and setting the cause of this as NullPointerException. This way you are explicit in what is wrong."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T08:02:23.650",
"Id": "14204",
"ParentId": "14203",
"Score": "6"
}
},
{
"body": "<p>Personally I would</p>\n\n<ul>\n<li>always log rather than use e.printStackTrace. You can log to console if you require. By logging you can then change it easily to file logging and include your own comments</li>\n<li>use File.seperator instead of \\. This gives a system independent way of separating your file paths.</li>\n<li>Consider making dbName final. You do not need to initialise it first and then in the ctor. Just do it in the ctor. Things like dbName should not be mutable.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T12:36:51.783",
"Id": "22992",
"Score": "0",
"body": "Thanks for your reply. Normally I log, just to handle the exception I added `e.printStackTrace`. The `File.separator` is new to me, but very nice to know, thanks. The dbName I changed to `final private String dbName;`. Greetz."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T13:44:21.040",
"Id": "22993",
"Score": "0",
"body": "Hi hofmeister, SUN convention say that is should be private final String dbName with the final after the private. Glad I could help"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T14:21:17.970",
"Id": "22994",
"Score": "0",
"body": "By logging the errors, rather than handling them separately, you can have better control of what gets logged and to where."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T15:15:43.633",
"Id": "22995",
"Score": "0",
"body": "When testing dabasebase you can use `new File(dir+\"/test.db\").delete();` ... After you have to opening it and manage unexpected results."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T12:23:07.687",
"Id": "14205",
"ParentId": "14203",
"Score": "6"
}
},
{
"body": "<p>From <em><a href=\"http://cyclo.ps/books/Prentice.Hall.Effective.Java.2nd.Edition.May.2008.pdf\" rel=\"nofollow\">Effective Java</a></em></p>\n\n<p>At the first glance : </p>\n\n<p>you can put your class <em>final</em></p>\n\n<pre><code>public final class Database {\n</code></pre>\n\n<p>and also the strings like : <br></p>\n\n<pre><code>final String file = directory.toString();\nfinal String extension = file.substring(file.lastIndexOf(\".\"));\n</code></pre>\n\n<p>Remove initialisation of fields : <br></p>\n\n<pre><code>private String dbName;\nprivate SqlJetDb db;\n</code></pre>\n\n<p>Then in <code>public void GetDirectoryContent</code> use <code>Files</code> and <code>Paths</code> from <em><a href=\"http://docs.oracle.com/javase/tutorial/essential/io/fileio.html\" rel=\"nofollow\">new nio.2 java 7 package</a></em></p>\n\n<p>And take care :</p>\n\n<pre><code>finally { // many possible problems\n</code></pre>\n\n<p>Read deeply and read again Joshua Bloch for good code, ... and enjoy yourself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T07:16:06.900",
"Id": "23035",
"Score": "0",
"body": "Why remove private `String dbName;` and `private SqlJetDb db;`? Other functions use this aswell. Or did I missed something? I use Java6, so I cannot use `nio`, right? Greetz."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T07:23:12.070",
"Id": "23036",
"Score": "0",
"body": "You do not have to remove field, but initialization of them, Objects are initalized to `null` at compile time, and `\"\"` String is initialized for nothing. Yes : nio.2 is linked to Java 7, so you cannot use it : it does not matter if you will not use new tools, if not a study to upgrade JVM may be needed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T07:30:23.340",
"Id": "23037",
"Score": "0",
"body": "Fixed `dbName`. But I cannot initialize `SqlJetDb` there is now default consturctor with no parameter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T07:48:29.380",
"Id": "23038",
"Score": "0",
"body": "look comments in http://svn.sqljet.com/repos/sqljet/branches/maven/sqljet/src/main/java/org/tmatesoft/sqljet/core/table/SqlJetDb.java . Constructor(File, boolean) exist, but no default Constructor (not needed). . . . about your smelly problems, all responses are in Effective Java, not easy to understand, but necessary."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T14:43:40.260",
"Id": "14206",
"ParentId": "14203",
"Score": "4"
}
},
{
"body": "<p>First of all, I'd leave the SqlJetException unchecked and not catch it in close method. I hate exceptions in close methods because what am I supposed to do with it? If I could do anything, I've already caught it, but most times it has to be muted <code>catch(xxxx) {}</code>.</p>\n\n<p>I never use printStackTrace.</p>\n\n<p>Does the GetDirectoryContent method insert records? The name is not clear enough, it's supposed to get a directory content, not insert any content. And it returns nothing... I think a better name would be something like </p>\n\n<pre><code>saveContentFrom(String directory)\n</code></pre>\n\n<p>Is this class a public API? If so, I would check for errors like \"this param is null\".</p>\n\n<p>CreateDatabase, OpenDatabaseConnection and CloseDatabaseConnection are public, and you use them in GetDirectoryContent... what would happen if someone creates a database and calls your GetDirectoryContent? I would make those 3 methods private.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T07:12:10.587",
"Id": "23033",
"Score": "0",
"body": "I swaped `GetDirectoryContent` to a own class. Now I open the database connection with the `Database` class. The class which include `GetDirectoryContent` just read the data and append them to a `ArrayList`. Later I insert with the Database class the content of the `ArrayList`. Better? Greetz."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T14:54:18.083",
"Id": "14207",
"ParentId": "14203",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "14205",
"CommentCount": "14",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T07:48:48.380",
"Id": "14203",
"Score": "7",
"Tags": [
"java",
"file-system",
"error-handling",
"database",
"sqlite"
],
"Title": "Storing .h files in SQLite using SQLJet"
}
|
14203
|
<p>I followed <a href="http://tomszuszai.com/content/articles/tutorials/how_to_write_a_simple_sql_factory_in_php" rel="nofollow">this tutorial</a> to create an SQL "factory".</p>
<p>The link shows how to make a class who's methods will output SQL statements based on the arguments you pass to it, and I've expanded on it with the class below.</p>
<p>Basically, as an example of its usage: if you wanted to select from a database you can pass it an array of attributes to select, followed by the table name, and if there are conditions to the select, you pass it an array, where the array key is the column the condition is based on, and the array value is the value of that column - so a simple select would look something like this:</p>
<pre><code>$theAttributes = array('name','age','height')
$theTable = 'people';
$theConditions = array('hair_colour' => 'brown');
$select = $this->executeSelect($theAttributes,$theTable,$theConditions);
</code></pre>
<p>and then <code>$insert[0]</code> would be the number of rows that were selected by the query, and <code>insert[1]</code> would be an array containing each row that was returned as an array.</p>
<p>I'm just wondering if I could get some feedback on it as it seems to work fine for me, but I'm very new to PHP, so some advice such as inefficiency, insecurity, or if it's just plain wrong.</p>
<pre><code>require './config/config.inc.php';
require './config/n_spaces.inc.php';
require_once(__DIR__.'/SqlStatement.php');
require_once(__DIR__.'/MySqlStatement.php');
class PDOdriver {
public $conn;
public function __construct()
{
$db_host = DB_HOST;
$dbname = DB_NAME;
$this->conn = new PDO("mysql:host=$db_host;dbname=$dbname",DB_USER,DB_PASS)
or die('Cannot connect to the server, please inform your Network Administrator');
$this->st = new MySqlStatement();
}
public function executeInsert($theAttributes,$theTable,$theConditions = NULL) {
foreach($theAttributes as $index => $value) {
$bind_params[] = ":$index";
}
if(!isset($theConditions)){
$sqlstmt = trim($this->st->setTables($theTable)->setAttributes(array_keys($theAttributes))->setValues($bind_params)->makeInsert());
}
else {
$sqlstmt = trim($this->st->setTables($theTable)->setAttributes(array_keys($theAttributes))->setValues($bind_params)->setConditions($theConditions)->makeInsert());
}
if($stmt = $this->conn->prepare($sqlstmt)) {
foreach($theAttributes as $index => &$value) {
$stmt->bindParam(":$index",$value);
}
if($stmt->execute()) {
$rowCount = $stmt->rowCount();
$success[0] = $rowCount;
$success[1] = $this->conn->lastInsertId();
return $success;
}
else {
$success[0] = 'Cannot Execute';
$stmt = NULL;
return $success;
}
}
else {
$success[0] = 'Cannot Prepare';
$stmt = NULL;
return $success;
}
}
public function executeSelect($theAttributes,$theTable,$theConditions = NULL,$fetch_style = "FETCH_ASSOC") {
if(is_array($theConditions)) {
foreach($theConditions as $index => $value){
$bind_conditions[] = "$index = :$index";
}
$sqlstmt = trim($this->st->setAttributes($theAttributes)->setTables($theTable)->setConditions($bind_conditions)->makeSelect());
}
elseif(!is_null($theConditions) && !is_array($theConditions)){
$sqlstmt = trim($this->st->setAttributes($theAttributes)->setTables($theTable)->setConditions($theConditions)->makeSelect());
}
else {
$sqlstmt = trim($this->st->setAttributes($theAttributes)->setTables($theTable)->makeSelect());
}
if($stmt = $this->conn->prepare($sqlstmt)) {
if(is_array($theConditions)) {
foreach($theConditions as $index => &$value) {
$stmt->bindParam(":$index",$value);
}
}
if($stmt->execute()) {
$success[0] = $stmt->rowCount();
if($success[0] > 0) {
if($fetch_style === "FETCH_ASSOC") {
while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
$results[] = $result;
}
$success[1] = $results;
}
elseif($fetch_style === "FETCH_BOTH"){
while($result = $stmt->fetch(PDO::FETCH_BOTH)) {
$results[] = $result;
}
$success[1] = $results;
}
elseif($fetch_style === "COUNT"){
}
}
$stmt = NULL;
return $success;
}
else {
$success[0] = 'Cannot Execute';
$stmt = NULL;
return $success;
}
}
else {
$success[0] = 'Cannot Prepare';
$stmt = NULL;
return $success;
}
}
public function executeUpdate($theAttributesColumn,$theAttributesValue,$theTable,$theConditions)
{
if(is_array($theConditions)) {
foreach($theConditions as $index => $value){
$bind_conditions[] = "$index = :$index";
}
$sqlstmt = trim($this->st->setUpdateAttributes($theAttributesColumn, $theAttributesValue)->setTables($theTable)->setConditions($bind_conditions)->makeUpdate());
}
else {
$sqlstmt = trim($this->st->setUpdateAttributes($theAttributesColumn, $theAttributesValue)->setTables($theTable)->makeUpdate());
}
if($stmt = $this->conn->prepare($sqlstmt)) {
if(is_array($theConditions)) {
foreach($theConditions as $index => &$value) {
$stmt->bindParam(":$index",$value);
}
}
if($stmt->execute()) {
$success[0] = $stmt->rowCount();
return $success;
}
else {
$success[0] = 'Cannot Execute';
$stmt = NULL;
return $success;
}
}
else {
$success[0] = 'Cannot Prepare';
$stmt = NULL;
return $success;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Long wall of text incoming. Hope it helps :)</p>\n\n<p>First a comment on your file extensions. PHP doesn't care what a file's extension is, it could be an HTML file, text file, or anything. It's just convention that makes us use \".php\". Eventually it was determined that adding the \".inc\" extension would help distinguish that a file was to be included somehow. We don't have to use this convention, but usually when we do we replace \".php\" with \".inc\". Seeing them together is just a little odd.</p>\n\n<p>Unless it can't be helped, you should avoid using the <code>require/include_once()</code> functions. These are a bit slower than a regular <code>require/include()</code>. It won't make much difference in such a small application, but if you start going crazy with includes later and are using the <code>_once()</code> versions heavily, you will notice a definite drop in performance.</p>\n\n<p>In PHP there are special kinds of \"functions\" called language constructs. These functions are native C Language functions that PHP offers directly, without needing to do anything special with them. Theses constructs are generally indistinguishable from traditional functions. The only difference between them is that they are faster and some allow custom syntax that is different from normal function behavior. Your <code>require()</code> functions are so called constructs. So are <code>include()</code>s, <code>echo()</code>s and quite a few others. The point here is that these constructs, as I previously mentioned, have custom syntax. They can be used the same way that you would use a traditional function, or they can use this custom syntax. This custom syntax allows you to neglect adding parenthesis around the construct's parameters. This is a commonly accepted practice. The reason I bring this up is that you are switching back and forth between the two methods. Generally speaking, you should choose a \"style\" and be consistent with it.</p>\n\n<pre><code>require './config/config.inc.php';\nrequire './config/n_spaces.inc.php';\nrequire_once __DIR__.'/SqlStatement.php';\nrequire_once __DIR__.'/MySqlStatement.php';\n//OR\nrequire('./config/config.inc.php');\nrequire('./config/n_spaces.inc.php');\nrequire_once(__DIR__.'/SqlStatement.php');\nrequire_once(__DIR__.'/MySqlStatement.php');\n</code></pre>\n\n<p>The <code>or die()</code> short-circuiting syntax is usually frowned upon. The \"traditional\" way to do it is to wrap it in an if statement and handle the <code>die()</code> portion a little differently. You could have it redirect, throw an error, log an error, try another solution, connect to a default, any combination, or anything else really. But usually <code>die()</code> is thought of as being a very \"inelegant\" way to approach this. The problem is that many new developers saw this and said, \"Oh boy! A quick and easy way!\" and immediately adopted it. This is fine for development environments, but in a real life applications customers aren't going to want to see a white page with little or no writing on it.</p>\n\n<pre><code>$this->conn = new PDO(\"mysql:host=$db_host;dbname=$dbname\",DB_USER,DB_PASS);\nif( ! $this->conn ) {\n $this->logErr('Cannot connect to the server, please inform your Network Administrator');\n}\n</code></pre>\n\n<p>Adding \"the\" to a variable seems odd and unnecessary. Those variables would mean the same thing if typed more simply as <code>$attributes, $table, $conditions</code>. Words like \"the\" are implied and usually a programmer will add them, or their own favorite placeholder, in the proper place when reading it in their head. This is the hallmark of a beginner programmer who is still trying to make sense of the language by making it read more like plain english. Many of us started off doing this :)</p>\n\n<p>If you need to iterate over an array to read just the keys, then you can use <code>array_keys()</code> and loop over that instead. There is no need to define a variable you aren't going to use. The same goes for iterating over an array to read just the values. So you don't always have to define the keys, or indices, when iterating over an array with a foreach loop.</p>\n\n<pre><code>$attrKeys = array_keys( $theAttributes );\nforeach( $attrKeys AS $index ) {\n</code></pre>\n\n<p>As you progress in learning the PHP language, you will come across some principles or common practices. One of these principles is called the \"Don't Repeat Yourself\" or DRY Principle. This states that you should try to make your code as reusable as possible without redundancies. So when you have a variable you need to define that is mostly the same, and only changes a little based on an if/else statement, or some other requirement, you can set it up to be less redundant. For instance:</p>\n\n<pre><code>$sqlstmt = $this->st->setTables($theTable)->setAttributes(array_keys($theAttributes))->setValues($bind_params);\nif(isset($theConditions)){\n $sqlstmt = $this->st->setConditions($theConditions);\n}\n$sqlstmt = trim( $sqlstmt . $this->st->makeInsert() );\n</code></pre>\n\n<p>Of course, there is another common practice to do with the above code. It's probably a principle, but I don't know it by name if it is. The closest thing I can think of is the \"Single Responsibility\" Principle. Anyways, the specific instance that I'm eluding to here is that one line of code should do just one thing. This is to help ensure that your code doesn't become illegible. So, that long <code>$sqlstmt</code> definition should be broken up into a few different parts to make it more legible. For instance.</p>\n\n<pre><code>$attrKeys = array_keys($theAttributes);//can reuse from that loop I mentioned above\n\n$table = $this->st->setTables($theTable);\n$attributes = $this->st->setAttributes( $attrKeys );\n//careful, $attributes may conflict with $theAttributes if you remove \"the\" as I suggested\n$values = $this->st->setValues($bind_params);\nif(isset($theConditions)){\n $values = $this->st->setConditions($theConditions);\n}\n$sqlstmt = trim( $values . $this->st->makeInsert() );\n</code></pre>\n\n<p>Never assign a variable in a statement. This could lead to problems latter during troubleshooting. PHP made a mistake in allowing this syntax, and continues to allow it. IDE's don't know any better because they know PHP says its valid. If you accidentally forget to add two equals signs \"==\" in a conditional statement you will end up assigning a variable a new value which will cause unexpected results. And, as I just pointed out, your IDE won't know any better because its valid. If you get in the habit of never assigning variables from statements you will know that if you ever see it then you have found your issue. It isn't really foolproof, but it also helps other programmers trying to read your code know where a variable is being declared.</p>\n\n<pre><code>$stmt = $this->conn->prepare($sqlstmt);\nif( $stmt ) {\n</code></pre>\n\n<p>Always define your arrays before using them as arrays. If you don't, you run the risk of changing a string when you really meant to change an array. PHP allows array syntax to be used on strings to access specific characters in a string. For instance in the first part of the following example, <code>$success</code> is a string with the value of \"abc\". When accessed as an array, the \"index\" is actually referring to the string's character at that position. So <code>[0]</code> is \"a\" and <code>[1]</code> is \"b\". And if you change the character at that position, you change the string. So to avoid this we redefine <code>$success</code> as an array before trying to access it as such to ensure that we haven't accidentally used it somewhere else. We also do this because we should anyways. You are probably receiving silent notices here about <code>$success</code> being undeclared before being used. It isn't enough to crash PHP, but they are still errors and should be avoided.</p>\n\n<pre><code>$success = 'abc';\n$success[0] = $rowCount;//$success = $rowCount . 'bc';\n$success[1] = $this->conn->lastInsertId();//$success = $rowCount . $this->conn->lastInsertId() . 'c';\n//Instead\n$success = 'abc';\n//some code that makes you forget you used $success already\n$success = array();\n$success[0] = $rowCount;\n$success[1] = $this->conn->lastInsertId();\n</code></pre>\n\n<p>Another thing to note about the above code. When appending onto an array, you do not need to explicitly define the keys being used unless you wish to change a value that already exists, you are creating an associative array, or you want to start counting from a different position rather than \"0\". If the array <code>$success</code> already exists and we set the value at index \"0\", then we are changing any value that already exists at that index. If we want to be able to access an array value via key, we usually assign it some associative index to define it, this index is usually descriptive and will make it easy to understand what is being accessed, such as an ID. If we want a numerically indexed array, but don't want to start the index at the traditional \"0\" position, we can pass an integer to the first element key we add to the array and all indices that occur after that key will be in sequential order starting from that integer. So, if we simply want to append data onto an array we use the following syntax and the numerical keys will be assigned for us.</p>\n\n<pre><code>$success[] = $rowCount;\n$success[] = $this->conn->lastInsertId();\n</code></pre>\n\n<p>The other two functions appear to be very similar, so the above comments can be used for them too. Eluding back to my comment about DRY. If you find that you are repeating tasks, especially in if/else statements right next to each other, you can make that task into a function to allow for reuse. This will reduce your code size drastically and increase legibility quite a bit too. This isn't just limited to similar if/else statements though. If you have two functions that look very similar you can probably create a third to deal with those similarities. A simple example would be creating a function to create that initial <code>$sqlstmt</code> variable seen as you seem to use it in multiple functions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T20:24:14.553",
"Id": "14227",
"ParentId": "14213",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "14227",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T16:49:01.623",
"Id": "14213",
"Score": "4",
"Tags": [
"php",
"beginner",
"object-oriented",
"sql"
],
"Title": "Efficiently accessing the database"
}
|
14213
|
<p>This is just a program to show the use of conditional variables when two threads are involved. One thread wants a non-zero value of <code>count</code>, and other thread is responsible for signaling it when the count is non-zero.</p>
<p>Is there something in this code which still needs an improvement? Is there something which could have been done in a better way?</p>
<pre><code>#include <iostream>
/* Declaration of a Mutex variable `mutexA`. */
pthread_mutex_t mutexA;
/* Declaration of a Condition Variable `conditionVariableA`. */
pthread_cond_t conditionVariableA;
/* `functionA` and `functionB` are the argument functions of the two threads (declared
below) */
void* functionA (void*);
void* functionB (void*);
/* `count` is the variable shared between threads `A` and `B`.
Thread `A` wants it to be non zero. Thread `B` will be responsible for making it
non-zero and then issuing a signal. */
int count = -100;
int main ()
{
// Declaration of two threads namely `A`, and `B`.
pthread_t A, B;
// Initializing the mutex lock to be shared between the threads.
pthread_mutex_init (&mutexA, NULL);
/* The function `pthread_cond_init()` initialises the Condition Variable referenced by
variable `conditionVariableA` with attributes referenced by variable `attributes`. If
`attributes` is NULL, the default condition variable attributes are used. */
pthread_cond_init (&conditionVariableA, NULL);
/* Definition of two threads namely A and B */
pthread_create (&A, NULL, functionA, NULL);
pthread_create (&B, NULL, functionB, NULL);
pthread_join (A, NULL);
pthread_join (B, NULL);
}
void* functionA (void* argA)
{
while (1)
{
pthread_mutex_lock (&mutexA);
if (count <= 0)
{
std :: cout << "\ngnitiaW!\n";
pthread_cond_wait (&conditionVariableA, &mutexA);
}
else
{
// Do something.
std :: cout << "\nTime to enjoy!\n";
return 0;
}
pthread_mutex_unlock (&mutexA);
}
return 0;
}
void* functionB (void* argB)
{
while (1)
{
pthread_mutex_lock (&mutexA);
count++;
if (count > 0)
{
pthread_cond_signal (&conditionVariableA);
std :: cout << "\nSignaled!\n";
return 0;
}
else
{
std :: cout << "\nNot signaled yet!";
}
pthread_mutex_unlock (&mutexA);
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Couple of issues:</p>\n\n<p>The code is not exception safe.<br>\nAny resource that has an open/close symantic should be handled via RAII</p>\n\n<pre><code>{\n pthread_mutex_lock (&mutexA);\n\n // Code\n // This may throw an exception thus will\n // cause the code to miss the unlock.\n\n pthread_mutex_unlock (&mutexA);\n}\n</code></pre>\n\n<p>To fix this you should us an RAII locker object.</p>\n\n<pre><code>{\n MutexLocker lock(mutexA); // constructor calls lock.\n // detructor calls unlock.\n // Code\n // This may throw an exception\n // and it still works correctly.\n}\n</code></pre>\n\n<p>It may work in this simple example:</p>\n\n<pre><code> if (count <= 0)\n {\n std :: cout << \"\\ngnitiaW!\\n\";\n pthread_cond_wait (&conditionVariableA, &mutexA); \n }\n</code></pre>\n\n<p>But normally you need to place the wait() inside a loop.</p>\n\n<pre><code> while (count <= 0)\n {\n std :: cout << \"\\ngnitiaW!\\n\";\n pthread_cond_wait (&conditionVariableA, &mutexA); \n }\n</code></pre>\n\n<p>If there are multiple threads that could enter this function then between the signal from the producer thread and this thread waking up from the wait another thread could have stolen the object. Thus you need to recheck the state you were waiting for and go back to sleep if it was stolen.</p>\n\n<p>This would have been fixed by the MutexLocker above. But the code as it stands leaves the lock locked.</p>\n\n<pre><code> else\n {\n // Do something.\n std :: cout << \"\\nTime to enjoy!\\n\";\n\n // You are returning early without unlock the lock.\n // This causes all your other threads to stall\n // and probably causes deadlock.\n return 0;\n }\n\n // This point is not reached if you return early.\n pthread_mutex_unlock (&mutexA);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T18:22:05.427",
"Id": "14221",
"ParentId": "14214",
"Score": "10"
}
},
{
"body": "<p>A few years later, C++11 solves all of the problems <a href=\"https://codereview.stackexchange.com/a/14221/31292\">Loki</a> pointed out in a much cleaner way. Your mutex and condition variable become:</p>\n\n<pre><code>std::mutex mutexA;\nstd::condition_variable conditionVariableA;\n</code></pre>\n\n<p>Handling holding a lock through a scope shold use one of the two standard locks, depending on whether you need to unlock it. In <code>functionB()</code>, you don't need to unlock:</p>\n\n<pre><code>while (1)\n{\n std::lock_guard<std::mutex> lk(mutexA);\n\n count++;\n\n if (count > 0)\n {\n conditionVariableA.notify_one();\n std :: cout << \"\\nSignaled!\\n\";\n return 0;\n }\n else\n {\n std :: cout << \"\\nNot signaled yet!\";\n }\n} \n</code></pre>\n\n<p>Whereas in the other, you do, so you use a different lock:</p>\n\n<pre><code>while (1)\n{\n std::unique_lock<std::mutex> lk(mutexA);\n\n if (count <= 0)\n {\n std::cout << \"\\ngnitiaW!\\n\";\n conditionVariableA.wait(lk, mutexA);\n }\n else\n {\n // Do something.\n std::cout << \"\\nTime to enjoy!\\n\";\n return 0;\n }\n}\n</code></pre>\n\n<p>Threads are easier too:</p>\n\n<pre><code>std::thread A(functionA);\nstd::thread B(functionB);\n\nA.join();\nB.join();\n</code></pre>\n\n<p>And neither function has to return a <code>void*</code> anymore. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-30T19:16:29.960",
"Id": "115451",
"ParentId": "14214",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "14221",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T16:53:06.267",
"Id": "14214",
"Score": "5",
"Tags": [
"c++",
"synchronization",
"pthreads"
],
"Title": "Maintaining a count with two threads using conditional variables"
}
|
14214
|
<p>I'm only just beginning in programming. </p>
<p>The goal of the program is to check to make sure images are properly rendered within a program(within a VM)</p>
<p>. Below is the code, and I am asking what I can do to clean it up.</p>
<p>I don't think you can tell much without the .png's, but I would appreciate it if anyone knows where/how I can optimize my code.</p>
<p>Thank you very much for any help,</p>
<pre><code>var=(0) #Empty Variable
jpgl=0 #NUMBER PASSES
vm = App("C:\Program Files (x86)\VMware\VMware Workstation\\vmware.exe")
switchApp("vm")
reg=( )
reg.find( )
#------------------------------------
#BEGINNING SPECIAL CASES/NAVIGATION
if not exists( ):
switchApp("vm")
type(Key.BACKSPACE)
onAppear( ,type(Key.BACKSPACE))
if exists( ):
click( )
#if exists( ):#attempt to get rid of.
# click( )
else:
exists( )
click( )
exists( )
click( )
wait(1)
if not exists ( ):#if the image hasn't already loaded, wait the maximum 5 seconds
wait(5)
#END FOLDER NAVIGATION
#----------------------------------
#BEGIN IMAGE CHECK 1
if not exists ( ):
print("B-JPEG_L-20.jpg not displayed correctly")
if exists( ):
print("B-JPEG_L-20.jpg Unable to play")
click( )
else:
jpgl=jpgl+1#if the image exists, it moves on by clicking "next"
click( )
wait(1)
if not exists ( ):
wait(5)
#DONE IMAGE CHECK 1
#----------------------------------
#BEGIN IMAGE CHECK 2
.....
#end code
</code></pre>
|
[] |
[
{
"body": "<p>One way to get started improving your script is to find repeated code, then create a function to hold it.</p>\n\n<p>For example, if your code starting with #BEGIN IMAGE CHECK 1 is duplicated for subsequent image checks, it could become a function that takes a Sikuli image file name - define it somewhere near the top of your file (NOTE: This assumes the same image filename is used consistently across this entire chunk of code, which may not be true in your unedited code):</p>\n\n<pre><code>def check_image(image_filename):\n if not exists(image_filename):\n print(\"%s not displayed correctly\" % image_filename)\n if exists(image_filename):\n print(\"%s Unable to play\" % image_filename)\n click(image_filename)\n else: \n jpgl = jpgl + 1 \n click(image_filename)\n wait(1) \n if not exists (image_filename):\n wait(5) \n</code></pre>\n\n<p>Then below that you can call the function with:</p>\n\n<pre><code>check_image('foo.jpg')\n</code></pre>\n\n<p>Then you should have a starting point for incrementally refining your code. At some point creating a class to hold your test logic could be useful as well.</p>\n\n<p>I recommend reading up on functions and classes in Python - solid knowledge in those areas really helps out with Sikuli development:</p>\n\n<p><a href=\"http://docs.python.org/tutorial/controlflow.html#defining-functions\" rel=\"nofollow\">http://docs.python.org/tutorial/controlflow.html#defining-functions</a></p>\n\n<p><a href=\"http://docs.python.org/tutorial/classes.html#tut-classes\" rel=\"nofollow\">http://docs.python.org/tutorial/classes.html#tut-classes</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T00:36:03.187",
"Id": "14279",
"ParentId": "14215",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T20:26:49.303",
"Id": "14215",
"Score": "4",
"Tags": [
"python"
],
"Title": "How do I refine my code in Sikuli? Seems very long and redundant"
}
|
14215
|
<p>First of all, I came up with that question on SO already. But I am offered different solution which are "better" in some ways. The goal is to improve this specific version, not to create another one.</p>
<p>Here is what it is about:</p>
<p>Reading <em>Coding Horror</em>, I just came across the FizzBuzz another time. The original post is <a href="http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html" rel="nofollow">here</a>.</p>
<p>I just started to code it down. It was a job of a minute, but there are several things that I do not like.</p>
<pre><code>public void DoFizzBuzz()
{
var combinations = new Tuple<int, string>[]
{
new Tuple<int, string> (3, "Fizz"),
new Tuple<int, string> (5, "Buzz"),
};
for (int i = 1; i <= 100; i++)
{
bool found = false;
foreach (var comb in combinations)
{
if (i % comb.Item1 == 0)
{
found = true;
Console.Write(comb.Item2);
}
}
if (!found)
{
Console.Write(i);
}
Console.Write(Environment.NewLine);
}
}
</code></pre>
<p><strong>So my questions are:</strong></p>
<ol>
<li>How to get rid of the <code>bool found</code>? </li>
<li>Is there a better way of testing than the <code>foreach</code>?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T18:15:01.877",
"Id": "23014",
"Score": "2",
"body": "Here's a way: http://code.google.com/p/fizzbuzz/"
}
] |
[
{
"body": "<p>Since you are printing at the same time as you are trying to figure out if it was found, then no, you cannot. If you do not mind using higher level approach such as Linq, then here is my version below. It just might be a tad faster for large number of combinations if <code>Console.Write</code> and <code>Console.WriteLine</code> are slow.</p>\n\n<pre><code>namespace FizzBuzzTest\n{\n using System;\n using System.Diagnostics.Contracts;\n using System.IO;\n using System.Linq;\n\n public static class FizzBuzz\n {\n private static readonly Tuple<int, string>[] combinations = new[] \n { \n new Tuple<int, string> (3, \"Fizz\"), \n new Tuple<int, string> (5, \"Buzz\"), \n };\n\n public static void PrintFizzBuzz(\n TextWriter textWriter = Console.Out,\n int start = 1,\n int end = 100)\n {\n foreach (string value in GenerateFizzBuzz(start: start, end: end))\n {\n textWriter.Writeline(value);\n }\n }\n\n public static IEnumerable<string> GenerateFizzBuzz(\n int start = 1,\n int end = 100)\n {\n Contract.Requires(start >= 0, \"Negative start value is not allowed.\");\n Contract.Requires(end >= 0, \"Negative end value is not allowed.\");\n Contract.Requires(start > end, \"Start must be greater than end.\");\n\n for (int i = start; i <= end; i++)\n {\n var humanReadableTokens = from cmb in combinations\n where i % cmb.Item1 == 0\n select cmb.Item2;\n string humanReadableStr = String.Concat(humanReadableTokens);\n yield return humanReadableStr == String.Empty ? i.ToString() : humanReadableStr;\n }\n }\n\n public static int Main(string[] args)\n {\n PrintFizzBuzz();\n\n // PrintFizzBuzz(textWriter: Console.Error);\n\n // Or you can create your own subclass of TextWriter which gives you the ability to read and clear its buffer if you want to test FizzBuzz.\n // var testWriter = new testTextWriter();\n // PrintFizzBuzz(textWriter: testWriter);\n // Assert somethng about testWriter.Buffer\n // testWriter.ClearBuffer();\n // Reuse the testWriter object for further testing. \n\n // Or you could take the values in from command line if there are exactly two integers.\n // Parse(...);\n // DoFizzBuzz(start: start, end: end);\n\n return 0;\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T05:44:23.847",
"Id": "23107",
"Score": "0",
"body": "Nice idea. LINQ definitly helps here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T21:27:33.053",
"Id": "23153",
"Score": "0",
"body": "this suggestion may be OTT, but my only suggestion would be to pull out the UI logic (console writeline) and perhaps provide another parameter callback that could handle this? Doing this could even then allow for a bit of Unit testing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T21:47:22.047",
"Id": "23155",
"Score": "0",
"body": "@dreza, I would not put this code in the production hence I would not test it, but yeah, it is not hard to modify it to allow for testing, so check out the revised version. I like my approach better than the one with callbacks because I had to make fewer modification to the core code, and yet tests are now easy to write. http://blog.objectmentor.com/articles/2009/06/05/rich-hickey-on-testing"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T23:18:27.737",
"Id": "23158",
"Score": "0",
"body": "@Leonid yes, I like it. The GenerateFizzBuzz method is completely isolated from how it's going to be used and even better doesn't have that extra parameter like I originally suggested."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T20:25:08.373",
"Id": "14228",
"ParentId": "14216",
"Score": "2"
}
},
{
"body": "<p>*<strong><em>this post has been heavily modified since it was originally written since I was in a foul mode when I wrote the original post, if any comments seem weird or out of place it's most likely due to this editing</em>*</strong></p>\n\n<p>You are clearly moving away from what I would call the \"clean and simple\" approach with your solution. From your description I understand it as if this is how you would solve the problem, given that someone asked you to do it for an interview.</p>\n\n<p>I strongly believe that your solution is overcomplicated for this problem, and too many assumptions are made on your side on how the problem will evolve in the future. Doing stuff like this is in contradiction to the software principle called <strong>KISS (keep it simple stupid)</strong>, and due to these \"assumptions\" you are making it harder to read, understand and change the code. </p>\n\n<p>I will post the original/clean solution that I think is much better suited for this problem, and then I'll follow up with a short description of why I think the \"clean\" solution is better than yours.</p>\n\n<h1>Clean Solution:</h1>\n\n<pre><code>for(int i=0; i <= 100; ++i) {\n string s = \"\"\n\n if(i%(5*3) == 0) {\n s = \"FizzBuzz\";\n } else if (i % 3 == 0) {\n s = \"Fizz\";\n } else if (i % 5 == 0) {\n s = \"Buzz\";\n } else {\n s = i.ToString();\n }\n\n Console.WriteLine(s)\n}\n</code></pre>\n\n<p>In the clean solution, it is clear what is happening and what values we check for [even the 5*3-value], in your solution you hide away the only thing interesting in this code (the replacement of strings for numeric values). </p>\n\n<p>You make it harder to grasp what is happening by placing the values and the strings into an <strong>unnecessary Tuple-object</strong> and hide these important values behind something called \"comb.item1\" and \"comb.item2\".</p>\n\n<p>The only time your solution would make sense is if it's known that the next iteration would require 25 replacements in similar fashion (7=\"Foo\", 11=\"Bar\", 77=\"FooBar\"). However, then you would still run into problems and have to handle the \"multiple match\"-issue in another way [f.e. 3*5*7].</p>\n\n<p>The entire idea with programming is to keep the code as easy/clean as possible [good book: Martin Fowler - Clean Code] and avoid making \"smart solutions\" when it is not known what to expect next. Writing <strong>overly complicated solutions is something that would make warning bells go off for any recruiter</strong>.</p>\n\n<p>Your solution makes it easy to add more replacements, but next iteration might as well be:</p>\n\n<p><em>replace anything dividable with 9 with 'bazzinga' and then don't bother with fizz and buzz. Unless program is running on a Sunday, Sundays are as everyone knows 'Happy Sunday Sharing'-day, and string should then read 'FizzySundayBuzz' or 'FizzySunday'.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T09:16:59.277",
"Id": "23044",
"Score": "4",
"body": "-1: aggressive language only makes you sound silly; if you have trouble understanding OP's simple-enough code then I think you are in no position to offer alternatives; I don't believe that someone capable of writing the question's code is incapable of writing what you wrote."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T09:27:42.430",
"Id": "23046",
"Score": "2",
"body": "KISS certainly has its place, but that's not the question here. Presumably, the OP wrote the code the way he did because he expected that more cases will be added in the future."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T10:23:23.007",
"Id": "23050",
"Score": "1",
"body": "ANeves: you are right, sorry for language. But I see these overly complicated solutions all the time. and nowhere in his description does it claim why he decides to do it in a complicated way.\n\n\nsvick: and that's my point exactly, why make it harder at this point and assume that it will evolve in that particular manner? That assumption is what makes code hard to maintain. Next iteration is just as likely to state \"when a multiple of 9 is found, you should only write 'bazzinga', unless it's also a Sunday, then you write 'godspeed' and the original rules regarding fizz and buzz applies."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T15:11:25.553",
"Id": "23057",
"Score": "2",
"body": "Agreed that I'd adopt the simpler technique such as applied here. At the same time, I think it a useful exercise to write a version that uses a data list like that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T05:36:56.150",
"Id": "23105",
"Score": "0",
"body": "My version is what first evolved from the KISS version. I wanted to factor out all magic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T10:44:28.370",
"Id": "23117",
"Score": "2",
"body": "This is obviously a learning exercise for the OP (and the rest of us, including you). Rather than coming across as offensive, why not add to the discussion in a positive way? Your solution could also use some work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T12:33:08.643",
"Id": "23124",
"Score": "0",
"body": "Thank you dreza and Oj, I'll make sure to edit my post once I'm on a computer and improve on the simple solution to contain the appropriate if, else if, else if, else structure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T08:29:20.073",
"Id": "23167",
"Score": "0",
"body": "Minus the bits about it being a joke and not being able to understand it, I would give this a +1. But with those in place, the best I can do is not to downvote. Keep It Simple Stupid is a good principle, and worth repeating even in a case like this where the point is to explore alternative methods which could be more generically useful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T21:16:01.940",
"Id": "23231",
"Score": "0",
"body": "@DanielMesSer +1 After your edits I feel that's a much more constructive approach to a code review process."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T22:40:28.240",
"Id": "23234",
"Score": "1",
"body": "Lesson learned here. Don't be an ass to others just because you're in a \"foul mood\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T18:34:37.340",
"Id": "64610",
"Score": "0",
"body": "Mental exercises are fun but each time you are about to generalize something, think, **will we really add more conditions with different constants in the future?** For FizzBuzz, obviously, no. +1"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T22:25:52.443",
"Id": "14233",
"ParentId": "14216",
"Score": "3"
}
},
{
"body": "<p>While I think making the code table driven is a reasonable idea, I think you're doing that (mostly) the wrong way.</p>\n\n<p>If you're going to go beyond the obvious solution (e.g., @DanienMeSer's), you should <em>accomplish</em> something by doing so. The obvious problems (IMO) with the original code are that it's not very extensible (e.g., if you had 50 cases instead of three, you'd probably need to rewrite entirely), and it doesn't separate concerns very well (e.g., the logic and the I/O are quite tightly intermingled).</p>\n\n<p>At least IMO, the key here is ensuring that each function (including <code>main</code>) has a clearly defined purpose and layer of abstraction at which it operates. If it delegates <em>everything</em> to lower layers, then it's not doing anything to justify its own existence. At the opposite extreme, doing everything in one layer/function means you're not actually using functions, classes, etc., to keep the code simple and manageable.</p>\n\n<p>With that idea in mind, I'd start by thinking about what the ideal top-level code would look like, then write the lower layers to support that. In this case, it seems to me that it makes sense for the top layer to generate inputs, and write out the result for each:</p>\n\n<pre><code>for (int i=start; i<end; i++)\n console.WriteLine(fizzbuzz(i));\n</code></pre>\n\n<p>That's pretty simple, <em>but</em> it still accomplishes something useful: it generates inputs, writes outputs, and isolates logic from I/O. This is a decided contrast to a <code>Main</code> that just contains a single function call to <code>doEverything();</code> (usually under some other name) that just forces the reader to navigate through more code before they find anything meaningful.</p>\n\n<p>From there, we obviously need to define the <code>fizzbuzz</code> function to do the dirty work:</p>\n\n<pre><code>string fizzbuzz(int i) {\n // logic here\n}\n</code></pre>\n\n<p>We have two choices for implementing that. One is mostly monolithic, but still make use of your table to produce the values:</p>\n\n<pre><code>string fizzbuzz(int i) {\n string ret;\n foreach (var comb in combinations) {\n if (i % comb.Item1 == 0)\n ret += comb.item2;\n }\n if (ret.Length() == 0)\n ret = i.toString();\n return ret;\n}\n</code></pre>\n\n<p>Personally, I think I'd break that up into two pieces though: one that's a simple map from multiple of 3/5 to \"fizz\"/\"buzz\", and the other to provide a default value in case the first \"fails\":</p>\n\n<pre><code>string check_mult(int i) {\n string ret = new String();\n foreach (var comb in combinations) {\n if (i % comb.Item1 == 0)\n ret += comb.item2;\n }\n return ret;\n}\n</code></pre>\n\n<p>...then the second, with the full <code>fizzbuzz</code> logic, which is now pretty trivial:</p>\n\n<pre><code>string fizzbuzz(int i) {\n string ret = check_mult(i);\n if (ret.length() == 0)\n ret = i.toString();\n return ret;\n}\n</code></pre>\n\n<p>I'd note that these also give us some building blocks that at least at first blush look like they stand at least a little chance of being <em>useful</em>. One maps multiples of arbitrary numbers to arbitrary strings, and another attempts to map numbers to strings, with a default of mapping the input directly to a string if the first fails.</p>\n\n<p>If you wanted to make this a bit more generic, you'd put just a bit more of the logic into the table, so the first element in the <code>tuple</code> was an object instead of just a value. Then instead of dealing only with multiples of specified values, you could deal with an arbitrary function of an input value. I'll leave that modification for somebody else to deal with though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T05:41:00.997",
"Id": "23106",
"Score": "0",
"body": "breaking this into multiple pieces is a very good starting point. Having a simple function to achieve what is wanted definitly makes the difference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-16T05:25:17.087",
"Id": "108901",
"Score": "0",
"body": "In check_mult, ret needs to be initalized to string.Empty, otherwise you return a null...and then the ret.Length throws a null reference exxception."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-16T06:50:59.797",
"Id": "108904",
"Score": "0",
"body": "@jmoreno: Oops, quite right. I should have remembered that Java makes you do everything manually, but I've gotten spoiled by years of C++, where such things happen automatically."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T00:12:57.827",
"Id": "14278",
"ParentId": "14216",
"Score": "7"
}
},
{
"body": "<p>I think if you're going to set up a set of data to iterate over you should start thinking more functionally. Why not use an array of functions and aggregate over them instead? That puts the logic in the functions, not in the function that utilises the data.</p>\n\n<p>For example:</p>\n\n<pre><code>static void Main(string[] args)\n{\n var generators = new Func<string, int, string>[]\n {\n (s, i) => i % 3 == 0 ? s + \"Fizz\" : s,\n (s, i) => i % 5 == 0 ? s + \"Buzz\" : s,\n (s, i) => s ?? i.ToString()\n };\n var results = Enumerable.Range(0, 100).Select(i => generators.Aggregate((string)null, (s, f) => f(s, i))).ToList();\n results.ForEach(Console.WriteLine);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T16:33:41.113",
"Id": "23136",
"Score": "0",
"body": "This is pretty cool, but if you had a lot of suffixes, then spelling `var generators` in code would take much more space than just typing out the data. Lisp has macros for that; perhaps one can utilize T4 transforms to generate the code for C#, though just about anything other than the most trivial code is an overkill for C#."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T23:09:06.460",
"Id": "23213",
"Score": "1",
"body": "The idea of using T4 for anything like this makes me nauseous. I can't see how typing those generates out is any worse than typing the data. The data alone doesn't define intent and is incapable of capturing the need to conditionally output the number if noting else was outputted. Instead, that logic has to live in the code that parses the data. Ultimately it doesn't matter too much. This is nothing but a mind exercise with a goal to learn. This is why I posted an alternative method in the first place."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T01:22:16.993",
"Id": "24699",
"Score": "0",
"body": "You're welcome. Glad to see you enjoyed it. I think that approaching problems like this with a more functional mindset (rather than imperative) leads you to more elegant solutions. They're often more concise too. Cheers!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T10:11:15.933",
"Id": "14288",
"ParentId": "14216",
"Score": "11"
}
},
{
"body": "<p>First of all I think Daniel MesSer have made some strong points although if you are going for something simpler and more readable I think this approach is even more easy to read:</p>\n\n<pre><code>for(int i = 1; i <= 100; i++) \n{\n string output = null;\n\n if (i % 3 == 0)\n {\n output += \"Fizz\";\n }\n\n if (i % 5 == 0)\n {\n output += \"Buzz\";\n }\n\n if (output == null)\n {\n output = i;\n }\n\n Console.WriteLine(output);\n}\n</code></pre>\n\n<p>Although it is possible to replace the last if with the ?? operator, this is the most readable version, in my opinion.</p>\n\n<p>If there are compelling reasons to introduce a table we could use more or less the same solution. The advantage with this solution is that I've gotten rid of the bool but instead I use a variable that holds the printout for each number. Another benefit of this solution is that I only need to have one call to Console.WriteLine instead of multiple calls to Console.Write / WriteLine embedded in the logic.</p>\n\n<pre><code>var combinations = new Tuple<int, string>[] \n{ \n new Tuple<int, string> (3, \"Fizz\"), \n new Tuple<int, string> (5, \"Buzz\"), \n};\n\nfor (int i = 1; i <= 100; i++)\n{\n string output = null;\n\n foreach (var comb in combinations)\n {\n if (i % comb.Item1 == 0)\n {\n output += comb.Item2;\n }\n }\n\n if (output == null)\n {\n output = i.ToString();\n }\n\n Console.WriteLine(output);\n}\n</code></pre>\n\n<p>You could get rid of the foreach and replace it with a LINQ expression but i doubt that the majority would find it easier to read.</p>\n\n<pre><code>var combinations = new Tuple<int, string>[] \n{ \n new Tuple<int, string> (3, \"Fizz\"), \n new Tuple<int, string> (5, \"Buzz\"), \n};\n\nfor (int i = 1; i <= 100; i++)\n{\n string output = combinations.Where(combination => i % combination.Item1 == 0)\n .Aggregate((string)null, (sum, value) => sum += value.Item2);\n\n if (output == null)\n {\n output = i.ToString();\n }\n\n Console.WriteLine(output);\n}\n</code></pre>\n\n<p>For fun, why not make the whole thing unreadable by making it into a single LINQ expression:</p>\n\n<pre><code>var combinations = new Tuple<int, string>[] \n{ \n new Tuple<int, string> (3, \"Fizz\"), \n new Tuple<int, string> (5, \"Buzz\"), \n};\n\nEnumerable.Range(1, 100)\n .Select(i => combinations.Where(combination => i % combination.Item1 == 0)\n .Aggregate((string)null, (sum, value) => sum += value.Item2) ?? i.ToString())\n .ToList()\n .ForEach(Console.WriteLine);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T17:46:38.627",
"Id": "23588",
"Score": "0",
"body": "+1 for clearly illustrating the plunge into absurdity. I'm reminded of the anecdote where the boss says \"Jane is not such a good programmer, she never tackles difficult problems. Her solutions are too simple.\""
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T23:21:26.710",
"Id": "14515",
"ParentId": "14216",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "14288",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T17:59:15.107",
"Id": "14216",
"Score": "6",
"Tags": [
"c#",
"optimization",
"interview-questions",
"fizzbuzz"
],
"Title": "Writing FizzBuzz"
}
|
14216
|
<p>I am having difficulty deciding how to implement an exception handling strategy.</p>
<p>I am using an observer pattern to allow "plugin" programmers to subscribe to <code>Message</code>s. These subscribers generally log a unique error (and do some other stuff) under an exceptional circumstance during handling the message. The code snippet below is an example of what a common implementation (and its interface) looks like:</p>
<pre><code>// API interface
interface IMessageListener {
void onMessage(Message m);
}
class StuffMessageListener implements IMessageListener {
...
@Override void onMessage(Message m) {
try {
Stuff s = stuffDAO.getStuff(..); // throws SQLException
...
m.reply(true);
} catch (SQLException e) {
// if an exception happens, log it, and reply to the message
log.error(A_UNIQUE_ERROR_CODE, e);
m.reply(false);
}
}
}
</code></pre>
<p>What irks me is that the catch block has become very redundant code, copied throughout 95% of the ~50 existing listeners. Can we come up with something better?</p>
<p>A good solution should:</p>
<ul>
<li>be easy to use/understand for an amateur programmer</li>
<li>keep the programmer aware of the existence/potential of exceptions</li>
<li>minimize the chance of a programmer accidentally "swallowing" an exception</li>
<li>reduce the amount of "boilerplate" code</li>
</ul>
<p>There is a subtle requirement needed for the solution. The <code>UNIQUE_ERROR_CODE</code> should be unique across all <strong>declarations</strong> of the listeners. That way, I could gain statistics based upon where the error was caught across all listeners.</p>
<p>If the <code>UNIQUE_ERROR_CODE</code> is buried underneath an abstract class, or is used outside <code>onMessage(..)</code>, I will lose the needed "uniqueness."</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T17:40:23.097",
"Id": "23007",
"Score": "0",
"body": "What does `m.reply(boolean)` do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T17:42:18.553",
"Id": "23008",
"Score": "0",
"body": "It signals to the sender of the message that the handling was (un)successful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T17:44:46.090",
"Id": "23009",
"Score": "0",
"body": "Why not make it assume by default that it was unsuccessful?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T17:47:03.980",
"Id": "23011",
"Score": "0",
"body": "Thx for the suggestion @NickODell. I could use that strategy and add a `suppressReply()` method, but I'm not sure how much I like that.. The reason for this new method is because in some cases, the message should not be replied to."
}
] |
[
{
"body": "<h1>Allow throwing exceptions</h1>\n\n<p>Do you really think your user is capable of handling all the exceptions?</p>\n\n<pre><code>interface IMessageListener {\n void onMessage(Message m) throws Exception;\n}\n</code></pre>\n\n<p>Of course if some plugin wants to handle the exception, nothing prevents he/she of using <code>try/catch</code>. But no one is forced to do so and if, according to your knowledge, the <code>catch</code> block is almost always the same, put it outside in the code calling <code>onMessage()</code>.</p>\n\n<h1>Give your user a simplified adapter</h1>\n\n<pre><code>abstract class ThrowingMessageListenerAdapter implements IMessageListener {\n\n @Override\n public void onMessage(Message m) {\n try {\n doOnMessage(m);\n } catch (SQLException e) {\n // if an exception happens, log it, and reply to the message\n log.error(A_UNIQUE_ERROR_CODE, e);\n m.reply(false);\n }\n }\n\n protected abstract void doOnMessage(Message m) throws Exception;\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T20:50:33.137",
"Id": "23016",
"Score": "0",
"body": "I really like this answer. However, there is a fixed requirement that the user must not throw a exception in the `onMessage()` (like JMS). Please check my update to know why the adapter solution will not preserve unique error codes."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T17:45:34.810",
"Id": "14218",
"ParentId": "14217",
"Score": "9"
}
},
{
"body": "<p>best thing would be to</p>\n\n<p>implement <code>getStuff</code> method with Message m as a parameter to it.\nThis way you can catch the exception inside your method which set</p>\n\n<pre><code>m.reply(true) or m.reply(false)\n</code></pre>\n\n<p>inside your code\nitself making it easier for others to use it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T17:55:11.383",
"Id": "23012",
"Score": "0",
"body": "Side effects should be avoided, not encouraged."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T17:46:03.460",
"Id": "14219",
"ParentId": "14217",
"Score": "0"
}
},
{
"body": "<p>This looks like a good place to use an abstract class instead of an interface:</p>\n\n<pre><code>abstract class MessageListener{\n void onMessage(Message m){\n try{ onMessageLogic(m); }\n catch(Exception e){ ... }\n }\n abstract void onMessageLogic(Message m) throws Exception;\n}\n\nclass StuffMessageListener extends MessageListener{\n onMessageLogic(Message m) throws Exception{ \n /* possibly exception-raising code here */ \n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T17:48:30.340",
"Id": "14220",
"ParentId": "14217",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "14218",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T17:37:38.727",
"Id": "14217",
"Score": "5",
"Tags": [
"java",
"exception-handling"
],
"Title": "Allowing \"plugin\" programmers to subscribe to messages"
}
|
14217
|
<p>I wrote / modified two scripts to count Facebook and Twitter reactions. Anything I can do to improve these?</p>
<p>Count Facebook Reactions</p>
<pre><code> class FacebookReactions
{
public $url;
function __construct($url)
{
$query = 'SELECT like_count, total_count FROM link_stat WHERE url="'.$url.'"';
$apifql="https://api.facebook.com/method/fql.query?format=json&query=".urlencode($query);
$json=file_get_contents($apifql);
$fb_obj=json_decode($json);
$fb_array=object_2_array($fb_obj);
$this->total = $fb_array[0]['total_count'];
$this->like = $fb_array[0]['like_count'];
}
}
</code></pre>
<p>Count Twitter Reactions</p>
<pre><code> class TwitterReactions
{
public $url = '';
public $output = array();
public $count = 0;
public $total = 100;
function __construct($url,$total)
{
$this->url = $url;
$query = 'http://search.twitter.com/search.json?q='.$url.'&result_type=mixed&rpp='.$total;
$reactions=file_get_contents($query);
$reactions_array=json_decode($reactions, TRUE);
foreach($reactions_array as $key => $results)
{
if(is_array($results)){
foreach($results as $key => $result){
$this->output[$key]['user'] = $result['from_user'];
$this->output[$key]['image'] = $result['profile_image_url'];
$this->output[$key]['message'] = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a href=\"\\0\">\\0</a>", $result['text']);
$this->output[$key]['date'] = date('m.d.y',strtotime($result['created_at']));
}
}
}
$this->count = count($this->output);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Both classes have undefined or unused class properties. The first class does not use the <code>$url</code> property and never defines the <code>$total</code> or <code>$like</code> properties. The second class just doesn't use the <code>$total</code> property. If these properties really aren't being used, then you can just remove them from the class. However, if you meant to use them, then you will have to do so using the following syntax: <code>$this->url</code>.</p>\n\n<p>PHP will soon be deprecating default method types. In other words, methods must be explicitly defined as <code>public</code>, <code>private</code>, or <code>protected</code>. Right now they are all public by default, but there's no telling how long that will last. Plan for the future and start defining them now so you won't have to later.</p>\n\n<p>I'm not sure where the <code>object_2_array()</code> function is coming from as this is not a function included in the default PHP library. If you are just trying to get the JSON object into an array, then you can do the same thing you did for your twitter JSON object and set the second parameter of <code>json_decode()</code> to TRUE.</p>\n\n<p>Instead of explicitly defining the first array index, just shift the first element off the initial array. Makes it a little more pleasant to read and removes ambiguity as to where the \"0\" index came from. If you don't want to modify the existing array, you can just assign the value of the first array element to a different variable. However, as it stands this does not appear to matter as the initial array is not being used anyways. Both methods are shown below.</p>\n\n<pre><code>$results = $fb_array[0];\n//OR\n$results = array_shift( $fb_array );\n\n$this->total = $results['total_count'];\n$this->like = $results['like_count'];\n</code></pre>\n\n<p>When using foreach loops to iterate over an array, it is not always necessary to define the array key as a parameter, only if you are planning on using that value. So, on your first foreach loop in the twitter constructor you can remove the <code>$key =></code> bit as it is unnecessary. Also, keep in mind, it is usually a bad idea to overwrite a variable and should be avoided if not explicitly meant. Even though it is unused, you are overwriting your first <code>$key</code> variable with the second foreach loop. This is bad practice as it could lead to mistakes later. If you need another <code>$key</code> variable you can call it <code>$key2</code> and the first <code>$key1</code>, or keep the first as it is and call the second key <code>$index</code>. Or anything else really, just so long as it makes sense.</p>\n\n<p>With all that being said, I don't think it was necessary to create these as classes. These are simple enough to where you could have more easily created these procedurally. Additionally, please make sure code you submit for review is functional. As it stands, many of these errors looks like they could have been made from copy-pasting code together.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T21:00:31.520",
"Id": "14230",
"ParentId": "14225",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T19:49:52.360",
"Id": "14225",
"Score": "2",
"Tags": [
"php",
"facebook"
],
"Title": "Counting Facebook and Twitter Reactions"
}
|
14225
|
<p>I am writing a WPF application that needs to access information from a database (I am currently using Entity Framework code first, so data access is via <code>DbContext</code>). </p>
<p>My ViewModels directly instantiate my <code>DbContext</code> derived class and query this to obtain the information they require. I understand that this is bad for the following reasons:</p>
<ul>
<li>My ViewModel now has a dependency on <code>DbContext</code>. </li>
<li>my viewModel is more difficult to test.</li>
<li>It will be difficult to switch to a different data provider if required e.g. <code>ObjectContext</code> instead of <code>DbContext</code>.</li>
</ul>
<p>The common solution I have seen to this problem is to define a repository to keep my ViewModels unaware of which data access technology I am using.</p>
<p>I have defined the following generic repository class:</p>
<pre><code>public interface IRepository<T>
{
IEnumerable<T> GetAll();
IEnumerable<T> Find(Expression<Func<T, bool>> where);
// other data access methods could also be included.
void Add(T entity);
void Attach(T entity);
void Delete(T entity);
}
</code></pre>
<p>My concrete repository looks like this:</p>
<pre><code>public class Repository<T> : IRepository<T> where T : class
{
private DbSet<T> _entitySet;
public Repository(DbContext context)
{
if (context == null)
throw new ArgumentNullException("context");
_entitySet = context.Set<T>();
}
public IEnumerable<T> GetAll()
{
return _entitySet;
}
public IEnumerable<T> Find(Expression<Func<T, bool>> where)
{
return _entitySet.Where(where);
}
public void Add(T entity)
{
_entitySet.Add(entity);
}
public void Attach(T entity)
{
_entitySet.Attach(entity);
}
public void Delete(T entity)
{
_entitySet.Remove(entity);
}
}
</code></pre>
<p>Any viewModel that requires access to the database now has a constructor parameter so that a repository can be injected. As far as I can tell this solves all of the problems listed above - my viewModels no longer depend on 'DbContext', they can be tested by using a mocked implementation of the <code>IRepository</code> interface and I could switch to the <code>ObjectContext</code> API by creating a different implementation of the <code>IRepository</code> interface.</p>
<p>This is great except in some cases I may require access to other repositories that contain different entities E.G. <em>Customers</em> and <em>Products</em>. I may also sometimes need to add, update and save the changes to multiple entities in one go. I could change my viewModel constructors to accept just the entities they require but this doesn't smell right to me.</p>
<p>One solution is to use the following interface:</p>
<pre><code>public interface IUnitOfWork : IDisposable
{
IRepository<T> RepositoryFor<T>() where T : class;
void SaveChanges();
}
</code></pre>
<p>The idea here is that the unit of work allows my viewModels to request entities from the data source and any changes can be saved in one go. The implication of this interface is that any entities requested belong to the same 'context'.</p>
<p>an example of a concrete implementation looks like this:</p>
<pre><code>public class UnitOfWork : IUnitOfWork
{
private DbContext _context;
public UnitOfWork(DbContext context)
{
if (context == null)
throw new ArgumentNullException("context");
_context = context;
}
public IRepository<T> RepositoryFor<T>() where T : class
{
return new Repository<T>(_context);
}
public void SaveChanges()
{
_context.SaveChanges();
}
public void Dispose()
{
_context.Dispose();
}
}
</code></pre>
<p>My ViewModel constructors now have an <code>IUnitOfWork</code> injected rather than a repository and the <code>IUnitOfWork</code> instance allows me to request generic repositories for each entity and then save all changes to the same context using the <code>SaveChanges()</code> method.</p>
<p>This still solves the problems listed earlier and also allows me to make changes to multiple entities within my viewModels. My next concern was over the lifetime of the <code>IUnitOfWork</code> instance. My implementation is using <code>DbContext</code> and my understanding is that the this type should be (generally speaking) short lived.</p>
<p>Consider the following scenario:</p>
<ol>
<li>An <code>IUnitOfWork</code> instance is passed into my ViewModel constructor.</li>
<li>I retrieve some entities, work with them and then save the changes to the database.</li>
<li>I dispose the <code>IUnitOfWork</code> instance.</li>
<li>I now need to carry out another series of operations so need to create a new <code>IUnitOfWork</code> instance - My ViewModel is now dependant on my concrete application of the interface.</li>
</ol>
<p>The alternative is to keep the <code>IUnitOfWork</code> around for the lifetime of the ViewModel but this means that the underlying <code>DbContext</code> will be keeping track of all changes I make.</p>
<p>My solution to this was to create another interface:</p>
<pre><code>public interface IUnitOfWorkProvider
{
IUnitOfWork GetUnitOfWork();
}
</code></pre>
<p>The idea here is that a concrete instance will be injected into my ViewModels via the constructor. Whenever I need to do any data access I will just do something like this:</p>
<pre><code>using (IUnitOfWork uow = provider.GetUnitOfWork())
{
// Carry out all data access here...
uow.SaveChanges();
}
</code></pre>
<p>What I would like to know is, <strong>is my implementation of the repository and unit of work patterns acceptable? Will this cause me any major problems?</strong></p>
<p><strong>Update</strong></p>
<p>As was pointed out to me by <em>dreza</em> in the comments, my viewModels are retrieving their own data from the repository. I'm not sure how to pass the data into my viewModels without having a unique interface or class per viewModel to encapsulate this information.</p>
<p>In it's current state the repository can also (potentially) return any entity repository that is requested. e.g. in my customerViewModel I may want to work only with <em>Customer</em> and <em>Product</em> entities but there is nothing to stop me requesting other unrelated entities. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T01:15:52.883",
"Id": "23025",
"Score": "0",
"body": "The implementations seem pretty standard to me. However I'm not sure of the usage of these within viewmodels. I always tended to go down the track that other objects were reponsible for populating the viewmodels themselves, not the viewmodels fetching the needed data. Is there any particular reason for this approach?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T07:12:57.060",
"Id": "23034",
"Score": "0",
"body": "This is simply what I have come up with myself based on the information I have recently learnt. I am certainly open to learning a different approach though; do you have any examples of how your method would be achieved? All the MVVM examples I have seen are usually fairly simple and just create the data directly."
}
] |
[
{
"body": "<p><strong>NOTE</strong>: After Ben correctly commented that he was doing this from the WPF not MVC approach my answer was biased to MVC so although I'll leave it here it it may not have much relevance to what he is actually looking for.</p>\n\n<hr>\n\n<p>Typically I worked on the assumption that as much as possible my viewModels were DTO's \nperhaps with validation attribute capabilities, or I've seen some uses where they use message notification to provide updates to the view. I guess the theory is that the view models themselves could be populated by a variety of methods, or the data used to populate them could come from a variety of places. </p>\n\n<p>From what I gather a view model is essentially a method of of providing a set of data that is required by the specially by the caller/view in question. This data may come from a variety of places, and these places may vary. The viewmodel itself doesn't care, it just transports the data to the view that knows what to do with it.</p>\n\n<p>Also, in my mind by doing this I think unit tests may be easier to write. There are many ways of skinning the cat of course. My favourite flavor of the month is using a service like class to do any mapping from data model to view model. I've also heard modules such as <a href=\"https://github.com/AutoMapper/AutoMapper\" rel=\"nofollow\">Auto mapper</a> are excellent modules for doing this mapping for you as well.</p>\n\n<p>NOTE: These are just examples of how you might use your Repository and IOW without making them part of your viewmodel.</p>\n\n<p>So in my current way of working, I do something like below:</p>\n\n<pre><code>public class TopLevelClass\n{\n private readonly IUnitOfWork _unitOfWork;\n\n public TopLevelClass(IUnitOfWork iow)\n {\n // injected by a DI framework such as Ninject, Unity ??\n _unitOfWork = iow;\n }\n\n // just an example of doing something with not using IUnitOfWork in viewmodel\n public void DoMySpecialSomething(string mySpecialId)\n {\n var repository = _unitOfWork.RepositoryFor<MySpecialModel>();\n var mySpecialModel = repository.SingleOrDefault(p => p.Id = mySpecialId);\n\n var viewModel = new MySpecialService().GetViewModel(mySpecialModel);\n\n // do something with my view model ???\n }\n\n public MySpecialViewModel GetSomethingEvenMoreSpecial(string mySpecialName, string goldMedal)\n {\n var mySpecialModel = new MySpecialModel\n {\n Name = mySpecialName,\n OlympicMedal = goldMedal\n };\n\n return new MySpecialService().GetViewModel(mySpecialModel);\n }\n}\n\n// Maybe this might also work from an IMySpecialService interfaces ????\npublic class MySpecialService\n{\n public MySpecialViewModel GetViewModel(MySpecialModel model)\n {\n return new MySpecialViewModel\n {\n Id = model.Id,\n IsEnabled = !string.isNullOrEmpty(model.Name),\n Name = model.Name,\n OlympicMedal = model.Medal\n };\n }\n}\n\npublic class MySpecialViewModel\n{\n [DisplayName(\"Your Id\")]\n public int Id { get; set; }\n // other properties etc\n}\n\npublic class MySpecialModel\n{\n public int Id { get; set; }\n // other properties here\n}\n</code></pre>\n\n<p>I guess if I was doing TDD I would have created the view model and stubbed the MySpecialService first and created perhaps a test like</p>\n\n<pre><code>// Using standard microsoft testing project\n[TestMethod]\npublic void MySpecialModel_IsValidTest()\n{\n var model = new MySpecialModel\n {\n Id = 45\n };\n\n var service = new MySpecialService();\n var viewModel = service.GetViewModel(model);\n\n Assert.AreEqual(model.Id, 45);\n} \n\nI hope that might give you some ideas in what you might want to (or not) do differently.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T12:02:07.240",
"Id": "23122",
"Score": "0",
"body": "Thanks you for your feedback. Just to be clear, when I talk about viewModels I am talking about them being used in the context of WPF and not ASP.NET MVC. Its not entirely clear from your response so I thought it was worth mentioning just to be clear."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T20:35:25.210",
"Id": "23151",
"Score": "0",
"body": "@Benjamin ahh ok, my bad. You did say that in your question. sorry about that, you can probably ignore my answer unless it gave you some new ideas :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T14:39:40.447",
"Id": "23175",
"Score": "0",
"body": "no problem at all. +1 anyway as your point about viewModels not querying the data source directly (either directly via DbContext or via an interface) is still valid and has made me reconsider my approach."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T08:44:37.163",
"Id": "14286",
"ParentId": "14226",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T19:59:07.790",
"Id": "14226",
"Score": "24",
"Tags": [
"c#",
"design-patterns",
"entity-framework"
],
"Title": "Generic repository and unit of work code"
}
|
14226
|
<p>I coded this because it seemed like a fun project, would be awesome if someone reviewed this.</p>
<p>Thanks!</p>
<pre><code>#! /bin/sh
#function that checks if dependencies are installed
check_software() {
#check if md5sum is installed
if [ $(command -v md5sum) > /dev/null 2>&1 ]; then
echo 'md5sum'
#check if md5 is installed
elif [ $(command -v md5) > /dev/null 2>&1 ]; then
echo 'md5'
#if neither are installed, quit
else
echo "Neither md5sum nor md5 are installed. Quitting." 1>&2
exit 1
fi
}
#function to check if we're moving to same filesystem type
check_filesystem() {
#df gives us detailed information about the file, use awk to get only the disk
DISK1=$(df "$SOURCE" | tail -1 | head -1 | awk '{print $1}')
#run dirname to remove the last bit of the path as the file does not exist yet
DISK2=$(df $(dirname "$DESTINATION") | tail -1 | head -1 | awk '{print $1}')
if [ "$DISK1" == "$DISK2" ]; then
echo 1
else
echo 0
fi
}
main() {
CHECKSOFT=$(check_software)
#if file is being moved on the same filesystem
if [ "$(check_filesystem)" == "1" ]; then
#move normally
if [ "$FLAGS" != '' ]; then
mv "-""$FLAGS" "$SOURCE" "$DESTINATION"
else
mv "$SOURCE" "$DESTINATION"
fi
else
echo "Starting bettermv"
#copy the file
cp -p "$SOURCE" "$DESTINATION"
#this bit of code extracts only the hashes from the output produced
if [ "$CHECKSOFT" = "md5sum" ]; then
CHECKSUMSOURCE="$($CHECKSOFT "$SOURCE" | awk '{print $1}')"
CHECKSUMDEST="$($CHECKSOFT "$DESTINATION" | awk '{print $1}')"
else
CHECKSUMSOURCE="$($CHECKSOFT "$SOURCE" | awk '{print $4}')"
CHECKSUMDEST="$($CHECKSOFT "$DEST" | awk '{print $4}')"
fi
#compare checksums and if they match up
if [ "$CHECKSUMSOURCE" == "$CHECKSUMDEST" ]; then
#remove original and exit
rm "$SOURCE"
echo "Move completed successfuly"
return 0
#if they don't match up
else
#display error message and quit
echo "Checksums did not match, please try again" 1>&2
rm "$DESTINATION"
exit 1
fi
fi
}
FLAGS=''
#get all the move flags and store them in a variable
while getopts "finv" opt; do
case $opt in
f)
FLAGS="$FLAGS""f"
;;
i)
FLAGS="$FLAGS""i"
;;
n)
FLAGS="$FLAGS""n"
;;
v)
FLAGS="$FLAGS""v"
;;
\?)
echo "Invalid argument $OPTARG"
;;
esac
done
#shift optindex past the flags
shift $(( OPTIND-1 ))
#iterate through files to move and move them to the destination (last argument supplied)
for i in $@; do
if [ $i != ${BASH_ARGV[0]} ]; then
SOURCE=$i
DESTINATION="${BASH_ARGV[0]}""$(basename $SOURCE)"
main
fi
done
exit 0
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T23:38:54.580",
"Id": "23018",
"Score": "2",
"body": "The convention in codereview.se is that the code being reviewed is pasted. We insist on that so that we can always see the history of changes even if an external site goes down."
}
] |
[
{
"body": "<p>I'll start with your entry point and will go through you code step by step.\nThe last code block will contain an updated version. </p>\n\n<p>The key elements in my changes are split your functions and only do one specific task, e.g. extra function for getting a checksum of a file and another one comparing two checksums etc. A function should also get all necessary information by <strong>PARAMETER</strong> not by an environment variable set outside. This simplifies testing a lot.</p>\n\n<p>The getopts part is fine but you should just store the flag with the additional \"-\" as it will simplify things later in your code. You may also want to exit if an unknown parameter was provided. I would also rename <code>FLAGS</code> to <code>MV_FLAGS</code> as it describes better what the flags are for. You would normally also print a usage if an invalid parameter was provided. After parsing the options you should also check if enough parameters were provided and print a message otherwise but this is just a UX thing.</p>\n\n<pre><code>MV_FLAGS=''\n#get all the move flags and store them in a variable\nwhile getopts \"finv\" opt; do\n case $opt in\n f) MV_FLAGS=\"$MV_FLAGS\"f ;;\n i) MV_FLAGS=\"$MV_FLAGS\"i ;;\n n) MV_FLAGS=\"$MV_FLAGS\"n ;;\n v) MV_FLAGS=\"$MV_FLAGS\"v ;;\n ?)\n echo \"Invalid argument $1\" >&2\n exit 1\n ;;\n esac\ndone\n[ -n \"$MV_FLAGS\" ] && MV_FLAGS=\"-$MV_FLAGS\"\n\n#shift optindex past the flags\nshift $(( OPTIND-1 ))\n\nif [ $# -lt 1 ] ; then\n echo \"You must specify additional filenames\" >&2\n exit 1\nfi\n</code></pre>\n\n<p>For the next part you should definitely quote <code>$@</code> as otherwise you won't handle parameters with spaces correctly. There is also no need to compare <code>$i</code> with <code>${BASH_ARGV[0]}</code> as <code>$@</code> contains the parameter starting at <code>1</code>. Instead of specifying environment variables to call your main function you should specify them as a parameter instead. <code>BASH_ARGV</code> is according to <a href=\"http://manpages.debian.net/cgi-bin/man.cgi?query=bash&apropos=0&sektion=0&manpath=Debian%206.0%20squeeze&format=html&locale=en\">man bash</a> also only set if you have debugging enabled, so it is not portable. I also don't really understand what <code>DESTINATION</code> should be, but you should change it as well. You should also either quote your parameters with <code>\"</code> or use <code>${</code> I wouldn't mix them and there is no need to use <code>\"</code> as well as <code>${}</code>. You should also check if the source file is a valid file before pushing calling your function. The function name could also be improved, e.g <code>move_file</code></p>\n\n<pre><code>for i in \"$@\" ; do\n SOURCE=\"$i\"\n DESTINATION=\"$0\"\"$(basename \"$SOURCE\")\"\n if [ ! -f \"$SOURCE\" ] ; then\n echo \"$SOURCE does not exist, ignoring.\" >&2\n continue\n fi\n move_file \"$SOURCE\" \"$DESTINATION\"\ndone\n</code></pre>\n\n<p>In your <code>main</code> and my <code>move_file</code> function you always call check_software but there is no need for it. It is enough to call it once at the beginning. You should also create a function handling verifying the filenames so your code doesn't get clustered with the different program parameters etc:</p>\n\n<pre><code>#function that checks if dependencies are installed\ncheck_software() {\n for name in md5sum md5 openssl ; do\n if [ $(type \"$name\") > /dev/null 2>&1 ] ; then\n return 0\n fi\n done\n return 1\n}\n\nif ! check_software ; then\n echo \"Neither md5sum, md5 nor openssl are installed. Quitting.\" >&2\n exit 1\nfi\n</code></pre>\n\n<p>Your <code>check_filesystem</code> can also be simplified a lot if you use a device number instead of parsing <code>df</code>, I'd also rename it to <code>same_filesystem</code></p>\n\n<pre><code>same_filesystem() {\n if [ $# -ne 2 ] ; then\n echo \"Usage: $0 source target\" >&2\n return 1\n fi\n FS1=$(stat -c \"%d\" \"$1\")\n FS2=$(stat -c \"%d\" \"$(dirname \"$2\")\" )\n [ \"$FS1\" -eq \"$FS2\" ]\n return $?\n}\n</code></pre>\n\n<p>You can also simplify your <code>main</code>/<code>move_file</code> function a bit, e.g:</p>\n\n<pre><code>move_file() {\n # we already checked if the necessary programs are available no\n # need to check again\n if [ $# -ne 2 ] ; then\n echo \"Usage: $0 source target\" >&2\n return 1\n fi\n\n SOURCE=\"$1\"\n DESTINATION=\"$2\"\n\n if [ -f \"$DESTINATION\" ] ; then\n # do something if file already exists?!\n :\n fi\n\n #if file is being moved on the same filesystem\n if same_filesystem \"$SOURCE\" \"$DESTINATION\" ; then\n mv $MV_FLAGS -- \"$SOURCE\" \"$DESTINATION\"\n return 0\n fi\n\n echo \"Starting bettermv\" >&2\n #copy the file\n cp -p \"$SOURCE\" \"$DESTINATION\"\n\n if verify_files \"$SOURCE\" \"$DESTINATION\" ; then\n rm \"$SOURCE\"\n return 0\n else\n echo \"Error moving $SOURCE to $DESTINATION, abort.\" >&2\n rm \"$DESTINATION\"\n return 1\n fi\n}\n\nget_checksum() {\n if [ $# -ne 1 ] ; then\n echo \"Usage: $0 source\" >&2\n return 1\n fi\n if type openssl >/dev/null 2>&1 ; then\n echo $(openssl md5 \"$1\" | awk '{print $2}')\n elif type md5sum >/dev/null 2>&1 ; then\n echo $(md5sum \"$1\" | awk '{print $1}')\n elif type md5 >/dev/null 2>&1 ; then\n echo $(md5 \"$1\" | awk '{print $4}')\n fi\n return 1\n}\n\nverify_files() {\n if [ $# -ne 2 ] ; then\n echo \"Usage: $0 source target\" >&2\n return 1\n fi\n\n CHECKSUM1=$(get_checksum \"$1\")\n CHECKSUM2=$(get_checksum \"$2\")\n\n [ $CHECKSUM1 = $CHECKSUM2 ]\n return $?\n}\n</code></pre>\n\n<p>The complete script with all changes (i tested it):</p>\n\n<pre><code>#!/bin/sh\n\n#function that checks if dependencies are installed\ncheck_software() {\n for name in md5sum md5 openssl ; do\n if type \"$name\" 1>/dev/null 2>&1 ; then\n return 0\n fi\n done\n return 1\n}\n\nif ! check_software ; then\n echo \"Neither md5sum, md5 nor openssl are installed. Quitting.\" >&2\n exit 1\nfi\n\n\nmove_file() {\n # we already checked if the necessary programs are available no\n # need to check again\n if [ $# -ne 2 ] ; then\n echo \"Usage: $0 source target\" >&2\n return 1\n fi\n\n SOURCE=\"$1\"\n DESTINATION=\"$2\"\n\n if [ -f \"$DESTINATION\" ] ; then\n # do something if file already exists?!\n :\n fi\n\n #if file is being moved on the same filesystem\n if same_filesystem \"$SOURCE\" \"$DESTINATION\" ; then\n mv $MV_FLAGS -- \"$SOURCE\" \"$DESTINATION\"\n return 0\n fi\n\n echo \"Starting bettermv\" >&2\n\n #copy the file\n cp -p \"$SOURCE\" \"$DESTINATION\"\n\n if verify_files \"$SOURCE\" \"$DESTINATION\" ; then\n rm \"$SOURCE\"\n return 0\n else\n echo \"Error moving $SOURCE to $DESTINATION, abort.\" >&2\n rm \"$DESTINATION\"\n return 1\n fi\n}\n\n\nsame_filesystem() {\n if [ $# -ne 2 ] ; then\n echo \"Usage: $0 source target\" >&2\n return 1\n fi\n\n FS1=$(stat -c \"%d\" \"$1\")\n FS2=$(stat -c \"%d\" \"$(dirname \"$2\")\" )\n\n [ \"$FS1\" -eq \"$FS2\" ]\n return $?\n}\n\n\nget_checksum() {\n if [ $# -ne 1 ] ; then\n echo \"Usage: $0 source\" >&2\n return 1\n fi\n\n if type md5sum >/dev/null 2>&1 ; then\n echo $(md5sum -- \"$1\" | awk '{print $1}')\n elif type md5 >/dev/null 2>&1 ; then\n echo $(md5 \"$1\" | awk '{print $4}')\n elif type openssl >/dev/null 2>&1 ; then\n echo $(openssl md5 \"$1\" | awk '{print $2}')\n else\n return 1\n fi\n}\n\n\nverify_files() {\n if [ $# -ne 2 ] ; then\n echo \"Usage: $0 source target\" >&2\n return 1\n fi\n\n CHECKSUM1=$(get_checksum \"$1\")\n CHECKSUM2=$(get_checksum \"$2\")\n\n [ $CHECKSUM1 = $CHECKSUM2 ]\n return $?\n}\n\n\n\nMV_FLAGS=''\n#get all the move flags and store them in a variable\nwhile getopts \"finv\" opt; do\n case $opt in\n f) MV_FLAGS=\"$MV_FLAGS\"f ;;\n i) MV_FLAGS=\"$MV_FLAGS\"i ;;\n n) MV_FLAGS=\"$MV_FLAGS\"n ;;\n v) MV_FLAGS=\"$MV_FLAGS\"v ;;\n ?)\n echo \"Invalid argument $1\" >&2\n exit 1\n ;;\n esac\ndone\n\n[ -n \"$MV_FLAGS\" ] && MV_FLAGS=\"-$MV_FLAGS\"\n\n#shift optindex past the flags\nshift $(( OPTIND-1 ))\n\nif [ $# -lt 1 ] ; then\n echo \"You must specify additional filenames\" >&2\n exit 1\nfi\n\nfor i in \"$@\" ; do\n SOURCE=\"$i\"\n DESTINATION=\"$0\"\"$(basename \"$SOURCE\")\"\n\n if [ ! -f \"$SOURCE\" ] ; then\n echo \"$SOURCE does not exist, ignoring.\" >&2\n continue\n fi\n\n move_file \"$SOURCE\" \"$DESTINATION\"\ndone\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T09:24:52.917",
"Id": "23045",
"Score": "0",
"body": "Whoa, that is an incredibly detailed response. Thank you for taking the time to type all that up, I've learned a lot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T04:23:00.617",
"Id": "14243",
"ParentId": "14231",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "14243",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T21:44:14.820",
"Id": "14231",
"Score": "5",
"Tags": [
"bash",
"shell"
],
"Title": "Shell script that verifies checksums when moving between filesystems"
}
|
14231
|
<p>I have made this class that runs a query. I want to optimize my code and want to have some expert advice.</p>
<p>Here is the class:</p>
<pre><code>class testClass extends Model
{
protected $_var1;
protected $_var2;
protected $_var3;
public function __construct($var1,$var2, $var3)
{
$this->_var1= $this->$var1;
$this->_var2= $this->var2;
$this->_var3= 8; // i need this 8 if no value is passed
}
public function testMethod(){
$query = "SELECT * from table where id = ".this->_var1." AND name= ".$this->var2." AND x= ".$this->var3;
return $runQuery($query);
// $runquery is another method…not in concern here..it returns the results…just take my words :)
}
}
</code></pre>
<p>Usage of class:</p>
<pre><code> $r= new testClass($var1, $var2, $var3);
$result = $r->testMethod();
</code></pre>
<p>How can I improve this? Or is this even a good way to do it?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T00:59:26.057",
"Id": "23022",
"Score": "3",
"body": "Welcome to CR, we don't have \"expert\" advice, but I'll see what I can do for you. 32bitfloat did a pretty good job already, I just want to add a few things. First, variable names should be descriptive. `$var1, $var2, $var3` doesn't tell us enough. Second, your style is inconsistent. The constructor's opening brace is on a new line while the `testMethod()`'s is on the same line. Your indentation is also pretty inconsistent. Finally, a single line of code should never be so long as to cause illegibility. You appear to know how to concatenate strings, just concatenate to `$query` a few times."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T01:07:03.580",
"Id": "23024",
"Score": "1",
"body": "Sorry, last comment. This probably shouldn't have been a class. You would be much better off working with procedural code first and working your way up to classes and OOP."
}
] |
[
{
"body": "<p>I'm not sure what you want to achieve with the constructor.</p>\n\n<pre><code>public function __construct($var1,$var2, $var3)\n {\n $this->_var1= $this->$var1;\n $this->_var2= $this->var2;\n $this->_var3= 8; // i need this 8 if no value is passed\n\n }\n</code></pre>\n\n<p>If you want to set the properties to the given parameters, you should do</p>\n\n<pre><code> $this->_var1= $var1;\n</code></pre>\n\n<hr>\n\n<p>And with</p>\n\n<pre><code>$this->_var3= 8; // i need this 8 if no value is passed\n</code></pre>\n\n<p>you always set property $_var3 to 8, nonetheless if $var3 is being passed.</p>\n\n<p>For setting a default value to a paramter you can write it like this</p>\n\n<pre><code>public function __construct($var1, $var2, $var3 = 8)\n {\n $this->_var1 = $var1;\n $this->_var2 = $var2;\n $this->_var3 = $var3;\n\n }\n</code></pre>\n\n<p>so if you call</p>\n\n<pre><code>$r = new testClass($var1, $var2, 10);\n</code></pre>\n\n<p>$this->_var3 would be set to 10, and if you call</p>\n\n<pre><code>$r = new testClass($var1, $var2);\n</code></pre>\n\n<p>$this->_var3 would be set to the default 8.</p>\n\n<hr>\n\n<p>In your testMethod you're using $this->var2 & $this->var3, without the underline. These properties are not defined.</p>\n\n<hr>\n\n<pre><code>return $runQuery($query);\n</code></pre>\n\n<p>remove the $ in the function's name, or it would be taken as variable.</p>\n\n<hr>\n\n<p>In your SQL-Query there's a column named \"name\". In all cases where the column types are strings, you have to write the value in single quotes.</p>\n\n<pre><code>$query = \"SELECT * from table where id = \".this->_var1.\" AND name= '\".$this->_var2.\"' AND x= \".$this->_var3; \n</code></pre>\n\n<hr>\n\n<p>For debugging purposes, set</p>\n\n<pre><code>ini_set('display_errors', 1);\nerror_reporting(E_ALL);\n</code></pre>\n\n<p>to the starting script.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T01:04:34.473",
"Id": "23023",
"Score": "1",
"body": "If a variable is called as a function then it is called a variable function. These allow you to set a function's name as a string value in a variable and call the function dynamically, however they are considered big no-no's and should be avoided. In this instance though, I do not think he was trying to use variable functions, however that is what he would have been calling, not a variable :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T06:14:39.100",
"Id": "23031",
"Score": "0",
"body": "You're right, I didn't verbalized that well. Just thought OP has a typo and finish =)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T00:47:16.173",
"Id": "14237",
"ParentId": "14234",
"Score": "6"
}
},
{
"body": "<p>This class has one serious problem:</p>\n\n<h2>SQL Injection</h2>\n\n<p>Your method builds a query from variables. If these variables come from user input then you have an <a href=\"http://en.wikipedia.org/wiki/SQL_injection\">SQL Injection vulnerability</a>. This class has no control over what is passed to it, so it is a vulnerable part of your system. You could avoid it by not passing user input to it, but it is much better to never have the vulnerability in the first place.</p>\n\n<p>It looks like you might be using the mysql_* functions. Please, don't use mysql_* functions to write new code. They are no longer maintained and the community has begun deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi.</p>\n\n<h2>Other Comments</h2>\n\n<p>It is good that you are passing your dependencies in your constructor.</p>\n\n<p>Underscore in class properties are a waste of time. In OOP you should almost never have public properties. By having only <code>protected</code> and <code>private</code> properties you can rely on the <code>public</code> method interface to interact with the class. This is an important difference because <strong>the <code>public</code> methods of a class are testable</strong>. Now, without public properties the underscore just gets in the way.</p>\n\n<p>Consider sticking to a single paradigm. <code>runQuery</code> is a procedure that you have defined. Why not encapsulate the query within an object (PDO is a good object for running queries, or perhaps use a DB object of your own)?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T20:09:49.070",
"Id": "23095",
"Score": "2",
"body": "The more I play around with OOP and the more my knowledge grows, the more I realize that bit about the underscore is true. I would like to point out that is only for the properties. I still find it helpful to distinguish my methods with a preceding underscore."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T02:56:35.110",
"Id": "14241",
"ParentId": "14234",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "14237",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T22:51:39.787",
"Id": "14234",
"Score": "1",
"Tags": [
"php",
"php5"
],
"Title": "Class that runs a query"
}
|
14234
|
<p>Please review my database design:</p>
<p><img src="https://i.stack.imgur.com/ftdd7.png" alt="flowchart"></p>
<p>I think it is quite self-explanatory, but to be absolutely clear:</p>
<p>My goal is to make an application which has a super flexible user management (which is why the groups are in tree-form and the groups and users have a habtm relationship) and a super modular way to build pages (which is why the pages consist of widget-blocks).</p>
<p>The reason I made users and profiles separate is because the users table will not change and is only needed for authentication and authorization. However, the profiles table will change according to the wishes of the client. So it might not have a signature, but an avatar field instead. Or maybe it will be completely empty / not exist at all.</p>
<p>A widget could be anything, it could be a poll, it could be a piece of content, it could be a navigation, it could be a collection of comments, whatever.</p>
<p>The reason I chose to make subdomains, locales and layouts separate tables instead of just putting the names into pages is because I want to limit the options that are available to the client. Just because I have a three-columns.ctp in my layouts folder doesn't necessarily mean I want the client to be able to choose it.</p>
<p>Same goes for the widgets. And besides limiting choice, not every plugin, controller and action in my plugins-folder is a widget, so I need a table to clarify which are.</p>
<p>A block is a widget on a page which sits in a container (e.g. the right column in a 3 column layout) at a particular position which is decided by the index (lower index means higher).</p>
<p>So that's my explanation, what do you guys think? Is this as good as it can be? Or do you have (a) suggestion(s) to make it even more flexible and modular.</p>
<p>Oh and to be clear, the widgets will of course have their own tables to store the information they need to store.</p>
<pre><code>-- ---
-- Globals
-- ---
-- SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
-- SET FOREIGN_KEY_CHECKS=0;
-- ---
-- Table 'users'
--
-- ---
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` INTEGER NULL AUTO_INCREMENT DEFAULT NULL,
`username` VARCHAR(32) NOT NULL,
`password` VARCHAR(32) NOT NULL,
`created` DATETIME NOT NULL,
`modified` DATETIME NOT NULL,
PRIMARY KEY (`id`)
);
-- ---
-- Table 'groups'
--
-- ---
DROP TABLE IF EXISTS `groups`;
CREATE TABLE `groups` (
`id` INTEGER NULL AUTO_INCREMENT DEFAULT NULL,
`parent_id` INTEGER NULL DEFAULT NULL,
`name` VARCHAR(32) NOT NULL,
`lft` INTEGER NOT NULL,
`rght` INTEGER NOT NULL,
`created` DATETIME NOT NULL,
`modified` DATETIME NOT NULL,
PRIMARY KEY (`id`)
);
-- ---
-- Table 'groups_users'
--
-- ---
DROP TABLE IF EXISTS `groups_users`;
CREATE TABLE `groups_users` (
`id` INTEGER NULL AUTO_INCREMENT DEFAULT NULL,
`group_id` INTEGER NOT NULL,
`user_id` INTEGER NOT NULL,
PRIMARY KEY (`id`)
);
-- ---
-- Table 'profiles'
--
-- ---
DROP TABLE IF EXISTS `profiles`;
CREATE TABLE `profiles` (
`id` INTEGER NULL AUTO_INCREMENT DEFAULT NULL,
`user_id` INTEGER NOT NULL,
`email` VARCHAR(64) NULL DEFAULT NULL,
`birthday` DATE NULL DEFAULT NULL,
`signature` MEDIUMTEXT NULL DEFAULT NULL,
PRIMARY KEY (`id`)
);
-- ---
-- Table 'pages'
--
-- ---
DROP TABLE IF EXISTS `pages`;
CREATE TABLE `pages` (
`id` INTEGER NULL AUTO_INCREMENT DEFAULT NULL,
`parent_id` INTEGER NULL DEFAULT NULL,
`subdomain_id` INTEGER NOT NULL,
`locale_id` INTEGER NOT NULL,
`layout_id` INTEGER NOT NULL,
`path` VARCHAR(128) NOT NULL,
`name` VARCHAR(32) NOT NULL,
`visible` bit NOT NULL DEFAULT 0,
`lft` INTEGER NOT NULL,
`rght` INTEGER NOT NULL,
`created` DATETIME NOT NULL,
`modified` DATETIME NOT NULL,
PRIMARY KEY (`id`)
);
-- ---
-- Table 'locales'
--
-- ---
DROP TABLE IF EXISTS `locales`;
CREATE TABLE `locales` (
`id` INTEGER NULL AUTO_INCREMENT DEFAULT NULL,
`name` VARCHAR(3) NOT NULL,
PRIMARY KEY (`id`)
);
-- ---
-- Table 'layouts'
--
-- ---
DROP TABLE IF EXISTS `layouts`;
CREATE TABLE `layouts` (
`id` INTEGER NULL AUTO_INCREMENT DEFAULT NULL,
`name` VARCHAR(8) NOT NULL,
PRIMARY KEY (`id`)
);
-- ---
-- Table 'subdomains'
--
-- ---
DROP TABLE IF EXISTS `subdomains`;
CREATE TABLE `subdomains` (
`id` INTEGER NULL AUTO_INCREMENT DEFAULT NULL,
`name` VARCHAR(8) NOT NULL,
PRIMARY KEY (`id`)
);
-- ---
-- Table 'widgets'
--
-- ---
DROP TABLE IF EXISTS `widgets`;
CREATE TABLE `widgets` (
`id` INTEGER NULL AUTO_INCREMENT DEFAULT NULL,
`plugin` VARCHAR(32) NOT NULL,
`controller` VARCHAR(32) NOT NULL,
`action` VARCHAR(32) NOT NULL,
PRIMARY KEY (`id`)
);
-- ---
-- Table 'containers'
--
-- ---
DROP TABLE IF EXISTS `containers`;
CREATE TABLE `containers` (
`id` INTEGER NULL AUTO_INCREMENT DEFAULT NULL,
`layout_id` INTEGER NOT NULL,
`name` VARCHAR(8) NOT NULL,
PRIMARY KEY (`id`)
);
-- ---
-- Table 'blocks'
--
-- ---
DROP TABLE IF EXISTS `blocks`;
CREATE TABLE `blocks` (
`id` INTEGER NULL AUTO_INCREMENT DEFAULT NULL,
`page_id` INTEGER NOT NULL,
`container_id` INTEGER NOT NULL,
`widget_id` INTEGER NOT NULL,
`parameters` BLOB NULL DEFAULT NULL,
`index` INTEGER NOT NULL,
`created` DATETIME NOT NULL,
`modified` DATETIME NOT NULL,
PRIMARY KEY (`id`)
);
-- ---
-- Foreign Keys
-- ---
ALTER TABLE `groups` ADD FOREIGN KEY (parent_id) REFERENCES `groups` (`id`);
ALTER TABLE `groups_users` ADD FOREIGN KEY (group_id) REFERENCES `groups` (`id`);
ALTER TABLE `groups_users` ADD FOREIGN KEY (user_id) REFERENCES `users` (`id`);
ALTER TABLE `profiles` ADD FOREIGN KEY (user_id) REFERENCES `users` (`id`);
ALTER TABLE `pages` ADD FOREIGN KEY (parent_id) REFERENCES `pages` (`id`);
ALTER TABLE `pages` ADD FOREIGN KEY (subdomain_id) REFERENCES `subdomains` (`id`);
ALTER TABLE `pages` ADD FOREIGN KEY (locale_id) REFERENCES `locales` (`id`);
ALTER TABLE `pages` ADD FOREIGN KEY (layout_id) REFERENCES `layouts` (`id`);
ALTER TABLE `containers` ADD FOREIGN KEY (layout_id) REFERENCES `layouts` (`id`);
ALTER TABLE `blocks` ADD FOREIGN KEY (page_id) REFERENCES `pages` (`id`);
ALTER TABLE `blocks` ADD FOREIGN KEY (container_id) REFERENCES `containers` (`id`);
ALTER TABLE `blocks` ADD FOREIGN KEY (widget_id) REFERENCES `widgets` (`id`);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T14:24:55.250",
"Id": "36312",
"Score": "0",
"body": "In my experience, the terms most flexible and best / right / optimal rarely belong in the same sentence ;)"
}
] |
[
{
"body": "<p>I'm not a database designer so I can only speak to the question as an application developer.</p>\n\n<ol>\n<li><p>I don't see any mechanism for limiting access to pages or groups of pages. It would seem like one use of user groups would be to give all members of a group certain privileges for certain pages and/or groups of pages.</p></li>\n<li><p>The entire mechanism looks like it's based on content rendered for a specific medium. Any deviation in the properties of the medium could cause problems. For example: web pages intended for a desktop browser can get cramped on a laptop and worse on a mobile device. My desktop, for example has a 30\" 2560x1600 display - stuff that looks great on it can look very odd on smaller monitors. And what about printing?</p></li>\n<li><p>I don't see where the actual content is located or what types of content are supported.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T17:15:31.967",
"Id": "14264",
"ParentId": "14235",
"Score": "2"
}
},
{
"body": "<p>Sorry for having this as an answer, should be a comment but not enough rep.</p>\n\n<p>#1 in Donald McLean's answer could be solved with Acl, the database's structure looks well set up for it.</p>\n\n<p>#2 is often solved CakePHP-wise by using a different layout... But that also relies on #3, content.</p>\n\n<p>I'm seconding #3, that's a problem.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T04:43:48.683",
"Id": "19221",
"ParentId": "14235",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T22:55:52.727",
"Id": "14235",
"Score": "2",
"Tags": [
"sql",
"database",
"cakephp"
],
"Title": "Flexible and modular CMS with user management in CakePHP"
}
|
14235
|
<p>Was the best way to implent this? For example it will only say "It's nice I know." If you first ask "hat" and then answer "yes".</p>
<p>This is how I'm thinking:</p>
<pre><code>Topic = 0
local messages = {
{"name", "I'm Bob, the owner of this little shop."},
{"job", "I sell stuff."},
{"hat|head", "You like my hat?", Topic = 1},
{Topic == 1, "yes", "It's nice I know."}}
for i, a in ipairs(messages) do
if isMsg(a[1], msg) then
makeSay(a[2])
return true
end
end
</code></pre>
<p>Functions</p>
<pre><code>function isMsg(messages, msg)
local keys = split(messages, "|")
if getmsg(keys, msg) then
return true
end
return false
end
function table.contains(table, element)
for _, value in ipairs(table) do
if value == element then
return true
end
end
return false
end
function getmsg(t, msg)
for v, a in ipairs(t) do
if msgcontains(msg, a) then
return true
end
end
return false
end
function keyContains(t, msg)
for v, t in ipairs(t) do
if t == msg then
return true
end
end
return false
end
function split(str, pat)
local t = {} -- NOTE: use {n = 0} in Lua-5.0
local fpat = "(.-)" .. pat
local last_end = 1
local s, e, cap = str:find(fpat, 1)
while s do
if s ~= 1 or cap ~= "" then
table.insert(t,cap)
end
last_end = e+1
s, e, cap = str:find(fpat, last_end)
end
if last_end <= #str then
cap = str:sub(last_end)
table.insert(t, cap)
end
return t
end
</code></pre>
|
[] |
[
{
"body": "<p>I see a lot of problems here...</p>\n\n<ul>\n<li>are the answers selectable in the GUI? If not such predefined answers are not quite user-friendly, prone to typos etc.</li>\n<li>You might have to escape strings with \"|\" then unescape them. Yes chances are low, but that's how bugs start.</li>\n<li>Use closures. Do not redefine your table every time you run that function</li>\n<li><code>for k,v in ipairs(tbl)</code> is a lot slower than <code>for i, #tbl do</code></li>\n<li>Is there an actual difference between <code>keyContains</code> and <code>table.contains</code>?</li>\n</ul>\n\n<h2>Use Hash-Tables</h2>\n\n<p>Lua has a pretty fast implementation of them, so your decision code could be made a lot faster - and easier to read like this</p>\n\n<pre><code>local messages = {\n [\"name\"] = \"I'm Bob, the owner of this little shop.\",\n [\"job\"] = \"I sell stuff.\",\n}\n\nfunction getanswer(question)\n return messages[question];\nend\n</code></pre>\n\n<ul>\n<li>Since Lua hashes all strings anyway you will almost always win using hashtables.</li>\n<li>Your string can contain any value</li>\n<li>it's a lot easier to read.</li>\n</ul>\n\n<p>Now for the topics. I will skip the part where you \"revert\" from topics, since you have to know yourself whether you need to \"cancel out\" or \"time out\" or don't allow it in general.</p>\n\n<pre><code>local messages = {\n [1] = \"Hello stranger!\",\n [\"name\"] = \"I'm Bob, the owner of this little shop.\",\n [\"job\"] = \"I sell stuff.\",\n [\"hat\"] = {\n [1] = \"You like my hat?\",\n [\"yes\"] = \"It's nice I know.\",\n [\"no\"] = \"You ...!\",\n },\n}\nlocal topic = messages;\n\nfunction getanswer(question)\n if type(topic[question]) == \"table\" then\n topic = topic[question];\n return topic[1];\n else\n return topic[question];\n end\nend\n</code></pre>\n\n<p>You could also implement random answers quite easily by just adding more integer key values and selecting one with <code>math.random(1, #topic)</code></p>\n\n<p>if there are duplicate topics, just duplicate the table. Yeah it looks like a big overhead but in most cases it doesn't really matter. An alternative is just referencing the table like</p>\n\n<pre><code>messages.head = messages.hat;\n</code></pre>\n\n<p>Though that might get hard to maintain. There are other options but my answer would just get longer and longer...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T17:10:29.507",
"Id": "14338",
"ParentId": "14236",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T23:44:06.947",
"Id": "14236",
"Score": "7",
"Tags": [
"lua"
],
"Title": "Very basic chatbot"
}
|
14236
|
<p>I'm trying to get some feedback on my code for the lexicon exercise (#48) in <em>Learn Python the Hard Way</em>. I have only recently started learning Python and want to make sure I have my fundamentals down before progressing. I have some experience coding (only with kdb+/q in my work environment) but none in Python, so all advice is welcomed.</p>
<pre><code>verb=['go','kill','eat']
direction=['north','south','east','west']
noun=['bear','princess']
stop=['the','in','of']
vocab={'verb':verb,'direction':direction,'noun':noun,'stop':stop}
def scan(sentence):
wordlist=sentence.split()
result=[] #initialize an empty list
for word in wordlist:
found=False
for key,value in vocab.items():
if word.lower() in value: #convert to lower case so that we can handle inputs with both cases
result.append((key,word))
found=True
break
if not found:
try:
word=int(word)
result.append(('number',word))
except ValueError:
result.append(('error',word))
return result
</code></pre>
<p>Python version 2.6.</p>
|
[] |
[
{
"body": "<pre><code>verb=['go','kill','eat']\ndirection=['north','south','east','west']\nnoun=['bear','princess']\nstop=['the','in','of']\n</code></pre>\n\n<p>There is not a lot of point in storing these in separate variables only to stick them inside <code>vocab</code> just put the list literals inside <code>vocab</code></p>\n\n<pre><code>vocab={'verb':verb,'direction':direction,'noun':noun,'stop':stop}\n</code></pre>\n\n<p>Python convention say to make constant ALL_CAPS. I'd also not abbreviate the names. Code is read more then written, so make it easy to read not to write.</p>\n\n<pre><code>def scan(sentence):\n wordlist=sentence.split()\n result=[] #initialize an empty list\n</code></pre>\n\n<p>Pointless comment. Assume you reader understand the language. You don't need to explain what [] means.</p>\n\n<pre><code> for word in wordlist:\n</code></pre>\n\n<p>I'd use <code>for word in sentence.split():</code></p>\n\n<pre><code> found=False\n</code></pre>\n\n<p>Boolean logic flags are delayed gotos. Avoid them when you can</p>\n\n<pre><code> for key,value in vocab.items():\n if word.lower() in value: #convert to lower case so that we can handle inputs with both cases\n</code></pre>\n\n<p>Your dictionary is backwards. It maps from word types to lists of words. It'd make more sense to have a dictionary mapping from word to the word type.</p>\n\n<pre><code> result.append((key,word))\n found=True\n break\n if not found:\n</code></pre>\n\n<p>Rather then this, use an <code>else</code> block on the for loop. It'll be execute if and only if no break is executed.</p>\n\n<pre><code> try:\n word=int(word)\n result.append(('number',word))\n</code></pre>\n\n<p>Put this in the else block for the exception. Generally, try to have as little code in try blocks as possible. Also I wouldn't store the result in word again, I'd put in a new local.</p>\n\n<pre><code> except ValueError:\n result.append(('error',word))\n\n return result \n</code></pre>\n\n<p>My approach:</p>\n\n<pre><code>WORD_TYPES = {\n 'verb' : ['go', 'kill', 'eat'],\n 'direction' : ['north', 'south', 'east', 'west'],\n 'noun' : ['bear', 'princess'],\n 'stop' : ['the','in','of']\n}\n# invert the dictionary\nVOCABULARY = {word: word_type for word_type, words in WORD_TYPES.items() for word in words}\n\ndef scan(sentence):\n tokens = []\n for word in sentence.split():\n try:\n word_type = VOCABULAR[word]\n except KeyError:\n try:\n value = int(word)\n except ValueError:\n tokens.append( ('error',word) )\n else:\n tokens.append( ('int', value) )\n else:\n tokens.append( (word_type, word) )\n return tokens\n</code></pre>\n\n<p>Alternately, using some regular expressions:</p>\n\n<pre><code>classifications = []\nfor word_type, words in WORD_TYPES.items():\n word_expression = '|'.join(\"(?:%s)\" % re.escape(word) for word in words)\n expression = r\"\\b(?P<%s>%s)\\b\" % (word_type, word_expression)\n classifications.append(expression)\nclassifications.append(r\"\\b(?P<int>\\d+)\\b\")\nclassifications.append(r\"\\b(?P<error>\\w+)\\b\")\nparser = re.compile('|'.join(classifications))\n\ndef scan(sentence):\n return [(match.lastgroup, match.group(0)) for match in parser.finditer(sentence)]\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<p>If your version of python is to old to use the dict comphrensions you can use:</p>\n\n<pre><code>dict((word, word_type) for word_type, words in WORD_TYPES.items() for word in words)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T13:00:09.387",
"Id": "23051",
"Score": "0",
"body": "thanks for the response! Very much appreciated. Would you mind walking me through the dictionary inversion? I was trying to drop it into my terminal and play with it but I get a SyntaxError:invalid syntax. It seemed to me to be some sort of variant on list comprehension where for each word in words (i.e. for each element in the value-pairs) it assigns the wordtype (i.e. the key in the original dictionary key-value pair) to that element. Not sure why it doesn't work though..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T15:02:15.987",
"Id": "23056",
"Score": "0",
"body": "@JPC, which version of python are you running? The dict comprehension is a newer feature. But you've got the right idea of how it works. I'll add an alternate way"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T17:27:02.377",
"Id": "23061",
"Score": "0",
"body": "seem's I'm running on 2.6.4. Thanks! I appreciate it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T17:43:17.783",
"Id": "23065",
"Score": "0",
"body": "@JPC, yeah I think you need 2.7 for the dict comp."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T04:13:48.200",
"Id": "14242",
"ParentId": "14238",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-08-02T01:37:03.527",
"Id": "14238",
"Score": "9",
"Tags": [
"python",
"beginner",
"parsing",
"python-2.x"
],
"Title": "Learn Python the Hard Way #48 — lexicon exercise"
}
|
14238
|
<p>I changed some methods used previously, and I am wondering if I need to do the multiple for loops over and over again. How do I convert my arrays to lists to use in nested <code>for</code> loops?</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading.Tasks;
using TwoWayAnova;
namespace TwoWayAnovaTable
{
public partial class TwoWayAnovaTable : Form
{
public TwoWayAnovaTable()
{
InitializeComponent();
}
private static readonly char[] Separators = { ',', ' ' };
private static double _aTreatmentSumOfSquares;
private static double _bTreatmentSumOfSquares;
private static double _interactionSumOfSquares;
private static double _errorSumOfSquares;
private static double _sumOfSquares;
private static double _aMeanTreatmentSumOfSquares;
private static double _bMeanTreatmentSumOfSquares;
private static double _interactionMeanSumOfSquares;
private static double _meanErrorSumOfSquares;
private static double _aTreatmentDegreesOfFreedom;
private static double _bTreatmentDegreesOfFreedom;
private static double _interactionDegreesOfFreedom;
private static double _errorDegreesOfFreedom;
private static double _totalDegreesOfFreedom;
private static double _aTestStatistic;
private static double _bTestStatistic;
private static double _interactionTestStatistic;
private static double _aPValue;
private static double _bPValue;
private static double _interactionPValue;
private static void ProcessFile()
{
var lines = File.ReadLines("Data.csv");
var numbers = ProcessRawNumbers(lines);
var rowTotal = new List<double>();
var squareRowTotal = new List<double>();
var rowMean = new List<double>();
var totalElements = 0;
var totalInRow = new List<int>();
var rowTotalSquareByN = new List<double>();
var sumOfSquareOfBlock = new List<double>();
foreach (var values in numbers)
{
var sumOfRow = values.Sum();
rowTotal.Add(sumOfRow);
squareRowTotal.Add(values.Select(v => v * v).Sum());
rowMean.Add(sumOfRow / values.Count);
totalInRow.Add(values.Count);
totalElements += values.Count;
rowTotalSquareByN.Add(rowTotal.Select(r => r * r / values.Count).Sum());
sumOfSquareOfBlock = squareRowTotal - rowTotalSquareByN;
}
var grandTotal = rowTotal.Sum();
}
int aNum = 3, bNum = 3;
double[] totalSumPerBlock = new double[bNum];
double[] totalSumOfSquaresPerBlock = new double[bNum];
int[] blockTotalElements = new int[bNum];
double[] totalSquarePerBlockByN = new double[bNum];
double[] blockMean = new double[bNum];
double[] sumOfSquaresTotalOfBlock = new double[bNum];
for (int i = 0; i < bNum; i++)
{
for (int j = 0; j < aNum; j++)
{
totalSumPerBlock[i] += rowTotal[j + i * 3];
totalSumOfSquaresPerBlock[i] += squareRowTotal[j + i * 3];
blockTotalElements[i] += totalInRow[j + i * 3];
sumOfSquaresTotalOfBlock[i] += sumOfSquareOfBlock[j + i * 3];
}
totalSquarePerBlockByN[i] += totalSumPerBlock[i] * totalSumPerBlock[i] / blockTotalElements[i];
blockMean[i] = totalSumPerBlock[i] / blockTotalElements[i];
}
double[] grandTotalAllBlocks = new double[bNum];
double[] grandBlockSumOfSquares = new double[bNum];
int[] grandNumberOfElements = new int[bNum];
double[] grandSumOfSquares = new double[bNum];
double[] grandBlockSquaresSumByN = new double[bNum];
double[] grandBlockMean = new double[bNum];
double finalSum = 0;
double finalSumOfSquaresRow = 0;
int finalElements = 0;
double finalSumOfSquaresByN = 0;
double finalSumOfSquares = 0;
double finalMean = 0;
for (int i = 0; i < bNum; i++)
{
for (int j = 0; j < aNum; j++)
{
grandTotalAllBlocks[i] += rowTotal[i + 3 * j];
grandBlockSumOfSquares[i] += squareRowTotal[i + 3 * j];
grandNumberOfElements[i] += totalInRow[i + 3 * j];
}
grandBlockSquaresSumByN[i] = grandTotalAllBlocks[i] * grandTotalAllBlocks[i] / grandNumberOfElements[i];
grandBlockMean[i] = grandTotalAllBlocks[i] / grandNumberOfElements[i];
finalSum += grandTotalAllBlocks[i];
finalSumOfSquaresRow += grandBlockSumOfSquares[i];
finalElements += grandNumberOfElements[i];
finalSumOfSquaresByN = finalSum * finalSum / finalElements;
finalSumOfSquares = finalSumOfSquaresRow - finalSumOfSquaresByN;
finalMean = finalSum / finalElements;
}
for (int i = 0; i < numbers.Count; i++)
{
_errorSumOfSquares += sumOfSquareOfBlock[i];
_interactionSumOfSquares += rowTotalSquareByN[i];
}
for (int i = 0; i < bNum; i++)
{
_aTreatmentSumOfSquares += totalSquarePerBlockByN[i];
_bTreatmentSumOfSquares += grandBlockSquaresSumByN[i];
_interactionSumOfSquares = _interactionSumOfSquares - totalSquarePerBlockByN[i] - grandBlockSquaresSumByN[i];
}
_interactionSumOfSquares = (-1) * (_aTreatmentSumOfSquares - _bTreatmentSumOfSquares) + finalSumOfSquaresByN;
_aTreatmentSumOfSquares -= finalSumOfSquaresByN;
_bTreatmentSumOfSquares -= finalSumOfSquaresByN;
_sumOfSquares = _errorSumOfSquares + _bTreatmentSumOfSquares + _interactionSumOfSquares + _aTreatmentSumOfSquares;
_aTreatmentDegreesOfFreedom = aNum - 1;
_bTreatmentDegreesOfFreedom = bNum - 1;
_interactionDegreesOfFreedom = _aTreatmentDegreesOfFreedom * _bTreatmentDegreesOfFreedom;
_errorDegreesOfFreedom = (totalElements - 1) - _aTreatmentDegreesOfFreedom - _bTreatmentDegreesOfFreedom - _interactionDegreesOfFreedom;
_totalDegreesOfFreedom = totalElements-1;
_aMeanTreatmentSumOfSquares = _aTreatmentSumOfSquares / _aTreatmentDegreesOfFreedom;
_bMeanTreatmentSumOfSquares = _bTreatmentSumOfSquares / _bTreatmentDegreesOfFreedom;
_interactionMeanSumOfSquares = _interactionSumOfSquares / _interactionDegreesOfFreedom;
_meanErrorSumOfSquares = _errorSumOfSquares / _errorDegreesOfFreedom;
_aTestStatistic = TwoWayAnovaClass.CalculateTestStatistic(_aMeanTreatmentSumOfSquares,_meanErrorSumOfSquares);
_bTestStatistic = TwoWayAnovaClass.CalculateTestStatistic(_bMeanTreatmentSumOfSquares, _meanErrorSumOfSquares);
_interactionTestStatistic = TwoWayAnovaClass.CalculateTestStatistic(_interactionMeanSumOfSquares, _meanErrorSumOfSquares);
_aPValue = TwoWayAnovaClass.CalculatePValue(_aTestStatistic, _aTreatmentDegreesOfFreedom, _errorDegreesOfFreedom);
_bPValue = TwoWayAnovaClass.CalculatePValue(_bTestStatistic, _bTreatmentDegreesOfFreedom, _errorDegreesOfFreedom);
_interactionPValue = TwoWayAnovaClass.CalculatePValue(_interactionTestStatistic, _interactionDegreesOfFreedom, _errorDegreesOfFreedom);
TSS = _aTreatmentSumOfSquares.ToString();
ESS = _errorSumOfSquares.ToString();
BSS = _bTreatmentSumOfSquares.ToString();
ISS = _interactionSumOfSquares.ToString();
TotSS = _sumOfSquares.ToString();
TDF = _aTreatmentDegreesOfFreedom.ToString();
BDF = _bTreatmentDegreesOfFreedom.ToString();
IDF = _interactionDegreesOfFreedom.ToString();
EDF = _errorDegreesOfFreedom.ToString();
TotDF = _totalDegreesOfFreedom.ToString();
TMS = _aMeanTreatmentSumOfSquares.ToString();
BMS = _bMeanTreatmentSumOfSquares.ToString();
IMS = _interactionMeanSumOfSquares.ToString();
EMS = _meanErrorSumOfSquares.ToString();
FT = _aTestStatistic.ToString();
FBk = _bTestStatistic.ToString();
FIn = _interactionTestStatistic.ToString();
pT = _aPValue.ToString();
pBl = _bPValue.ToString();
pI = _interactionPValue.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
ReadFile();
display();
}
private void display()
{
textBoxTSS.Text = TSS;
textBoxESS.Text = ESS;
textBoxISS.Text = ISS;
textBoxBSS.Text = BSS;
textBoxTotSS.Text = TotSS;
textBoxTDF.Text = TDF;
textBoxEDF.Text = EDF;
textBoxIDF.Text = IDF;
textBoxBDF.Text = BDF;
textBoxTotDF.Text = TotDF;
textBoxTMS.Text = TMS;
textBoxEMS.Text = EMS;
textBoxBMS.Text = BMS;
textBoxIMS.Text = IMS;
textBoxFT.Text = FT;
textBoxFB.Text = FBk;
textBoxFI.Text = FIn;
textBoxpT.Text = pT;
textBoxpB.Text = pBl;
textBoxpI.Text = pI;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>First off, add a </p>\n\n<pre><code>using OneWayAnovaClassLibrary;\n</code></pre>\n\n<p>to the top of your partial class. That way you can change all of the calls from the library from:</p>\n\n<pre><code>OneWayAnovaClassLibrary.OneWayAnova(...)\n</code></pre>\n\n<p>into:</p>\n\n<pre><code>OneWayAnova(...)\n</code></pre>\n\n<p>These assignment could also be changed to go right into your static strings.</p>\n\n<p>This line:</p>\n\n<pre><code>static string TSS, ESS, TotSS, TDF, EDF, TotDF, TMS, EMS, F, p;\n</code></pre>\n\n<p>Should be split into a line per variable. You should also rename the variables to something meaningful:</p>\n\n<pre><code>static string TreatmentSumOfSquares;\nstatic string ErrorSumOfSquares;\n...\n</code></pre>\n\n<p>You need to get more consistent with your use of var vs variable type. My suggestion would be to use var anywhere a variable is assigned within a method.</p>\n\n<p>I would also change the array declarations to List declarations. This will allow you to change a couple of the for(...) loops into foreach(...) loops.</p>\n\n<p>In your library, I'm not sure why you are doing this in your methods:</p>\n\n<pre><code>double errorSumOfSquares = 0;\nreturn errorSumOfSquares = sumOfSquares - treatmentSumOfSquares;\n</code></pre>\n\n<p>They should be</p>\n\n<pre><code>return sumOfSquares - treatmentSumOfSquares;\n</code></pre>\n\n<p>You also need to store sumOfSquares somewhere that the other methods will be able to access it. Currently, it is only valid in the method that you are calculating it in.</p>\n\n<p>The method names should be changed to start with a capital letter <em>treatmentSumOfSquares</em> would be <em>TreatmentSumOfSquares</em> etc. This is standard C# naming convention.</p>\n\n<p>Anywhere you have an array passed into a method, change it to IEnumerable.</p>\n\n<p>This is a good start, there are a few more things I see, but they are pretty minor. If you want a full clean up, let me know and I'll add it later.</p>\n\n<p>Good luck.</p>\n\n<p><strong>EDIT:</strong> </p>\n\n<p>Here is a first kick at the can for a clean up. I have basically used what Jesse posted for the library, but renamed to methods to portray what they are doing. The way you named them before indicated to me that they were Properties</p>\n\n<p>Code partially cleaned up:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing OneWayAnovaClassLibrary;\n\nnamespace OneWayAnovaTable\n{\n public class OneWayAnovaTable : Form\n {\n public OneWayAnovaTable()\n {\n InitializeComponent();\n }\n\n private static readonly char[] Separators = {',', ' '};\n\n\n // Not sure why these are static\n // Leaving them because you probably have a reason.\n private static double _treatmentSumOfSquares;\n private static double _errorSumOfSquares;\n private static double _sumOfSquares;\n private static double _meanTreatmentSumOfSquares;\n private static double _meanErrorSumOfSquares;\n private static double _testStatistic;\n\n // Not sure what these variables represent\n // Rename as appropriate.\n private static double _tdf;\n private static double _edf;\n private static double _totDf;\n private static double _p;\n\n private static void ProcessFile()\n {\n var lines = File.ReadLines(\"Data.csv\");\n var numbers = ProcessRawNumbers(lines);\n\n var rowTotal = new List<double>();\n var squareRowTotal = new List<double>();\n var rowMean = new List<double>();\n var totalElements = 0;\n var totalInRow = new List<int>();\n\n\n foreach (var values in numbers)\n {\n var sumOfRow = values.Sum();\n\n rowTotal.Add(sumOfRow);\n squareRowTotal.Add(values.Select(v => v*v).Sum());\n rowMean.Add(sumOfRow/values.Count);\n totalInRow.Add(values.Count);\n totalElements += values.Count;\n }\n\n var grandTotal = rowTotal.Sum();\n\n _sumOfSquares = OneWayAnova.CalculateTotalSumOfSquares(squareRowTotal, grandTotal, totalElements);\n _treatmentSumOfSquares = OneWayAnova.CalculateTreatmentSumOfSquares(rowTotal.ToArray(), totalInRow,\n grandTotal,\n totalElements);\n _errorSumOfSquares = OneWayAnova.CalculateErrorSumOfSquares(_sumOfSquares, _treatmentSumOfSquares);\n _meanTreatmentSumOfSquares = OneWayAnova.CalculateMeanTreatmentSumOfSquares(_treatmentSumOfSquares,\n totalInRow.ToArray());\n _meanErrorSumOfSquares = OneWayAnova.CalculateMeanErrorSumOfSquares(_errorSumOfSquares, (numbers.Count - 1),\n (totalElements - 1));\n _testStatistic = OneWayAnova.CalculateTestStatistic(_meanTreatmentSumOfSquares, _meanErrorSumOfSquares);\n _p = OneWayAnova.CalculatePValue(_testStatistic, (numbers.Count - 1), (totalElements - (numbers.Count - 1)));\n\n _tdf = (numbers.Count() - 1);\n _edf = (totalElements - numbers.Count());\n _totDf = (totalElements - 1);\n }\n\n private static List<List<double>> ProcessRawNumbers(IEnumerable<string> lines)\n {\n var numbers = new List<List<double>>();\n /*System.Threading.Tasks.*/\n Parallel.ForEach(lines, line =>\n {\n lock (numbers)\n {\n numbers.Add(ProcessLine(line));\n }\n });\n return numbers;\n }\n\n private static List<double> ProcessLine(string line)\n {\n var list = new List<double>();\n foreach (var s in line.Split(Separators, StringSplitOptions.RemoveEmptyEntries))\n {\n double i;\n if (Double.TryParse(s, out i))\n {\n list.Add(i);\n }\n }\n return list;\n }\n\n private void button2_Click(object sender, EventArgs e)\n {\n ProcessFile();\n Display();\n }\n\n private void Display()\n {\n textBoxTSS.Text = _treatmentSumOfSquares.ToString(CultureInfo.InvariantCulture);\n textBoxESS.Text = _errorSumOfSquares.ToString(CultureInfo.InvariantCulture);\n textBoxTotSS.Text = _sumOfSquares.ToString(CultureInfo.InvariantCulture);\n textBoxTDF.Text = _tdf.ToString(CultureInfo.InvariantCulture);\n textBoxEDF.Text = _edf.ToString(CultureInfo.InvariantCulture);\n textBoxTotDF.Text = _totDf.ToString(CultureInfo.InvariantCulture);\n textBoxTMS.Text = _meanTreatmentSumOfSquares.ToString(CultureInfo.InvariantCulture);\n textBoxEMS.Text = _meanErrorSumOfSquares.ToString(CultureInfo.InvariantCulture);\n textBoxF.Text = _testStatistic.ToString(CultureInfo.InvariantCulture);\n textBoxp.Text = _p.ToString(CultureInfo.InvariantCulture);\n }\n }\n}\n\nnamespace OneWayAnovaClassLibrary\n{\n public static class OneWayAnova\n {\n public static double CalculateTotalSumOfSquares(IEnumerable<double> squareRowTotal, double grandTotal,\n int totalOfAllElements)\n {\n return squareRowTotal.Sum() - (grandTotal*grandTotal/totalOfAllElements);\n }\n\n public static double CalculateTreatmentSumOfSquares(double[] rowTotal, IEnumerable<int> totalInRow,\n double grandTotal,\n int totalOfAllElements)\n {\n return totalInRow.Select((t, i) => rowTotal[i]*rowTotal[i]/t).Sum() -\n (grandTotal*grandTotal/totalOfAllElements);\n }\n\n public static double CalculateErrorSumOfSquares(double sumOfSquares, double treatmentSumOfSquares)\n {\n return sumOfSquares - treatmentSumOfSquares;\n }\n\n public static double CalculateMeanTreatmentSumOfSquares(double errorSumOfSquares, int[] totalInRow)\n {\n return errorSumOfSquares/(totalInRow.Length - 1);\n }\n\n public static double CalculateMeanErrorSumOfSquares(double errorSumOfSquares, int a, int b)\n {\n return errorSumOfSquares/(b - a);\n }\n\n public static double CalculateTestStatistic(double meanTreatmentSumOfSquares, double meanErrorSumOfSquares)\n {\n return meanTreatmentSumOfSquares/meanErrorSumOfSquares;\n }\n\n public static double CalculatePValue(double fStatistic, int degreeNum, int degreeDenom)\n {\n return Integrate(0, fStatistic, degreeNum, degreeDenom);\n }\n\n // As it stands, this can be made private\n public static double Integrate(double start, double end, int degreeFreedomT, int degreeFreedomE)\n {\n const int Iterations = 100000;\n double x, sum = 0, sumT = 0;\n var dist = (end - start)/Iterations;\n\n for (var i = 1; i < Iterations; i++)\n {\n x = start + (i*dist);\n sumT += IntegralFunction(x - (dist/2), degreeFreedomT, degreeFreedomE);\n sum += IntegralFunction(x, degreeFreedomT, degreeFreedomE);\n }\n\n x = start + (Iterations*dist);\n sumT += IntegralFunction(x - (dist/2), degreeFreedomT, degreeFreedomE);\n return (dist/6)*\n (IntegralFunction(start, degreeFreedomT, degreeFreedomE) +\n IntegralFunction(end, degreeFreedomT, degreeFreedomE) + (2*sum) + (4*sumT));\n }\n\n // As it stands, this can be made private\n public static double IntegralFunction(double x, int degreeFreedomT, int degreeFreedomE)\n {\n return ((Math.Pow(degreeFreedomE, degreeFreedomE/2.0)*Math.Pow(degreeFreedomT, degreeFreedomT/2.0))/\n (Factorial((degreeFreedomE/2) - 1)*Factorial((degreeFreedomT/2) - 1)))*\n Factorial((((degreeFreedomT + degreeFreedomE)/2) - 1))*\n (Math.Pow(x, (degreeFreedomE/2) - 1)/\n Math.Pow((degreeFreedomT + (degreeFreedomE*x)), ((degreeFreedomE + degreeFreedomT)/2.0)));\n }\n\n // As it stands, this can be made private\n public static double Factorial(double n)\n {\n return n.Equals(0) ? 1.0 : n * Factorial(n - 1);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T15:32:30.113",
"Id": "23059",
"Score": "0",
"body": "I would love a full clean up, if you don't mind posting it. Also, I am not very comfortable using IEnumerable, in the sense, I find it confusing implementing, though it is a powerful tool. Would you please show how to use it in the methods correctly? Thank you for your time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T05:45:09.333",
"Id": "23108",
"Score": "0",
"body": "I am using static, because the tutorial I started learning from used static for my data and methods. What do you recommend using, as I will be having return values?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T08:04:04.377",
"Id": "23113",
"Score": "0",
"body": "+1, but I wouldn't go so far as saying `My suggestion would be to use var _anywhere_ a variable is assigned within a method.`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T14:11:21.870",
"Id": "23127",
"Score": "1",
"body": "@CamelUno static is a keyword that makes the instances the same across all instances of this class. So if you have class objA, objB, objC and have a static prop = 3, prop will have the same value across all the instances. Now if you took the static off, each instance could be assigned a different value for prop, so you could have objA.Prop = 1, objB.Prop = 2 and objC.Prop = 3. Like I said, I'm not too worried about it because I don't know enough on how this class is going to be used. Maybe take a read [Here](http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.80).aspx)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T14:14:19.603",
"Id": "23128",
"Score": "0",
"body": "@ANeves I see your point, and there are discussions all over about it, with people on both sides. Personally, I prefer to use var, but I see the value of implicitly declaring with the type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T07:07:41.480",
"Id": "23244",
"Score": "0",
"body": "@JeffVanzella: I was working on the improved program you gave me, and I changed some things around for a higher calculation program. Do I need to call the multiple for loops so many times? What is a more efficient way to do so? Considering converting arrays into lists in the double for loops."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T14:24:08.987",
"Id": "14258",
"ParentId": "14248",
"Score": "6"
}
},
{
"body": "<p>Here's a take on it (note it uses LINQ to simplify a bit). There's a few other potential improvements (such as removing the file reading from the UI class and putting it in its own, etc.) but I just opted to clean up the existing code a bit:</p>\n\n<p><strong>Program for button and Function calling is here:</strong></p>\n\n<pre><code>namespace OneWayAnovaTable\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using System.Linq;\n using System.Threading.Tasks;\n using System.Windows.Forms;\n\n using OneWayAnovaClassLibrary;\n\n public partial class OneWayAnovaTable : Form\n {\n private string tss, ess, totSs, tdf, edf, totDf, tms, ems, f, p;\n\n public OneWayAnovaTable()\n {\n this.InitializeComponent();\n }\n\n private void button2_Click(object sender, EventArgs e)\n {\n this.ReadFile();\n this.Display();\n }\n\n private void ReadFile()\n {\n var lines = File.ReadLines(\"Data.csv\");\n var numbers = new List<List<double>>();\n var separators = new[] { ',', ' ' };\n /*System.Threading.Tasks.*/\n Parallel.ForEach(lines, line =>\n {\n var list = new List<double>();\n foreach (var s in line.Split(separators, StringSplitOptions.RemoveEmptyEntries))\n {\n double i;\n\n if (double.TryParse(s, out i))\n {\n list.Add(i);\n }\n }\n\n lock (numbers)\n {\n numbers.Add(list);\n }\n });\n\n var rowTotal = new double[numbers.Count];\n var squareRowTotal = new double[numbers.Count];\n var rowMean = new double[numbers.Count];\n var totalElements = 0;\n var totalInRow = new int[numbers.Count()];\n ////var grandTotalMean = 0.0;\n ////var grandMean = 0.0;\n\n for (var row = 0; row < numbers.Count; row++)\n {\n var values = numbers[row].ToArray();\n\n rowTotal[row] = values.Sum();\n squareRowTotal[row] = values.Select(v => v * v).Sum();\n rowMean[row] = rowTotal[row] / values.Length;\n totalInRow[row] += values.Length;\n totalElements += totalInRow[row];\n ////grandTotalMean += rowMean[row];\n ////grandMean += rowMean[row] / numbers.Count;\n }\n\n var grandTotal = rowTotal.Sum();\n\n var sumOfSquares = OneWayAnova.TotalSumOfSquares(squareRowTotal, grandTotal, totalElements);\n var treatmentSumOfSquares = OneWayAnova.TreatmentSumOfSquares(rowTotal, totalInRow, grandTotal, totalElements);\n var errorSumOfSquares = OneWayAnova.ErrorSumOfSquares(sumOfSquares, treatmentSumOfSquares);\n var meanTreatmentSumOfSquares = OneWayAnova.MeanTreatmentSumOfSquares(treatmentSumOfSquares, totalInRow);\n var meanErrorSumOfSquares = OneWayAnova.MeanErrorSumOfSquares(errorSumOfSquares, (numbers.Count - 1), (totalElements - 1));\n var fStatistic = OneWayAnova.TestStatistic(meanTreatmentSumOfSquares, meanErrorSumOfSquares);\n var pValue = OneWayAnova.pValue(fStatistic, (numbers.Count - 1), (totalElements - (numbers.Count - 1)));\n\n this.tss = treatmentSumOfSquares.ToString();\n this.ess = errorSumOfSquares.ToString();\n this.totSs = sumOfSquares.ToString();\n this.tdf = (numbers.Count() - 1).ToString();\n this.edf = (totalElements - numbers.Count()).ToString();\n this.totDf = (totalElements - 1).ToString();\n this.tms = meanTreatmentSumOfSquares.ToString();\n this.ems = meanErrorSumOfSquares.ToString();\n this.f = fStatistic.ToString();\n this.p = pValue.ToString();\n }\n\n private void Display()\n {\n this.textBoxTSS.Text = this.tss;\n this.textBoxESS.Text = this.ess;\n this.textBoxTotSS.Text = this.totSs;\n this.textBoxTDF.Text = this.tdf;\n this.textBoxEDF.Text = this.edf;\n this.textBoxTotDF.Text = this.totDf;\n this.textBoxTMS.Text = this.tms;\n this.textBoxEMS.Text = this.ems;\n this.textBoxF.Text = this.f;\n this.textBoxp.Text = this.p;\n }\n }\n}\n</code></pre>\n\n<p><strong>The Library file with all the functions is here:</strong></p>\n\n<pre><code>namespace OneWayAnovaClassLibrary\n{\n using System;\n using System.Collections.Generic;\n using System.Linq;\n\n public static class OneWayAnova\n {\n public static double TotalSumOfSquares(IEnumerable<double> squareRowTotal, double grandTotal, int totalOfAllElements)\n {\n return squareRowTotal.Sum() - (grandTotal * grandTotal / totalOfAllElements);\n }\n\n public static double TreatmentSumOfSquares(double[] rowTotal, IEnumerable<int> totalInRow, double grandTotal, int totalOfAllElements)\n {\n return totalInRow.Select((t, i) => rowTotal[i] * rowTotal[i] / t).Sum() - (grandTotal * grandTotal / totalOfAllElements);\n }\n\n public static double ErrorSumOfSquares(double sumOfSquares, double treatmentSumOfSquares)\n {\n return sumOfSquares - treatmentSumOfSquares;\n }\n\n public static double MeanTreatmentSumOfSquares(double errorSumOfSquares, int[] totalInRow)\n {\n return errorSumOfSquares / (totalInRow.Length - 1);\n }\n\n public static double MeanErrorSumOfSquares(double errorSumOfSquares, int a, int b)\n {\n return errorSumOfSquares / (b - a);\n }\n\n public static double TestStatistic(double meanTreatmentSumOfSquares, double meanErrorSumOfSquares)\n {\n return meanTreatmentSumOfSquares / meanErrorSumOfSquares;\n }\n\n public static double pValue(double fStatistic, int degreeNum, int degreeDenom)\n {\n return Integrate(0, fStatistic, degreeNum, degreeDenom);\n }\n\n public static double Integrate(double start, double end, int degreeFreedomT, int degreeFreedomE)\n {\n const int Iterations = 100000;\n double x, sum = 0, sumT = 0;\n var dist = (end - start) / Iterations;\n\n for (var i = 1; i < Iterations; i++)\n {\n x = start + (i * dist);\n sumT += IntegralFunction(x - (dist / 2), degreeFreedomT, degreeFreedomE);\n sum += IntegralFunction(x, degreeFreedomT, degreeFreedomE);\n }\n\n x = start + (Iterations * dist);\n sumT += IntegralFunction(x - (dist / 2), degreeFreedomT, degreeFreedomE);\n return (dist / 6) * (IntegralFunction(start, degreeFreedomT, degreeFreedomE) + IntegralFunction(end, degreeFreedomT, degreeFreedomE) + (2 * sum) + (4 * sumT));\n }\n\n public static double IntegralFunction(double x, int degreeFreedomT, int degreeFreedomE)\n {\n return ((Math.Pow(degreeFreedomE, degreeFreedomE / 2.0) * Math.Pow(degreeFreedomT, degreeFreedomT / 2.0)) / (Factorial((degreeFreedomE / 2) - 1) * Factorial((degreeFreedomT / 2) - 1))) * Factorial((((degreeFreedomT + degreeFreedomE) / 2) - 1)) * (Math.Pow(x, (degreeFreedomE / 2) - 1) / Math.Pow((degreeFreedomT + (degreeFreedomE * x)), ((degreeFreedomE + degreeFreedomT) / 2.0)));\n }\n\n public static double Factorial(double n)\n {\n return n == 0 ? 1.0 : n * Factorial(n - 1);\n }\n }\n}\n</code></pre>\n\n<p><strong>The entry point is in another program as follows:</strong></p>\n\n<pre><code>namespace OneWayAnovaTable\n{\n using System;\n using System.Windows.Forms;\n\n /// <summary>\n /// Holds the main entry point for the application.\n /// </summary>\n internal static class Program\n {\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n private static void Main()\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n\n using (var tempObj = new OneWayAnovaTable())\n {\n tempObj.ShowDialog();\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T21:58:34.793",
"Id": "23602",
"Score": "0",
"body": "Yes, this is a lot cleaner, and you have done a great job given what you had to work with, but this can be taken further. Functions can be shorter, a lot more work can be outsourced to a class that is not responsible for GUI, and the `Display` method can be fed a single object which contains `tss` through `p` as readonly properties with more descriptive names. That said, the original computation is a bit hard to follow without understanding the domain."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-11T13:35:35.930",
"Id": "23618",
"Score": "0",
"body": "Oh, I agree fully. Hence my opening statement in which I deliberately limit myself to the immediate possibilities :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T15:32:07.643",
"Id": "14263",
"ParentId": "14248",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T10:06:05.330",
"Id": "14248",
"Score": "4",
"Tags": [
"c#",
"performance",
".net",
"statistics"
],
"Title": "Two-way ANOVA table"
}
|
14248
|
<p>I have the following control structure that I would like to improve:</p>
<pre><code>if(number >= 100) then doSetInc(id, 8, 20)
elseif(number >= 91) then doSetInc(id, 8, 30)
elseif(number >= 81) then doSetInc(id, 8, 50)
elseif(number >= 7) then doSetInc(id, 8, 70)
elseif(number >= 1) then doSetInc(id, 8, 100)
end
</code></pre>
|
[] |
[
{
"body": "<p>Kinda hard to know what you mean with better since you don't specify in what regard.</p>\n\n<p>In regards to cleaner code:</p>\n\n<ul>\n<li><p>FunctionName doSetInc is a bit weird, what does it do?</p></li>\n<li><p>You are sending in 3 variables into the function, it's common practice to use as few as possible (rarely more than 2, 0 or 1 prefered).</p></li>\n<li><p>You are always sending in \"id\" and \"8\" into the function, thus this function might not need those attributes and could be set in another way.</p></li>\n</ul>\n\n<p>Other than that, since I find no easy mathematical similarities between these checks and what to do, I would say no, you can't improve it given this small piece of code and no other context.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T12:37:25.167",
"Id": "14251",
"ParentId": "14249",
"Score": "6"
}
},
{
"body": "<p>1.<br>\nWhat does 'doSetInc' do? Its not a descriptive name.<br>\n - Where does that 8 come from?<br>\n - Where does that 20 come from?<br>\n<br>\nBad code good code: <a href=\"http://commadot.com/wp-content/uploads/2009/02/wtf.png\" rel=\"nofollow\">http://commadot.com/wp-content/uploads/2009/02/wtf.png</a><br>\n<br>\n<br>\n2.<br>\nYou have a set of ranges and for each a specific value is to be derived. Depending on how many integers there are to be evaluated, you might want to make a hash containing what each integer turns into.</p>\n\n<p>It would look something like this:</p>\n\n<blockquote>\n <p>derived_id{1}->20<br>\n derived_id{2}->20<br>\n ...<br>\n derived_id{64}->70<br>\n ...<br></p>\n</blockquote>\n\n<p>At that you can replace the entire block with a single line.</p>\n\n<pre><code>doSetInc(id, 8, derived_id{number})\n</code></pre>\n\n<p>And if you would improve the readability like I suggested above, it would become a single easily readable line.</p>\n\n<p>Be careful though, at this point people may start to feel like you haven't really done anything.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T10:57:33.590",
"Id": "14323",
"ParentId": "14249",
"Score": "4"
}
},
{
"body": "<h1>1)</h1>\n\n<p>To simplify the if else conditions, use <code><</code> instead of <code>>=</code>.\nNote: This only works correctly if <code>number</code> isn't a decimal. Be sure to <a href=\"http://lua-users.org/wiki/SimpleRound\" rel=\"nofollow\">round</a>.</p>\n\n<p>Old Code:</p>\n\n<pre><code>if(number >= 100) then doSetInc(id, 8, 20)\nelseif(number >= 91) then doSetInc(id, 8, 30)\nelseif(number >= 81) then doSetInc(id, 8, 50)\nelseif(number >= 7) then doSetInc(id, 8, 70)\nelseif(number >= 1) then doSetInc(id, 8, 100)\nend\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>if( 99 < number ) then doSetInc(id, 8, 20)\nelseif(90 < number ) then doSetInc(id, 8, 30)\nelseif(80 < number ) then doSetInc(id, 8, 50)\nelseif( 6 < number ) then doSetInc(id, 8, 70)\nelseif( 0 < number ) then doSetInc(id, 8, 100)\nend \n</code></pre>\n\n<h1>2)</h1>\n\n<p>Create a function that retrieves the value of the third parameter, since that's the only thing that changes for the <code>doSetInc</code> calls.</p>\n\n<h1>3)</h1>\n\n<p>Rename <code>doSetInc</code> to <code>setInc</code>.</p>\n\n<h1>4)</h1>\n\n<p>Declare variables as <code>local</code>, unless <code>global</code> is required.</p>\n\n<h2>Final Code</h2>\n\n<pre><code>-- core function\nlocal getGrade = function(x)\n local val \n if ( 99 < number ) then val = 20\n elseif (90 < number ) then val = 30\n elseif (80 < number ) then val = 50\n elseif ( 6 < number ) then val = 70\n elseif ( 0 < number ) then val = 100\n return val;\nend \n\nsetInc(id, 8, getGrade( number ) )\n</code></pre>\n\n<p>Use case:</p>\n\n<pre><code>local number = 10\nlocal id = \"283\"\nlocal setInc = function(a,b,c) \n print( \"setInc(\"..a..\", \" .. b .. \", \" .. c .. \")\" )\nend\n\nsetInc(id, 8, getGrade( number ) )\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-13T05:38:46.823",
"Id": "15559",
"ParentId": "14249",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T11:37:12.443",
"Id": "14249",
"Score": "8",
"Tags": [
"lua"
],
"Title": "Is there a better way of implementing this control structure?"
}
|
14249
|
<p>Below is some code that I've been working to simplify, however I feel there is more that can be done. Please note that I did clean up the <code>articles.search</code> method.</p>
<pre><code>class HomeController < ApplicationController
@@articles_per_page = 6
def index
@paged_articles = articles.search(:user_id=> @@user_id, :page=>'1', :per_page=>@@articles_per_page)
@tags = get_tags
@next_page_url = url_for(:controller =>:home, :action => :page, :page_id=> 2)
@page_title = "Recent articles"
end
def tags
@paged_articles = articles.search(:page=>'1',:tags=>params[:tag_name], :per_page=>@@articles_per_page)
@tags = get_tags
@next_page_url = url_for(:controller =>:home, :action => :page, :tag_name => params[:tag_name], :page_id=> 2)
@page_title = "Search articles by tags"
render :index
end
def about
@page_title = "About"
end
private
def get_tags
articles.getTags 'param1', 'param2'
end
end
</code></pre>
<p>I simplified it this way</p>
<pre><code>class HomeController < ApplicationController
@@articles_per_page = 6
@@first_page_articles_options = {:page=>'1', :per_page=>@@articles_per_page}
@@second_page_url_options = {:controller =>:home, :action => :page, :page_id=> 2}
def index
@paged_articles = articles.search(@@first_page_articles_options)
@tags = get_tags
@next_page_url = url_for(@@second_page_url_options)
@page_title = "Recent articles"
end
def tags
@@first_page_articles_options[:tags] = params[:tag_name]
@paged_articles = articles.search(@@first_page_articles_options)
@tags = get_tags
@@second_page_url_options[:tag_name] = params[:tag_name]
@next_page_url = url_for(@@second_page_url_options)
@page_title = "Search articles by tags"
render :index
end
def about
@page_title = "About"
end
private
def get_tags
articles.getTags 'param1', 'param2'
end
end
</code></pre>
<p>So what do you think? Is there any way to make it more better and cleaner?</p>
|
[] |
[
{
"body": "<p>You can move urls and titles to helpers and articles search to separate method</p>\n\n<pre><code>class HomeController < ApplicationController\n # this methods can be used in view template\n helper_method :next_page_url, :page_title\n\n @@articles_per_page = 6\n @@first_page_articles_options = {:page=>'1', :per_page=>@@articles_per_page}\n @@second_page_url_options = {:controller =>:home, :action => :page, :page_id=> 2}\n\n\n def index\n @paged_articles = articles.search(@@first_page_articles_options)\n @tags = get_tags\n end\n\n def tags\n @paged_articles = load_articles\n @tags = get_tags\n\n render :index\n end\n def about\n @page_title = \"About\"\n end\n\n private\n\n def load_articles\n ...\n end \n\n ...\n\n # helpers\n\n def next_page_url\n if filter_by_tags?\n url_for(@@second_page_url_options) \n else\n @@second_page_url_options[:tag_name] = params[:tag_name]\n url_for(@@second_page_url_options)\n end \n end\n\n def page_title\n if filter_by_tags?\n \"Recent articles\" \n else\n \"Search articles by tags\"\n end \n end\n\n def filter_by_tags?\n params[:tag_name].present?\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T14:17:08.523",
"Id": "23055",
"Score": "0",
"body": "How do I do it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T21:40:07.330",
"Id": "23154",
"Score": "0",
"body": "update my answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T05:29:56.430",
"Id": "23162",
"Score": "0",
"body": "There is no implementation of helper method yet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T08:19:00.097",
"Id": "23245",
"Score": "0",
"body": "next_page_url and page_title declared as helper methods and available in views, see http://apidock.com/rails/ActionController/Helpers/ClassMethods/helper_method"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T19:40:45.330",
"Id": "23445",
"Score": "0",
"body": "You should use constants where you use class variables here."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T14:04:50.197",
"Id": "14254",
"ParentId": "14250",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "14254",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T12:37:21.647",
"Id": "14250",
"Score": "0",
"Tags": [
"ruby",
"ruby-on-rails",
"pagination",
"active-record"
],
"Title": "Pagination and Controller setup"
}
|
14250
|
<p>Following is the code that I'm currently using to validate the user given IP address (IPV4 and IPV6). It makes use of apache commons-validator's <code>InetAddressValidator</code>. However, their function validates only IPV4 address and not IPV6. </p>
<pre><code>public static boolean isValidInetAddress(final String address){
boolean isValid = false;
if(address == null || address.trim().isEmpty())
return isValid;
if(InetAddressValidator.getInstance().isValid(address)){
isValid = true;
} else { //not an IPV4 address, could be IPV6?
try {
isValid = InetAddress.getByName(address) instanceof Inet6Address;
} catch (UnknownHostException ex) {
isValid = false;
}
}
return isValid;
}
</code></pre>
<p>Is there a better way?</p>
<p>(P.S commons-validator does regex pattern matching for IPV4 address validation) </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T07:03:41.407",
"Id": "50871",
"Score": "0",
"body": "Keep in mind that `InetAddress.getByName` can do DNS lookups."
}
] |
[
{
"body": "<p>It seems fine if there is not any simpler Java or Apache Commons API.</p>\n\n<p>I'd modify a few small things:</p>\n\n<ul>\n<li>The <code>isValid</code> boolean would be unnecesary if you return immediately when you know the return value. (<a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\">Flattening Arrow Code</a>)</li>\n<li><code>(address == null || address.trim().isEmpty())</code> could be changed to <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html#isBlank%28java.lang.CharSequence%29\"><code>StringUtils.isBlank</code></a>.</li>\n<li>According to the <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-142311.html#449\">Code Conventions for the Java Programming Language</a> if statements always should use braces.</li>\n</ul>\n\n\n\n<pre><code>public static boolean isValidInetAddress(final String address) {\n if (StringUtils.isBlank(address)) {\n return false;\n }\n if (InetAddressValidator.getInstance().isValid(address)) {\n return true;\n }\n\n //not an IPV4 address, could be IPV6?\n try {\n return InetAddress.getByName(address) instanceof Inet6Address;\n } catch (final UnknownHostException ex) {\n return false;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T11:10:22.367",
"Id": "23119",
"Score": "1",
"body": "Thanks for the review! I didn't know about Flatening arrow code!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T10:54:00.087",
"Id": "14291",
"ParentId": "14252",
"Score": "13"
}
},
{
"body": "<p>You can use the InetAddressUtils from httpclient library:</p>\n\n<pre><code>/**\n * @param ip the ip\n * @return check if the ip is valid ipv4 or ipv6\n */\nprivate static boolean isValidIp(final String ip) {\n return InetAddressUtils.isIPv4Address(ip) || InetAddressUtils.isIPv6Address(ip);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T12:13:07.367",
"Id": "36285",
"ParentId": "14252",
"Score": "8"
}
},
{
"body": "<p><a href=\"https://seancfoley.github.io/IPAddress/\" rel=\"nofollow noreferrer\">The IPAddress Java library</a> will do it. Disclaimer: I am the project manager.</p>\n\n<p>This library supports IPv4 and IPv6 transparently, so validating either works the same below, and it supports CIDR subnets and other subnet formats as well.</p>\n\n<p>Verify if an address is valid:</p>\n\n<pre><code> String str = \"fe80::6a05:caff:fe3:123%2\";\n IPAddressString addrString = new IPAddressString(str);\n try {\n IPAddress addr = addrString.toAddress();\n ...\n } catch(AddressStringException e) {\n //e.getMessage provides validation issue\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-11T15:14:53.320",
"Id": "191805",
"ParentId": "14252",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "14291",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T13:14:44.033",
"Id": "14252",
"Score": "9",
"Tags": [
"java",
"validation",
"networking",
"ip-address"
],
"Title": "Validate IP address in Java"
}
|
14252
|
<p>I have the following SQL query I am trying to use (save/make easy future modifications to) that is essentially the same query over and over and over, <code>UNION</code>ed each time, with only minor changes to the <code>WHERE</code> clause. </p>
<p>I am more familiar with MS Access, which allows me to use an <code>IIf</code> statement in the <code>SELECT</code> clause to accomplish the same, but I was not sure how to do this with Oracle, so I came up with this mess instead.</p>
<p>Since there may be future changes in the query, such as adding or removing items from the <code>common.jurisdiction_td.state_cd</code> pull, I want to be able to reduce the overall size/repeteiveness of the query so making those changes is easier. Other values like the dates are more flexible, so I've got those plugging in as user-specified variables already. It's the more static criteria that I'm concerned about, since I don't want to have the end-user putting in the same variable for those fields 10,000 times before the next potential change.</p>
<p>Is there a way I can simplify this so that either the <code>UNION</code>s are reduced and/or the sub-queries are smaller, more compact, and better able to be manipulated?</p>
<p>I had also considered <code>SELECT</code>ing my needed fields in the top-level query, but the DB is very large and each individual step takes a few minutes to run as-is. I was worried that doing <code>SELECT *, '<variable field value>'</code> in the sub-queries would make the process run far too long. (I have not tested this method, but I have assumed it is no good. Please correct me if that's wrong!)</p>
<p>Also, I feel like the use of <code>()</code> is a bit overboard, but this was produced by a query builder, and I'm presenting the output of that here.</p>
<pre><code>SELECT Count(DISTINCT billrevw.bill_hdr.icn),
billrevw.bill_hdr.bill_orgn_id,
billrevw.bill_hdr.type_of_bill,
billrevw.bill_hdr.bill_type_cd,
'<1000' AS TBC
FROM common.jurisdiction_td,
billrevw.bill_hdr
WHERE ( ( billrevw.bill_hdr.icn LIKE '%00' )
AND ((( ( billrevw.bill_hdr.bill_orgn_id LIKE 'GAL%' )
OR ( billrevw.bill_hdr.bill_orgn_id LIKE 'GSA%' )
OR ( billrevw.bill_hdr.bill_orgn_id LIKE 'GEE%' ) )))
AND ( billrevw.bill_hdr.fnlzd_paid_posting_dt BETWEEN
'01-May-2012 0:00:00' AND '31-Jul-2012 0:00:00' )
AND ( billrevw.bill_hdr.bill_type_cd <> '6' )
AND ( common.jurisdiction_td.state_cd NOT IN (
'139', '199', '219', '239' ) )
)
AND (( ( billrevw.bill_hdr.rptng_exclusn_cd NOT IN ( 'MOD', 'NFS' ) )
OR ( billrevw.bill_hdr.rptng_exclusn_cd IS NULL ) ))
AND ( billrevw.bill_hdr.ttl_chrg BETWEEN 0 AND 999.99 )
AND billrevw.bill_hdr.dw_jrsdctn_row_id =
common.jurisdiction_td.dw_jrsdctn_row_id
(
+
)
GROUP BY billrevw.bill_hdr.bill_orgn_id,
billrevw.bill_hdr.type_of_bill,
billrevw.bill_hdr.bill_type_cd
UNION
SELECT Count(DISTINCT billrevw.bill_hdr.icn),
billrevw.bill_hdr.bill_orgn_id,
billrevw.bill_hdr.type_of_bill,
billrevw.bill_hdr.bill_type_cd,
'1000-5000' AS TBC
FROM common.jurisdiction_td,
billrevw.bill_hdr
WHERE ( ( billrevw.bill_hdr.icn LIKE '%00' )
AND ((( ( billrevw.bill_hdr.bill_orgn_id LIKE 'GAL%' )
OR ( billrevw.bill_hdr.bill_orgn_id LIKE 'GSA%' )
OR ( billrevw.bill_hdr.bill_orgn_id LIKE 'GEE%' ) )))
AND ( billrevw.bill_hdr.fnlzd_paid_posting_dt BETWEEN
'01-May-2012 0:00:00' AND '31-Jul-2012 0:00:00' )
AND ( billrevw.bill_hdr.bill_type_cd <> '6' )
AND ( common.jurisdiction_td.state_cd NOT IN (
'139', '199', '219', '239' ) )
)
AND (( ( billrevw.bill_hdr.rptng_exclusn_cd NOT IN ( 'MOD', 'NFS' ) )
OR ( billrevw.bill_hdr.rptng_exclusn_cd IS NULL ) ))
AND ( billrevw.bill_hdr.ttl_chrg BETWEEN 1000 AND 4999.99 )
AND billrevw.bill_hdr.dw_jrsdctn_row_id =
common.jurisdiction_td.dw_jrsdctn_row_id
(
+
)
GROUP BY billrevw.bill_hdr.bill_orgn_id,
billrevw.bill_hdr.type_of_bill,
billrevw.bill_hdr.bill_type_cd
UNION
SELECT Count(DISTINCT billrevw.bill_hdr.icn),
billrevw.bill_hdr.bill_orgn_id,
billrevw.bill_hdr.type_of_bill,
billrevw.bill_hdr.bill_type_cd,
'5000-10000' AS TBC
FROM common.jurisdiction_td,
billrevw.bill_hdr
WHERE ( ( billrevw.bill_hdr.icn LIKE '%00' )
AND ((( ( billrevw.bill_hdr.bill_orgn_id LIKE 'GAL%' )
OR ( billrevw.bill_hdr.bill_orgn_id LIKE 'GSA%' )
OR ( billrevw.bill_hdr.bill_orgn_id LIKE 'GEE%' ) )))
AND ( billrevw.bill_hdr.fnlzd_paid_posting_dt BETWEEN
'01-May-2012 0:00:00' AND '31-Jul-2012 0:00:00' )
AND ( billrevw.bill_hdr.bill_type_cd <> '6' )
AND ( common.jurisdiction_td.state_cd NOT IN (
'139', '199', '219', '239' ) )
)
AND (( ( billrevw.bill_hdr.rptng_exclusn_cd NOT IN ( 'MOD', 'NFS' ) )
OR ( billrevw.bill_hdr.rptng_exclusn_cd IS NULL ) ))
AND ( billrevw.bill_hdr.ttl_chrg BETWEEN 5000 AND 9999.99 )
AND billrevw.bill_hdr.dw_jrsdctn_row_id =
common.jurisdiction_td.dw_jrsdctn_row_id
(
+
)
GROUP BY billrevw.bill_hdr.bill_orgn_id,
billrevw.bill_hdr.type_of_bill,
billrevw.bill_hdr.bill_type_cd
UNION
SELECT Count(DISTINCT billrevw.bill_hdr.icn),
billrevw.bill_hdr.bill_orgn_id,
billrevw.bill_hdr.type_of_bill,
billrevw.bill_hdr.bill_type_cd,
'10000-25000' AS TBC
FROM common.jurisdiction_td,
billrevw.bill_hdr
WHERE ( ( billrevw.bill_hdr.icn LIKE '%00' )
AND ((( ( billrevw.bill_hdr.bill_orgn_id LIKE 'GAL%' )
OR ( billrevw.bill_hdr.bill_orgn_id LIKE 'GSA%' )
OR ( billrevw.bill_hdr.bill_orgn_id LIKE 'GEE%' ) )))
AND ( billrevw.bill_hdr.fnlzd_paid_posting_dt BETWEEN
'01-May-2012 0:00:00' AND '31-Jul-2012 0:00:00' )
AND ( billrevw.bill_hdr.bill_type_cd <> '6' )
AND ( common.jurisdiction_td.state_cd NOT IN (
'139', '199', '219', '239' ) )
)
AND (( ( billrevw.bill_hdr.rptng_exclusn_cd NOT IN ( 'MOD', 'NFS' ) )
OR ( billrevw.bill_hdr.rptng_exclusn_cd IS NULL ) ))
AND ( billrevw.bill_hdr.ttl_chrg BETWEEN 10000 AND 24999.99 )
AND billrevw.bill_hdr.dw_jrsdctn_row_id =
common.jurisdiction_td.dw_jrsdctn_row_id
(
+
)
GROUP BY billrevw.bill_hdr.bill_orgn_id,
billrevw.bill_hdr.type_of_bill,
billrevw.bill_hdr.bill_type_cd;
</code></pre>
|
[] |
[
{
"body": "<p>first of all you must avoid using \"or\" in where clause.</p>\n\n<p>second, I understand that your sql code is not full, but still I think that you can get rid of all unions and use case/decode instead.</p>\n\n<p>third, I would suggest not to use tables in \"from\" which fields not used in \"select\" use in/exists instead.</p>\n\n<p>consider query I've wrote</p>\n\n<pre><code>Select Count(Distinct Icn), t.*\n From (Select Bh.Icn\n ,Bh.Bill_Orgn_Id\n ,Bh.Type_Of_Bill\n ,Bh.Bill_Type_Cd\n ,Case\n When Bh.Ttl_Chrg Between 0 And 999.99 Then\n '<1000'\n When Bh.Ttl_Chrg Between 1000 And 4999.99 Then\n '1000-5000'\n When Bh.Ttl_Chrg Between 5000 And 9999.99 Then\n '5000-10000'\n When Bh.Ttl_Chrg Between 10000 And 24999.99 Then\n '10000-25000'\n End Tbc\n From Billrevw.Bill_Hdr Bh\n Where Bh.Icn Like '%00'\n And Substr(Bh.Bill_Orgn_Id, 1, 3) In ('GAL', 'GSA', 'GEE')\n And Bh.Fnlzd_Paid_Posting_Dt Between '01-May-2012 0:00:00' And\n '31-Jul-2012 0:00:00'\n And Bh.Bill_Type_Cd <> '6'\n And Exists\n (Select Null\n From Common.Jurisdiction_Td j\n Where j.State_Cd Not In ('139', '199', '219', '239')\n And Bh.Dw_Jrsdctn_Row_Id = j.Dw_Jrsdctn_Row_Id)\n And Nvl(Bh.Rptng_Exclusn_Cd, '') Not In ('MOD', 'NFS')) t\n Group By t.Bill_Orgn_Id, t.Type_Of_Bill, t.Bill_Type_Cd, t.Tbc\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T14:33:34.810",
"Id": "32532",
"Score": "0",
"body": "Why not use `OR`? Thanks for the `CASE` and `IN`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-10T07:52:40.323",
"Id": "32616",
"Score": "0",
"body": "`or` is very costly"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-10T19:35:33.123",
"Id": "32660",
"Score": "0",
"body": "You really shouldn't be using `BETWEEN` for ranges, even when it's (probably) a fixed-precision type. Please use an exclusive upper-bound (`'<'`) - such as `... CASE WHEN bh.ttl_chrg >= 0 AND bh.ttl_chrg < 1000 THEN ....`. This will also protect you if the precision _does_ change in the future. Also, I find it difficult to believe that an `OR` is very costly; is there something in the Oracle documentation I'm not aware of?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-11T05:51:34.350",
"Id": "32686",
"Score": "1",
"body": "`select * from table_name where ( :A is null or A=:A )` full table scan\n\n`select * from table_name where :A is not null and A=:A\nunion all\nselect * from table_name where :A is null`\ntable scan and index access"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T21:34:41.770",
"Id": "39808",
"Score": "0",
"body": "@Babur \"where :A is null\" is going to be a full table scan, unless you have employed some special kind of indexing technique."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T21:35:26.397",
"Id": "39809",
"Score": "0",
"body": "OR is not neccessarily a full table scan. Index-based methods, such as a fast full index scan, are common with OR's. An IN() is logically the same as an OR anyway, and they produce the same transformed query."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-11T13:29:34.500",
"Id": "19490",
"ParentId": "14253",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T13:23:42.857",
"Id": "14253",
"Score": "0",
"Tags": [
"sql",
"oracle"
],
"Title": "Simplify Oracle SQL Unions"
}
|
14253
|
<p>I have a program that displays colorful shapes to the user. It is designed so that it is easy to add new shapes, and add new kinds of views.</p>
<p>Currently, I have only two shapes, and a single text-based view. In the near future, I'm going to implement a <code>Triangle</code> shape and a <code>BezierCurve</code> shape. </p>
<p>I'm also going to implement these views:</p>
<ul>
<li><code>GraphicalView</code> - uses a graphics library to render shapes on screen.</li>
<li><code>OscilloscopeView</code> - draws the shapes on an oscilloscope.</li>
<li><code>DioramaView</code> - a sophisticated AI directs robotic arms to construct the scene using construction paper, string, and a shoebox.</li>
</ul>
<p>The MVC pattern is essential here, because otherwise I'd have a big intermixed tangle of oscilloscope and AI and Graphics library code. I want to keep these things as separate as possible.</p>
<pre><code>#model code
class Shape:
def __init__(self, color, x, y):
self.color = color
self.x = x
self.y = y
class Circle(Shape):
def __init__(self, color, x, y, radius):
Shape.__init__(self, color, x, y)
self.radius = radius
class Rectangle(Shape):
def __init__(self, color, x, y, width, height):
Shape.__init__(self, color, x, y)
self.width = width
self.height = height
class Model:
def __init__(self):
self.shapes = []
def addShape(self, shape):
self.shapes.append(shape)
#end of model code
#view code
class TickerTapeView:
def __init__(self, model):
self.model = model
def render(self):
for shape in self.model.shapes:
if isinstance(shape, Circle):
self.showCircle(shape)
if isinstance(shape, Rectangle):
self.showRectangle(shape)
def showCircle(self, circle):
print "There is a {0} circle with radius {1} at ({2}, {3})".format(circle.color, circle.radius, circle.x, circle.y)
def showRectangle(self, rectangle):
print "There is a {0} rectangle with width {1} and height {2} at ({3}, {4})".format(rectangle.color, rectangle.width, rectangle.height, rectangle.x, rectangle.y)
#end of view code
#set up
model = Model()
view = TickerTapeView(model)
model.addShape(Circle ("red", 4, 8, 15))
model.addShape(Circle ("orange", 16, 23, 42))
model.addShape(Circle ("yellow", 1, 1, 2))
model.addShape(Rectangle("blue", 3, 5, 8, 13))
model.addShape(Rectangle("indigo", 21, 34, 55, 89))
model.addShape(Rectangle("violet", 144, 233, 377, 610))
view.render()
</code></pre>
<p>I'm very concerned about the <code>render</code> method of <code>TickerTapeView</code>. In my experience, whenever you see code with a bunch of <code>isinstance</code> calls in a big <code>if-elseif</code> block, it signals that the author should have used polymorphism. But in this case, defining a <code>Shape.renderToTickerTape</code> method is forbidden, since I have resolved to keep the implementation details of the view separate from the model.</p>
<p><code>render</code> is also smelly because it will grow without limit as I add new shapes. If I have 1000 shapes, it will be 2000 lines long.</p>
<p>Is it appropriate to use <code>isinstance</code> in this way? Is there a better solution that doesn't violate model-view separation and doesn't require 2000-line <code>if</code> blocks?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T19:48:32.090",
"Id": "23144",
"Score": "0",
"body": "Not sure if you are just exclusively using this pattern for your example, but the O(n) search pattern in `render()` can be replaced by a O(1) search pattern with a `dict`. (e.g. `shape_render_methods = {'circle': showCircle, 'rectangle': showRectangle}`, called like this. `for shape in shapes: shape_render_methods[shape.name]()`)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T19:54:28.817",
"Id": "23145",
"Score": "0",
"body": "Good observation. I considered using a dict, but I wasn't sure it was a portable solution. Do all object oriented languages guarantee that you can use a class name as the key to a dictionary? In my mind, this is a language-agnostic problem, so it should have a language-agnostic solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T19:57:11.097",
"Id": "23146",
"Score": "0",
"body": "I'm not sure that they do. In any case, I think it's better that you define a `name` attribute for your shape class--that's what I meant to imply by `shape.name`. The above code was meant as an example pattern, not an actual implementation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T20:08:58.570",
"Id": "23148",
"Score": "0",
"body": "Oops, I must have misread your first comment. On second look, that code is indeed language agnostic. Giving each shape subclass its own `name` would work, but I'm wary of restating type information in a new form. [Don't Repeat Yourself](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself), as they say."
}
] |
[
{
"body": "<p>Here's one approach:</p>\n\n<pre><code>SHAPE_RENDERER = {}\n\ndef renders(shape):\n def inner(function):\n SHAPE_RENDERER[shape] = function\n return function\n return inner\n\n@renders(Circle)\ndef draw_circle(circle, view):\n ...\n\n@renders(Triangle)\ndef draw_triangle(triangle, view):\n ....\n\ndef render_shape(shape, view):\n SHAPE_RENDERER[shape.__class__](shape, view)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T20:12:12.327",
"Id": "23149",
"Score": "0",
"body": "This nicely resolves the 2000-line method problem. But can this approach be taken in other OO languages that don't support decorators? In which case I imagine you'd need an `initialize_SHAPE_RENDERER` method which takes 2000 lines to populate the dict, and now we're back at the start."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T21:20:40.823",
"Id": "23152",
"Score": "0",
"body": "@Kevin, this depends on what other OO language. For example, in Java you could do something with reflection or annotations. In C++ you could do some magic with macros and static objects."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T15:22:40.860",
"Id": "14262",
"ParentId": "14257",
"Score": "2"
}
},
{
"body": "<p>This answer is a bit too easy, so may be a catch but I wonder:\nWhy don't you add a .show() method to Circle class which will be equivalent of showCircle, then the same with Rectangle etc and then just:</p>\n\n<pre><code>for shape in self.model.shapes: \n shape.show() \n</code></pre>\n\n<p>or better, .show() returns sth which a render function will take care of it if you want to do fancier things: </p>\n\n<pre><code>for shape in self.model.shapes: \n self.renderer(shape.show())\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T11:59:45.460",
"Id": "23121",
"Score": "0",
"body": "I can't put any display-specific code in my shape classes, since I have resolved to keep the implementation details of the view separate from the model. Or if you mean that `show()` only returns data that the view can use to distinguish between shape types, then that's just an `isinstance` call in disguise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T19:43:26.823",
"Id": "23143",
"Score": "0",
"body": "@Kevin: I wonder if `show()` can return non-implementation specific rendering data. `Rectangle.show`, for example would return something in the form of \"LINE POINT1 POINT2, LINE POINT2 POINT3, LINE POINT3 POINT4, LINE POINT4 POINT1\", which can be interpreted by `render()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T20:23:27.403",
"Id": "23150",
"Score": "0",
"body": "That would indeed work very well if every shape could be precisely defined using only lines and points. However, circles and beziers can't be represented just by straight lines, so I'd need a `CURVE` rendering object in addition to `LINE`. In which case I need a `renderRenderingObject` method which can distinguish between concrete subclasses of the `RenderingObject` class, and then we're back to my original problem, albeit at a smaller scale."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T01:19:00.030",
"Id": "85847",
"Score": "0",
"body": "Each view calls <shape>.show(). Each view also provides primitives that <shape>.show() can call to display itself in that view. The sequence of primitive calls is the same regardless of the view. So view says <circle>.show(self), which says, eg, <view>.curve(x, y, r, 0, 360), where (x,y) is the center of the circle, r is the radius, and 0, 360 indicate the portion of the curve to draw. Each view implements curve() in its own terms. The view doesn't have to know which shape it's calling and the shape doesn't have to know which view is drawing it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T22:01:18.077",
"Id": "14276",
"ParentId": "14257",
"Score": "0"
}
},
{
"body": "<p>Why would this not work?</p>\n\n<pre><code>#model code\n\nclass Shape:\n def __init__(self, color, x, y):\n self.color = color\n self.x = x\n self.y = y\n\nclass Circle(Shape):\n def __init__(self, color, x, y, radius):\n Shape.__init__(self, color, x, y)\n self.radius = radius\n\n def show(self, v):\n v.curve(self.x, self.y, self.radius, 0, 360)\n\nclass Rectangle(Shape):\n def __init__(self, color, x, y, width, height):\n Shape.__init__(self, color, x, y)\n self.width = width\n self.height = height\n\n def show(self, v):\n v.line(self.x, self.y, self.x+self.width, self.y)\n v.line(self.x+self.width, self.y, \n self.x + self.width, self.y + self.height)\n v.line(self.x + self.width, self.y + self.height,\n self.x, self.y + self.height)\n v.line(self.x, self.y + self.height, self.x, self.y)\n\n....\n\n#end of model code\n\n#view code\n\nclass TickerTapeView:\n def __init__(self, model):\n self.model = model\n def render(self):\n for shape in self.model.shapes:\n shape.show(self)\n\n def curve(self, x, y, radius, start, end):\n print(\"Curve at ({0},{1}) with radius {2} goes from {3}o to {4}o\".format(x, \n y, radius, start, end)\n\n def line(self, x1, y1, x2, y2):\n print(\"Line from ({0},{1}) to ({2},{3})\".format(x1, y1, x2, y2)\n\n#end of view code\n\n#set up\n\nmodel = Model()\nview = TickerTapeView(model)\n\nmodel.addShape(Circle (\"red\", 4, 8, 15))\nmodel.addShape(Circle (\"orange\", 16, 23, 42))\nmodel.addShape(Circle (\"yellow\", 1, 1, 2))\nmodel.addShape(Rectangle(\"blue\", 3, 5, 8, 13))\nmodel.addShape(Rectangle(\"indigo\", 21, 34, 55, 89))\nmodel.addShape(Rectangle(\"violet\", 144, 233, 377, 610))\n\nview.render()\n</code></pre>\n\n<p>GraphicalView, OscilloscopeView, and DioramaView each have to implement curve() and line(), obviously, each doing the right thing to display the shape described in its own terms.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-09T13:58:57.120",
"Id": "86746",
"Score": "0",
"body": "I like the idea of passing the view into `show` - a nice twist on Joel's comment, that removes the need for a component that can distinguish between lines/curves/etc. I would need a `View.describe(text_description)` method, if I wanted `TickerTapeView` to print the same kind of information that it does in my original post. I'm faintly concerned that the base `View` class would eventually become cluttered with abstract methods like that as I add more subclasses, but for this particular example it seems entirely manageable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T01:37:55.013",
"Id": "48897",
"ParentId": "14257",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T14:16:45.080",
"Id": "14257",
"Score": "2",
"Tags": [
"python",
"mvc"
],
"Title": "Displaying colorful shapes to the user"
}
|
14257
|
<p>JUnit is a unit testing framework for the Java language. It was created by Kent Beck, Erich Gamma, and David Saff.</p>
<p>It's official site is <a href="http://junit.sourceforge.net" rel="nofollow">http://junit.sourceforge.net</a> </p>
<p>JUnit tasks can be started from ANT with the <junit> tag. JUnit can also be integrated with the Eclipse IDE, allowing the user to easily execute all unit tests in a project. </p>
<p>Sources: <a href="https://en.wikipedia.org/wiki/JUnit" rel="nofollow">Wikipedia</a>, <a href="http://junit.sourceforge.net/#Documentation" rel="nofollow">JUnit documentation</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T14:28:34.537",
"Id": "14259",
"Score": "0",
"Tags": null,
"Title": null
}
|
14259
|
JUnit is a unit testing framework for the Java language.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T14:28:34.537",
"Id": "14260",
"Score": "0",
"Tags": null,
"Title": null
}
|
14260
|
<p>I'm thinking about the usage of percent, example, in margins.</p>
<p>We can use overlay to separate our layout by DPI sizes, but why can't we use percentage?</p>
<p>Something like that:</p>
<pre><code>Display display = getWindowManager().getDefaultDisplay();
float width = display.getWidth();
float height = display.getHeight();
//20% of left margin
float imageMarginLeft = ( width * 20 ) / 100;
</code></pre>
<p>And then set this margin to the image, or whatever element.</p>
<p>Is this bad?</p>
|
[] |
[
{
"body": "<p>You can simplify math whenever possible. No reason to multiply by 20 then divide by 100. Just multiply by .20. If you needed a result that was twenty percent in addition to 100 percent of what you already had you could multiply by 1.2. It saves a process making your code just a tad more efficient! </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T07:49:47.950",
"Id": "23111",
"Score": "1",
"body": "The compiler will probably optimize the expression, but even if it doesn't, the efficiency gain is negligible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T07:51:12.620",
"Id": "23112",
"Score": "0",
"body": "@S.L. Barth-Nowadays your right but people used to count processes, and I was taught that inefficient code should never be a supplement for efficient code. Yes, this one computation will never be recognized, but discounting simple math procedures over a million lines of code is arguably incorrect. And for that matter why not? I look at that line and think well that's not very sharp, but to each their own I suppose."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T08:09:24.947",
"Id": "23114",
"Score": "2",
"body": "Seems we've been taught different things then. I was taught that \"It's easier to make correct code go fast, than to make fast code correct\". Either way, I do agree that it's good to simplify maths - in general it makes the code more legible, and it may prevent rounding errors."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T08:12:51.943",
"Id": "23115",
"Score": "0",
"body": "@S.L.Barth- Perfect, that was my true intent in passing the info, the so called efficiency was more of thing to continually think about. I like the quote! Real similar to \"cheap blanks aren't good and good blanks aren't cheap\"!)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T06:25:57.453",
"Id": "14284",
"ParentId": "14265",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T17:29:06.080",
"Id": "14265",
"Score": "2",
"Tags": [
"java",
"android"
],
"Title": "What about percentage usage?"
}
|
14265
|
<p>I have made a custom login form for my site, with the help of PDO (until now I used simple MySQL connection and sanitizing), and it looks like this:</p>
<pre><code>session_name('NEWCOOKIE');
session_start();
require_once "config.php";
$member_username = $_POST['username'];
$member_password = $_POST['password'];
$crypt_pass = crypt($member_password,"somesalt");
try{
$dbh = new PDO('mysql:host=localhost;dbname='.DB_NAME, DB_USERNAME, DB_PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
echo "Fatal error.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
$sth = $dbh->prepare("SELECT * FROM ".DB_PREFIX."_users WHERE username = :user AND password = :pass");
$sth->bindParam(':user', $member_username);
$sth->bindParam(':pass', $crypt_pass);
$sth->execute();
$total = $sth->rowCount();
$row = $sth->fetch();
if($total > 0){
if($row['activated']){
$_SESSION["user_username"] = $member_username;
$_SESSION["user_logedIn"] = true;
$_SESSION["user_id"] = $row['user_id'];
$_SESSION["timeout"] = time();
header("location: index.php");
}
else{
echo "ACCOUNT NOT ACTIVE";
}
}
else{
echo "WRONG PASSWORD OR USERNAME";
}
</code></pre>
<p>Is this safe? I know that nothing is 100% safe, but I have a small number of users (around 200-300), and 1000 visitors a month, so I don't expect very "professional" attacks and programming experts. </p>
<p>My questions are:</p>
<ol>
<li><p>As you can see, I don't use sanitizing at all. I thought that PDO will do that part of the job, or I am wrong?</p></li>
<li><p>I hope that crypting of password is good (with no MD5 or SHA, is <code>crypt()</code> recommended)?</p></li>
<li><p>File config.php contains username and pass of my database. Should I protect it somehow, what permissions to set?</p></li>
<li><p>Any other (serious) problem with this code?</p></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T17:28:30.170",
"Id": "23062",
"Score": "0",
"body": "You might want to read [*this*](http://www.codinghorror.com/blog/2005/04/encryption-for-dummies.html)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T17:37:02.063",
"Id": "23269",
"Score": "0",
"body": "Something about that `if($total > 0)` condition irks me; I want it to be `== 1` but I can't devise a compelling reason."
}
] |
[
{
"body": "<p>Well, let's see:</p>\n\n<ul>\n<li>You're using PDO and prepared statements, no risk of SQL injection there. Great!</li>\n<li>Your PDO code may throw an Exception (Specifically, a <code>PDOException</code>) <strong>at any time</strong>, so the whole database code block should be kept inside of the <code>try/catch</code> block.</li>\n<li><code>crypt</code> in on itself isn't 100% secure. See <strong><a href=\"https://stackoverflow.com/q/4795385/871050\" title=\"How do you use bcrypt for password hashing?\">This question</a></strong> for more details.</li>\n<li>Database credentials are not constant. They can change over time, and you may want to change the server, change the user, add an additional database etc in the near/far future. The solution is to use functions (or better yet, classes) and pass the credentials as variables, rather then applying them as app-wide constants.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T17:39:29.057",
"Id": "23064",
"Score": "0",
"body": "Tnx for the answers.So, should i end \"catch\" block at the end of file, or just after $row = $sth->fetch(); ? Regarding database credentials, this is small-sized project, and i dont expect it to expand over time. Also, i am not very good with OOP, so i am totaly unfamilliar with classes :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T17:44:02.743",
"Id": "23066",
"Score": "0",
"body": "@SomeoneS: The try/catch block should encapsulate the database code. Personally, I would encapsulate the whole thing in either a mapper class, or some sort of function schema, and try/catch when calling the functions (keeping the actual database code clean from distractions)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T17:30:08.423",
"Id": "14268",
"ParentId": "14267",
"Score": "5"
}
},
{
"body": "<p>Be sure that you're checking for a one-time (per page load) random token in your form to help protect against CSRF attacks. You can use <code>mcrypt</code> or <code>bcrypt</code> to ensure your tokens are cryptographically-sound.</p>\n\n<p>Simply add a hidden form to your field with the value being your token:</p>\n\n<pre><code><input type=\"hidden\" name=\"token\" value=\"<?php echo $token; ?>\">\n</code></pre>\n\n<p>Store that token in your session array:</p>\n\n<pre><code>$_SESSION['token'] = $token;\n</code></pre>\n\n<p>And finally, match the tokens from the post and sessions arrays:</p>\n\n<pre><code>if (!isset($_SESSION['token'])) { return false; } // Session token isn't set\nelse if (!isset($_POST['token'])) { return false; } // Post token isn't set\nelse if ($_SESSION['token'] !== $_POST['token']) { return false; } // Possible CSRF attempt\nelse if ($_SESSION['token'] === $_POST['token']) { return true; } // Looks valid!\nelse { return false; }\n</code></pre>\n\n<p>You can store most of this in a separate method for re-use with other forms.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-31T08:12:27.647",
"Id": "111878",
"Score": "0",
"body": "I wouldn't recommend a new CSRF token per page load as this creates browser usability issues. Per session based is fine."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T08:36:22.537",
"Id": "14285",
"ParentId": "14267",
"Score": "5"
}
},
{
"body": "<p>Not much of an security wizard, not at all really, but I've seen a few answers here regarding this and they all tend towards the advice I'm about to give.</p>\n\n<ol>\n<li>From what I've seen its still good to sanitize even though you are using PDO, couldn't hurt anyways.</li>\n<li><code>md5()</code>, if I'm remembering correctly, is not as secure as <code>sha()</code>, but both are more secure than <code>crypt()</code>. BTW: <code>crypt()</code> is an encryption algorithm, not a hashing algorithm, though, from what I've seen, they are very similar but the distinction was made clear so its obviously important for some reason. Both <code>md5()</code> and <code>sha()</code> are still vulnerable to collision attacks, but are still widely used right now because of how unlikely it is to succeed. I'm not sure of a good alternative, if there even is one. Its hard to find a \"perfect\" encryption because they don't exist. Eventually they all will be beaten.</li>\n<li>I honestly do not see a problem with saving your database connection variables as constants in a config file. While, yes, they will change over time, it won't be very frequent, and changing a variable in a function is not much different from changing a constant in a config file. The best way to secure it is to make sure it is below the web root directory and that your htaccess file prevents access to unauthorized files.</li>\n<li>Would consider throwing in an <code>exit</code> after your header to prevent the code from continuing to run after the header has been sent. Common practice. Also, your try/catch block is flawed. Truth tried explaining it, but I don't think it translated very well. What he is trying to say is that the logic for accessing and reading the database should be in the try block. In other words, your binding of parameters, and anything else that is dependent upon a successful database connection should be between the try braces. As it stands right now it will attempt to connect and if it fails it will still attempt to bind those parameters and probably throw more errors.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T13:56:52.140",
"Id": "14376",
"ParentId": "14267",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T17:24:44.337",
"Id": "14267",
"Score": "4",
"Tags": [
"php",
"security",
"pdo",
"authentication"
],
"Title": "Custom login system (PDO, sanitizing, hash)"
}
|
14267
|
<p>This doesn't seem quite right, but it's the best I could do. Is there a way to do this better? My goal is to use DEBUG when I'm developing by doing a 'cc -DDEBUG' at the prompt.</p>
<pre><code>#ifndef DEBUG
#define ptrValues ptrvaluesRemote
#else
#define ptrValues ptrValuesLocal
#endif
ptrLinks = (struct sLinkDescriptionLayout*) ptrValues();
</code></pre>
|
[] |
[
{
"body": "<p>Not much prettier, but maybe preferable depending on how you need to use it later:</p>\n\n<pre><code>#ifdef DEBUG\n#define DEBUG_FLAG 1\n#else\n#define DEBUG_FLAG 0\n#endif\n\nptrLinks = (struct sLinkDescriptionLayout*) DEBUG_FLAG?ptrValuesLocal():ptrValuesRemote();\n</code></pre>\n\n<p>The C preprocessor is simultaneously fantastic and terrible.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T20:32:57.980",
"Id": "23097",
"Score": "0",
"body": "It would be nice if there was a ternary operator in the preprocessor"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T20:12:33.443",
"Id": "14275",
"ParentId": "14273",
"Score": "3"
}
},
{
"body": "<p>Perhaps use NDEBUG (as used in assert.h) instead of making up your own. Also note that unless you put an ifdef around the two functions you might get a linkage warning (as one of the functions might be unused). A warning is undesirable, but so is putting the ifdef around the functions, which will result in one of the functions not being compiled and in time the function may rot.</p>\n\n<p>Note that you might achieve the same end using the tool-chain to modify the symbol table. </p>\n\n<p>Another alternative would be to name the two functions the same in two separate files and link one or the other as required - that would be a cleaner solution, but would need documenting.</p>\n\n<p>Also...</p>\n\n<p>Perhaps make <code>ptrLinks</code> and <code>ptrValuesEtc</code> the same type so that a cast is unnecessary.</p>\n\n<p>Consider whether <code>ptrLinks</code> and <code>ptrValuesEtc</code> are correctly named:</p>\n\n<ul>\n<li>they appear to the uninitiated (me) to mean different things;</li>\n<li>also, one is a function and the other a pointer but their form is the same.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T04:23:28.807",
"Id": "23102",
"Score": "0",
"body": "I like this answer. Do you see any problems with using NDEBUG on Windows?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T04:33:24.850",
"Id": "23103",
"Score": "0",
"body": "There is no problems with using NDEBUG on windows. It is used in DevStudio and is defined for release builds."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T04:36:32.600",
"Id": "23104",
"Score": "3",
"body": "I disagree with the idea of using NDEBUG. As there is a difference between Debug/Release and NDEBUG/ ! NDEBUG. The NDBUG flag basically turns assert on/off. I can see a situation where you want to turn asserts on in release mode to help diagnose a problem that only happens in release build."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T20:01:39.327",
"Id": "23147",
"Score": "0",
"body": "Great input. Thank you both. I have thought about wrapping the two functions in `#ifdef` but I _am_ concerned about having the function code branch, one for production and one for debug. It's a tangential topic, but a good one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-18T05:30:06.560",
"Id": "24082",
"Score": "0",
"body": "Keep assertion control (`-DNDEBUG`) separate from the rest of your debugging (so I agree 100% with @LokiAstari — and upvoted his comment too)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T03:05:23.990",
"Id": "14281",
"ParentId": "14273",
"Score": "4"
}
},
{
"body": "<p>I recommend making the function name macro into a function-like macro instead of an object-like macro — give it an empty argument list. Also, it is usually best to keep the logic positive, so use <code>#ifdef</code> rather than <code>#ifndef</code>. This is hardly critical here, but in more complex situations, it is a good guideline to follow.</p>\n\n<p>These observations lead to:</p>\n\n<pre><code>#if defined(DEBUG)\n#define ptrValues() ptrValuesLocal()\n#else\n#define ptrValues() ptrvaluesRemote()\n#endif\n\nptrLinks = (struct sLinkDescriptionLayout*) ptrValues();\n</code></pre>\n\n<p>Personally, I would also have:</p>\n\n<pre><code> typedef struct sLinkDescriptionLayout sLinkDescriptionLayout;\n</code></pre>\n\n<p>Then I wouldn't need the <code>struct</code> in the cast:</p>\n\n<pre><code>ptrLinks = (sLinkDescriptionLayout *)ptrValues();\n</code></pre>\n\n<p>I'd probably go for a shorter name, too, (perhaps <code>LinkDesc</code>, but it depends on what the other names in the code are) but that's very much less critical.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-18T05:37:54.567",
"Id": "14812",
"ParentId": "14273",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T19:54:11.760",
"Id": "14273",
"Score": "2",
"Tags": [
"c"
],
"Title": "Doing #ifdef DEBUG and #define func() right?"
}
|
14273
|
<p>I am building a JSON restful web api in Node.js and so far I only got the main structure, however I am not 100% sure I am doing this correct from scratch, I still have to get used to the fact that Node.js is event driven.</p>
<p><strong>Directory structure:</strong></p>
<pre><code>1. main.js
2. modules
a. router.js
b. config.js
c. routes.js
</code></pre>
<p><strong>1. main.js</strong> - contains the main entry point - <code>node main.js</code>
<strong>2. modules</strong> - folder that contains all the modules.</p>
<p><strong>2a. router.js</strong> - contains "singleton" class module that will handle routing.</p>
<pre><code>var Router = function(routes){
this.routes = routes;
Router.route = function(){
console.log('routing from singleton router...');
};
return Router;
};
module.exports = Router;
</code></pre>
<p><strong>2b. config.js</strong> - contains the global configuration.</p>
<pre><code>exports.config = {
port: 9090
};
</code></pre>
<p><strong>2c. routes.js</strong> - contains the global routing schema, the router module will get the module injected (from main.js)</p>
<pre><code>exports.routes = {
'POST /users': { 'controller': 'users', 'action': 'create' },
'GET /users': { 'controller': 'users', 'action': 'getSelf' },
'GET /users/:uid/posts/:pid': { 'controller': 'users', 'action': 'getPostsFromUser' }
};
</code></pre>
<p>This is the structure so far, I am planning to extend it to this directory structure:</p>
<pre><code>1. main.js
2. modules
a. router.js
b. config.js
c. routes.js
d. loader.js (model loader, connection pool etc.)
e. validator.js (validates input)
d. controller.js (main controller, how to inherit from this? through inheritance?)
3. controllers - contains controllers
4. models - contains models
</code></pre>
<p>How to handle connection pooling in the structure? Would it be an idea to create a "registry" class, I come from a PHP background and that is how I would share objects, instead of dependency injection.</p>
<p><strong>sample registry.js</strong></p>
<pre><code>var Registry = function(){
this.data = {};
Registry.push = function(key, value){
return this.data[key] = value;
};
Registry.pull = function(key){
return this.data[key];
}
return Registry;
};
module.exports = Registry;
</code></pre>
<p>As I said, I am kinda new to Node.js and I want to make sure I get it right from scratch. </p>
<p>If you got any suggestions, comments, tips I really appreciate your help and time.</p>
|
[] |
[
{
"body": "<p>Sorry if I'm not answering your specific question, but are asking about overall style, or something else? There's no \"right/wrong way\" for many things in node.</p>\n\n<p>For example, I would have used <a href=\"http://expressjs.com/\" rel=\"nofollow\">http://expressjs.com/</a> for this:</p>\n\n<pre><code>var express = require('express')\nvar app = express.createServer()\napp.use(express.bodyParser())\n\napp.get('/users', function(req, resp, next) {\n ...\n})\n\napp.get('/users/:uid/posts/:pid', function(req, resp, next) {\n ...\n})\n\napp.post('/users', function(req, resp, next) {\n ...\n})\n\napp.listen(9090)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T01:05:04.563",
"Id": "14280",
"ParentId": "14274",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "14280",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T20:10:23.687",
"Id": "14274",
"Score": "2",
"Tags": [
"javascript",
"node.js"
],
"Title": "Node.js building a JSON restful web api structure"
}
|
14274
|
<p>I've got a simple sinatra webapp that pulls data from <a href="http://pinboard.in" rel="nofollow">Pinboard</a>'s RSS api, parses the info, and re-displays it. There are 4 tasks I need to perform with the data:</p>
<ol>
<li>I need to remove all instances of a specific tag from all items (in this case, <code>want</code>)</li>
<li>I need to create a list of all unique tags across all the items returned</li>
<li>I need to dynamically remove certain tags from the list if they are already being used to filter the list</li>
<li>I need to add an attribute to each item that is the host of the url associated with that item (i.e. <code>amazon.com</code> for whatever long amazon url may have been added)</li>
<li>I need to return a list of unique locations across all the items returned</li>
</ol>
<p>Here is the way I am currently handling this:</p>
<pre><code>items = []
tags = []
locations = []
begin
JSON.parse(data).each do |item|
# Remove the tag want from the list of tags,
# strip any extra whitespace, and add a location attribute
item['t'].each { |t| t.strip! }
item['t'].delete_if { |tag| tag == 'want' }
# Try like hell to parse the url. Assign an error string as a last resort
begin
item['l'] = /https?:\/\/(?:[-\w\d]*\.)?([-\w\d]*\.[a-zA-Z]{2,3}(?:\.[a-zA-Z]{2})?)/i.match(item['u'])[1]
rescue
item['l'] = "URL Parse error"
end
# Add the item's tags
item['t'].each do |tag|
tags << tag unless tags.include? tag or filter_tags.include? tag
end
locations << item['l'] unless locations.include? item['l']
items << item
end
rescue
end
return items, tags.sort, locations.sort
</code></pre>
<p>I really don't like this. It just doesn't feel clean to me, what with the creation of the empty arrays, and adding stuff in, etc. But my thought was that it's better to do a single iteration over the data returned than to do multiple loops. But now I am considering this instead:</p>
<pre><code>items = JSON.parse(data)
# Remove the want tag from all items
items.each { |i| i['t'].delete_if { |t| t == 'want' }}
#generate a list of tags
tags = items.map { |i| i['t']}.flatten.uniq.sort
tags.delete_if { |t| filter_tags.include? t }
# Parse the url
re = /https?:\/\/(?:[-\w\d]*\.)?([-\w\d]*\.[a-zA-Z]{2,3}(?:\.[a-zA-Z]{2})?)/i
items.each { |i| i['l'] = re.match(i['u'])[1] }
# Generate a list of locations
locations = items.map { |i| i['l']}.flatten.uniq.sort
return items, tags, locations
</code></pre>
<p>It feels cleaner, and seems like it's easier to read, but I'm not sure if the nested <code>delete_if</code> in the first bit is going too far. I'm also not sure how I feel about iterating over the items multiple times, or chaining <code>flatten.uniq.sort</code> for both <code>tags</code> and <code>locations</code></p>
|
[] |
[
{
"body": "<p>The second version is undoubtedly better, more readable, even if you iterate multiple times over the data. </p>\n\n<p>The problem is: both versions, specially the first, suffer from a common problem: imperative style (\"do this, do that\"). Are you familiar with the difference between imperative (focus on statements and state change) and functional programming (focus on expressions and immutable data)? it's easy, just try to code without in-place updates (no <code>each</code>, <code>delete_if</code>, <code>bang!</code> methods, ...) and you'll see that you'll end up writing less code, easier to test, to debug and to understand. You'll pay a bit of memory/speed performance, but it's usually worth it.</p>\n\n<p>Now, using a functional approach and taking advantage of existing libraries (<code>uri</code>), that's what I'd write (some details may not be right, but you get the idea):</p>\n\n<pre><code>require 'uri'\n\ndef parse(data, filter_tags)\n items, nested_tags, nested_locations = JSON.parse(data).map do |item|\n location = URI.parse(item[\"l\"]).host rescue \"URL Parse error\"\n tags = item[\"t\"].map(&:strip) - filter_tags\n [item, tags, location]\n end.transpose\n\n [items, nested_tags.flatten(1).uniq.sort, nested_locations.flatten(1).uniq.sort]\nend\n</code></pre>\n\n<p>More on functional programming with Ruby: <a href=\"http://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">http://code.google.com/p/tokland/wiki/RubyFunctionalProgramming</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T16:05:57.443",
"Id": "23131",
"Score": "0",
"body": "Awesome. Thanks for the tips. I'll definitely be reading through your linked doc. The only thing this isn't doing is removing the tag from the item's tags. Is there a better way to do that, other than `item['t'].delete_if { |t| t == 'want' }`? It seems like that's the one thing I _have_ to edit in place."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T16:08:01.967",
"Id": "23132",
"Score": "0",
"body": "@Gordon. No need to use `delete_if`, there is `reject`. Note though that you can create a new variable holding `filter_tags + [\"want\"]`, and now use it instead of `filter_tags`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T16:22:20.793",
"Id": "23134",
"Score": "0",
"body": "Not trying to start a discussion in the comments, but if I don't edit `item['t']` in place, then when I iterate over the items in the view, I'd have to pass another array down the line, or add another attribute to the `item`. So rather than doing that, wouldn't `delete_if` or `reject` be simpler? sorry if there's something I'm missing here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T16:25:05.377",
"Id": "23135",
"Score": "0",
"body": "@GordonFontenot: ok, now I understand what you mean. The solution is not hard: make all the processing you need at this point; instead of returning `item` values unchanged, create new ones that hold the values you expect in the view. That way you don't need to update anything."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T14:59:42.283",
"Id": "14298",
"ParentId": "14283",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "14298",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T03:25:03.990",
"Id": "14283",
"Score": "3",
"Tags": [
"ruby",
"json",
"comparative-review"
],
"Title": "Filtering Pinboard API results by tags"
}
|
14283
|
<p>I am running a scheduled script on my iPhone that logs in to a website, downloads a PDF, adds it to iBooks and uploads it to dropbox. All of this happens only when it has WiFi access.</p>
<p>I want to make it as error proof as possible. So I am open for criticism and tipps since it is my first bash script.</p>
<pre><code>#!/bin/sh
DATE=$(date "+%Y%m%d")
DATE_LOCALE=$(date "+%d.%m.%Y")
#LOGDATE=$(date "+%F %T")
DOMAIN=http://url.to.site
DOMAIN_LOGOUT=http://url.to.site/logout
URL1=http://url.to.site/issuefiles/
URL2=_paper/pdfs/paper
URL3=_complete.pdf
url=$URL1$DATE$URL2$DATE$URL3
FILENAME="/path/paper"$DATE"_complete.pdf"
ITEMNAME="paper"$DATE"_complete"
COOKIEFILE=/path/cookie.txt
ICONFILE=/path/title.jpg
INFOFILE=/path/Info.plist
USERAGENT="Mozilla/5.0 (compatible; MSIE 7.01; Windows NT 5.0)"
IP_ADDRESS=$(ifconfig en0 | grep inet | cut -d: -f2 | awk '{ print $2}')
IP_ADDR_VAL=$(echo "$IP_ADDRESS" | grep -Ec '^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])')
if [ $IP_ADDR_VAL -eq 1 ]; then
#Get the title image for the app icon
cd /path
wget http://path.to.site/title.jpg >/dev/null 2>&1
#Debug last command
if [ $? == 0 ]
then
echo $(date "+%F %T") : wget successful
else
echo $(date "+%F %T") : wget not successful
fi
#Check if downloaded correctly
if [ -e "$ICONFILE" ]
then
echo $(date "+%F %T") : title.jpg downloaded
else
echo $(date "+%F %T") : title.jpg not downloaded
fi
#Get token
TOKEN=$(curl -A "$USERAGENT" --cookie $COOKIEFILE --cookie-jar $COOKIEFILE http://url.to.site/ | grep "token" | sed -e 's/<input type=\"hidden\" name=\"token\" value=\"//' | sed -e 's/\" \/>//' )
curl -A "$USERAGENT" --data-urlencode "username=myuser" --data-urlencode "password=mypassword" --data-urlencode "token="$TOKEN --cookie $COOKIEFILE $DOMAIN >/dev/null 2>&1
#Debug last command
if [ $? == 0 ]
then
echo $(date "+%F %T") : curl for token successful
else
echo $(date "+%F %T") : curl for token not successful
fi
#Download of epaper file
curl -A "$USERAGENT" -L --progress-bar -o $FILENAME --cookie $COOKIEFILE $url
#Debug last command
if [ $? == 0 ]
then
echo $(date "+%F %T") : curl for Download of pdf successfull
else
echo $(date "+%F %T") : curl for Download of pdf successfull
fi
#logout
LTOKEN=$(curl -A "$USERAGENT" --cookie $COOKIEFILE --cookie-jar $COOKIEFILE $DOMAIN | grep "ltoken" | sed "s/.* value=\"\(.*\)\".*/\1/")
curl -A "$USERAGENT" --data-urlencode "ltoken="$LTOKEN --cookie $COOKIEFILE $DOMAIN_LOGOUT
#delete cookiefile
if [ -e "$COOKIEFILE" ]
then
rm $COOKIEFILE
#Debug last command
if [ $? == 0 ]
then
echo $(date "+%F %T") : Cookie file deleted
else
echo $(date "+%F %T") : Cookie file not deleted
fi
fi
#if file exists
if [ -e "$FILENAME" ]
then
#If downloaded file exeeds 1MB it should have been a success
#fsize=$(stat -c %s $FILENAME)
#echo $fsize
if [ $(stat --format="%s" "$FILENAME") -gt 1000000 ]; then
#import to iBooks and add to newsstand
cd /private/var/mobile/Media/Books/Purchases/
echo $(date "+%F %T") : $(python /path/ibooks.py import $FILENAME)
md5=($(md5sum $FILENAME))
appdir=/private/var/stash/Applications/$md5.app
if [ ! -e "$appdir" ]
then
mkdir $appdir
if [ -e "$ICONFILE" ]
then
cp $ICONFILE $appdir/Icon.png
rm $ICONFILE
else
echo $(date "+%F %T") : Error. No Iconfile available.
fi
cd /path
python parse.py $ITEMNAME $md5
if [ -e "$INFOFILE" ]
then
cp $INFOFILE $appdir
rm $INFOFILE
else
echo $(date "+%F %T") : Error. No Info file available
fi
else
echo $(date "+%F %T") : Appdirectory alsready exists!
fi
#Upload to dropbox
echo $(date "+%F %T") : Uploading to Dropbox...
cd /path
./dropbox_uploader.sh upload $FILENAME "/DestPathOnDropbox/"$ITEMNAME".pdf"
#Debug last command
if [ $? == 0 ]
then
echo $(date "+%F %T") : Upload to Dropbox successful!
#curl -k -s $PROWL_URL >/dev/null 2>&1
else
echo $(date "+%F %T") : Upload to Dropbox not successful!
fi
rm $FILENAME
else
#Filesoize too small. Delete download
echo $(date "+%F %T") : Filesize too small. Expected more!
rm $FILENAME
fi
fi
#Delete title.jpg
if [ -e /path/title.jpg ]
then
rm /path/title.jpg
fi
echo $(date "+%F %T") : Done!!
else
echo $(date "+%F %T") : No WiFi! Aborted...
fi
</code></pre>
|
[] |
[
{
"body": "<p>I don't have time to look through everything, but here's some low-hanging fruit:</p>\n\n<pre><code>if [ -e /path/title.jpg ]\nthen\n rm /path/title.jpg\nfi\n</code></pre>\n\n<p>can be reduced to:</p>\n\n<pre><code>rm -f /path/title.jpg\n</code></pre>\n\n<p>Because <code>man rm</code> says about <code>-f</code>:</p>\n\n<pre><code>ignore nonexistent files and arguments, never prompt\n</code></pre>\n\n<p><strong>EDIT</strong>: Another thing. Instead of</p>\n\n<pre><code>some_command arg1 arg2 arg3\n\nif [ $? == 0 ]\nthen\n ...\n</code></pre>\n\n<p>You can just say:</p>\n\n<pre><code>if some_command arg1 arg2 arg3\nthen\n ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T19:55:42.110",
"Id": "14307",
"ParentId": "14287",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "14307",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T09:10:49.937",
"Id": "14287",
"Score": "2",
"Tags": [
"bash",
"ios"
],
"Title": "Tips on good practice in my bash script that logs in to a website, downloads a PDF, adds it to iBooks and uploads it to dropbox"
}
|
14287
|
<p>I want to load some CSV columns or contents in my Ajax code. Please help me or improve my code. This will be live API code for me.</p>
<p>Data will be downloaded from Yahoo Finance in CSV format on an interval, and updated into this chart code. The values will be updated and chart will continue to be updated.</p>
<pre><code><?php $row = 1; if(($handle = fopen("table.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE){
$row++;
for ($c=0; $c<1; $c++)
{
echo $data[$c];
}
for ($c1=5; $c1<6; $c1++)
{
$data[$c];
}
for ($c2=4; $c2<5; $c2++)
{
$data[$c];
}
fclose($handle);
}
?>
<script type="text/javascript" src="http://www.stoquity.com/js/jazaa/amcharts.js"></script>
<script type="text/javascript" src="http://www.stoquity.com/js/jazaa/raphael.js" type="text/javascript"></script>
var chart;
var chartData = [
{ year: '(here is the data from csv "col 1 row 1")', income: '(here is the data from csv "col 5 row 1")', expenses: '(here is the data from csv "col 4 row 1")'},{ year: '(here is the data from csv "col 1 row 2")', income: '(here is the data from csv "col 5 row 2")', expenses: '(here is the data from csv "col 4 row 2")'},{year: '(here is the data from csv "col 1 row 3")', income: '(here is the data from csv "col 5 row 3")',expenses: '(here is the data from csv "col 3 row 3")'}];
AmCharts.ready(function () {
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.pathToImages = "../amcharts/images/";
chart.dataProvider = chartData;
chart.categoryField = "year";
chart.startDuration = 1;
// AXES
// category
var categoryAxis = chart.categoryAxis;
categoryAxis.gridPosition = "start";
// value
// in case you don't want to change default settings of value axis,
// you don't need to create it, as one value axis is created automatically.
// GRAPHS
// column graph
var graph1 = new AmCharts.AmGraph();
graph1.type = "column";
graph1.title = "Income";
graph1.valueField = "income";
graph1.lineAlpha = 0;
graph1.fillAlphas = 1;
chart.addGraph(graph1);
// line
var graph2 = new AmCharts.AmGraph();
graph2.type = "line";
graph2.title = "Expenses";
graph2.valueField = "expenses";
graph2.lineThickness = 2;
chart.addGraph(graph2);
// LEGEND
// WRITE
chart.write("chartdiv");
});
</script>
</head>
<body>
<div id="chartdiv" style="width:850px; height:300px;"></div>
</body>
</code></pre>
|
[] |
[
{
"body": "<p>Did you read or even try this code before posting it? Sorry if this seems rude, but it just seems obvious that if this was run you would immediately notice something was wrong. I'm mostly looking at the PHP code here, as it is full of issues. The JS appears to be fine, except I would consider moving those graphs into a separate functions. More on that below.</p>\n\n<p><strong>PHP</strong></p>\n\n<p>Wow, so many things on just the first line.</p>\n\n<p>Only do one thing per line, this helps with legibility. Also, try to avoid putting statements on the same line as the opening or closing php tags, unless opening and closing them on the same line (templates usually).</p>\n\n<p>Don't assign variables in statements (if, while, etc...) as it can lead to mistakes. PHP allows this, but IMO they should deprecate it. Though they probably won't because it might cause issues with the way for loops are declared. It is very easy to forget a second equals sign and mistakenly assign a new value to a variable that you were actually trying to compare, and your IDE wont catch it because its valid. If you get in the habit of not doing this then you know that if you ever see it while troubleshooting you know you've found your issue. And if your IDE is smart enough it will warn you about accidental assignments.</p>\n\n<p>Double quotes are used to tell PHP that the following string has a character or variable that needs to be escaped. As such PHP requires a little bit of extra processing power to read that string than if it were just single quoted. The speed is really negligible and is not really a \"good\" reason for making this switch, but I like to point it out anyways. This is a very controversial issue, so take it or leave it.</p>\n\n<p>The first line rewritten:</p>\n\n<pre><code><?php\n$row = 1;\n$handle = fopen( 'table.csv', 'r' );\nif( $handle !== FALSE ) {\n</code></pre>\n\n<p>Correct me if I'm wrong, but doesn't your for loop just print once on each while iteration? In this case, why loop at all? The same thing can be accomplished with <code>array_shift()</code> or by specifying the first index.</p>\n\n<pre><code>echo array_shift( $data );\n//or to avoid manipulating array\necho $data[ 0 ];\n</code></pre>\n\n<p>Why are all of your for loops only looping once? What is their purpose? Let me read you your code and you can follow along. Starting inside the while loop and doing the following on each iteration.</p>\n\n<ol>\n<li>Increment unused row variable</li>\n<li>Loop once\n<ol>\n<li>Echo first element of new CSV array</li>\n<li>End of loop, increment a counter that won't really be used</li>\n</ol></li>\n<li>Loop once with a specific number that's not used\n<ol>\n<li>Use first counter to point at the second value of array, Do nothing with it</li>\n<li>End of loop, increment a counter that isn't used</li>\n</ol></li>\n<li>Loop once with another specific number that's not used\n<ol>\n<li>Use first counter to point at the second value of array, Do nothing with it</li>\n<li>End of loop, increment a counter that isn't used</li>\n</ol></li>\n<li>Close file early so that only first entry was retrieved and while loop ends early</li>\n</ol>\n\n<p>I'm not sure what those other loops are being used for, but If you want to do something every 5th iteration just add an if statement with a mod of 5.</p>\n\n<pre><code>if( $c % 5 === 0 ) {\n</code></pre>\n\n<p>What is the purpose of <code>$row</code>, <code>$c1</code>, and <code>$c2</code>? These variables are unused. And What is the purpose of just declaring <code>$data[ $c ]</code> in each of these loops, it doesn't do anything. At least the first loop echoed it.</p>\n\n<p>Why are you closing your handle while you are still using the file? Close it after the loop unless you meant to only fetch the first entry.</p>\n\n<p><strong>JS</strong></p>\n\n<p>You can reduce the amount of work you are doing by following the \"Don't Repeat Yourself\" (DRY) Principle. You should also look at the Single Responsibility Principle to break up that ready function a little more. Now, my JS is a little rusty, but here's how I'd apply the DRY principle. I have not tested it, but hopefully it gets the point across.</p>\n\n<pre><code>function graph( properties ) {\n graph = new AmCharts.AmGraph();\n for( property in properties ) {\n graph[ property ] = properties[ property ];\n }\n\n return graph;\n}\n\ngraph1Properties = {\n type : \"column\",\n title : \"Income\",\n valueField : \"income\",\n lineAlpha : 0,\n fillAlphas : 1\n};\ngraph1 = graph( graph1Properties );\nchart.addGraph( graph1 );\n\ngraph2Properties = {\n type : \"line\",\n title : \"Expenses\",\n valueField : \"expenses\",\n lineThickness : 2\n};\ngraph2 = graph( graph2Properties );\nchart.addGraph( graph2 );\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T16:36:00.333",
"Id": "14380",
"ParentId": "14289",
"Score": "3"
}
},
{
"body": "<p>i am understanding you. but my actual probalme is that, there is a csv file. i want to fetch data from that csv file to AJAX variable.</p>\n\n<p>var chartData = [</p>\n\n<p>{ year: '(here is the data from csv \"col 1 row 1\")', \nincome: '(here is the data from csv \"col 5 row 1\")',<br>\nexpenses: '(here is the data from csv \"col 4 row 1\")'},</p>\n\n<p>{ year: '(here is the data from csv \"col 1 row 2\")',<br>\nincome: '(here is the data from csv \"col 5 row 2\")',<br>\nexpenses: '(here is the data from csv \"col 4 row 2\")'},</p>\n\n<p>{year: '(here is the data from csv \"col 1 row 3\")',<br>\nincome: '(here is the data from csv \"col 5 row 3\")',\nexpenses: (here is the data from csv \"col 3 row 3\")},</p>\n\n<p>]</p>\n\n<p>but continuously 254 time</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T09:24:20.453",
"Id": "14523",
"ParentId": "14289",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T10:36:01.103",
"Id": "14289",
"Score": "2",
"Tags": [
"javascript",
"php",
"html",
"csv"
],
"Title": "Updating a chart from Yahoo Finance CSV files"
}
|
14289
|
<p>I am interested in the community opinion about the following approach for the synchronization.
Generally it is based on the idea to have a configurable way to apply locking on some logic parts.</p>
<p>Any comments and review is appreciated :) .</p>
<p><code>lock.properties</code> keeps configuration:</p>
<pre><code>foo=true
bar=false
</code></pre>
<p><code>SynFactory.java</code> produces locks:</p>
<pre><code>import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class SyncFactory {
private static HashMap<String, Object> locks = null;
public static synchronized Object getLock(String key) {
init();
return locks.containsKey(key) ? locks.get(key) : new Object();
}
private static void init() {
if (locks == null) {
try {
locks = new HashMap<String, Object>();
Properties properties = new Properties();
properties.load(SyncFactory.class.getClassLoader().getResourceAsStream("lock.properties"));
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
// key=true => locking with ine object
// key=false => lock object should always be new
if (Boolean.parseBoolean(String.valueOf(entry.getValue()))) {
locks.put((String) entry.getKey(), new Object());
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
</code></pre>
<p><code>Service.java</code> actual usage:</p>
<pre><code>public class Service {
public void foo() {
synchronized (SyncFactory.getLock("foo")) {
// do some logic
}
}
public void bar() {
synchronized (SyncFactory.getLock("bar")) {
// do some logic
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-01-31T20:20:21.227",
"Id": "291557",
"Score": "0",
"body": "What do you think you are accomplishing with this?"
}
] |
[
{
"body": "<p><a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Semaphore.html\" rel=\"nofollow\">Java 5 Semaphore</a> is ready made, tested, and secure tool for your problem. </p>\n\n<p>You certainly find something on the Net searching \"<code>semaphore java lock</code>\"</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T13:55:29.400",
"Id": "23126",
"Score": "0",
"body": "Sorry I don't get how it could help. Your approach uses acquiring lock to control the state of sync, but it still requires some logic to apply the restrictions when to acquire or release the locking state on particular method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T14:20:33.187",
"Id": "23129",
"Score": "0",
"body": "No matter, I was not certain to be right for the way you are looking for, just tried to be helpful if can take advantage on resctriction and constrains pointed by Semaphore. However it seems you can use synchronized http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Hashtable.html"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T11:39:18.957",
"Id": "14292",
"ParentId": "14290",
"Score": "1"
}
},
{
"body": "<p>I just don't see a point in this factory. It has nothing in common with locking except class name, <code>getLock</code> method and \"lock.properties\" string inside. It's just a global hash map.\nYou always can (should) use <code>synchronized</code> with <code>this</code> or even better with private ivar. Any need too use your factory makes me think there is a bad design.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T13:50:11.900",
"Id": "23125",
"Score": "0",
"body": "the point is to have configurable way to apply lock on the same object and have actually sync or crate new object each time and have no sync"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T11:42:22.493",
"Id": "14293",
"ParentId": "14290",
"Score": "2"
}
},
{
"body": "<ol>\n<li>Your large outer <code>if</code> inside <code>init()</code> makes me a sad panda, why don't you just put a conditional <code>return</code> right in the beginning of the method? Still I'm curious whether you can provide a use-case for this approach.</li>\n<li>Why even lazy? Do you expect no <code>getLock()</code> calls in most cases when your app is ran?</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T18:06:10.207",
"Id": "23138",
"Score": "0",
"body": "1. There are two kind of people who do return first and who write if. As for the real world example I can't provide one but who knows what could happen in future and might be it would be mainstream. 2. It is done with a lazy initialization just for that example in real life I would leave it for the IOC container"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T17:45:37.690",
"Id": "14302",
"ParentId": "14290",
"Score": "2"
}
},
{
"body": "<p>Do you use synchronization to ensure visibility and prevent parallel running of two (or more) pieces of code? If yes, I agree with Dmitry Makarenko, I also don't see a real use-case of this class. The coder knows which pieces of code use the same shared data when they write the code, so runtime configuration is unnecessary.</p>\n\n<p>If you use it only to prevent parallel running of two (or more) piece of code which do not access the same shared data it could be fine but <code>SemaphoreFactory</code> would be a better, more intuitive name for this class.</p>\n\n<p>Two other notes:</p>\n\n<ul>\n<li>Using <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html#stringPropertyNames%28%29\" rel=\"nofollow\"><code>Properties.stringPropertyNames</code></a> and <code>getProperty</code> instead of <code>entrySet</code> would make the <code>init</code> method easier to read (no casting required) without a real performance loss (since it runs only once).</li>\n<li><p>Using a guard clause in the <code>init</code> method would make the code flatten:</p>\n\n<pre><code>if (locks != null) {\n return;\n}\ntry {\n ...\n} catch (IOException e) {\n throw new RuntimeException(e);\n}\n</code></pre>\n\n<p>See: <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">Flattening Arrow Code</a></p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T21:47:45.490",
"Id": "14362",
"ParentId": "14290",
"Score": "2"
}
},
{
"body": "<h3>Everyone else has failed to mention:</h3>\n<p>Locks on <code>non-final</code> references are less than useless as they do not guarantee anything.</p>\n<p>Right now, in both cases, you just have all the overhead of <code>synchronized</code> with none of the guarantees! <em>But worse, naive maintainers will think there is a guarantee when there is none.</em></p>\n<p>Thread Safe and non-Thread Safe versions of classes exist for a reason. Whatever you think you are accomplishing with this, especially if it is performance related, you are misguided.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-01-31T20:36:34.697",
"Id": "291561",
"Score": "0",
"body": "oh dear, it was sarcasm back in 2012, this code makes no sense, it was for fun only, but still thanks for paying attention to that"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-01-31T20:15:42.997",
"Id": "154108",
"ParentId": "14290",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T10:45:42.123",
"Id": "14290",
"Score": "3",
"Tags": [
"java",
"multithreading",
"locking",
"synchronization"
],
"Title": "Configurable synchronization approach in Java"
}
|
14290
|
<p>I have a table with forms in two colors - the first row is one color, the second is the other. Can you please tell me if there is a way to optimize my code (such as with <a href="https://github.com/symfony/symfony/blob/master/src/Symfony/Bridge/Twig/Resources/views/Form/form_table_layout.html.twig" rel="nofollow">this</a>)?</p>
<p>I have two CSS classes:</p>
<pre><code>tr.content1{
background-color: #EFF4FA;
}
tr.content2{
background-color: #F7FAFD;
}
</code></pre>
<p>And the table looks this way:</p>
<pre><code> <tr class="content1">
<td>Previous Plan:</td>
<td>{{ form_row(form.prev_plan) }}</td>
</tr>
<tr class="content2">
<td>Previous Server:</td>
<td>{{ form_row(form.prev_srv) }}</td>
</tr>
</code></pre>
<p>There is also a problem this way - I get some text in the second column in front of the form field.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T14:52:09.090",
"Id": "23253",
"Score": "0",
"body": "ewww... Tables and CSS together, what blasphemy!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T16:06:48.787",
"Id": "23255",
"Score": "1",
"body": "@showerhead: Well, how else would one structure and style tabular data?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T16:12:20.613",
"Id": "23259",
"Score": "0",
"body": "@Lèsemajesté: You can use spans and divs in this case, but there are other solutions too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T16:16:16.887",
"Id": "23260",
"Score": "2",
"body": "@showerhead: That is far less semantic than using tables, and far less accessible to users of assistive technologies. `DL`s _maybe_. But tables are still the ideal and most proper way of presenting tabular data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T16:50:59.113",
"Id": "23261",
"Score": "0",
"body": "@Lèsemajesté: I admit to not being well versed in this topic, which probably disqualifies me from this discussion already, but spans and divs are standards and are still presented sequentially, so they should still be accessible by assistive technologies. They are cleaner, which makes them ideal for developers, and can be stylized with CSS far more easier."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T17:12:59.697",
"Id": "23262",
"Score": "1",
"body": "@showerhead: There is nothing \"clean\" about having a document entirely comprised of `div`s and `span`s and using CSS to imitate the proper semantic elements. That'd be like replacing all of your links with `spans` that have `onclick` handlers or using `span`s in place of `h1`, `h2`, `h3`.... `div`s and `span`s do not have a `summary` attribute, `colgroup`s, proper table headers, nor do they have `axis`, `scope`, or `headers` attributes to associate the data cells with their respective headers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T17:21:13.493",
"Id": "23263",
"Score": "0",
"body": "And if all we should be using are `div`s and `span`s just because they can be styled using CSS to look however you want, then why bother having so many semantically specific tags in HTML? Why bother having `h1`-`h6`/`p`/`blockquote`/`table`/`thead`/`tbody`/`tr`/`th`/`td`/`ul`/`section`/`nav`/etc.? Or better yet, why not just use only `div`s or only `span`s? After all, you can set either of them to render as block-level or inline elements."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T19:11:05.913",
"Id": "23273",
"Score": "0",
"body": "@Lèsemajesté: I believe we have come to misunderstand one another. I may have been too general in my first comment and I did not clear it up in any of the following ones. My Apologies. Hopefully this clears it up a little better. http://stackoverflow.com/questions/83073/why-not-use-tables-for-layout-in-html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T19:11:36.737",
"Id": "23274",
"Score": "0",
"body": "Never would it be acceptable to replace prefab elements with stylized \"replacements\". And if the OP were using all of the properties you mentioned, or even just some, I would not have said anything. However this is a VERY simplistic LAYOUT. It is not tabular, except for the fact that it has a header. My comment was to imply that you can get a similar layout more simply and cleanly with div and spans and that a table in this instance was unnecessary. You can just as easily use section, H1, and p tags to accomplish the same thing, it need not be entirely divs and spans."
}
] |
[
{
"body": "<p>Depending on your requirements (is javascript allowed, which browsers can be used), I'd go for a CSS only solution.</p>\n\n<p><strong>CSS:</strong></p>\n\n<pre><code>table.zebra tr:nth-child(odd) { \n background-color: #EFF4FA; \n}\n\ntable.zebra tr:nth-child(even) { \n background-color: #F7FAFD; \n}\n</code></pre>\n\n<p><strong>PHP:</strong></p>\n\n<pre><code><table class=\"zebra\">\n <tr>\n <td>Previous Plan:</td>\n <td>{{ form_row(form.prev_plan) }}</td>\n </tr>\n <tr>\n <td>Previous Server:</td>\n <td>{{ form_row(form.prev_srv) }}</td>\n </tr>\n</table>\n</code></pre>\n\n<p>Here's the catch:</p>\n\n<p>You can't use these wonderfull selectors in every browser (IE < 9, I'm looking at you!). Only in most of them. There's a great explanation of the <a href=\"http://www.w3.org/TR/css3-selectors/#nth-child-pseudo\">selector at w3c</a> and an overview over browsers supporting it at <a href=\"http://caniuse.com/#feat=css-sel3\">caniuse</a>.</p>\n\n<p>And if you still want to use CSS3 selectors and need early IE support, there's javascript providing it (e.g. <a href=\"http://selectivizr.com/\">selectivizr</a> - I never used it, but it's easy to find alternatives). Just search for \"css3 selectors in IE\" in your favorite search engine.</p>\n\n<p>I guess this still doesn't solve your text overlay issues, but for that, you'd best point to an example page.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T16:56:58.490",
"Id": "14301",
"ParentId": "14294",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "14301",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T12:48:09.490",
"Id": "14294",
"Score": "4",
"Tags": [
"php",
"css",
"twig"
],
"Title": "Optimizing a table - Twig, CSS"
}
|
14294
|
<p>I have 2 tables. One holds only first column of my "data table" rest is stored in another table, that is placed right to first. What I need to do is to get all the data from specific row to pass it to jqplot.</p>
<p>My tables look like <a href="http://jsfiddle.net/Misiu/eajpy/1/" rel="nofollow noreferrer">this</a>. My code basically works, but I think it can be improved.</p>
<pre><code>$('table#baseTable > tbody > tr > td').click(function() {
var rowIndex = $(this).parent().index();
$('div#log').html(rowIndex);
var myData = [];
$('#dataTable tbody tr:eq(' + rowIndex + ')').map(function() {
return $(this.cells).get();
}).each(function() {
var headerVal = $(this).closest("table").find("thead > tr > th").eq($(this).index()).html();
myData.push([headerVal, $(this).html()]);
})
alert(myData);
console.log(myData);
});
</code></pre>
<p>I'm using this code in ASP page, so that every time I use UpdatePanel I must call my functions again.</p>
<p>This is my plot function:</p>
<pre><code>function plot() {
var $plot;
var dataTableRows = $('#Grid3_br tbody tr');
$('td.akcje').on('click', function() {
var $newTitle = $(this).next().text();
var myData = [],
element = $(this),
rowIndex = element.parent().index();
$(dataTableRows[rowIndex]).map(function() {
return $(this.cells).get();
}).each(function(index, value) {
myData.push(['M' + index, parseFloat($(this).html())]);
})
$('#wykres1').empty();//clears old plot. Don't know why re-plotting don't work for me
$plot = $.jqplot('wykres1', [myData], {
title: $newTitle,
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
tickOptions: {
formatString: '%s'
}
},
yaxis: {
tickOptions: {
formatString: '%.2f zł'
}
}
},
highlighter: {
show: true,
sizeAdjust: 7.5,
tooltipAxes: 'y'
},
cursor: {
show: false
}
});
$(window).resize(function() {
$plot.replot({
resetAxes: true
});
});
});
}
</code></pre>
|
[] |
[
{
"body": "<p>I'll start with your selectors:</p>\n\n<p>First off, you should never have a selector with anything left of an id - searches for ids are about the fastest you can get on the DOM.</p>\n\n<p>Second, if you don't want to wrap other tables in your tables (I assume you don't), get rid of the immediate child stuff (P > C). Searching by tag is also pretty fast, so we use the id-element as our base for that.</p>\n\n<pre><code>$('#baseTable tbody td').click(function() {\n var rowIndex = $(this).parent().index();\n $('#log').html(rowIndex);\n\n var myData= [];\n\n $($('#dataTable tbody tr')[rowIndex]).map(function() {\n return $(this.cells).get();\n }).each(function() {\n var headerVal = $(this).closest('table').find('thead th')\n .eq($(this).index()).html();\n myData.push([headerVal,parseFloat($(this).html())]);\n })\n\n alert(myData);\n console.dir(myData);\n});\n</code></pre>\n\n<p>Next, you should cache elements you found, use more than once and which don't change. And usually, it's a bad choice to bind events to the elements directly. I'm assuming jQuery 1.7 is ok and you don't really want to use jQuery 1.4, so we can use <a href=\"http://api.jquery.com/on/\" rel=\"noreferrer\">on for event binding</a>.</p>\n\n<pre><code>var logDiv = $('#log'),\n dataTableRows = $('#dataTable tbody tr');\n\n$('#baseTable tbody').on('click', 'td', function() {\n var myData = [],\n element = $(this),\n rowIndex = element.parent().index();\n\n logDiv.html(rowIndex);\n\n $(dataTableRows[rowIndex]).map(function() {\n return $(this.cells).get();\n }).each(function() {\n var headerVal = $(this).closest('table').find('thead th')\n .eq($(this).index()).html();\n myData.push([headerVal,parseFloat($(this).html())]);\n })\n\n alert(myData);\n console.dir(myData);\n});\n</code></pre>\n\n<p>Next, accessing the DOM is rather slow. If you need the data for jqplot, do you need the table headers and can the data change?</p>\n\n<p>Anyway, I'd store all data in an array beforehand. Now it looks like this:</p>\n\n<pre><code>var logDiv = $('#log'),\n dataTable = $('#dataTable'),\n dataTableHeaders = [],\n dataTableData = [];\n\n// cache data table headers\ndataTable.find('thead th').each(function(col) {\n dataTableHeaders[col] = $(this).html();\n});\n\n// cache full row (including headers) for data table\ndataTable.find('tbody tr').each(function(row) {\n var rowData = (dataTableData[row] = []);\n $(this).children().each(function(col) {\n rowData[2 * col] = dataTableHeaders[col];\n rowData[2 * col + 1] = parseFloat($(this).html());\n });\n});\n\n// the onClick - but on tr instead of td and with a fast lookup\n$('#baseTable tbody').on('click', 'tr', function() {\n var rowIndex = $(this).index(),\n myData = dataTableData[rowIndex];\n logDiv.html(rowIndex);\n alert(myData);\n console.dir(myData);\n});\n</code></pre>\n\n<p>I still don't like the need for <code>index()</code>. I like it even less than event binding on elements, so I'll compromise:</p>\n\n<pre><code>var logDiv = $('#log'),\n dataTable = $('#dataTable'),\n dataTableHeaders = [],\n dataTableData = [];\n\ndataTable.find('thead th').each(function(col) {\n dataTableHeaders[col] = $(this).html();\n});\n\ndataTable.find('tbody tr').each(function(row) {\n var rowData = (dataTableData[row] = []);\n $(this).children().each(function(col) {\n rowData[2 * col] = dataTableHeaders[col];\n rowData[2 * col + 1] = parseFloat($(this).html());\n });\n});\n\n$('#baseTable tbody tr').each(function(row) {\n $(this).on('click', function() {\n var data = dataTableData[row];\n logDiv.html(row);\n alert(data);\n console.dir(data);\n });\n});\n</code></pre>\n\n<p>Here's my last step (this is not really needed, but I like it): we isolate this code from the outside world and make accidental messups a lot harder. And we enable a recalculation and rebinding of the click event if anything changes (number of rows / cols or the content).</p>\n\n<pre><code>var tableData = (function(){\n var logDiv = $('#log'),\n cacheRows = function() {\n var dataTable = $('#dataTable'),\n dataTableHeaders = [],\n dataTableData = [];\n // fetch headers\n dataTable.find('thead th').each(function(col) {\n dataTableHeaders[col] = $(this).html();\n });\n // fetch column data, prepare row arrays\n dataTable.find('tbody tr').each(function(row) {\n var rowData = (dataTableData[row] = []);\n $(this).children().each(function(col) {\n rowData[2 * col] = dataTableHeaders[col];\n rowData[2 * col + 1] = parseFloat($(this).html());\n });\n });\n // return row arrays\n return dataTableData;\n },\n bindOnClick = function() {\n var dataTableData = cacheRows();\n $('#baseTable tbody tr').each(function(row) {\n $(this).on('click', function() {\n var data = dataTableData[row];\n logDiv.html(row);\n alert(data);\n console.dir(data);\n });\n });\n };\n bindOnClick();\n return {\n refresh: bindOnClick\n };\n})();\n</code></pre>\n\n<p>\nNow, when the tables change, you can preserve the intended behavior by calling <code>tableData.refresh()</code>. This is still a little messy because we never call <code>off</code>, but as we only use jQuery to change the DOM, we rely on it to unbind event handlers if we change elements. It's probably better to change the returned object so it has two functions: one to refresh the cache and one to rebind. rebinding is needed when the whole table was rebuilt and no DOM node is reused. Otherwise, this leaks event handlers. If you update the table infrequently, you should be fine. For frequent updates, I'd change it back to using the <code>index</code> function again.</p>\n\n<p><strong>Edit:</strong> Here's an example for what I described in my comment below.</p>\n\n<pre><code>var prepareForPlotting = function(baseSelector, dataSelector, clickhandler) {\n var cacheRows = function() {\n var dataTable = $(dataSelector),\n dataTableHeaders = [],\n dataTableData = [];\n // fetch headers\n dataTable.find('thead th').each(function(col) {\n dataTableHeaders[col] = $(this).html();\n });\n // fetch column data, prepare row arrays\n dataTable.find('tbody tr').each(function(row) {\n var rowData = (dataTableData[row] = []);\n $(this).children().each(function(col) {\n rowData[2 * col] = dataTableHeaders[col];\n rowData[2 * col + 1] = parseFloat($(this).html());\n });\n });\n // return row arrays\n return dataTableData;\n },\n bindOnClick = function() {\n var dataTableData = cacheRows();\n $(baseSelector + ' tbody tr').each(function(row) {\n $(this).on('click', function() {\n clickhandler(row, dataTableData[row]);\n });\n });\n };\n bindOnClick();\n return {\n recache: cacheRows,\n rebind: bindOnClick\n };\n}\n\nvar logDiv = $('#log'),\n baseHandler = prepareForPlotting('#baseTable', '#dataTable',\n function(row, data) {\n logDiv.html(row);\n alert(data);\n console.dir(data);\n }\n );\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T06:05:10.200",
"Id": "23243",
"Score": "0",
"body": "wow :) Thanks for that. I'm still trying to learn jQuery and I would like to learn the best practices at start, so any advice's like Your are very helpful. Any future updates on this are welcome :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T06:39:24.967",
"Id": "23299",
"Score": "1",
"body": "Your answer is awesome! I'am looking for a way to change this in some kind of plugin, so that I will be able to use it more than ones on page. In my solution I'm using 4 tables like shown here http://jsfiddle.net/Misiu/9j5Xy/12/ this is simple. These 2 solution are used in asp 2.0 webpage, so every time I request data from server (my update panel updates) I must init all javascript again. So can Your awesome code be changed into plogin? So that I can call it like $('wrapper').plotData()? Or should I leave Your solution? Which one is better?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T07:47:47.957",
"Id": "23301",
"Score": "1",
"body": "In that case, I'd make it a function with the selectors as parameters. You call it once per table combination and use the return value for refreshes on new data (so you can register it as an eventhandler for a 'change' event you fire when data changes on a table). But I'd first drop the alert and the call to logDiv :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T07:56:09.147",
"Id": "23302",
"Score": "0",
"body": "Alert and log was only for test purposes. I'll edit my question and add code that I'm using right now :) So Your saying that it would be better to turn it to function with 2 parameters: one-div wrapping all tables and second-div displaying plot."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T08:02:41.807",
"Id": "23303",
"Score": "1",
"body": "not the div, I'd pass the selectors for baseTable and dataTable and a callback function. The callback updates the plot (so you can target different plotting areas)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T08:14:12.883",
"Id": "23305",
"Score": "0",
"body": "I have all tables wrapped inside one div (like in that jsfiddle link from comment above), so instead can I pass only one parameter - that wrapper div selector? But I don't understand that callback function approach. Could You explain it a bit? I'm a beginner :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T08:29:59.853",
"Id": "23306",
"Score": "1",
"body": "I would pass the selectors instead of the div so you can delete the dom nodes and rebuild the table and have it still work. The callback function... I'll add an example in my answer, it would be too long for a comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T08:51:40.403",
"Id": "23307",
"Score": "0",
"body": "thanks again for Your answer and comments. I would like to click upvote button 100 times for this, but I can only once. Really grate peace of code and brilliant explanation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-17T13:15:01.013",
"Id": "38957",
"Score": "0",
"body": "@Arne I like function identifiers, they make code more readable and easier to debug in my opinion (stack trace looks better with `name()->otherName()` instead of `function()->function()`). So I would write: ` $(this).on('click', function rowClicked() {`\n\nBut I what is more important, I would avoid making functions in loops (or in `each`). Simply why should we declare _n_ (which in our case could be huge) functions if we can use one (http://jsfiddle.net/tomalec/cvPWv/2/).\nIs there any reason, I have missed not to use http://jsfiddle.net/tomalec/cvPWv/3/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-18T11:08:56.780",
"Id": "39028",
"Score": "0",
"body": "@tomalec yeah, function identifiers are neat for traces and could/should be used here. I'd probably do some of the stuff differently now (Use angular or backbone!)... About your second fiddle: will this work? The function is going to be called by jQuery. If I recall correctly, it will be called with the DOM element you clicked on as \"this\" and the event as the only argument to the function. You can't change that, so where would your function get its arguments from?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-18T23:18:20.010",
"Id": "39085",
"Score": "0",
"body": "@Arne Personaly I started to be function identifier fetishist, I see no point in usage of unnamed anonymous functions every where.\n\n Regarding fidle, it should. If you will provide fiddle with your code I can double check. You are right event is the only argument. However, according to http://api.jquery.com/on/ `.on( events [, selector ] [, data ], handler(eventObject) )` so you can add data: `{rowIndex: rowIndex}` into `event.data`. Simple, clean, and easy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-18T23:25:47.617",
"Id": "39086",
"Score": "0",
"body": "That was regarding fiddle [/2/](http://jsfiddle.net/tomalec/cvPWv/2/).\n \nYou are right [/3/](http://jsfiddle.net/tomalec/cvPWv/3/) won't work."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T17:50:42.037",
"Id": "14303",
"ParentId": "14295",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "14303",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T13:42:08.163",
"Id": "14295",
"Score": "8",
"Tags": [
"javascript",
"jquery"
],
"Title": "Select row based on another table row index"
}
|
14295
|
<p>I have been working on a little project to tidy up my log table which has exceeded the shared host provider limits:) So I have done some script that is working except one thing at the end: optimise DB.</p>
<p>This script will run in cron so I hope security should not be issue.</p>
<p>My questions are:</p>
<ol>
<li>the code is working, however I would like to learn how to do it better, so If you could point out thing that I shouldn't do and I did I would appreciate</li>
<li>if someone could tell me why my optimise DB doesn't work I would also thanks.</li>
<li>Performance!!! It will run on a table which has 1million rows and I am worried that his script wont perform fast enough. Any idea how to work this out?</li>
</ol>
<p>I know I should use PDO (next step - as I am not familiar with it yet) but as a first step I am proud that I could put together something that is working. </p>
<pre><code><?php
include 'opendb.php';
//functions
function test($string){
echo "<p>".$string."</p>";
}
function db_rows($db,$ord){
$dbquery="SELECT azon FROM $db ORDER BY azon $ord LIMIT 1";
$dbresult=mysql_query($dbquery);
$row = mysql_fetch_array($dbresult);
$dbrow = $row['azon'];
return $dbrow;
}
// end of functions
//config information...
$acttable = 'foo';
$today = date("yW_Hi");
$newdb = 'test_'.$today;
$firstact= db_rows($acttable,"asc");
$lastact= db_rows($acttable,"desc");
$upto=$firstact+25000;
test($lastact);
test($firstact);
if ($lastact-$firstact>50000) {
//create a new table
$newdbsql=" CREATE TABLE $newdb ( `azon` bigint(20) NOT NULL AUTO_INCREMENT, `mikor` datetime NOT NULL, `felhazon` int(11) NOT NULL, `felhnev` varchar(255) NOT NULL, `muvelet` varchar(20) NOT NULL, `sql` varchar(255) NOT NULL, `tabla` varchar(255) NOT NULL, `mezok` varchar(255) NOT NULL, `ertekek` text NOT NULL, `feltetel` varchar(255) NOT NULL, `ip` varchar(255) NOT NULL, `bongeszo` varchar(255) NOT NULL, PRIMARY KEY (`azon`), KEY `mikor` (`mikor`), KEY `felhazon` (`felhazon`), KEY `felhnev` (`felhnev`), KEY `muvelet` (`muvelet`), KEY `tabla` (`tabla`), KEY `feltetel` (`feltetel`)) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3524772 ;" ;
test($newresult);
$newresult = mysql_query($newdbsql);
// copy all the data
$query = "INSERT INTO $newdb SELECT * FROM $acttable WHERE $acttable.azon < $upto";
test($query);
$result = mysql_query($query);
// so what has happened...
if ($result) {
test("ok");
$delquery = "DELETE FROM $acttable WHERE $acttable.azon < $upto";
test($delquery);
$delresult = mysql_query($delquery);
if ($delresult) {
test("Deleted rows - OK");
} else {
test("failed to delete...");
// then tidy up everything:)
$res = mysql_query('SHOW TABLE STATUS WHERE Data_free / Data_length > 0.1 AND Data_free > 102400');
while($optrow = mysql_fetch_assoc($res)) {
mysql_query('OPTIMIZE TABLE ' . $optrow['Name']);
}
}
}
else {
test("failed to copy...");
}
}
else {
test("no work needs to be done.");
}
// close db
mysql_close($conn);
?>
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>Your Select statement.</p>\n\n<pre><code>SELECT azon FROM $db ORDER BY azon ASC/DESC LIMIT 1\n</code></pre>\n\n<p>you could simplify the statement like this:</p>\n\n<pre><code>SELECT MAX(azon)/MIN(azon) AS 'azon' FROM $db\n</code></pre>\n\n<p>There are some discussions about the gain of performance by using MIN/MAX instead of ORDER BY + LIMIT. I personally experienced that MIN/MAX is faster, especially on tables with many rows.</p></li>\n<li><p>You can simply copy a table structure by using</p>\n\n<pre><code>CREATE TABLE `$newdb` LIKE `$acttable`\n</code></pre>\n\n<p>but you'd have to set the AUTO_INCREMENT manually after this, otherwise it would be set to 1.</p>\n\n<pre><code>ALTER TABLE `$newdb` AUTO_INCREMENT=3524772\n</code></pre>\n\n<p>(I don't see the purpose on this, maybe it's not even nessecary?)</p></li>\n<li><p>Your optimize.</p>\n\n<ul>\n<li>I'm quite irritated about the way to want to query this. You're calling that statement inside the else-condition -> after your delete has failed. It should be called inside the if-condition (or I missunderstood the goal).<br /></li>\n<li>You should consider using InnoDB instead of MyISAM (in general), because there would be no need (and possibility) of running an OPTIMIZE.</li>\n</ul></li>\n<li><p>There should be no performance issue on the php-side as long as you do not iterate through the many rows.\nYou may want to increase the <code>max_execution_time</code>-directive to prevent the script from stopping, but I consider this is not nessecary.</p>\n\n<p>On MySQL-side, i really suggest changing to InnoDB (you may want to read <a href=\"https://dba.stackexchange.com/questions/20437/innodb-vs-myisam-with-many-indexes/20449#20449\">this</a>).</p></li>\n</ol>\n\n<hr>\n\n<p>Conclusion:<br />\nBesides the little changes of the statements and the use of OPTIMIZE inside your if-condition, there are no required improvements for <strong>exactly this</strong> script in my opinion. I strongly recommend to change the database engine when you make your changes for using PDO. This of course means more effort, as there are many variables which you can or should set to the InnoDB engine, but I think it is worth it. In fact, there aren't real advantages on using MyISAM, less then ever in performance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T05:05:03.077",
"Id": "23161",
"Score": "1",
"body": "Thank you ever so much your time and effort to look through a beginners code like mine. I ma going to see PDO and I will check the innoDB settings too. Thanks again!!!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T00:28:11.923",
"Id": "14314",
"ParentId": "14296",
"Score": "4"
}
},
{
"body": "<p>I'm not sure, but from what I gather you are trying to access the first and last item in the <code>$acttable</code> with the following code?</p>\n\n<pre><code>$firstact= db_rows($acttable,\"asc\");\n$lastact= db_rows($acttable,\"desc\");\n</code></pre>\n\n<p>If so, then this is the wrong way to go about it. You are essentially building the same array twice. Build it once, then use <code>array_shift()</code> and <code>array_pop()</code> respectively to get the first and last items from the resulting database row. Or if you need to reverse it and use entire array, use <code>array_reverse()</code>.</p>\n\n<p>Where are these magic numbers coming from 25000, 50000, 102400? What are they? Define these as constants to avoid confusion. For example:</p>\n\n<pre><code>define( \"LIMIT\", 25000 );\ndefine( \"MAX_ACT\", 50000 );\ndefine( \"SIZE\", 102400 );\n</code></pre>\n\n<p>Consider formatting your <code>$newdbsql</code> so that it is easier to read. Right now it is just one jumbled line. PHP doesn't care about white space, and to the best of my knowledge, neither does MySQL.</p>\n\n<p>After you create the <code>$newdbsql</code> statement, you immediately try to print the results with <code>test()</code> before even applying it. This will throw up a warning because that variable is undefined. I copied the problem bit below. Since you seem to use the <code>test()</code> function quite frequently after querying a database, I would consider creating a <code>mysql_query()</code> wrapper that does this for you to avoid mistakes like this in the future. This applies the \"Don't Repeat Yourself\" (DRY) Principle. Which can probably be applied elsewhere in this script. I'm not sure if you are keeping the <code>test()</code> function in for cron, or if this is literally just for troubleshooting, so this may not be necessary.</p>\n\n<pre><code>//Problem Code\ntest($newresult);\n$newresult = mysql_query($newdbsql); \n//Suggested Solution\nfunction query( $sql ) {\n $result = mysql_query( $sql );\n test( $result );\n return $result;\n}\n</code></pre>\n\n<p>The only efficiency problem I see is the number of database queries you are making. I don't know if its possible to lessen the amount, but I would try, as that's going to be a big factor.</p>\n\n<p>Also, make sure your style remains consistent throughout. So far I've seen a few different styles in this code. This makes me think this was copy-pasted together.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T14:48:55.773",
"Id": "14378",
"ParentId": "14296",
"Score": "3"
}
},
{
"body": "<p>Two minor notes:</p>\n\n<ol>\n<li><p>The <code>test</code> function does not really test anything. I'd consider renaming it to <code>log</code> or something similar.</p></li>\n<li><p>I'd move the logic into a function and use guard clauses instead of if-else branches. See: <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">Flattening Arrow Code</a></p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T17:56:40.770",
"Id": "14382",
"ParentId": "14296",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "14314",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T14:08:01.267",
"Id": "14296",
"Score": "5",
"Tags": [
"php",
"optimization",
"mysql"
],
"Title": "PHP backup log table from MySQL"
}
|
14296
|
<p>I have the following redundant-feeling design to convert between <code>enum</code>s and strings regarding a class that stores <code>enum</code>s. The approach doesn't scale if there are more <code>enum</code>s and in any event, less-redundant code is also better.</p>
<h3>Questions</h3>
<ol>
<li><p>If there will be more <code>enum</code>s, would it be possible to avoid defining two explicit conversion functions per enum type and device a system where the caller sees just one (i.e. <em>convert</em>) or two different function names (i.e. <code>convertto</code>/<code>convertfrom</code> for all the <code>enum</code>s, not just per <code>enum</code> type)? Perhaps using some kind deduction magic with <code>auto</code> and <code>decltype</code>? It looks like ambiguity sets in since only the return value can be used to separate the different functions overloads (even if done with function templates).</p></li>
<li><p>Is the following design of separating the conversion functions and putting them to an anonymous <code>namespace</code> good design (I've thought about putting the conversion functions to a file, say conversions.incl and including it)?</p></li>
</ol>
<p>The idea would be make the multiple (i.e. more <code>enum</code>s than the one presented here) conversions as implicit as possible</p>
<p>The conversions would be used like this:</p>
<p><strong>random.cpp</strong></p>
<pre><code>string token_string = "none"; //In reality this will be externally, user, generated.
some_class_instance->set_type(enum_conversion(token_string));
token_string = enum_conversion(some_class_instance->get_type());
</code></pre>
<p>And to present one <code>enum</code> and related conversions (but there could be more):</p>
<p><strong>some_class.h</strong></p>
<pre><code>class some_class
{
public:
enum class enum_type
{
none = 0,
type1 = 1,
type2 = 2
}
void set_type(enum_type);
enum_type get_type() const;
private:
enum_type type_;
};
namespace
{
std::array<std::pair<std::string, some_class::enume_type>, 3> type_map;
bool initialize_map()
{
type_map[0] = std::make_pair("none", some_class::enum_type::none);
type_map[1] = std::make_pair("type1", some_class::enum_type::type1);
type_map[2] = std::make_pair("type2", some_class::enum_type::type2);
}
bool initialization_result = initialize_map();
some_class::enum_type enum_conversion(std::string const& enum_type)
{
for(auto val: type_map)
{
if(val.first == enum_type)
{
return val.second;
}
}
return type_map[0].second;
}
std::string enum_conversion(some_class::enum_type enum_type)
{
for(auto val: type_map)
{
if(val.second == enum_type)
{
return val.first;
}
}
return type_parameter_map[0].first;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I would use some template logic to achieve the affect in a more scalable way:</p>\n\n<pre><code>#include <iostream>\n#include <sstream>\n#include <string>\n#include <algorithm>\n\n// This is the type that will hold all the strings.\n// Each enumeration type will declare its own specialization.\n// Any enum that does not have a specialization will generate a compiler error\n// indicating that there is no definition of this variable (as there should be\n// be no definition of a generic version).\ntemplate<typename T>\nstruct enumStrings\n{\n static char const* data[];\n};\n\n// This is a utility type.\n// Created automatically. Should not be used directly.\ntemplate<typename T>\nstruct enumRefHolder\n{\n T& enumVal;\n enumRefHolder(T& enumVal): enumVal(enumVal) {}\n};\ntemplate<typename T>\nstruct enumConstRefHolder\n{\n T const& enumVal;\n enumConstRefHolder(T const& enumVal): enumVal(enumVal) {}\n};\n\n// The next two functions do the actual work of reading/writing an\n// enum as a string.\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& str, enumConstRefHolder<T> const& data)\n{\n return str << enumStrings<T>::data[data.enumVal];\n}\n\ntemplate<typename T>\nstd::istream& operator>>(std::istream& str, enumRefHolder<T> const& data)\n{\n std::string value;\n str >> value;\n\n // These two can be made easier to read in C++11\n // using std::begin() and std::end()\n // \n static auto begin = std::begin(enumStrings<T>::data);\n static auto end = std::end(enumStrings<T>::data);\n\n auto find = std::find(begin, end, value);\n if (find != end)\n { \n data.enumVal = static_cast<T>(std::distance(begin, find));\n } \n return str;\n}\n\n\n// This is the public interface:\n// use the ability of function to deduce their template type without\n// being explicitly told to create the correct type of enumRefHolder<T>\ntemplate<typename T>\nenumConstRefHolder<T> enumToString(T const& e) {return enumConstRefHolder<T>(e);}\n\ntemplate<typename T>\nenumRefHolder<T> enumFromString(T& e) {return enumRefHolder<T>(e);}\n</code></pre>\n\n<p>Then you can use it like this:</p>\n\n<pre><code>// Define Enum Like this\nenum X {Hi, Lo};\n// Then you just need to define their string values.\ntemplate<> char const* enumStrings<X>::data[] = {\"Hi\", \"Lo\"};\n\nint main()\n{\n X a=Hi;\n\n std::cout << enumToString(a) << \"\\n\";\n\n std::stringstream line(\"Lo\");\n line >> enumFromString(a);\n\n std::cout << \"A: \" << a << \" : \" << enumToString(a) << \"\\n\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T07:48:40.150",
"Id": "23164",
"Score": "0",
"body": "I feel this design is far superior. I tried something like this, but run into problems with the specializations (hence my comment on overloading with specializations). Then I went into the second best alternative I could make to compile. The simple arrays feel like being enough (and perhaps the fastest) since they will be quite short, around ten items maximum. But anyway, thanks for the code and heads up, this was a good learning experience!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T12:27:33.730",
"Id": "23173",
"Score": "0",
"body": "A further question, if I still may, how would one define the conversions without using streams? E.g. template<typename T>\nT convertTo(std::string const& token)\n{\n std::stringstream line(token);\n T a;\n line >> enumFromString(a);\n\n return a;\n}\nbut this doesn't feel the most straightforward solution. Also, for some reason, I can't seem to find a way to do this to the other direction, to produce a string from enum.\n }"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T14:13:27.477",
"Id": "23174",
"Score": "0",
"body": "Hmm... Moreover, now when I'm trying this more, it looks like the ostream conversion doesn't compile. My VS 2012 RC fails with error messages \"Error 1 error C2440: '<function-style-cast>' : cannot convert from 'const some_namespace::some_class::X' to 'some_namespace::`anonymous-namespace'::enumConstRefHolder<T>'\" and\nerror C2677: binary '[' : no global operator found which takes type 'const some_namespace::some_class::X' (or there is no acceptable conversion)\"\n\nAnd I'm too rookie to fix the error message myself, I gather. Can I still lend your hand for a moment..? :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T16:06:23.477",
"Id": "23203",
"Score": "0",
"body": "I think I've found the crux of the matter: my enums are strongly typed, so they can't be used to index the arrays as-is, but with a cast like so \"return str << enumStrings<T>::data[static_cast<int>(data.enumValue_)];\" then also the constructor of EnumConstRefHolder needs to take the parameter by constant reference. It looks like the strongly typed enums can be cast to integer and they work without their underlying type specified. Though, it probably is better to specify one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T16:24:47.520",
"Id": "23205",
"Score": "0",
"body": "To still add comments (if someone cares to read them this far), the default underlying type is int, but it can be changed and hence it's safer to \"interrogate\" it during compilation. The cast can be done with std::underlying_type like this \"return str << enumStrings<T>::data[static_cast<std::underlying_type<T>::type>(data.enumValue)\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T16:27:23.820",
"Id": "23206",
"Score": "0",
"body": "And further [R. Martinho Fernandes](http://codereview.stackexchange.com/users/3426/r-martinho-fernandes) has a bit cleaner helper function over at [Stackoverflow](http://stackoverflow.com/questions/8357240/how-to-automatically-convert-strongly-typed-enum-into-int)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T20:42:11.193",
"Id": "23207",
"Score": "0",
"body": "It also looks like as if enumConstRefHolder and enumRefHolder can be removed. If someone is interested, I can post the code after changes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T21:19:22.610",
"Id": "23209",
"Score": "0",
"body": "that's what I get for trying to tidy the code without compiling. I have fixed the errors."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-14T11:17:32.803",
"Id": "32848",
"Score": "0",
"body": "note: I had to include <algorithm> for this code to compile"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-05T17:05:41.563",
"Id": "149774",
"Score": "0",
"body": "What is the advantage of this approach compared to using a type safe `enum` and a `std::map`. E.g. `enum class Foo {Lo, Hi}; const std::map<Foo, const std::string> FooStrings;` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-05T18:30:57.470",
"Id": "149786",
"Score": "0",
"body": "@JamieBullock: At the time it was written the array was the only object that could be initialized inline (now with C++11 you can do it with a map)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-20T23:38:56.930",
"Id": "165765",
"Score": "0",
"body": "Is there any way to add a + or += operator to this? It would be nice to be able to append this to other strings without having to convert to streams first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-20T23:56:32.800",
"Id": "165768",
"Score": "0",
"body": "@rost0031: `enumToString(a)` returns a `char const*`. If you already have a string then the `operator+` already works as expected. If you want to add something to this you need to convert it to `std::string` with `std::string(enumToString(a))`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-21T00:02:55.340",
"Id": "165772",
"Score": "0",
"body": "Hmm, I'm getting the following error: `no match for 'operator+' (operand types are 'const char [597]' and 'enumConstRefHolder<CBI2CDevices>') \"Application only\" + enumToString(_CB_EUIROM);` This works fine if I do `ss << enumToString(_CB_EUIROM);` and then append ss.str()."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T17:04:36.307",
"Id": "469361",
"Score": "0",
"body": "I'm using this design, but I had to change `char const*` to `std::string`. I'm not sure how else it would work. `std::find` matches based on an equality operator.\nAnd as mentioned here https://stackoverflow.com/questions/15050766/comparing-the-values-of-char-arrays-in-c `char const*` doesn't have an equality operator.\nIt might work if `std::find` used `strcmp`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T01:13:01.200",
"Id": "469442",
"Score": "0",
"body": "@HesNotTheStig You can compare a `std::string` to `char const*`. This is because `operator==(std::string const&, std::string const&)` is a free standing function and C++ lax rules of type conversion. Because there is not exact match the compiler will attempt to convert the parameters to make the operator work. Since `std::string` has a non `explicit` default constructor it can construct a string in-place using this default constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T01:13:52.600",
"Id": "469443",
"Score": "0",
"body": "@HesNotTheStig The code above compiles and runs for me (in C++ 11 and above). So if it is not working then there is something else wrong that we need to find."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T14:44:35.170",
"Id": "469552",
"Score": "0",
"body": "It compiles fine. It's just that when it was running, it wasn't matching correctly. Upon debugging, I determined that it was comparing the pointers. Changing it to `std::string` made it behave correctly for me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T15:11:39.520",
"Id": "469556",
"Score": "0",
"body": "@HesNotTheStig That does not make sense. It never compares `char*` to `char*` so there is not pointer comparison. Can you make a gist that shows the error."
}
],
"meta_data": {
"CommentCount": "19",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T01:30:21.487",
"Id": "14315",
"ParentId": "14309",
"Score": "26"
}
},
{
"body": "<p>A good start.<br>\n<strong>But</strong> you need to templatize your functions and the <code>type_map</code> by the enum to make the design extensible. That is a simple change so I will not focus on that.</p>\n\n<p>About the only other thing is that you search when doing a conversion in either direction. By choosing the appropriate container to hold the information you can do a quick lookup in one direction (though not in both without some fancier than normal containers).</p>\n\n<p>Otherwise I quite like it.</p>\n\n<p>It's not the style I would have chosen - see <a href=\"/a/14315\">my alternative answer</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T04:47:20.727",
"Id": "14319",
"ParentId": "14309",
"Score": "0"
}
},
{
"body": "<p>In most cases, the requirement of converting between c++ enumeration and string representation arises from interfacing to another program that does not understand your enumeration declarations. Often this other program will be a SQL database.</p>\n\n<p><strong>Hence I would go for a code generator to ensure consistency over the whole system.</strong></p>\n\n<p>The code generator could walk the whole database catalog and create an enumeration c-header and corresponding string arrays for everything in the database that could potentially carry enumeration semantics. Writing such a generator is less then a days work.</p>\n\n<p>Note that this approach does not only free you from writing the string part. It also frees you from writing the enumeration definition altogether.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-20T22:20:55.583",
"Id": "95909",
"Score": "1",
"body": "This is the approach I use for embedded firmware programming. I use the most capable and expressive language (say C#) and generate headers for all the less sophisticated languages (say C or C++), directly from the C# code, which is annotated with Attributes."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T13:54:12.783",
"Id": "33231",
"ParentId": "14309",
"Score": "6"
}
},
{
"body": "<p>\nHere is a template class that enables writing and reading enum class members as strings. It is a simplification of Loki Astari's design. It avoids the need for helper functions, as suggested by Veski, by using the <code>enable_if<></code> and <code>is_enum<></code> templates.</p>\n\n<p>The idea is to replace <code>template <T></code> with</p>\n\n<pre><code>template <typename T,\n typename std::enable_if<std::is_enum<T>::value>::type* = nullptr>\n</code></pre>\n\n<p>The consequence is that the <code>operator<<()</code> and <code>operator>>()</code> templates are only instantiated for enums (because of the Substitution Failure Is Not An Error (SFINAE) principle). Then the helper classes <code>enumConstRefHolder</code> and <code>enumRefHolder</code>, and the functions <code>enumToString()</code> and <code>enumFromString()</code>, are no longer needed.</p>\n\n<p>In addition to recognizing an enum member by a string (normalized to be all capital letters), the code recognizes its integer representation. (For the example below, both <code>\"FaST\"</code> and <code>\"1\"</code> will be read as <code>Family::FAST</code>.)</p>\n\n<p>EnumIO.h:</p>\n\n<pre><code>#ifndef ENUMIO_H_\n#define ENUMIO_H_\n\n#include <algorithm>\n#include <ios>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\n// A template class that enables writing and reading enum class\n// members as strings.\n//\n// Author: Bradley Plohr (2017-05-12)\n//\n// Note: The idea to keep the enum names as a static member in a\n// template comes from Loki Astari:\n//\n// https://codereview.stackexchange.com/questions/14309\n// /conversion-between-enum-and-string-in-c-class-header\n//\n// Usage example:\n//\n// Enums.h:\n// -------\n// #ifndef ENUMS_H_\n// #define ENUMS_H_\n//\n// enum class Family { SLOW, FAST };\n//\n// TODO: other enum classes\n//\n// #endif /* ENUMS_H_ */\n//\n//\n// Enums.cc:\n// --------\n// #include \"Enums.h\"\n// #include \"EnumIO.h\"\n// #include <string>\n// #include <vector>\n//\n// template <>\n// const std::vector<std::string>& EnumIO<Family>::enum_names()\n// {\n// static std::vector<std::string> enum_names_({ \"SLOW\", \"FAST\" });\n// return enum_names_;\n// }\n//\n// TODO: enum names for other enum classes\n//\n//\n// t_EnumIO.cc:\n// -----------\n// #include \"EnumIO.h\"\n// #include \"Enums.h\"\n// #include <iostream>\n//\n// int\n// main()\n// {\n// Family family;\n//\n// family = Family::SLOW;\n// std::cout << family << std::endl;\n//\n// std::cin >> family;\n// std::cout << family << std::endl;\n//\n// return 0;\n// }\n//\n// For the input\n//\n// fAsT\n//\n// the output is\n//\n// SLOW\n// FAST\n\ntemplate <typename T>\nclass EnumIO\n{\npublic:\n static const std::vector<std::string>& enum_names();\n};\n\ntemplate <typename T,\n typename std::enable_if<std::is_enum<T>::value>::type* = nullptr>\nstd::ostream&\noperator<<(std::ostream& os, const T& t)\n{\n os << EnumIO<T>::enum_names().at(static_cast<int>(t));\n\n return os;\n}\n\nstatic std::string\ntoUpper(const std::string& input)\n{\n std::string copy(input);\n std::transform(copy.cbegin(), copy.cend(), copy.begin(),\n [](const unsigned char i) { return std::toupper(i); });\n\n return copy;\n}\n\ntemplate <typename T,\n typename std::enable_if<std::is_enum<T>::value>::type* = nullptr>\nstd::istream&\noperator>>(std::istream& is, T& t)\n{\n std::string input;\n is >> input;\n if (is.fail())\n return is;\n input = toUpper(input);\n\n // check for a match with a name\n int i = 0;\n for (auto name : EnumIO<T>::enum_names()) {\n if (toUpper(name) == input) {\n // Here we assume that the integer representation of\n // the enum class is the default. If the enum class\n // members are assigned other integers, this code\n // must be extended by consulting a vector containing\n // the assigned integers.\n t = static_cast<T>(i);\n\n return is;\n }\n ++i;\n }\n\n // check for a match with an integer\n int n = static_cast<int>(EnumIO<T>::enum_names().size());\n std::istringstream iss(input);\n int value;\n iss >> value;\n if (not iss.fail() && 0 <= value && value < n) {\n t = static_cast<T>(value); // See the comment above.\n return is;\n }\n\n is.setstate(std::ios::failbit);\n\n return is;\n}\n\n#endif /* ENUMIO_H_ */\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-05-13T03:30:48.027",
"Id": "310310",
"Score": "0",
"body": "Thanks, Loki, for the reply. However, I would ask for more information: (a) what needs to be done to \"templatize \\[my\\] functions and the type_map by the enum\"; and (b) I don't do a search when converting from enum to string (the code is just like yours)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-05-13T04:36:19.190",
"Id": "310314",
"Score": "0",
"body": "Isn't this way too heavy to read an enum?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-05-12T23:11:01.983",
"Id": "163211",
"ParentId": "14309",
"Score": "4"
}
},
{
"body": "<p>If you have large enumerations, you might find that linear search in an array is inefficient. There's also a real risk of accidentally omitting one or more of the mappings.</p>\n\n<p>I solved this a different way by writing the enum→string conversion as a <code>switch</code> (with compiler warnings to indicate a missed <code>case</code>), and then generating a string→enum <code>std::map</code> when it's first required:</p>\n\n<pre><code>std::string to_string(some_class::enum_type e) {\n switch (e) {\n // you might want to use a macro to get matching labels and strings\n case some_class::enum_type::none: return \"none\";\n case some_class::enum_type::type1: return \"type1\";\n case some_class::enum_type::type2: return \"type2\";\n // N.B. no 'default', or GCC won't warn about missing case\n }\n // invalid value\n return {};\n}\n\nsome_class::enum_type from_string(const std::string& s) {\n static auto const m = invert(some_class::enum_type::none,\n some_class::enum_type::type2,\n to_string);\n auto it = m.find(s);\n return it == m.end() ? some_class::enum_type::none : *it;\n}\n\ntemplate<typename T, typename R>\nstd::map<R,T> invert(T first, T last, R(*forward_func)(T))\n{\n if (first > last) std::swap(first, last);\n\n std::map<R,T> m;\n for (int i = first; i <= last; ++i) {\n T t = T(i);\n R r = to_string(t);\n m[r] = t;\n // Or: if (!m.insert_or_assign[t].second)\n // log_warning(m[r] and t both map to r);\n };\n return m;\n}\n</code></pre>\n\n<p>To make <code>from_string()</code> into a template, you'll want some sort of <code>enum_traits<T></code> to specify the 'first' and 'last' values and the default value to return if the string isn't found (your unit tests can use these limits when checking that every enum maps back to itself).</p>\n\n<p>You might also need to help the compiler select the correct overload of <code>to_string()</code>; alternatively, you should be able to inline it into <code>invert()</code>. In my case, some of the enums I inherited had more than one mapping to/from string, depending on the context, so calling them all <code>to_string</code> wasn't an option for me.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-23T09:32:12.327",
"Id": "173742",
"ParentId": "14309",
"Score": "1"
}
},
{
"body": "<p>If I customise my enum like hi = 10, low = 20, it gives me en error ..</p>\n\n<p>Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)</p>\n\n<pre><code>// Define Enum Like this\nenum X {Hi = 10, Lo = 20};\n// Then you just need to define their string values.\ntemplate<> char const* enumStrings<X>::data[] = {\"Hi\", \"Lo\"};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T14:49:47.690",
"Id": "464348",
"Score": "1",
"body": "This does not seem to be a code review of the original question. The answer does not review any portion of the original code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T12:51:06.453",
"Id": "236888",
"ParentId": "14309",
"Score": "-2"
}
}
] |
{
"AcceptedAnswerId": "14315",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T20:16:49.937",
"Id": "14309",
"Score": "26",
"Tags": [
"c++",
"c++11",
"converting",
"enum",
"namespaces"
],
"Title": "Conversion between enum and string in C++ class header"
}
|
14309
|
<p>I'm working on a custom CMS and I'm primarily a PHP/database guy. This is my first real project using jQuery in any complexity. I've got it all functioning, but needless to say, it's pretty messy and I know jQuery veterans would frown at the code.</p>
<p>What can I do to clean up my jQuery? What bad practices am I employing? I'm not looking for someone to rewrite it all for me, just want some tips that I can use for the future as well.</p>
<p>I use Twitter Bootstrap, so most of the functions are a part of that. wysihtml5 is a WYSIWYG editor, tagit is for post tags (think Wordpress).</p>
<p>One thing I'm wondering about is my .ajax stuff, such as if I'm handling responses correctly.</p>
<pre><code>$(document).ready(function() {
// add buttons to content textarea
$('#item_content').wysihtml5({
"html": true
});
$("#image_library").load('/admin/file/library', { 'csrf_atk' : $("input[name=csrf_atk]").val(), 'images' : $('#post_images').val() });
$("#post_tags").tagit({
allowSpaces: true,
});
$('#post_date').datepicker();
$('.container').hide();
var post_type = '<?php echo $type; ?>';
$('#'+post_type+'_container').show();
$('.post_types button').click(function(){
var target = "#" + $(this).data("target");
$(".container").not(target).hide();
$(target).show();
$('#post_type').val($(this).text());
});
$('.post_status button').click(function(){
$('#post_status').val($(this).text());
});
// on delete button click, remove image from site folder, database, queue, and from hidden field
$('#image_container').on('click', '.image-delete', function() {
var $this = $(this);
$.ajax({
url: '<?=base_url();?>admin/file/delete_image_relationship',
type: 'POST',
data: {
csrf_atk: $("input[name=csrf_atk]").val(),
item_id: $("input[name=item_id]").val(),
image_id: $(this).val(),
},
success: function(response){
console.log(response);
$this.parent().parent().remove();
// get image_id in delete button
var id = $this.val();
//find id in hidden field and remove it
$("#post_images").val(function(i, v) {
return v.replace( new RegExp('(?=(?:^|,))(,?)' + id + '(?=(?:,|$)),?'), '$1' );
});
},
});
});
// make save button display "Saving..."
$('#save').button();
// on save click, serialize all form elements and insert/update database
$('#save').click(function() {
$('#save').button('loading');
// get url to post data to
var url = $('#item_form').attr('action');
// save form data to serialized array
var data = $('#item_form').serializeArray();
// get post tags
var tags = $('#post_tags').tagit('assignedTags');
// add tags to serialized array
data.push({ name: "tags", value: tags});
$.ajax({
url: url,
type: 'POST',
data: data,
success: function(data){
console.log(data);
json = $.parseJSON(data);
if(json.status == 'success') {
console.log(json);
} else {
$('#response_msg').html(json.message).addClass('alert alert-error');
}
},
error: function(jqXHR, textStatus, errorThrown) {
if (errorThrown == 'Forbidden') {
alert("Session has expired, login again to save");
} else {
alert(errorThrown);
}
},
complete: function(){
setTimeout(function () {
$('#save').button('reset')
}, 1000)
}
});
});
// on button click, set image type in database
$('#image_container').on('click', '.image-type button', function() {
$this = $(this);
$.ajax({
url: '<?=base_url();?>admin/file/set_image_type',
type: 'POST',
data: {
csrf_atk: $("input[name=csrf_atk]").val(),
type: $this.text(),
image_id: $this.val(),
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
$('.fileUpload').fileUploader({
autoUpload: true,
allowedExtension: 'jpg|jpeg|gif|png',
afterEachUpload: function(data, status, formContainer) {
// add image_id to hidden field
$('#post_images').val(function(i,val) {
return val + (val ? ',' : '') + json.image_id;
});
$("#image_library").load('/admin/file/library', { 'csrf_atk' : $("input[name=csrf_atk]").val(), 'images' : $('#post_images').val() });
}
});
});
</code></pre>
|
[] |
[
{
"body": "<p>You'll want to think in terms of javascript rather than jQuery when you develop. jQuery is just a toolkit, not a framework. You may want to review some JS design patterns (Google, Essential JS Design Patterns) and make sure to check out the MV* chapter. </p>\n\n<p>Moving forward with your code, improve <strong>performance</strong> by not calling the jQuery object on a element via a selector more than once. In other words store <code>$('#save')</code> into a var like <code>$save</code>. Learn how to utilize <code>$(this)</code>. Use <a href=\"http://tobiasahlin.com/blog/quick-guide-chaining-in-jquery/\" rel=\"nofollow\">chaining</a> more. This will also prevent having to change 5 lines of code when you change an id. </p>\n\n<p><strong>Organize</strong> your code by consolidating into <a href=\"http://www.joezimjs.com/javascript/javascript-closures-and-the-module-pattern/\" rel=\"nofollow\">closed modules</a> -or- objects, at the least, and bring those variables like <code>post_type</code> into scope.</p>\n\n<p>Taking the next step would be organizing your objects into views, models, and event managers. You may want to check out Backbone and Underscore for more efficient event handling, data management, templating, and utilities.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T23:32:30.483",
"Id": "14341",
"ParentId": "14311",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T20:53:08.740",
"Id": "14311",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Cleaning up jQuery"
}
|
14311
|
<p><em><strong>Edit</em></strong> <em>Just did some further reading around the website and have come to the conclusion that this method leads to <a href="http://www.joelonsoftware.com/articles/LeakyAbstractions.html" rel="nofollow">Leaky Abstraction</a>, sorry for wasting peoples time. Time to head back to the drawing board.</em></p>
<p><strong>Situation Context</strong></p>
<p>I currently develop on my own, building codeigniter cms type websites for clients that want to manage products and run a cart like system. I have my boss who does the designs, sends me the psd and says get on with it, putting in his 2 cents in every now and then as he finds things he wants done differently.</p>
<p>I work with no other programmers so have no one to critique my methods, and with this being my first development role I would imagine i'm missing out on a lot of important feedback. </p>
<p>Anywho, the situation is this, I find myself doing the same types of queries often and have functions all over the show doing similar, but slightly different things. Some will be selecting all with a limit and others with an order by. So I decided maybe it wouldn't be a bad idea to set up a model that does most of my selecting based on the parameters I send it. The following is what I have mocked up over the last hour, before I go ahead with fine tuning it I wanted to pick some more experienced programmers brains to find out if this path is a flawed/dangerous one and i'm just not seeing it or if this isn't a bad idea and should continue.</p>
<p><strong>An Example Controller</strong></p>
<pre><code>public function query_helper(){
$table = 'entry';
$where = array();
$where[] = array('where' => 'entry_name', 'equals' => 'Up And Running!');
$where[] = array('where' => 'author_id', 'equals' => 1);
$order_by = array('entry_name', 'DESC');
$limit = array(1,0);
$data['record'] = $this->query_model->get($table, $where, $orwhere, $order_by, $limit);
$this->load->view('pages/query_helper', $data);
}
</code></pre>
<p><strong>The Model</strong></p>
<pre><code>class Query_model extends CI_Model {
/**
* This funtion selects an individual record based on the paramaters sent and returns
* only one result
*
* @return array
* @author Oliver
**/
function get($table, $where,$orwhere,$order_by, $limit){
for($i = 0; $i < count($where); $i++){
$this->db->where($where[$i]['where'],$where[$i]['equals']);
}
for($i = 0; $i < count($orwhere); $i++){
$this->db->or_where($orwhere[$i]['where'],$orwhere[$i]['equals']);
}
if($order_by){
// Variable must be array with condition followed by ASC or DESC
$this->db->order_by($order_by[0], $order_by[1]);
}
if($limit){
// Variable must be array with limit followed by start
$this->db->limit($limit[0], $limit[1]);
}
$query = $this->db->get($table);
return $query->row();
}
/**
* This funtion selects all records based on the paramaters sent, including the limit,
* and returns only one result
*
* @return array
* @author Oliver
**/
function get_all($table, $where, $orwhere, $order_by, $limit){
for($i = 0; $i < count($where); $i++){
$this->db->where($where[$i]['where'],$where[$i]['equals']);
}
for($i = 0; $i < count($orwhere); $i++){
$this->db->or_where($orwhere[$i]['where'],$orwhere[$i]['equals']);
}
if($order_by){
// Variable must be array with condition followed by ASC or DESC
$this->db->order_by($order_by[0], $order_by[1]);
}
if($limit){
// Variable must be array with limit followed by start
$this->db->limit($limit[0], $limit[1]);
}
$query = $this->db->get($table);
return $query->result();
}
/**
* This funtion inserts a record based on the paramaters sent.
*
* @return bool
* @author Oliver
**/
function insert($table, $data){
if($this->db->insert($table, $data)){
return true;
}
else{
return false;
}
}
/**
* This funtion updates a record based on the paramaters sent.
*
* @return bool
* @author Oliver
**/
function update($table, $data, $where, $orwhere){
for($i = 0; $i < count($where); $i++){
$this->db->where($where[$i]['where'],$where[$i]['equals']);
}
for($i = 0; $i < count($orwhere); $i++){
$this->db->or_where($orwhere[$i]['where'],$orwhere[$i]['equals']);
}
if($this->db->update($table, $data)){
return true;
}
else{ return false; }
}
/**
* This funtion deletes a record based on the paramaters sent.
*
* @return bool
* @author Oliver
**/
function delete($table, $where, $orwhere){
for($i = 0; $i < count($where); $i++){
$this->db->where($where[$i]['where'],$where[$i]['equals']);
}
for($i = 0; $i < count($orwhere); $i++){
$this->db->or_where($orwhere[$i]['where'],$orwhere[$i]['equals']);
}
if($this->db->delete($table)){
return true;
}
else{
return false;
}
}
</code></pre>
<p>}</p>
|
[] |
[
{
"body": "<p>Abstractions rarely result in optimizations, but that doesn't mean they aren't useful. Whether this a good idea or not depends upon whether you have a large number of tables that can be treated the same, and whether that helps you.</p>\n\n<p>In general it's not a good idea not because there are cases where it doessn't do what you want, but because it will add complextity for little gain. If your tables are relatively stable, you could use the same (or very similar) code to autogenerate stored procedures, which you then call directly -- you end up with more code, but it's easier to understand.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T05:35:46.673",
"Id": "14321",
"ParentId": "14313",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T23:56:29.717",
"Id": "14313",
"Score": "2",
"Tags": [
"php",
"optimization",
"sql",
"codeigniter"
],
"Title": "Is having preset queries prone for disaster?"
}
|
14313
|
<p>I have implemented an STL-like graph class. Could someone review it and tell me things that I could add to it?</p>
<p><strong>File graph.hpp</strong></p>
<pre><code>#include <vector>
#include <list>
using std::vector;
using std::list;
#ifndef GRAPH_IMPL
#define GRAPH_IMPL
namespace graph {
struct node
{
int v,w;
};
template<class T, bool digraph>
class graph;
template<class T>
class vertex_impl
{
friend class graph<T,true>;
friend class graph<T,false>;
private:
list<node> adj;
int index;
T masking;
public:
vertex_impl(int index = -1, const T& masking = T()) : index(index), masking(masking){}
vertex_impl(const vertex_impl& other) : index(other.index), masking(other.masking){}
typedef typename list<node>::iterator iterator;
typedef typename list<node>::const_iterator const_iterator;
typedef typename list<node>::reverse_iterator reverse_iterator;
typedef typename list<node>::const_reverse_iterator const_reverse_iterator;
typedef typename list<node>::size_type size_type;
iterator begin() { return adj.begin(); }
const_iterator begin() const { return adj.begin(); }
iterator end() { return adj.end(); }
const_iterator end() const { return adj.end(); }
reverse_iterator rbegin() { return adj.rbegin(); }
const_reverse_iterator rbegin() const { return adj.begin(); }
reverse_iterator rend() { return adj.rend(); }
const_reverse_iterator rend() const { return adj.rend(); }
size_type degree() const { return adj.size(); }
int name() const { return index; }
const T& mask() const { return masking; }
void set_mask(const T& msk) { masking = msk; }
};
template<class T, bool digraph>
class graph
{
private:
vector<vertex_impl<T> > adj;
typename vector<vertex_impl<T> >::size_type V,E;
public:
typedef vertex_impl<T> vertex;
typedef typename vector<vertex>::iterator iterator;
typedef typename vector<vertex>::const_iterator const_iterator;
typedef typename vector<vertex>::reverse_iterator reverse_iterator;
typedef typename vector<vertex>::const_reverse_iterator const_reverse_iterator;
typedef typename vector<vertex>::size_type size_type;
graph(size_type v) : adj(v), V(v), E(0)
{
for(size_type i = 0; i < v; ++i) {
adj[i].index = i;
}
}
iterator begin() { return adj.begin(); }
const_iterator begin() const { return adj.begin(); }
iterator end() { return adj.end(); }
const_iterator end() const { return adj.end(); }
reverse_iterator rbegin() { return adj.rbegin(); }
const_reverse_iterator rbegin() const { return adj.rbegin(); }
reverse_iterator rend() { return adj.rend(); }
const_reverse_iterator rend() const { return adj.rend(); }
void insert(int from, int to, int weight = 1)
{
adj[from].adj.push_back((node){to,weight});
E++;
if(!digraph)
adj[to].adj.push_back((node){from,weight});
}
void erase(int from, int to)
{
for(typename vertex::iterator i = adj[from].begin(); i != adj[from].end();) {
if(i->v == to) {
i = adj[from].adj.erase(i);
E--;
} else {
++i;
}
}
if(!digraph) {
for(typename vertex::iterator i = adj[to].begin(); i != adj[to].end();) {
if(i->v == from) {
i = adj[to].adj.erase(i);
} else {
++i;
}
}
}
}
size_type vertices() const { return V; }
size_type edges() const { return E; }
vertex& operator[](int i) { return adj[i]; }
const vertex& operator[](int i) const { return adj[i]; }
};
}
#endif
</code></pre>
<p><strong>File main.cpp</strong></p>
<pre><code>#include <stdio.h>
#include "graph.hpp"
int main()
{
graph::graph<char*,false> gr(5);
int m;
scanf("%d", &m);
for(int i=0; i<m; ++i) {
int a,b;
scanf("%d %d", &a, &b);
gr.insert(a,b);
}
for(graph::graph<char*,false>::size_type i = 0; i < 5; ++i) {
printf("%d: ", gr[i].name());
for(graph::graph<char*,false>::vertex::iterator j = gr[i].begin(); j != gr[i].end(); ++j) {
printf(" %d", j->v);
}
printf("\n");
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T19:22:54.280",
"Id": "83437",
"Score": "1",
"body": "Take a look at my blog post where it says how can we create a C++ graph using STL:\nhttp://theunixshell.blogspot.in/2014/02/creating-graph-using-stls-in-c.html"
}
] |
[
{
"body": "<ul>\n<li>your <code>node</code> type doesn't seem to be a node, but an <em>edge</em> (or an adjacency relationship, or something). Unless this implementation is based on some literature which describes entries in the adjacency list as <em>nodes</em>, I'd consider renaming it</li>\n<li>I have no idea what <em>mask</em> and <em>masking</em> are supposed to mean. They may be meaningful names in the context where you're using this graph, but it isn't clear that they are in a generic graph. It's just where the user attaches their arbitrary data to each vertex, right? Is it even used?</li>\n<li>the number of vertices is fixed at creation time, and you can only add edges. Is that sensible?</li>\n<li><code>graph::insert</code> doesn't check whether <code>from</code> and <code>to</code> are valid indices</li>\n<li>what does <code>digraph</code> mean here - directed graph? Because there is <a href=\"http://en.wikipedia.org/wiki/Digraphs_and_trigraphs\">another meaning</a> which is totally unrelated. Why not just say \"directed\"?</li>\n<li>it looks like <code>graph::V</code> is <em>always</em> identical to <code>adj.size()</code> (and is anyway never used), so you can remove it</li>\n<li><code>vertex_impl</code> is an internal implementation detail, yet you're exposing it. STL containers hide these details (list & tree nodes for example) inside the iterator, and only expose the user data. Is there a useful way of iterating <em>transparently</em> over the graph without exposing this?</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T16:09:08.793",
"Id": "14454",
"ParentId": "14322",
"Score": "6"
}
},
{
"body": "<p>The point of the include guards is to prevent multiple inclusion of anything.\nSo always put them at the top of the file:</p>\n<pre><code>#include <vector>\n#include <list>\n\n#ifndef GRAPH_IMPL\n#define GRAPH_IMPL\n</code></pre>\n<p>Because these are not at the top you include vector/list every time. This is just more work that does not need to be done.</p>\n<p>Never put using statements in a header file (in global context).</p>\n<pre><code>using std::vector;\nusing std::list;\n</code></pre>\n<p>Anybody that uses your header file now implicitly pulls vector/list into the global namespace. This can have undesirable effects with name resolution. Don't do this in a header file. If you must be lazy then use scope so you are not forcing your requirements onto others. There is always a typedef to make things easier.</p>\n<p>Comments (or well named members) would be an idea.</p>\n<pre><code> struct node\n {\n int v,w;\n };\n</code></pre>\n<p>No idea what that will be used for.<br />\nIf the user of your code library should not be seeing this then it should also be contained inside the private part of a classs so that they don't accidentally use it.</p>\n<h3>vertex_impl</h3>\n<ul>\n<li>Not sure what <code>vertex_impl</code> is for?</li>\n<li>Is it exposed externally?</li>\n<li>What is it implementing (its name contains <code>impl</code>)?</li>\n<li>Why can it have more than two nodes (To me a vertex is an edge that connects two nodes)?</li>\n<li>Why does the constructor not fully initialize the object (index is set externally).</li>\n<li>What is <code>masking</code> for?</li>\n<li>What is <code>index</code> for?</li>\n</ul>\n<p>When I build objects that contain containers I abstract the container used:</p>\n<pre><code>list<node> adj;\n</code></pre>\n<p>Here I would have gone:</p>\n<pre><code>typedef std::list<node> Container;\nContainer adj;\n</code></pre>\n<p>Then I would derive the other iterator types from Container. This means if the code changes there is only one location where the code needs to change.</p>\n<p>Having an explicit <code>rbegin()</code> and <code>rend()</code> implies that there is some ordering to the nodes. personally I would leave them out as their does not seem to be any way to logically define the order of traversal of a graph. If the user wants to iterate in the reverse order then can use <code>std::reverse_iterator</code>.</p>\n<h3>graph</h3>\n<p>Basically the same comments as vertex_impl</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T15:26:31.707",
"Id": "14486",
"ParentId": "14322",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "14454",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T10:34:56.480",
"Id": "14322",
"Score": "5",
"Tags": [
"c++",
"classes",
"graph",
"stl"
],
"Title": "STL-like graph implementation"
}
|
14322
|
<p>I wrote a predicate used in a <code>remove_if</code> call that deletes shared_ptr's of type StemmedSentence from an vector of sentences. </p>
<p>The predicate:</p>
<pre><code>class EraseSentenceIf {
ArrayStemmedSnippet * m_ass;
public:
EraseSentenceIf(ArrayStemmedSnippet *ass)
: m_ass(ass) {
}
bool operator()(const std::shared_ptr<
ArrayStemmedSnippet::StemmedSentence>& s) {
std::shared_ptr<ArrayStemmedSnippet::StemmedSentence> tmp = s;
// --- set StemmedSentnce object in ArrayStemmedSnippet class
s->setParent(m_ass);
// --- if true delete this sentence)
if (s->trimStopWords()) {
tmp.reset();
return true;
}
return false;
}
};
</code></pre>
<p>The remove_if call:</p>
<pre><code>EraseSentenceIf esi(this);
sentences.erase(
std::remove_if(
sentences.begin(), sentences.end(), esi),
sentences.end()
);
</code></pre>
<p>Declaration:</p>
<pre><code>std::vector<shared_ptr<StemmedSentence> > sentences;
</code></pre>
<p>The construction of the sentences objects looks like this:</p>
<pre><code>sentences.push_back(shared_ptr<StemmedSentence>(
new StemmedSentence(index, i - 1 )));
</code></pre>
<p>The code seems to run fine, valgrind / gdb does not moan. I just want to get sure that I handle the deletion (or release) of the shared_ptr in a correct way. Can somebody please confirm this? Maybe I can improve something or I overlooked an important point. Thanks for your comments!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T03:01:20.667",
"Id": "23176",
"Score": "0",
"body": "`tmp.reset();` only resets `tmp`, not the object inside of `sentences`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T03:15:44.947",
"Id": "23177",
"Score": "0",
"body": "@ildjarn: Because it was copied, incremented the reference counter and this is why I only delete `tmp` ?! I can not use `s` because the compiler says `error: ‘class ArrayStemmedSnippet::StemmedSentence’ has no member named ‘reset’`, which I understand. So how do I clearly delete it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T03:16:17.153",
"Id": "23178",
"Score": "0",
"body": "Just a side note: If you make your `operator()` `const`, you could pass your `EraseSentenceIf` object as temporary instead of using the `esi` variable."
}
] |
[
{
"body": "<p>Within the predicate you make a copy of the <code>shared_ptr</code> hence incrementing the reference count:</p>\n\n<pre><code> std::shared_ptr<ArrayStemmedSnippet::StemmedSentence> tmp = s;\n</code></pre>\n\n<p>A few lines later you explicitly reset <em>this copy</em> (note that this does not release any memory unless it's the last living <code>shared_ptr</code> referring to the pointee):</p>\n\n<pre><code> // --- if true delete this sentence)\n if (s->trimStopWords()) {\n // NOT NECESSARY -- reference count will be decremented when tmp falls out of scope\n tmp.reset();\n\n return true;\n }\n</code></pre>\n\n<p>The actual deletion occurs when the <code>shared_ptr</code> residing inside the <code>vector</code> is destroyed (assuming it's the last remaining copy):</p>\n\n<pre><code>sentences.erase(\n std::remove_if(\n sentences.begin(), sentences.end(), esi),\n sentences.end()\n);\n</code></pre>\n\n<p>So, everything will work fine as it is but the <code>tmp</code> variable in the predicate is unnecessary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T03:31:17.223",
"Id": "23179",
"Score": "0",
"body": "OK, I got it now. Means by simply returning `true` to `remove_if` tells `erase_if` to actually delete the pointer from the vector, right? Because I see that the destructor of the `StemmedSentence` object is called."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T03:49:21.663",
"Id": "23180",
"Score": "0",
"body": "@AndreasW.Wylach Right. Though technically, the deletion could occur during `remove_if` since it overwrites the items to be removed with those to be kept (hence causing the removed `shared_ptr`'s to be destroyed). `erase` just removes the garbage from the end of the `vector` once `remove_if` is finished."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T03:56:18.250",
"Id": "23181",
"Score": "0",
"body": "Ok, thanks for the suggestions! I made the changes and as I see in the allocations count of valgrind, indeed there are less allocations with this change. I basically forget that the `tmp` assignment makes a copy."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T03:18:44.523",
"Id": "14326",
"ParentId": "14325",
"Score": "1"
}
},
{
"body": "<ol>\n<li><p>The copy of the pointer is completely unnecessary: as long as the code is not sharing <code>shared_ptr</code>s among threads (which is really, really silly), taking a <code>shared_ptr</code> argument by reference ensures it lives at least until the function finishes executing.</p></li>\n<li><p>Even if the copy was necessary, passing by reference to immediately make a copy is a <em>pessimisation</em> as it forbids moves. <a href=\"https://stackoverflow.com/questions/10826541/passing-shared-pointers-as-arguments/10826907#10826907\">Don't pass <code>shared_ptr</code> by reference if you're going to copy it</a>.</p></li>\n<li><p>The pointer in the vector will be destroyed by <code>erase</code>, there's no need to manually <code>reset</code> anything.</p></li>\n<li><p>A predicate that mutates its argument is bound to raise eyebrows. Depending on the semantics of <code>setParent</code> it may or may not be problematic, but it is something I'd avoid if I could.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T03:42:26.290",
"Id": "23182",
"Score": "2",
"body": "+1; OP seems to be having difficulties understanding the founding principles behind smart pointers. I would suggest understanding the problem before taking up the buzzword solution. There are a lot of online resources, just a quick search on SO reveals many useful answers that successfully FAQ-ify the problem: http://stackoverflow.com/questions/395123/raii-and-smart-pointers-in-c/395519#395519"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T03:45:32.480",
"Id": "23183",
"Score": "0",
"body": "StemmedSentence is an nested class of ArrayStemmedSnippet and needs to point to the current ArrayStemmedSnippet object. I think there is no problem with that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T03:47:59.577",
"Id": "23184",
"Score": "0",
"body": "@Domagoj Pandža: Thank you for your kind suggestion. I am doing that already while I try something out (learning by doing), and I ask here if I am on the right track. Yes, smart pointers are new to me. So forgive me for my beginners mistakes."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T03:35:02.363",
"Id": "14327",
"ParentId": "14325",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "14326",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T02:58:17.447",
"Id": "14325",
"Score": "2",
"Tags": [
"c++",
"c++11"
],
"Title": "Is this predicate valid to delete single shared_ptr's?"
}
|
14325
|
<p>If I have an array:</p>
<pre><code>var names = ['John', 'Jim', 'Joe'];
</code></pre>
<p>and I want to create a new array from names which afterwards will look like:</p>
<pre><code>newNames = ['John John', 'Jim Jim', 'Joe Joe']
</code></pre>
<p>What I came up with is the following:</p>
<pre><code>var newNames = [];
var arr = null;
var loop = 0;
$.each(names, function (i, item) {
arr = [];
loop = 2;
while (loop--) {
arr.push(item);
}
newNames.push(arr.join(' '));
});
</code></pre>
<p>Seems like there should be a shorter, easier way to do this. As you can see we can repeat the names with a space n times. I'm experimenting with different ideas/concepts, having fun.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T12:20:06.710",
"Id": "451341",
"Score": "0",
"body": "Since then, JavaScript has added `String.repeat()`."
}
] |
[
{
"body": "<p>You could use the native <code>Array.map</code> method in modern browsers (<a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\">see MDN</a>)</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const newNames = ['John', 'Jim', 'Joe'].map( name => `${name} ${name}`);\nconsole.log(newNames);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-08-04T12:41:13.300",
"Id": "14333",
"ParentId": "14330",
"Score": "7"
}
},
{
"body": "<p>Create a function that operates on values in the manner you want...</p>\n\n<pre><code>function dupe(n) { return n + \" \" + n }\n</code></pre>\n\n<hr>\n\n<p>then use <code>Array.prototype.map</code>...</p>\n\n<pre><code>var newNames = names.map(dupe)\n</code></pre>\n\n<hr>\n\n<p>or jQuery's not quite compliant version, <code>$.map</code>...</p>\n\n<pre><code>var newNames = $.map(names, dupe)\n</code></pre>\n\n<hr>\n\n<p>You can also create a function factory that will make a <code>dupe</code> function that will add the operate on the value a given number of times.</p>\n\n<pre><code>function dupeFactory(i) {\n return function(n) {\n var j = i-1\n , m = n\n while (j--)\n m += \" \" + n\n return m\n }\n}\n</code></pre>\n\n<p>Then use it like this...</p>\n\n<pre><code>var newNames = names.map(dupeFactory(3))\n</code></pre>\n\n<hr>\n\n<p>Or make reuse of the functions created from the factory, by storing them in variables...</p>\n\n<pre><code>var dupe3 = dupeFactory(3),\n dupe6 = dupeFactory(6)\n\nnames.map(dupe6)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T12:51:11.840",
"Id": "23194",
"Score": "0",
"body": "Dang, this seems to be pretty straightforward and very clean. Thanks much."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T12:52:15.723",
"Id": "23195",
"Score": "0",
"body": "@DavidWhitten: You're welcome. I also added a solution that lets you choose how many times you want to append the name."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T12:53:42.763",
"Id": "23196",
"Score": "0",
"body": "Your `dupeFactory` does not work, it creates 2^n repetitions..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T12:58:22.117",
"Id": "23197",
"Score": "0",
"body": "http://jsfiddle.net/6THSR/"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T12:41:56.680",
"Id": "14334",
"ParentId": "14330",
"Score": "3"
}
},
{
"body": "<p>I guess you want to have a variable <code>loop</code> value:</p>\n\n<pre><code>var names = […];\n\nvar newNames = names.slice(0); // copy the names for the first part\nfor (var i=0; i<names.length; i++)\n for (var j=1; j<2; j++) // sic\n newNames[i] += \" \"+names[i];\n</code></pre>\n\n<p>Else, for a constantly two times a simple string concatenation will be shorter. Together with <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow\"><code>.map()</code></a>:</p>\n\n<pre><code>var newNames = names.map(function(name) {\n return name+\" \"+name;\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T12:43:55.343",
"Id": "14335",
"ParentId": "14330",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "14334",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T12:34:06.090",
"Id": "14330",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "Javascript Array processing"
}
|
14330
|
<p>I have pieced together some code that works for my project. However, it is pretty long, but self-similar. I am a jQuery beginner and I tried to shorten the code by using variables, but it didn't work so far. I guess I should use some <code>for()</code>-statement. Could you help me to simplify this code?</p>
<pre><code>//apply the class "active" to the menu items whose div is in the viewport and animate
$('#home').bind('inview', function (event, visible) {
if (visible == true) {
$('#menu li:nth-child(1)').stop().animate(
{backgroundPosition:"(0 0)"},
{duration:500});
$('#menu li:nth-child(1) a').css( {'color': 'white'} );
$('#nav li:nth-child(1)').stop().animate({opacity: 1}, 500);
} else {
$('#menu li:nth-child(1)').stop().animate(
{backgroundPosition:"(-200px 0)"},
{duration:500});
$('#menu li:nth-child(1) a').css( {'color': 'black'} );
$('#nav li:nth-child(1)').stop().animate({opacity: 0.2}, 500);
}
});
$('#referenzen').bind('inview', function (event, visible) {
if (visible == true) {
$('#menu li:nth-child(2)').stop().animate(
{backgroundPosition:"(0 0)"},
{duration:500});
$('#menu li:nth-child(2) a').css( {'color': 'white'} );
$('#nav li:nth-child(2)').stop().animate({opacity: 1}, 500);
} else {
$('#menu li:nth-child(2)').stop().animate(
{backgroundPosition:"(-200px 0)"},
{duration:500});
$('#menu li:nth-child(2) a').css( {'color': 'black'} );
$('#nav li:nth-child(2)').stop().animate({opacity: 0.2}, 500);
}
});
$('#unternehmen').bind('inview', function (event, visible) {
if (visible == true) {
$('#menu li:nth-child(3)').stop().animate(
{backgroundPosition:"(0 0)"},
{duration:500});
$('#menu li:nth-child(3) a').css( {'color': 'white'} );
$('#nav li:nth-child(3)').stop().animate({opacity: 1}, 500);
} else {
$('#menu li:nth-child(3)').stop().animate(
{backgroundPosition:"(-200px 0)"},
{duration:500});
$('#menu li:nth-child(3) a').css( {'color': 'black'} );
$('#nav li:nth-child(3)').stop().animate({opacity: 0.2}, 500);
}
});
$('#taetigkeit').bind('inview', function (event, visible) {
if (visible == true) {
$('#menu li:nth-child(4)').stop().animate(
{backgroundPosition:"(0 0)"},
{duration:500});
$('#menu li:nth-child(4) a').css( {'color': 'white'} );
$('#nav li:nth-child(4)').stop().animate({opacity: 1}, 500);
} else {
$('#menu li:nth-child(4)').stop().animate(
{backgroundPosition:"(-200px 0)"},
{duration:500});
$('#menu li:nth-child(4) a').css( {'color': 'black'} );
$('#nav li:nth-child(4)').stop().animate({opacity: 0.2}, 500);
}
});
$('#kontakt').bind('inview', function (event, visible) {
if (visible == true) {
$('#menu li:nth-child(5)').stop().animate(
{backgroundPosition:"(0 0)"},
{duration:500});
$('#menu li:nth-child(5) a').css( {'color': 'white'} );
$('#nav li:nth-child(5)').stop().animate({opacity: 1}, 500);
} else {
$('#menu li:nth-child(5)').stop().animate(
{backgroundPosition:"(-200px 0)"},
{duration:500});
$('#menu li:nth-child(5) a').css( {'color': 'black'} );
$('#nav li:nth-child(5)').stop().animate({opacity: 0.2}, 500);
}
});
$('#anfahrt').bind('inview', function (event, visible) {
if (visible == true) {
$('#menu li:nth-child(6)').stop().animate(
{backgroundPosition:"(0 0)"},
{duration:500});
$('#menu li:nth-child(6) a').css( {'color': 'white'} );
$('#nav li:nth-child(6)').stop().animate({opacity: 1}, 500);
} else {
$('#menu li:nth-child(6)').stop().animate(
{backgroundPosition:"(-200px 0)"},
{duration:500});
$('#menu li:nth-child(6) a').css( {'color': 'black'} );
$('#nav li:nth-child(6)').stop().animate({opacity: 0.2}, 500);
}
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T12:25:30.063",
"Id": "23198",
"Score": "0",
"body": "we can guess at the purpose of the function however it would be good if you could specifically state the requirememnts for your function. Also it would be good to see what you have attempted so we can help you improve. We wont just do work for you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T12:27:05.440",
"Id": "23199",
"Score": "2",
"body": "Please also show the HTML markup. Are those ids (`#anfahrt`, etc) the same nodes referenced by the `nth-child()`?"
}
] |
[
{
"body": "<p>I assume you have set up the links in the menu properly, i.e. they reference the elements they correspond to, something like</p>\n\n<pre><code><ul id=\"menu\">\n <li><a href=\"#home\">Home</a></li>\n <li><a href=\"#referenzen\">Referenzen</a></li>\n <!-- ... -->\n</ul>\n</code></pre>\n\n<p>So you can just search for the corresponding link with the <a href=\"http://api.jquery.com/attribute-equals-selector/\" rel=\"nofollow\">attribute selector <em><sup>[docs]</sup></em></a> and get the enclosing <code>li</code> element:</p>\n\n<pre><code>$('#home, #referenzen, ...').bind('inview', function (event, visible) {\n var $menu_element = $('#menu a[href=#' + this.id + ']').closest('li'), \n // get the '#nav li' element at the same position \n $nav_element = $('#nav li').eq($menu_element.index());\n\n $menu_element.stop().animate(\n {backgroundPosition: visible ? '(0 0)' : '(-200px 0)'},\n {duration: 500}\n ).find('a').css({color: visible ? 'white' : 'black'});\n $nav_element.stop().animate({opacity: visible ? 1 : 0.2}, 500);\n});\n</code></pre>\n\n<p>If you don't have set up the links correctly (you really should), give the <code>li</code> items in the <code>#menu</code> (and maybe <code>#nav</code>) list a (for example) <code>data-id</code> attribute with a value corresponding to the element's ID and again, use the attribute selector to get them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T12:27:59.683",
"Id": "14337",
"ParentId": "14336",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "14337",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T12:21:24.333",
"Id": "14336",
"Score": "1",
"Tags": [
"javascript",
"beginner",
"jquery",
"animation"
],
"Title": "Animation effects for menu items"
}
|
14336
|
<p>I am trying to learn C and have written a very basic socket library. I would be interested in any general design and coding comments.</p>
<p>Note that at this stage I am not bothered about implementing the most efficient networking model. I just want to get a simple synchronous model working then I can progress from there.</p>
<p>This is a client library only and the most pressing problem is how to retrieve data. I have implemented a function for the caller to pass in a function pointer for a callback function for received data. But how do I retrieve the recv data in the library? Do I poll on a timer? First phase is Windows winsock. but want to extend to simple Unix based synchronous when windows code working.</p>
<p><strong>basic_socket.h</strong></p>
<pre><code>#ifndef __BASIC_SOCKET_H__
#define __BASIC_SOCKET_H__
/* startup/shutdown */
int init();
void libcleanup();
int tcp_connect(const char* pcHost, int nPort);
int senddata(const char* data, size_t len);
void getdata();
/* setup client callback function for retrieved data */
void data_recv_callback(void (*mycallback_function)(const char*));
#endif /*__BASIC_SOCKET_H__ */
</code></pre>
<p><strong>basic_socket.c</strong></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
/* Not doing anything with linux yet */
#ifdef __linux
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#elif WIN32
#include <winsock.h>
#endif
SOCKET sockfd;
char buffer[4096];
typedef void (*cbfunc) (const char* s);
cbfunc g_cbfunc = 0;
/* helper function to connect to server */
SOCKET establish_connection(u_long nRemoteAddr, u_short nPort)
{
/* Create a stream socket */
struct sockaddr_in sinRemote;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd != INVALID_SOCKET) {
sinRemote.sin_family = AF_INET;
sinRemote.sin_addr.s_addr = nRemoteAddr;
sinRemote.sin_port = nPort;
if (connect(sockfd, (struct sockaddr*)&sinRemote, sizeof(struct sockaddr_in)) == SOCKET_ERROR) {
sockfd = INVALID_SOCKET;
}
}
return sockfd;
}
int init() {
#ifdef WIN32
WORD ver = MAKEWORD( 1, 1 );
WSADATA wsa = {0};
return WSAStartup(ver, &wsa);
#endif
return 0;
}
void libcleanup() {
WSACleanup();
}
u_long LookupAddress(const char* pcHost)
{
u_long nRemoteAddr = inet_addr(pcHost);
if (nRemoteAddr == INADDR_NONE) {
/* pcHost isn't a dotted IP, so resolve it through DNS */
struct hostent* pHE = gethostbyname(pcHost);
if (pHE == 0) {
return INADDR_NONE;
}
nRemoteAddr = *((u_long*)pHE->h_addr_list[0]);
}
return nRemoteAddr;
}
int tcp_connect(const char* pcHost, int nPort) {
struct in_addr Address;
u_long nRemoteAddress = LookupAddress(pcHost);
if (nRemoteAddress == INADDR_NONE) {
printf("lookup address error\n");
return 3;
}
memcpy(&Address, &nRemoteAddress, sizeof(u_long));
printf("%s : %u\n", inet_ntoa(Address), nPort);
puts("Connecting to remote host...");
sockfd = establish_connection(nRemoteAddress, htons(nPort));
if (sockfd == INVALID_SOCKET) {
printf("Unable to establish a connection with server %s\n", pcHost);
return 3;
}
printf("successfully connected to server %s\n", pcHost);
return 0;
}
int senddata(const char* data, size_t len) {
return send(sockfd, data, len, 0);
}
/* would I set a timer to periodically call this function??? */
void getdata() {
int n = 0;
char* rec = 0;
while((n = recv(sockfd, buffer, sizeof(buffer), 0)) > 0) {
buffer[n]= 0;
rec = malloc(n+1);
strncpy(rec, buffer, n+1);
if(g_cbfunc)
g_cbfunc(rec);
free(rec);
}
}
void data_recv_callback(void (*mycallback_function)(const char*)) {
g_cbfunc = mycallback_function;
}
</code></pre>
<p><strong>main.c (to exercise)</strong></p>
<pre><code>#include <stdio.h>
#include <string.h>
#include "basic_socket.h"
void dump_output(const char* s) {
puts(s);
}
int main(int argc, char* argv[]) {
char recbuf[4096] = {0};
const char* msg = "GET / HTTP/1.1\n\n";
int ret = init();
data_recv_callback(dump_output);
if(ret)
printf("Error initialising socket library: %d\n", ret);
tcp_connect("www.google.co.uk", 80);
/* retrieve google home page */
ret = senddata(msg, strlen(msg)+1);
printf("%i bytes sent\n", ret);
getdata();
libcleanup();
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>If you have not done anything with linux then don't even include the header files.<br>\nThis gives a user a false sense that this is correct which is unknowable until you test it.</p>\n\n<pre><code>#if WIN32\n#include <winsock.h>\n#else\n/* Not doing anything with linux yet */\n#error \"Untested in this environment\"\n#endif\n</code></pre>\n\n<p>The trouble with the socketaddr_in type is that a lot of the data is unspecified. So you need to make sure you manually zero the whole structure before you use it:</p>\n\n<pre><code>struct sockaddr_in sinRemote;\nbzero((char *) &sinRemote, sizeof(sinRemote));\n</code></pre>\n\n<p>I don't think the sockaddr_in is structured like you think. I don;t believe (I could be wrong on this) you can assume it is an integer. The on;y way I know of setting the destination host is</p>\n\n<pre><code>sinRemote.sin_addr.s_addr = nRemoteAddr;\n\n// don't believe your is portable.\n// This is the way I am used to doing it.\n\nstruct hostent *server = gethostbyname(nRemoteAddr);\nbcopy((char *)server->h_addr, \n (char *)&sinRemote.sin_addr.s_addr,\n server->h_length);\n</code></pre>\n\n<p>The port number is supposed to be in network byte order.</p>\n\n<pre><code> sinRemote.sin_port = nPort;\n\n // So you should write your code to make sure this always happens.\n\n sinRemote.sin_port = htons(nPort);\n</code></pre>\n\n<p>One assumes that <code>SOCKET_ERROR</code> is -1.<br>\nPersonally I don't see a point in hiding this value inside a variable it makes the code harder to read. The documentation says connect returns -1 on an error.</p>\n\n<pre><code> if (connect(sockfd, (struct sockaddr*)&sinRemote, sizeof(struct sockaddr_in)) == SOCKET_ERROR) {\n</code></pre>\n\n<p>This is definitely not an assumption I would make:</p>\n\n<pre><code> u_long nRemoteAddr = *((u_long*)pHE->h_addr_list[0]);\n</code></pre>\n\n<p>What happens if it returns an IPV6 address? Will it fit? What happens in the future and our alien overlords require IPV12. Will you destroy the last hope of humanity because your code crashes while trying to infect the aliens spaceship with your windows machine.</p>\n\n<p>This is undefined behavior if the amount of data read is 4096!</p>\n\n<p>while((n = recv(sockfd, buffer, sizeof(buffer), 0)) > 0) {</p>\n\n<pre><code> // Buffer overflow if n is the size of the buffer.\n buffer[n]= 0;\n</code></pre>\n\n<p>This is not threaded code (as there are no locks). So there seems little point in making a copy of the data here.</p>\n\n<pre><code> rec = malloc(n+1);\n strncpy(rec, buffer, n+1);\n\n if(g_cbfunc)\n g_cbfunc(rec);\n\n free(rec);\n</code></pre>\n\n<p>Pass a pointer to the buffer to g_cbfunc(). If it needs a copy then it can make a copy itself. Otherwise you are wasting resources making a copy.</p>\n\n<p>Since you have the length locally why not pass that information to g_cbfun() as a parameter. Otherwise it needs to scan the buffer looking for the zero byte (which if the data is binary and not text may be a problem).</p>\n\n<p>Rather than using a NULL as the default pointer use a function that does nothing. That way there is no need to test for NULL.</p>\n\n<pre><code> typedef void (*cbfunc) (const char* s, size_t count);\n void doNothing(const char* s, size_t count) {}\n\n // Just make sure if sombody sets a NULL callback then you set doNothing.\n cbfunc g_cbfunc = &doNothing;\n\n\n while((n = recv(sockfd, buffer, sizeof(buffer), 0)) > 0)\n {\n g_cbfunc(buffer, n);\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T02:31:50.240",
"Id": "14345",
"ParentId": "14340",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "14345",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T22:19:20.740",
"Id": "14340",
"Score": "3",
"Tags": [
"c",
"library",
"socket",
"callback"
],
"Title": "Basic socket library in C"
}
|
14340
|
<p>I wrote this recently for one of my projects. Are there any error you can spot or a feature which could be implemented without eating up resources or some optimisations? Also, this isn't meant for multi-cores.</p>
<pre><code>/*******************************************************************************
* @file mutex.c
* @date 31st August 2012
* @brief Generic implementation of mutex, read /notes/thread-safety
******************************************************************************/
#include <mutex.h>
OS_ERR mutex_acquire_try(mutex_t *mutex)
{
if(unlikely(cpu_atomic_cmpxchg(&mutex->lock, OS_UNLOCKED, OS_LOCKED) != OS_OKAY))
{
if(mutex->owner == current_thread)
goto recursive;
return OS_EBUSY;
}
mutex->owner = current_thread;
recursive:
mutex->recnt++;
return OS_OKAY;
}
static inline OS_ERR mutex_acquire_helper(mutex_t *mutex, time_t timeout)
{
while(unlikely(cpu_atomic_cmpxchg(&mutex->lock, OS_UNLOCKED, OS_LOCKED) != OS_OKAY))
{
if(mutex->owner == current_thread)
goto recursive;
if(mutex->lock == OS_DEAD)
return OS_EINVAL;
if(current_thread->priority >= mutex->owner->priority)
thread_boost(mutex->owner);
if(thread_queue_block(&mutex->queue, timeout) != OS_OKAY)
return OS_ETIMEOUT;
}
mutex->owner = current_thread;
recursive:
mutex->recnt++;
return OS_OKAY;
}
OS_ERR mutex_acquire_timeout(mutex_t *mutex, time_t timeout)
{
return mutex_acquire_helper(mutex, timeout);
}
OS_ERR mutex_acquire(mutex_t *mutex)
{
return mutex_acquire_helper(mutex, OS_TIME_INFINITE);
}
OS_ERR mutex_release(mutex_t *mutex)
{
if(mutex->owner != current_thread)
return OS_EINVAL;
if(--mutex->recnt)
goto exit;
thread_deboost(mutex->owner);
mutex->owner = NULL;
cpu_atomic_set(&mutex->lock, OS_UNLOCKED);
thread_queue_wake_one_now(&mutex->queue);
exit:
return OS_OKAY;
}
void mutex_init(mutex_t *mutex)
{
mutex->recnt = 0;
mutex->owner = NULL;
thread_queue_init(&mutex->queue);
cpu_atomic_set(&mutex->lock, OS_UNLOCKED);
}
void mutex_deinit(mutex_t *mutex)
{
if(mutex->owner == current_thread)
{
if(mutex->recnt > 1)
LOGE("Mutex: Deinit called on recursive lock @ %p\n", mutex);
mutex_release(mutex);
}
do {
while(thread_queue_count(&mutex->queue))
thread_yield();
} while(cpu_atomic_cmpxchg(&mutex->lock, OS_DEAD, OS_UNLOCKED) != OS_OKAY);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T10:08:21.460",
"Id": "23520",
"Score": "0",
"body": "How are `TRUE` and `FALSE` defined? Unless they have weird definitions (and I’d question that), their use in the above code is totally redundant. You can simply write `return mutex->owner == NULL;` etc. No need for the conditional."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T15:16:52.203",
"Id": "23530",
"Score": "0",
"body": "thanks, will do that, TRUE and FALSE are defined as 1 and 0 respectively in kernel.h"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-08T06:53:49.290",
"Id": "25029",
"Score": "0",
"body": "If it's uniprocessor you can just disable interrupts."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-09T06:16:02.430",
"Id": "25042",
"Score": "0",
"body": "Isn't that a spinlock implementation for UP ?"
}
] |
[
{
"body": "<p>Does this really work? You call <code>cpu_atomic_cmpxchg</code> without taking any notice of its return value. I guess the function must return true or false (1 or 0 etc) according to whether the lock was already taken or not and it seems likely that you should take notice of that. </p>\n\n<p>Also, if it were my code I'd drop all the unlikely() and likely() calls. For my money, they just obscure the code and I doubt they are necessary.</p>\n\n<p>I haven't read the functions in detail, so maybe I misunderstood the code...</p>\n\n<p>EDIT: Read it again and have some comments:</p>\n\n<ul>\n<li><p>Your point 10: \"Mutex MUST not be freed without calling mutex_deinit.\" is\nstrange. Isn't there a difference between freeing the mutex (lock/free is\nwhat you normally do, no?) and de-initialising it (which you would do when\nit is no longer needed, if at all)?</p></li>\n<li><p>'<strong>restrict</strong>' used in functions with a single parameter has no purpose</p></li>\n<li><p>Reviewers and readers would be more likely to understand what is going on if\nyour functions had some commets as to their intended purpose/use/return\nvalues etc.</p></li>\n<li><p>How do the 'atomic' functions wait for mutex availability?</p></li>\n<li><p>Shouldn't <code>mutex_init</code> fail on an already-initialised mutex?</p></li>\n<li><p>How do you know when it is safe to deinit a mutex?</p></li>\n<li><p>Your mutex flags are confusing. You have DEAD, BUSY, LOCKED, SUCCESS,\nREADY. Seems likely to me that there is some redundancy here. Or\nconflating state flags and return values.</p></li>\n<li><p>What is the point in all those MUTX flags if you assume the value of one of\nthem (in <code>if(unlikely(ret))</code>) - assuming the atomic function returns one.</p></li>\n<li><p>What is the difference between BUSY and LOCKED?</p></li>\n<li><p><code>mutex_acquire_timeout</code> doesn't tell the caller whether a timeout occurred!\n(or whether enquing falied!)</p></li>\n<li><p>So if the mutex has an owner already in <code>mutex_acquire_timeout</code>, you put the\nthread onto a queue, with a timeout. Presumably <code>thread_queue_enqueue</code>\nreturns either when awoken by <code>thread_queue_wake_highest_priority</code> in\n<code>mutex_release</code>, or when there is a timeout. But you carry on and\nreplace the mutex owner whatever the case...</p></li>\n<li><p>Your point 4 says a mutex can only be released by its owner, and yet\n<code>mutex_release</code> goes ahead and plays with the mutex queue whoever calls it.\nAlso sets state (ie releasing the local lock) before playing with the queue; surely there will be a race condition there.</p></li>\n</ul>\n\n<p>Sorry, but I don't believe this code 'works' in a meaningful way. Why are\nyou writing these primitives anyway? Why not use an existing kernel? It is\ngenerally a mistake to write your own (although I've worked at several that\nhave done, with bad consequences).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T13:32:09.707",
"Id": "23328",
"Score": "0",
"body": "1) My atomic function doesn't return till success, there are _try and _timeout modifiers if you can't wait.\n\n2) I am not using atomic for lock, it is for marking the mutex busy or ready.\n\n3) unlikely, likely, __restrict__ are just keywords to let compiler know more about your code and can also tell the person reading your code what you're expecting and atleast on ARM it can have performance impact by saving a branch which can stall the pipeline for few cycles. Apart from that, I've mentioned \"I've tested it on a Cortex-A8 (Uni Processor) cpu\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T08:36:08.517",
"Id": "23507",
"Score": "0",
"body": "I've edited the post, It's a work in progress so wait some time, this one is not the copy which worked.\n\n1) by freed it means freeing the memory where it's allocated, maybe you meant \"release\" which is legal without using deinit\n\n2) It is just for future purpose, I plan on expanding the code.\n\n3) You're more welcome to ask any question you have about code, commenting it was a big issue since i need to manually indent each line with 4 spaces to mark as code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T08:38:41.010",
"Id": "23508",
"Score": "0",
"body": "4) I don't understand you, atomic functions don't wait for mutex availability, it keeps retrying till it is able to spot \"MUTX_READY\" and then atomically swap it with \"MUTX_BUSY\" and from then on any other atomic function keeps looping till it finds 'MUTX_READY' again.\n\nYes, it should but if the lock is free it will have no effect so there's a check for owner if you read the code.\n\nkeep waiting till mutex is released and the queue is empty and hence there are no clients depending on this mutex and it can be freed.\n\nthere is no MUTX_LOCKED and MUTX_SUCESS are return codes if you look closely."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T08:42:25.000",
"Id": "23509",
"Score": "0",
"body": "MUTX_DEAD marks a deinit mutex so functions will not end in infinite loop if called on a deinit mutex (not yet uploaded the code). BUSY -> mutex data is being worked on, saving us a critical section and interrupt latency.\n\nagain, they are not flags, they're return codes.....\n\nLOCKED means the _try failed since it was already locked, BUSY means the mutex data is being exclusively worked on by some other function, so two mutex can be processed in multiple threads unlike when using a critical section.\n\nI just wrote timeout, wait for the next version\n\nSeriously ? read 2nd line in mutex_release..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T09:14:58.720",
"Id": "23511",
"Score": "0",
"body": "I am writing this for my own kernel (And I'm sure i could re-use this in future) which i'm going to submit as my thesis, well it's a long time since I'm not even in a college right now, Oh and please try to break things down in comments, It's pain typing multiple comments especially since these are void of text formatting."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T09:22:14.433",
"Id": "23512",
"Score": "0",
"body": "Also as for restrict, i think compiler should still benefit since it knows that any of the local pointers if any will also not be aliasing the pointer we have declared in prototype. Nonetheless if it isn't worth now, it isn't doing any bad either."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T09:25:59.423",
"Id": "23515",
"Score": "0",
"body": "**but I don't believe this code works in a meaningful way** You should have said that for the first version of the post alas the only thing you said then was something like you don't believe it works and you haven't read it yet.. **Why are you writing these primitives anyway? Why not use an existing kernel? It is generally a mistake to write your own (although I've worked at several that have done, with bad consequences)** This isn't a work project, It's serving as my testbed for trying out stuff and for educational purposes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T09:31:03.970",
"Id": "23516",
"Score": "0",
"body": "As for the queue timeout, thanks didn't think of that. Well I've removed _timeout till i can think of a better implementaion, thanks for your time and upvoting your response, hmm, it asks me to sign in while I'm already signed in for upvoting..."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T02:39:13.223",
"Id": "14395",
"ParentId": "14342",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T01:09:07.627",
"Id": "14342",
"Score": "3",
"Tags": [
"c",
"thread-safety",
"locking"
],
"Title": "Mutex implementation for a uniprocessor bare metal embedded OS"
}
|
14342
|
<p>I actually feel bad posting "yet another singleton"... I wrote the following one many years ago and had recently found another application for it. We had many threads, each running the same function that requires the use of a <code>boost::asio::io_service</code> instance. It was best that all threads shared the same <code>io_service</code> instance and also that that instance be destroyed before main returned. That last requirement (whose validity I now question, but, whatever..) meant no global or static object.</p>
<p>Here's a function that returns an instance of an object wrapped in a <code>shared_ptr</code>. What's special about it though is that we keep an additional reference count so the singleton is eagerly destructed when the last <code>shared_ptr</code> is gone.</p>
<p>For example, if you call the function twice, you have two <code>shared_ptr</code>s, each with a ref-count of 1, but our singleton's ref-count is 2. On the other hand, if you call the function only once and copy the returned <code>shared_ptr</code>, the <code>shared_ptr</code> has a ref-count of 2 but our singleton's ref-count is at one. Either way, the singleton instance gets destructed when the last <code>shared_ptr</code> is destructed.</p>
<p>One disadvantage of this code is that the class is instantiated from its default constructor.</p>
<pre><code>#include <memory>
#include <mutex>
// Deleter function given to the shared_ptr returned by get_shared_singleton.
template<typename T>
void release_shared(std::mutex& m, int& n, T*& p)
{
std::lock_guard<std::mutex> lg(m);
if(!--n)
{
delete p;
p = 0;
}
}
template<typename T>
std::shared_ptr<T> get_shared_singleton()
{
static std::mutex m;
std::lock_guard<std::mutex> lg(m);
static int n = 0; // Ref count.
static T* p = 0;
if(!p) p = new T();
++n;
return std::shared_ptr<T>(p, std::bind(release_shared<T>, std::ref(m), std::ref(n), std::ref(p)));
}
</code></pre>
<p>The requirements, more clearly stated:</p>
<ol>
<li>You wrote a function <code>foo()</code> that requires an instance of object X to perform its duty.</li>
<li><code>foo()</code> can be invoked concurrently from different threads.</li>
<li>Concurrent <code>foo()</code>s must share the same instance of object X.</li>
<li>If no <code>foo()</code> is running, there must be no instance of object X alive.</li>
<li><code>foo()</code> is in a library, you have no control of <code>main()</code> or the lifetime of threads that invoke <code>foo()</code>.</li>
</ol>
<p>What is the best code to provide a shared instance of an object that is both lazily-constructed and eagerly-destructed?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T11:31:00.333",
"Id": "23398",
"Score": "0",
"body": "Konrad mentioned that someone in the C++ chat had some other solution. That was me: https://gist.github.com/3284629. However that solution doesn't allow for reinitialization, which you seem to desire. To be honest, the way it is now, this looks like a nice question for StackOverflow instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T09:51:49.890",
"Id": "23518",
"Score": "0",
"body": "Why do you need item #4? It seems to me like this is both the most difficult requirement and a quite large WTF."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-13T17:28:38.813",
"Id": "23714",
"Score": "0",
"body": "Well... In effect, 4 follows from 5. If you can't \"manually\"\n destroy X, how else, other than a \"self-destructing\" X, could you achieve the effect?"
}
] |
[
{
"body": "<p>Well, the first objection to this code is that it’s not actually a singleton. It provides a centralised way of acquiring a a shared instance, true, but it doesn’t <em>ensure</em> that this is the only way an instance can be retrieved.</p>\n\n<p>On the contrary – the code requires that the class is publicly default constructible, i.e. not a singleton.</p>\n\n<p>Next, to address your actual use-case, the easiest <strong>and cleanest</strong> method is having a local object in the function that dispatches the threads, which is passed to the individual threads. Pseudo-code (since I never worked with Boost.Asio):</p>\n\n<pre><code>void f() {\n some_type the_shared_object;\n\n for (int i = 0; i < 5; ++i)\n boost::asio::thread_pool.spawn(some_thread_entry_point, the_shared_object);\n\n boost::asio::thread_pool.wait_all();\n}\n</code></pre>\n\n<p>Of course, this solution might need to be adapted but the general pattern remains valid.</p>\n\n<p>Coming back to your code, there are at least three things (apart from the name which, as I said, is wrong) which I’d improve:</p>\n\n<ul>\n<li><p>Use an <code>unsigned int</code> to count instances. <code>int</code> makes no sense.</p></li>\n<li><p>Use finer-grained locking (<a href=\"http://en.wikipedia.org/wiki/Double_checked_locking\" rel=\"nofollow\">double-checked locking</a>) for better performance. At the moment, your code uses a lot of redundant, costly locks.</p></li>\n<li><p>Worst of all, the code comes directly from the redundant ministry of redundancy: <code>shared_ptr</code> provides (thread-safe!) reference counting for you. Your code essentially provides functionality that <code>shared_ptr</code> already has. The following code does essentially the same:</p>\n\n<pre><code>template<typename T>\nstd::shared_ptr<T> get_shared_instance()\n{\n static std::shared_ptr<T> p(new T());\n return p;\n}\n</code></pre>\n\n<p>Notice that this code uses lazy, thread-safe initialisation. However, the resulting object may be destructed later than you might want. If you absolutely require this, you can <code>reset</code> the <code>shared_ptr</code> at the end of <code>main</code> – this can of course be done automatically by making the above a member function of a class which has <code>p</code> as a member variable and is instantiated locally in <code>main</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T17:58:54.447",
"Id": "23348",
"Score": "0",
"body": "Thanks for your input. But now I have to add one more detail. This code is part of a library. As such, I have no control over when the threads are created and I also have no control over main(). Does that change the perspective somewhat?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T17:59:33.870",
"Id": "23349",
"Score": "0",
"body": "Also, I don't understand how the simple solution you propose solves the problem I'm trying to avoid. The static shared_ptr<> will be destructed after main() returns. You can't reset() the static variable p. All you can reset() is a copy of it and the ref-count of p is always at least 1. If you can fix that by wrapping it in a class, would you be kind enough to write that sample code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T19:23:37.867",
"Id": "23354",
"Score": "0",
"body": "To address the first point: it might change it – that depends on whether the library abstracts this in a clean way. You don’t actually need control over thread creation – but you *do* need control over the joining of (waiting for) the threads. *If* you can wait for all threads to finish, you can probably use a local variable and somehow pass it to all the threads."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T19:25:34.807",
"Id": "23355",
"Score": "0",
"body": "About the second point, the code in my answer is the result of some iterating back and forth in my head and the result no longer perfectly approaches what you want. But you *can* call `reset` on a static object (however, to do this you need to expose it so you can no longer use a *local* static variable. Somebody in the C++ chat actually had a better (albeit a bit hacky) solution for this. Let’s hope he’ll still post it here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T01:28:09.430",
"Id": "23389",
"Score": "0",
"body": "Well, actually, I don't even have control over the threads' lifetime. My library provides a function foo(). That function can be invoked by 10 threads in parallel or just twice with 30 minutes in between. And I need is for all concurrent foo()s to share the same instance of object X and if no foo() is running then there must be no object X instance. (I think I'm going to edit my question to add this more generically stated requirements)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T01:33:53.227",
"Id": "23390",
"Score": "0",
"body": "Btw, I'll concede that this is probably better called \"get_shared_instance()\" rather than \"get_shared_singleton()\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T06:55:38.710",
"Id": "23394",
"Score": "0",
"body": "@screwnut Ah, well that requirement screws with my suggested method for sure."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T10:24:19.570",
"Id": "14401",
"ParentId": "14343",
"Score": "3"
}
},
{
"body": "<p>You can use a static <code>weak_ptr</code> in the function to <em>cache</em> the shared instance <em>without</em> extending its lifetime:</p>\n\n<pre><code>template<typename T>\nstd::shared_ptr<T> get_shared_instance()\n{\n static std::mutex m;\n static std::weak_ptr<T> cache;\n\n std::lock_guard<std::mutex> lg(m);\n\n std::shared_ptr<T> shared = cache.lock();\n if (cache.expired()) {\n shared.reset(new T);\n cache = shared;\n }\n return shared;\n}\n</code></pre>\n\n<p>So, the first caller will find a default-initialized weak_ptr counts as expired, and construct a new <code>T</code>.</p>\n\n<p>While the first caller is active (and keeping its new <code>T</code> alive), concurrent callers will get the same object, cached in the weak_ptr. When the last concurrent user is done, the object will be destroyed.</p>\n\n<p>A subsequent caller will find the <code>weak_ptr</code> expired (same as before the first call), and create a new <code>T</code> ... etc. etc.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T16:53:16.163",
"Id": "14455",
"ParentId": "14343",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "14455",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T01:15:52.290",
"Id": "14343",
"Score": "7",
"Tags": [
"c++",
"singleton"
],
"Title": "C++ shared_singleton"
}
|
14343
|
<p>My inclination is to make these methods static:</p>
<pre><code>package net.bounceme.dur.usenet.driver;
import java.util.List;
import java.util.logging.Logger;
import javax.mail.Folder;
import javax.mail.Message;
import javax.persistence.*;
import net.bounceme.dur.usenet.model.Article;
import net.bounceme.dur.usenet.model.Newsgroup;
class DatabaseUtils {
private static final Logger LOG = Logger.getLogger(DatabaseUtils.class.getName());
private EntityManagerFactory emf = Persistence.createEntityManagerFactory("USENETPU");
private EntityManager em = emf.createEntityManager();
public int getMax(Folder folder) {
int max = 0;
String ng = folder.getFullName();
String queryString = "select max(article.messageNumber) from Article article left join article.newsgroup newsgroup where newsgroup.newsgroup = '" + ng + "'";
try {
max = (Integer) em.createQuery(queryString).getSingleResult();
} catch (Exception e) {
LOG.info("setting max to zero");
}
LOG.severe(folder.getFullName() + "\t" + max);
return max;
}
public void persistArticle(Message message, Folder folder) {
em.getTransaction().begin();
String fullNewsgroupName = folder.getFullName();
Newsgroup newsgroup = null;
int max = getMax(folder);
TypedQuery<Newsgroup> query = em.createQuery("SELECT n FROM Newsgroup n WHERE n.newsgroup = :newsGroupParam", Newsgroup.class);
query.setParameter("newsGroupParam", fullNewsgroupName);
try {
newsgroup = query.getSingleResult();
LOG.fine("found " + query.getSingleResult());
} catch (javax.persistence.NoResultException e) {
LOG.fine(e + "\ncould not find " + fullNewsgroupName);
newsgroup = new Newsgroup(folder);
em.persist(newsgroup);
} catch (NonUniqueResultException e) {
LOG.warning("\nshould never happen\t" + fullNewsgroupName);
}
Article article = new Article(message, newsgroup);
em.persist(article);
em.getTransaction().commit();
}
public void close() {
em.close();
emf.close();//necessary?
}
}
</code></pre>
<p>However, I'm quite sure that I'm in the minority! Why?</p>
<p>A quick look at <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html" rel="nofollow">Math</a> shows that this isn't a strange or odd approach. The object itself keeps no state, really, so why would a bean or POJO be <strong>preferred</strong> to static methods?</p>
|
[] |
[
{
"body": "<p>Actually the object contains an entity manager which has state. In a simple application having only one shared entity manager might work but if you made this into an EJB in a Java-EE application you would definitely want each request to use it's own entity manager.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T23:41:03.820",
"Id": "23237",
"Score": "0",
"body": "Ok, I grudgingly take your point vis a vis the entity manager, but I was more asking in the general."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T10:18:49.440",
"Id": "23248",
"Score": "0",
"body": "@Thufir: Sometimes you just can't answer the OP's specific question but you have some useful comment on another part of the code (like Eelke's comment here, I guess). It's fine, ontopic and encouraged on this site (according to the FAQ)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T13:22:04.757",
"Id": "14354",
"ParentId": "14347",
"Score": "4"
}
},
{
"body": "<p>Static helper classes makes testing harder. Nick Malik has a good article on this topic: <a href=\"http://blogs.msdn.com/b/nickmalik/archive/2005/09/07/462054.aspx\">Killing the Helper class, part two</a>. </p>\n\n<p>Mocking non-static methods is closer to OOP and easier than static ones. Another gain is that you'll have simple tests: simple tests for the utility/helper class and simple tests for the clients of the utility class; the tests of the client classes don't have to know the internals of the utility class, and you don't need a DatabaseUtilsTestHelper class to keep in one place the mocking logic for the helper class. The linked article is worth the reading.</p>\n\n<p>Some other notes: </p>\n\n<ul>\n<li>Try not using short variable names like <code>ng</code>. They are hard to read.</li>\n<li><p><code>persistArticle</code> does not close the transaction in every path. You should rollback it in the <code>finally</code> block if it's still active:</p>\n\n<pre><code>final EntityTransaction transaction = em.getTransaction();\ntransaction.begin();\ntry {\n ... \n transaction.commit();\n} finally {\n if (transaction.isActive()) {\n transaction.rollback();\n }\n}\n</code></pre></li>\n<li><p><code>persistArticle</code> does not use the value of <code>max</code>, therefore the <code>getMax</code> call seems unnecessary.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T23:34:29.740",
"Id": "23235",
"Score": "0",
"body": "Please expand on \"Mocking non-static methods is closer to OOP and easier than static ones. \" --**why**?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T10:10:21.900",
"Id": "23247",
"Score": "0",
"body": "@Thufir: Because you don't need any trick (such as proxies, byte-code manipulation) to change the behavior of a static method for only a testcase. You can do it with pure polymorphism (which is a core OOP feature)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T20:51:54.997",
"Id": "14361",
"ParentId": "14347",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "14354",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T10:08:43.407",
"Id": "14347",
"Score": "3",
"Tags": [
"java",
"object-oriented",
"static"
],
"Title": "What's wrong with static utility classes, versus beans?"
}
|
14347
|
<p>As part of a question designed to help us understand the relationship between pointers and arrays in C, I've been asked to write an inner product function that doesn't use any array subscripting. Here's what I came up with, but it looks like the kind of complicated 'clever' coding that we've traditionally been told NOT to write.
Any feedback on it, or how it could be done better / more efficiently would be much appreciated.</p>
<pre><code>int inner_product(const int *a, const int *b, int n) {
const int *p, *q;
int result = 0;
for(p = a, q = b; p < a + n, q < b + n; p++, q++) {
result += *p * *q;
}
return result;
}
</code></pre>
<p>Edit - Inner product is simply summing the product of the indexes, so a[1,2,3] b[2,3,4] would be 1*2 + 2*3 + 3*4</p>
|
[] |
[
{
"body": "<p>Just a point, that code will error on compilation: p++ and q++ are not permitted operations if you have a const int.</p>\n\n<p>Now, to write it more cleanly (I know next to nothing about inner products, and google hasn't been much help):</p>\n\n<pre><code>int inner_product(const int *a, const int *b, int n)\n{\n int *p = a, *q = b;\n int result = 0;\n while( (p < a + n ) && (q < b + n ) ) /*|| might be required here, but a comma probably (never come across it) won't work*/\n {\n result += *p * *q;\n p++; q++;\n }\n return result;\n}\n</code></pre>\n\n<p>The if loop you used was messy, hard to read, and too 'clever'. This way, it is clear what your code is doing. To be even more easy to read, I'd surround my calls to the pointers <code>*p</code> in parenthesis: <code>(*p)</code>, but that's a matter of personal taste.</p>\n\n<p>Edit: Since the definition of inner product has now been defined for me, I can safely say that your algorithm is the most clean I could have come up with, and is the fastest by far (linear time).</p>\n\n<p>EDIT: Where I say <code>int *p = a, *q = b;</code>, it would be more proper to say <code>const int *p = a, *q = b;</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T15:23:47.443",
"Id": "23224",
"Score": "2",
"body": "Thanks for that, that code works and does the same job. It does however throw warnings about discarding the const qualifier for the line int *p =a, *q =b. That was the reason I put const in front of them in the first place, is this a warning one should ignore?\nAlso, my version does compile - from what I understand const int *p protects the value it points to but not p itself, hence the ++ compiling & working. I could be missing something here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T21:27:18.107",
"Id": "23232",
"Score": "0",
"body": "I wrote the program up with a sample main(), and learned that should I remove the `const` declarations from the function header, the warnings went away. To test the `const` not affecting pointer arithmetic, I googled, and found Stack Exchange questions where you are correct. You may continue to use the `const int` as you were before, it was not necessary for me to remove them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T21:33:13.093",
"Id": "23233",
"Score": "0",
"body": "Oh, as for the warnings, I'd just ignore them in my own code. That particular warning was a pointer-mismatch, and I could see there was none of any significance present."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T04:43:13.123",
"Id": "23242",
"Score": "1",
"body": "@T.C. Sorry, but -1. \"Where I say ... it would be more proper to say ...\" It's not more proper that way; it's *correct* that way. In addition, your opening line about incrementing the pointers is wrong, and there's no reason to make copies of `a` and `b`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T17:27:45.200",
"Id": "23268",
"Score": "0",
"body": "One more question on your edit though, \"proper to say const int *p = a, *q = b\", would I be right in thinking that the second declaration, *q = b will not be treated as having the const qualifier?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T00:08:01.313",
"Id": "23285",
"Score": "0",
"body": "@Saf The q would indeed have the const qualifier. It's basically like the `const int` is treated as \"type.\" For example: `const int a, *b, * const c;` is equivalent to: `const int a; const int *b; const int * const c;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T01:35:36.213",
"Id": "23287",
"Score": "0",
"body": "Corbin, I noted my gaps in knowledge in my Edits. +1 for the feedback, though.\n\nProper: Not necessary, but correct.\n\n@Saf, the comma operator in assignment simply creates another variable of the same type already specified. The reason the asterisk for a pointer is required is due to the fact that a pointer is not a type, simply a modifier for the variable itself (saying it points to an int, instead of is one, for example). `const char* c, *b;` does the same thing as: `const char *c; const char *b;`\n\nHope that helps, and thanks again for the feedback @Corbin."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T14:52:07.823",
"Id": "14355",
"ParentId": "14348",
"Score": "1"
}
},
{
"body": "<p>I have a few comments on style. (By which I really mean, 100% opinion... :D)</p>\n\n<hr>\n\n<p><strong>One declaration per line</strong></p>\n\n<p>A lot of people strongly disagree with this, but I find it much easier to read code that has one declaration per line.</p>\n\n<pre><code>const int *p;\nconst int *q;\n</code></pre>\n\n<p>Is a lot clearer to me than:</p>\n\n<pre><code>const int *p, *q;\n</code></pre>\n\n<p>Though really, the only time I've vehemently opposed to it is if both variables are not the same in terms of a pointer or value:</p>\n\n<pre><code>const int *p, q;\n</code></pre>\n\n<p>Is a harder to read and more prone to errors than:</p>\n\n<pre><code>const int *p;\nconst int q;\n</code></pre>\n\n<hr>\n\n<p><strong>n</strong></p>\n\n<p>I would name the <code>n</code> paramter something more meaningful. I would consider calling it <code>size</code> or <code>num</code>.</p>\n\n<p>It's fairly apparent that <code>n</code> is meant to be the number of elements, but two or three extra keystrokes seems worth the extra clarity.</p>\n\n<hr>\n\n<p><strong>Possible implementation</strong></p>\n\n<p>I would probably write the function something like this:</p>\n\n<pre><code>int inner_product(const int *a, const int *b, int num)\n{\n\n const int* end = a + num;\n\n int sum = 0;\n\n while (a != end) {\n sum += (*a) * (*b);\n ++a;\n ++b;\n }\n\n return sum;\n\n}\n</code></pre>\n\n<p>Since the two pointers are incremented at the same time, there's no reason to check both.</p>\n\n<p>This should be a tiny bit more efficient (well... probably not once the compiler does it's magic optimisations on the original), and I think it's a bit clearer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T17:23:11.960",
"Id": "23265",
"Score": "0",
"body": "Thanks for that. I've tested all of the suggestions here, will add a comment at the end of the original question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T21:40:01.313",
"Id": "23365",
"Score": "0",
"body": "Making this the answer as it runs a bit faster than the other three. Is it because it only has one comparison in the while loop possibly?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T03:09:57.743",
"Id": "14363",
"ParentId": "14348",
"Score": "4"
}
},
{
"body": "<p>I agree with all the points from Corbin but i personally would use a simple <code>for loop</code> instead as this is one of the more common ways to iterate through arrays:</p>\n\n<pre><code>int inner_product(const int *a, const int *b, int size) {\n\n int sum = 0;\n int i = 0;\n\n for (i=0; i<size; ++i) {\n sum += *(a+i) * *(b+i);\n }\n\n return sum;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T04:21:01.517",
"Id": "14365",
"ParentId": "14348",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "14363",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T11:48:07.933",
"Id": "14348",
"Score": "3",
"Tags": [
"c",
"homework"
],
"Title": "C inner product function without using array subscripting"
}
|
14348
|
<p>I needed to find away to left shift a number on a platform with buggy <code><<</code> and <code>>></code> bitwise operators. I came up with a rudimentary solution, but it looks ugly and inefficient. What's a better way to do this?</p>
<pre><code>float leftShift8(int value) {
return value * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2;
}
float rightShift8(int value) {
return value / 2 / 2 / 2 / 2 / 2 / 2 / 2 / 2;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T14:05:38.650",
"Id": "23220",
"Score": "2",
"body": "buggy shift operators? Are you sure? That sounds very suspect."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T14:13:56.410",
"Id": "23222",
"Score": "0",
"body": "just joking. the actual matter is more complicated so I used that as a justification."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-01T20:57:19.717",
"Id": "181062",
"Score": "0",
"body": "And on platforms with different endianness, how does this work out (versus your supposed claim of a \"buggy\" operator)? You're better off figuring out the actual bug with the shift operators..."
}
] |
[
{
"body": "<p>If I understand well, you are using a computer that have \"broken\" bit-wise operators? That is odd but maybe you can try this?</p>\n\n<pre><code>float leftShift8(int value)\n{\n return pow(2, 8) * value;\n}\n</code></pre>\n\n<p>This code simply do a power of 8 on the base that is 2. After that, you multiply by your value. It does the same thing as your code but I'm not sure why anyone would use this instead of bit-wise since bit-wise a much more faster I think. </p>\n\n<p>You could make this more general and useful like this</p>\n\n<pre><code>float leftShift(int value, int numberOfShift)\n{\n return pow(2, numberOfShift) * value;\n}\n</code></pre>\n\n<p><strong>EDIT: For the edited question about division, the is only a slight change. Thanks to T.C for this (answer below), I include it in my answer to make it more complete</strong></p>\n\n<pre><code>float rightShift(int value, int numberOfShift) \n{ \n return value/pow(2, numberOfShift); \n} \n</code></pre>\n\n<p>Anyway, I hope it will help.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T14:19:39.960",
"Id": "23223",
"Score": "0",
"body": "Great Jaff, thanks a ton, but can you solve the divide problem as well? Updated question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T13:14:51.053",
"Id": "14350",
"ParentId": "14349",
"Score": "7"
}
},
{
"body": "<p>Well, going on Jean-François's answer above, to solve the division:</p>\n\n<pre><code>float rightShift(int value, int numberOfShift)\n{\n return value/pow(2, numberOfShift);\n}\n</code></pre>\n\n<p>Again, there you go.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T14:59:40.077",
"Id": "14356",
"ParentId": "14349",
"Score": "3"
}
},
{
"body": "<p>Why wouldn't you do something like</p>\n\n<pre><code>float rightShift(int value, int numberOfShift)\n{\n float result = (float)value;\n while(numberOfShift-- > 0)\n value*=2.0f;\n return value;\n}\n\nfloat leftShift(int value, int numberOfShift)\n{\n float result = (float)value;\n while(numberOfShift-- > 0)\n value/=2.0f;\n return value;\n}\n</code></pre>\n\n<p>This would especially deal with the fact that you do not return int type, but float. Additionally, its a lot faster to do a 2*2*2 than pow(2,3)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T17:49:19.247",
"Id": "23270",
"Score": "1",
"body": "Multiplying is not faster in C++, the difference in only noticable in C. See this thread: http://stackoverflow.com/questions/2940367/what-is-more-efficient-using-pow-to-square-or-just-multiply-it-with-itself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T18:10:13.883",
"Id": "23272",
"Score": "1",
"body": "In c++ it doesn't make a noticeable difference. And Jean-François' code is much simpler easier to the programmer to read"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T14:43:45.690",
"Id": "14377",
"ParentId": "14349",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "14377",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T12:02:37.260",
"Id": "14349",
"Score": "-4",
"Tags": [
"c++",
"bitwise"
],
"Title": "Multiplying many times"
}
|
14349
|
<p>The page is assigning <code>$gid</code> to the url paramater gid. It then reads an XML file that looks like this:</p>
<pre><code><games>
<game>
<name>name 1</name>
<appID>1234</appID>
</game>
<game>
<name>name 2</name>
<appID>5678</appID>
</game>
</games>
</code></pre>
<p>The code I am using works correctly but takes a second to load because there are so many <code><game></code> elements on the list. Is there are more efficient way to go about foreach? Here is the code:</p>
<pre><code>$gid = (int) $_GET['gid'];
$gamespage = simplexml_load_file("http://gamepage.com/games?xml=1");
$games = $gamespage->games;
foreach ($games->game as $game) {
if ($gid == $game->appID) {
$appid = $game->appID;
$gamename = $game->name;
}
}
echo $gid, "<br />";
echo $appid, "<br />";
echo $gamename;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T01:58:05.403",
"Id": "23216",
"Score": "3",
"body": "I would suggest you try to get [this solution](http://stackoverflow.com/a/11813250/142162) working instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T01:59:17.783",
"Id": "23217",
"Score": "4",
"body": "It's probably not slow because of the `foreach` loop, but because you're fetching all of the data from a remote server every single time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T02:18:15.387",
"Id": "23218",
"Score": "0",
"body": "Profile your script. See how long it takes to fetch the data, and how long it takes to loop through the data. If you see the fetching is taking the bulk of the time, cache the data for x minutes rather than fetching on every request."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T13:08:05.430",
"Id": "23249",
"Score": "0",
"body": "I agree with icktoofay and Tim Cooper. XPATH and downloading a \"cached\" version would speed this up drastically. Or, if you don't want to use XPATH for some reason, then you can do as guillermoandrae stated and add a break in your if statement. Though I would suggest the first two solutions rather than the third. Otherwise this is as efficient as it gets."
}
] |
[
{
"body": "<p>Probably the only thing you can do to make it faster is to limit the number of results returned at one time. Could you maybe use pagination or something? Is there a reason you need to get all of them at once? Even if it was coming from a database, if there were enough records, it would take a couple seconds to get ALL of them. I'd do, for example, 50 per page.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T01:59:14.730",
"Id": "14352",
"ParentId": "14351",
"Score": "0"
}
},
{
"body": "<p>Add a <code>break</code> to that <code>if</code> statement to stop looping once you've found the correct node.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T02:21:18.997",
"Id": "14353",
"ParentId": "14351",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T01:56:00.623",
"Id": "14351",
"Score": "0",
"Tags": [
"php"
],
"Title": "Is there more efficient way of processing my XML file in PHP?"
}
|
14351
|
<p>I have the following code:</p>
<pre><code>from Bio import AlignIO
import itertools
out=open("test.csv","a")
align = AlignIO.read("HPV16_CG.aln.fas", "fasta")
n=0
def SNP(line):
result=[]
result.append(str(n+1))
result.append(line[0])
result.append(align[y].id.rsplit("|")[3])
result.append(x)
return result
while n<len(align[0]):
line = align[:,n]
y=0
for x in line:
if line[0]!=x:
print >> out, ','.join(map(str,SNP(line)))
y=y+1
else:
y=y+1
y=0
n=n+1
out.close()
f=open("test.csv","rU")
out=open("test_2.csv","a")
lines=f.read().split()
for key, group in itertools.groupby(lines, lambda line: line.partition(',')[0]):
print >>out, ','.join(group)
out.close()
f.close()
</code></pre>
<p>As you can see, I am currently writing two files. I really only need the second file.
Does anyone have any suggestions to combine both "subscripts" into one? </p>
<p>The input file "HPV16_CG.aln.fas" looks like this:</p>
<pre><code>>gi|333031|lcl|HPV16REF.1| Alpha-9 - Human Papillomavirus 16, complete genome.
ACTACAATAATTCATGTATAAAACTAAGGGCGTAACCGAAATCGGTTGAACCGAAACCGG
>gi|333031|gb|K02718.1|PPH16 Human papillomavirus type 16 (HPV16), complete genome
ACTACAATAATTCATGTATAAAACTAAGGGCGTAACCGAAATCGGTTGAACCGAAACCGG
>gi|196170262|gb|FJ006723.1| Human papillomavirus type 16, complete genome
ACTACAATAATTCATGTATAAAACTAAGGGCGTAACCGAAATCGGTTGAACCGAAACCGG
</code></pre>
<p>I really appreciate all the help/suggestions to help me improve this!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T22:02:21.873",
"Id": "30872",
"Score": "1",
"body": "If you do not read PEP8 in its entirety, you can still run `pep8 myfile.py` and `pylint myfile.py` and `pyflakes myfile.py` (and there may be others) in order to have cleaner code."
}
] |
[
{
"body": "<p>First of all, read <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a> (all of it!) and adhere to it. This is the de facto standard of Python code.</p>\n\n<p>In the following, I’ll tacitly assume PEP8 as given.</p>\n\n<p>Secondly, it would help if you had actually written what the expected output looks like. Given your input file, the script produces <strong>empty output</strong>.</p>\n\n<p>I don’t understand what the <code>while</code> loop is supposed to do. <code>align</code> represents a single <strong>alignment record</strong> – you are reading a <em>sequence</em> file which contains <em>multiple sequences</em>. Furthermore, what is <code>align[:, n]</code>? Did you maybe intend to access the <code>seq</code> sub-object?</p>\n\n<p>Likewise, the <code>SNP</code> method doesn’t <em>at all</em> make clear what its function is. And it implicitly uses global variables. This is error-prone and unreadable: use parameters instead. The function also accesses some object <code>align[y]</code> which won’t exist when <code>y > 0</code>, because <code>AlignIO.read</code> only reads a <em>single</em> alignment.</p>\n\n<p>Furthermore, if you’re handling CSV files, I’d strongly suggest using the <a href=\"http://docs.python.org/library/csv.html\" rel=\"nofollow\"><code>csv</code> module</a>. It’s not really less code in your particular case but it provides a more uniform handling and makes the code easily extensible.</p>\n\n<p>Just to show what this could look like when done cleaner, here’s the production of the <strong>first file</strong>. I’d love to show the full code but I really don’t understand what the code is supposed to do since it doesn’t work for me, and I’m unfamiliar with the function of <code>align[:,n]</code> (and I think there’s an error in the access to <code>align</code>, anyway.</p>\n\n<pre><code>#!/usr/bin/env python\n\nimport csv\nimport itertools\nimport sys\nfrom Bio import AlignIO\n\n\ndef snp(line, alignment, n, base, pos):\n \"\"\"Documentation missing!\"\"\"\n id = alignment[pos].id.rsplit('|')[3] # why rsplit?\n return [ str(n + 1), line[0], id, base ]\n\n\ndef main():\n # TODO Use command line argumnents to provide file names\n\n alignment = Bio.AlignIO.read('HPV16_CG.aln.fas', 'fasta')\n\n with csv.writer('test.csv') as out:\n for n in range(len(alignment[0])):\n line = align[ : , n]\n for pos, base in line:\n if line[0] != x:\n out.writerow(snp(line, alignment, n, base, pos))\n\n\nif __name__ == '__main__':\n sys.exit(main())\n</code></pre>\n\n<p>In this code I tried to give the variables meaningful names but – again, since I don’t know what this is supposed to do – I had to guess quite a lot based on usage.</p>\n\n<p>And by the way, <code>range(len(x))</code> is actually kind of an anti-pattern but I can’t for the heck of it remember the “correct” usage (and even the documentation advises this).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T19:20:45.477",
"Id": "14360",
"ParentId": "14357",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T16:09:17.473",
"Id": "14357",
"Score": "5",
"Tags": [
"python"
],
"Title": "Using Biopython, I would like to optimize this code"
}
|
14357
|
<p>I have a hard time adapting to jQuery and chaining. I think it's really neat at times, but how do I know when to use it and when to indent? I may suffer from some kind of OCD-ish behaviour, and this is not your concern, but I would like your input on what needs refactoring in this ol' bit of code:</p>
<pre><code>$(function() {
$('div.mainMenu > ul > li > a')
.each(
function () {
var $this = $(this);
var $sub = $this.next('ul');
var n = $sub.children().length;
$sub.hide();
if (n > 1) {
$this.append('<img src="img/expand.png">');
} else if (n == 1) {
$this.attr('href', $sub.find('a').first().attr('href'));
}
}
)
.click(
function (event) {
var $this = $(this);
var $sub = $this.next('ul');
var n = $sub.children().length;
if (n > 1) {
event.preventDefault();
var $img = $this.find('img');
if ($sub.is(':visible')) {
$img.attr('src', 'img/expand.png');
} else {
$img.attr('src', 'img/collapse.png');
}
$sub.slideToggle(n * 100);
}
}
)
.parent()
.find('li > ul')
.prev('a')
.append('<img src="img/submenu.png">');
});
</code></pre>
<p>I'm essentially modifying a menu and everything works, but there are some inconsistencies. Sometimes I use the "newline and indent" approach and other times it's the good ol' Java chaining that I'm used to. Is this good jQuery code, or how would you rewrite it?</p>
<p>Also, is there a way to incorporate chaining instead of my very simple conditionals (<code>if (n > 1)...</code>)? If there are any other bad smells in this code, please let me know. I feel so insecure when diving into something new.</p>
|
[] |
[
{
"body": "<p>Your code looks pretty decent IMHO. Here is how I prefer to do it:</p>\n\n<pre><code>(function($) { // Note that $ is now a parameter of the function and jQuery is added at the end - this is known as a \"wrapping method\" and avoids any potential conflicts with other libraries that may use the dollar sign\n \"use strict\"; // Put the browser's parser into strict mode if supported. Warning: may make you a better programmer\n\n $('div.mainMenu > ul > li > a').each(function() {\n var $this = $(this),\n $sub = $this.next('ul'),\n n = $sub.children().length; // All variables are grouped together in one var statement\n\n $sub.hide();\n\n if (n > 1) {\n $this.append('<img src=\"img/expand.png\">');\n } else if (n == 1) {\n $this.attr('href', $sub.find('a').first().attr('href'));\n }\n }).on(\"click\", function(event) { // \"click\" here has been changed to on(\"click\", ....) to match the new unified syntax in 1.7+\n var $this = $(this),\n $sub = $this.next('ul'),\n n = $sub.children().length;\n\n if (n > 1) {\n event.preventDefault();\n\n var $img = $this.find('img');\n\n if ($sub.is(':visible')) {\n $img.attr('src', 'img/expand.png');\n } else {\n $img.attr('src', 'img/collapse.png');\n }\n\n $sub.slideToggle(n * 100);\n }\n }).parent().find('li > ul').prev('a').append('<img src=\"img/submenu.png\" />');\n})(jQuery); // Pass jQuery to the wrapping function as a parameter\n</code></pre>\n\n<p>Note: the code in your two functions is similar, so consider moving it to a separate function to keep it DRY. Additionally, checking your code with jsLint/jQueryLint will help you track down code issues (although it might make you cry).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T17:38:49.160",
"Id": "14359",
"ParentId": "14358",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T16:25:13.920",
"Id": "14358",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Modifying a menu"
}
|
14358
|
<p>I've done some programming in the past, but I'm new to MIPS, which I'm trying to learn on my own. This program lists the first five perfect numbers. It uses the Lucas-Lehmer and Miller-Rabin primality tests. Any suggestions on how I could improve will be most appreciated.</p>
<pre><code> .data # marks the following as data
seed:
.word 127 # seed for random number sequence
newline:
.asciiz "\n" # newline character
tabchar:
.asciiz "\t" # tab character
header:
.asciiz "n\tp\tm\tpn\n"
.text # required - beginning of executable code
###############################################################################
# displays the first five perfect numbers
#
# register usage:
# $s0 n perfect number counter $s4 unused
# $s1 current prime $s5 unused
# $s2 mersenne number $s6 unused
# $s3 unused $s7 unused
#
# $t0 scratch $t5 unused
# $t1 scratch $t6 unused
# $t2 scratch $t7 unused
# $t3 unused $t8 unused
# $t4 unused $t9 unused
#
main: # required - address of first instruction
addiu $sp,$sp,-36 # make room for ra & s registers
sw $ra,0($sp) # preserve return address
sw $s0,4($sp)
sw $s1,8($sp)
sw $s2,12($sp)
sw $s3,16($sp)
sw $s4,20($sp)
sw $s5,24($sp)
sw $s6,28($sp)
sw $s7,32($sp)
la $a0,header # load address of string to print
li $v0,4 # os service "print_string"
syscall # call the os
li $s0,5 # get this many perfect numbers
move $s1,$zero # want first prime
main_loop:
move $a0,$s1 # get last prime
jal next_prime # get another prime
nop
move $s1,$v0 # preserve prime number (p)
move $a0,$s1 # for lucas_lehmer primality test
jal lucas_lehmer # test p
nop
beqz $v0,main_loop # iterate if mersenne number is not prime
move $s2,$v0 # save m
addi $t0,$s0,-5 # gives [-4,0]
neg $t0,$t0 # gives [0,4]
addiu $a0,$t0,1 # gives [1,5]
li $v0,1 # os service "print_int"
syscall # call the os
la $a0,tabchar # load address of string to print
li $v0,4 # os service "print_string"
syscall # call the os
move $a0,$s1 # p
li $v0,1 # os service "print_int"
syscall # call the os
la $a0,tabchar # load address of string to print
li $v0,4 # os service "print_string"
syscall # call the os
move $a0,$s2 # mersenne prime
li $v0,1 # os service "print_int"
syscall # call the os
la $a0,tabchar # load address of string to print
li $v0,4 # os service "print_string"
syscall # call the os
addiu $t0,$s1,-1 # p - 1
li $t1,1 # 2^0
sllv $t1,$t1,$t0 # 2^(p-1)
mult $t1,$s2 # 2^(p-1) * 2^p - 1
mflo $a0 # perfect number for printing
li $v0,1 # os service "print_int"
syscall # call the os
la $a0,newline # load address of string to print
li $v0,4 # os service "print_string"
syscall # call the os
addi $s0,$s0,-1 # decrement counter
bgtz $s0,main_loop # iterate, if there are not enough output
move $v0,$s0 # return code
lw $ra,0($sp)
lw $s0,4($sp)
lw $s1,8($sp)
lw $s2,12($sp)
lw $s3,16($sp)
lw $s4,20($sp)
lw $s5,24($sp)
lw $s6,28($sp)
lw $s7,32($sp)
addiu $sp,$sp,36 # return stack space
jr $ra
nop
###############################################################################
# Returns the first prime after $a0 in $v0.
#
# register usage
# $s0 n
# $t0 scratch
#
next_prime:
addiu $sp,$sp,-8
sw $ra,0($sp)
sw $s0,4($sp)
li $v0,2
blt $a0,$v0,np_return # return 2
andi $t0,$a0,1 #test for even
bne $t0,$zero,np_odd
nop
addiu $a0,$a0,1
b np_loop
nop
np_odd:
addiu $a0,$a0,2
np_loop:
move $s0,$a0 # save n
li $a1,5 # passes
jal miller_rabin # test
nop
bgtz $v0,np_return # return if prime
addiu $a0,$s0,2 # else add 2 and
b np_loop # try again
nop
np_return:
lw $ra,0($sp)
lw $s0,4($sp)
addiu $sp,$sp,8
jr $ra
nop
###############################################################################
# Miller-Rabin Primality test
# Returns zero in $v0 if $a0 (n) is composite. Else, returns $a0 in $v0
# $a1 contains the pass counter
#
# register usage
# $s0 n - 1 $s4 pass counter
# $s1 s $s5 used for working copy of s
# $s2 d $s6 constant one
# $s3 x $s7 unused
#
# $t0 scratch $t5 unused
# $t1 scratch $t6 unused
# $t2 scratch $t7 unused
# $t3 scratch $t8 unused
# $t4 unused $t9 unused
#
miller_rabin:
addiu $sp,$sp,-36 # make room for ra & s registers
sw $ra,0($sp) # preserve return address
sw $s0,4($sp)
sw $s1,8($sp)
sw $s2,12($sp)
sw $s3,16($sp)
sw $s4,20($sp)
sw $s5,24($sp)
sw $s6,28($sp)
sw $s7,32($sp)
li $s6,1 # constant
sub $s0,$a0,$s6 # n - 1
move $s4,$a1 # passes
li $t0,2 # test value
blt $a0,$t0,mr_composite # no primes less than 2
li $t0,4 # test value
blt $a0,$t0,mr_n_is_prime # n is 2 or 3
and $t0,$a0,$s6 # t0 = n & 1
beqz $t0,mr_composite # n is greater than 2 and even
move $s2,$s0 # d = n - 1
move $s1,$zero # s (iteration counter)
mr_loop0: # do while d is even
sra $s2,$s2,1 # d >>= 1
addu $s1,$s1,$s6 # s++
and $t0,$s2,$s6 # d still even?
beqz $t0,mr_loop0 # iterate
nop
mr_loop_1: # do $s4 times
lw $t2,seed # load previous random number
sll $t3,$t2,17 # algorithm from Hyatt & Rittman
xor $t2,$t2,$t3 # algorithm from Hyatt & Rittman
srl $t3,$t2,15 # algorithm from Hyatt & Rittman
xor $t2,$t2,$t3 # algorithm from Hyatt & Rittman
sw $t2,seed # save for next time
bgez $t2,mr_no_neg # is the seed negative?
nop
neg $t2,$t2 # yes, get the opposite
mr_no_neg: # 0 <= $t2
addiu $t3,$s0,-2 # get the range
div $t2,$t3 # for the remainder
mfhi $t2 # [0,n-4]
addiu $a0,$t0,2 # add the lower limit 2 <= $a0 <= n - 2
move $a1,$s2 # d (exponent)
addu $a2,$s0,$s6 # n (mod on n)
jal mod_exp # x = random^d % n
beq $v0,$s0,mr_continue # x == n - 1
nop
beq $v0,$s6,mr_continue # x == 1
move $s3,$v0 # x
move $s5,$s1 # copy of s (used as a counter)
mr_loop_2:
move $a0,$v0 # x (base)
li $a1,2 # e (exponent)
addu $a2,$s0,$s6 # n (modulas)
jal mod_exp # x = x^2 % n
nop
beq $v0,$s6,mr_composite # return false if x == 1
nop
beq $v0,$s0,mr_continue # break, iterate if x == n - 1
sub $s5,$s5,$s6 # decrement s counter
nop
bgtz $s5,mr_loop_2 # iterate if counter is positive
mr_composite:
move $v0,$zero # false
b mr_return
mr_continue:
sub $s4,$s4,$s6 # decrement pass counter
bgtz $s4,mr_loop_1 # iterate if positive
mr_n_is_prime:
add $v0,$s0,$s6 # n
mr_return:
lw $ra,0($sp)
lw $s0,4($sp)
lw $s1,8($sp)
lw $s2,12($sp)
lw $s3,16($sp)
lw $s4,20($sp)
lw $s5,24($sp)
lw $s6,28($sp)
lw $s7,32($sp)
addiu $sp,$sp,36 # return stack space
jr $ra
nop
################################################################################
# returns $a0 ^ $a1 % $a2 in $v0
#
# register usage
# $a0 base $a1 exponent
# $a2 modulas $v0 r
#
# $t0 scratch
#
mod_exp:
li $v0,1 # r
beqz $a1,me_exit # exponent zero, return
me_loop:
andi $t0,$a1,1 # test low order bit
beqz $t0,me_skip # skip augmentation if low order bit is zero
mult $v0,$a0
mflo $t0
div $t0,$a2
mfhi $v0 # r * b % m
me_skip:
mult $a0,$a0 # b *= b
mflo $a0
div $a0,$a2
mfhi $a0 # b^2 % m
sra $a1,$a1,1 # e >>= 1
bgt $a1,$zero,me_loop
nop
me_exit:
jr $ra
nop
################################################################################
# returns 0 (composite) or 2^p - 1 (prime)
#
# register usage
# $a0 p
#
# $t0 m (mersenne number)
# $t1 s
# $t2 loop counter
#
lucas_lehmer:
li $t0,1 # 2^0
sllv $t0,$t0,$a0 # 2^p
addiu $t0,$t0,-1 # 2^p - 1
li $t1,4 # s
addiu $t2,$a0,-2 # iterate this many times
beqz $t2,ll_prime # special case when p == 2
ll_loop:
mult $t1,$t1 # s *= s
mflo $t1
addiu $t1,$t1,-2 # s -= 2
div $t1,$t0
mfhi $t1 # s = (s^2 - 2) % m
addi $t2,$t2,-1
bgtz $t2,ll_loop # iterate when non-negative
nop
beqz $t1,ll_prime # prime if s == 0
move $v0,$zero # return false
b ll_exit
nop
ll_prime:
move $v0,$t0 # return a mersenne prime
ll_exit:
jr $ra
###############################################################################
</code></pre>
|
[] |
[
{
"body": "<p><strong>Comments</strong></p>\n\n<p>Overall, I think you do a really great job with your comments. You clearly separate each section of code, state its purpose, list the register usage (very important for assembly), and do <em>not</em> have many obvious comments spread throughout. You pretty much have that part nailed down.</p>\n\n<p>I just have a few minor things to address:</p>\n\n<ul>\n<li><p>You don't need to add a comment for every <code>syscall</code>. This can be added as a general comment at the top of the procedure(s) or the program.</p></li>\n<li><p>Don't be afraid to add a summary comment on top or to the side of a block of similar code. This may be beneficial for large procedures that execute instructions that can be explained with one comment on top or to the side (like you did with the <code># preserve return address</code> comment).</p></li>\n</ul>\n\n<p><strong>Structure</strong></p>\n\n<p>You also do pretty well with structure. It's not too difficult to follow the code. Labels clearly stand out and the respective instructions are indented well.</p>\n\n<p>I do still have some additional things to say about this:</p>\n\n<ul>\n<li><p>Put appropriate linebreaks within procedures:</p>\n\n<p>You may separate the <code>syscall</code>s, especially since there are so many of them.</p>\n\n<p>For larger procedures, you may separate the <code>jmp</code>s and branches, especially if there are around the middle of the procedure. The ones at the end are okay as-is, especially since they're most commonly there. It would be good to make it clear if a procedure will ever jump or branch, otherwise it may be assumed that it will always fall to the next one (no change in the flow).</p></li>\n<li><p>It may help to give the loop labels more accurate names.</p>\n\n<p>You should <em>especially</em> give distinction for nested loops. Even then, you would probably indent nested loops further unless this common style is to be maintained.</p>\n\n<p>Consider stating the <em>type</em> of loop used, such as <code>for</code> (counter), <code>while</code> (pre-test), or <code>do</code>-<code>while</code> (post-test). This may be an important distinction as it would otherwise take close reading of the code to determine the type of loop being used.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T20:52:24.457",
"Id": "41180",
"ParentId": "14366",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T04:23:59.280",
"Id": "14366",
"Score": "8",
"Tags": [
"beginner",
"primes",
"random",
"assembly"
],
"Title": "Listing the first five perfect numbers in MIPS assembly"
}
|
14366
|
<p>In python2.7:
2 for loops are always a little inefficient, especially in python. Is there a better way to write the following filter function?
It tags a line from a log file, if it is useful. Otherwise the line will be ignored. Because there are different possible interesting lines, it tries different compiled regexes for each line, until it finds one. Note that no more regexes are checked for a line, after the first one successfully matched.</p>
<pre><code>def filter_lines(instream, filters):
"""ignore lines that aren't needed
:param instream: an input stream like sys.stdin
:param filters: a list of compiled regexes
:yield: a tupel (line, regex)
"""
for line in instream:
for regex in filters:
if regex.match(line):
yield (line,regex)
break
</code></pre>
<p>(The "tagging" is done with the regex object itself, because it can be used later on for retrieving substrings of a line, like filename and row number in an occuring error)</p>
|
[] |
[
{
"body": "<p>I wouldn’t worry about performance of the loop here. The slow thing isn’t the loop, it’s the matching of the expressions.</p>\n\n<p>That said, I’d express the nested loops via list comprehension instead.</p>\n\n<pre><code>def filter_lines(instream, filters):\n return ((line, regex) for regex in filters for line in instream if regex.match(line))\n</code></pre>\n\n<p>Or alternatively, using higher-order list functions:</p>\n\n<pre><code>def filter_lines(instream, filters):\n return filter(lambda (line, rx): rx.match(line), itertools.product(instream, filters))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T15:55:09.637",
"Id": "23254",
"Score": "0",
"body": "I can't check this right now, but my guess is that your first alternative is way, way faster then my 2 nested for loops. Anyway, it's not perfect, because it still continues to match other regexes if one already successfully matched one line."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T16:11:10.053",
"Id": "23257",
"Score": "1",
"body": "@erikb Ah, I completely missed that aspect, to be honest. And I’m not sure why this code should be faster than yours. Unfortunately, I don’t see a good way of breaking out of the loop early without two explicit nested loops, sorry."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T15:42:26.487",
"Id": "14379",
"ParentId": "14368",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T12:38:30.100",
"Id": "14368",
"Score": "4",
"Tags": [
"python",
"python-2.x",
"regex",
"logging"
],
"Title": "Filtering lines in a log file using multiple regexes"
}
|
14368
|
<p>When you click on a span it enters the value into the input. That works fine, but as you can see the JS code is very big and there must be a better way to do this, but like I said I'm still learning. Maybe someone can give me a pointer in the right direction.</p>
<p>I suppose I have to use a variable somewhere but can't really figure it out on my own.</p>
<p><a href="http://jsfiddle.net/4UbRU/" rel="nofollow noreferrer">jsFiddle</a></p>
<pre><code>jQuery(document).ready(function() {
$("#spanval1").click(function(){
$('#hourvalue').val($('#spanval1').text());
});
$("#spanval2").click(function(){
$('#hourvalue').val($('#spanval2').text());
});
$("#spanval3").click(function(){
$('#hourvalue').val($('#spanval3').text());
});
jQuery('.hour_dropdown').hide()
jQuery("#more").click(function() {
$('.hour_dropdown').fadeToggle(200);
});
});
</code></pre>
|
[] |
[
{
"body": "<p>First off, <code>this</code> refers to the element you clicked on, so we can simplify your code a bit my replacing your second <code>#spanval</code> like so:</p>\n\n<pre><code>$(\"#spanval1\").click(function(){\n $('#hourvalue').val($(this).text());\n});\n</code></pre>\n\n<p>Next, you can extract that click handler into it's own function, allowing the index to be passed in as a parameter.</p>\n\n<pre><code>function handleClick(num){\n $(\"#spanval\"+num).click(function(){\n $('#hourvalue').val($(this).text());\n });\n}\n</code></pre>\n\n<p>This will allow us to replacing all of those click handlers in the main function with this:</p>\n\n<pre><code>handleClick(1);\nhandleClick(2);\nhandleClick(3);\n</code></pre>\n\n<p>Now, we're still being repetitive, so lets reduce the repetition using a <code>for loop</code>:</p>\n\n<pre><code>jQuery(document).ready(function() {\n\n var maximumNumber = 3;\n for(var n = 1; n <= maximumNumber; n++){\n handleClick(n);\n }\n\n jQuery('.hour_dropdown').hide()\n\n jQuery(\"#more\").click(function() {\n $('.hour_dropdown').fadeToggle(200);\n });\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T13:55:56.297",
"Id": "14375",
"ParentId": "14374",
"Score": "2"
}
},
{
"body": "<p>Building off of Danny's answer, if you have access to the HTML, you can add a class to each of your span tags and bind an event to that class:</p>\n\n<pre><code><span id=\"spanval1\" class=\"spanval\">1</span>\n<span id=\"spanval2\" class=\"spanval\">2</span>\n<span id=\"spanval3\" class=\"spanval\">3</span>\n</code></pre>\n\n<p>The event call can become more generic by using the event's <a href=\"http://docs.jquery.com/Types#Context.2C_Call_and_Apply\" rel=\"nofollow\">local context</a> 'this'. From the <code>.bind()</code> documentation:</p>\n\n<blockquote>\n <p>Within the handler, the keyword <em>this</em> refers to the DOM element to which the handler is bound. To make use of the element in jQuery, it can be passed to the normal $() function.</p>\n</blockquote>\n\n<p>'this' inside of the click event will be the DOM element that was clicked on that caused the event to fire. Then you would need only the following to setup the click event for all of the elements with the class 'spanval':</p>\n\n<pre><code>$(\".spanval\").click(function(){\n $('#hourvalue').val($(this).text());\n});\n</code></pre>\n\n<p>And with the rest of the script:</p>\n\n<pre><code>$(document).ready(function() {\n\n $(\".spanval\").click(function(){\n $('#hourvalue').val($(this).text());\n });\n\n $('.hour_dropdown').hide();\n\n $(\"#more\").click(function() {\n $('.hour_dropdown').fadeToggle(200);\n });\n\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T21:19:07.063",
"Id": "23278",
"Score": "0",
"body": "Typo alert: The first selector there should end with the letter L."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T22:20:40.237",
"Id": "23282",
"Score": "0",
"body": "Thanks. But can you perhaps explain me how (this) knows the value of the span?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T19:31:07.353",
"Id": "14385",
"ParentId": "14374",
"Score": "4"
}
},
{
"body": "<p>Here are some points worth considering:</p>\n\n<ol>\n<li><a href=\"http://www.stoimen.com/blog/2010/06/19/speed-up-the-jquery-code-selectors-cache/\" rel=\"nofollow\">Cache your selectors</a>! If there's one thing you can do to increase performance, it's caching selectors. Traversing the DOM is an expensive operation, and should be done only when absolutely necessary.</li>\n<li><p>Use an <a href=\"http://api.jquery.com/attribute-starts-with-selector/\" rel=\"nofollow\">attribute selector</a> (<code>span[id^=spanval]</code>). This'll allow you to select all <code>span</code>s who's ID starts with <code>spanval</code> (if not all of them are <code>span</code>s, you can use the attribute selector on its own (<code>[id^=spanval]</code>) which is a tad slower but works just as well).</p></li>\n<li><p>Whenever possible, try not to use the jQuery constructor. <a href=\"http://jsperf.com/using-jquery-without-the-constructor\" rel=\"nofollow\">It's much faster to call the static methods from the jQuery namespace</a> (when they're available). So instead of <code>$(this).text()</code>, try using <code>$.text(this)</code>.</p></li>\n</ol>\n\n<hr>\n\n<p>With that in mind, here's some sample code:</p>\n\n<pre><code>jQuery(document).ready(function($) {\n\n var $hourVal = $('#hourvalue'),\n $hourDropdown = $('.hour_dropdown');\n\n $('span[id^=spanval]').click(function(){\n $hourVal.val( $.text(this) );\n });\n\n $hourDropdown.hide()\n\n $(\"#more\").click(function() {\n $hourDropdown.fadeToggle(200);\n });\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T21:16:45.630",
"Id": "14387",
"ParentId": "14374",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "14385",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T13:35:17.097",
"Id": "14374",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "Entering a span value into the input"
}
|
14374
|
<p>I've setup up a nice, little parent class that I can extend easily to do Http request to servers offering some sort of data with JSON/XML/whatever output.</p>
<p>You can see the <code>init()</code> function that is defined in the child class. The request URl builder is defined in the parent class, as the callback is.</p>
<p>The desired result is like the following:</p>
<pre><code>// THE RESULT: (just an example - the class takes *any* sort of input)
http://example.com/HTTPservice?format=json&q=give_me_data&api_key=A0123456789Z
http:// example.com/HTTPservice ? format=json&q=give_me_data&api_key=A0123456789Z
SCHEME REQUEST URL PREFIX PREFIX_EACH/KEY/SEPARATOR/VALUE (repeating)
// Scheme
http://
// Request URI
example.com/HTTPservice
// Query Parts: Prefix - gets prepended to the result of http_builder :: get_query_parts()
? // $this->query_parts['prefix']
// Request Parts:
format=json // $this->request_parts['format] + $this->query_parts['separator'] + $this->request_parts['json']
& // $this->query_parts['prefix_each']
q=give_me_data // $this->request_parts['q] + $this->query_parts['separator'] + $this->request_parts['give_me_data']
& // $this->query_parts['prefix_each']
api_key=A0123456789Z // $this->request_parts['api_key] + $this->query_parts['separator'] + $this->request_parts['A0123456789Z']
</code></pre>
<p>So it defines a scheme (http/https), appends the main URl to the API and then appends the query string, which gets build from a key/value array.</p>
<p>It is capable of adding a prefix and suffix to the complete string, as well as <strong>adding single key/value pairs with prefix/suffix for each pair</strong>. It also adds a separator on demand.</p>
<pre><code>// Setup: extending class
class http_factory extends http_builder
{
public function init()
{
$this->scheme = 'http://';
$this->request_uri = "example.com/HTTPservice";
$this->query_parts = array(
'prefix' => '?'
,'suffix' => ''
,'separator' => '='
,'prefix_each' => '&'
,'suffix_each' => ''
);
$this->request_parts = array(
'format' => 'json'
,'q' => 'give_me_data'
,'api_key' => 'A0123456789Z'
);
}
} // END http_factory
// The core class
class http_builder
{
// Builds the complete string
public function get_request_uri()
{
// Prepare
$parts = array_map( 'urlencode', $this->request_parts );
$parts = array_map( 'htmlentities', $parts );
$uri = sprintf(
"%s%s%s%s%s"
,$this->scheme
,$this->request_uri
,$this->query_parts['prefix']
,implode( '', array_map(
array( $this, 'get_query_parts' )
,array_keys( $this->request_parts )
,$this->request_parts
) )
,$this->query_parts['suffix']
);
}
// Callback fn to build a string from the key/value pair
public function get_query_parts( $key, $value )
{
static $counter, $parts_count = 0;
! $parts_count AND $parts_count = count( $this->query_parts );
$counter++;
extract( $this->query_parts );
return implode(
''
// Allow single (value only) query parts without separator and prefix
,array(
( ! empty( $key ) AND 1 < $counter ) ? $prefix_each : ''
,$key
,! empty( $key ) ? $separator : ''
,$value
,! ( count( $this->query_parts ) === $counter ) ? $suffix_each : ''
)
);
}
} // END http_builder
</code></pre>
<blockquote>
<p><strong>Question</strong> How could I avoid all that crap with counting in the cb fn, without killing what's left from readability in the main request builder. Important is, that I need to have the prefix/suffix for <strong>each</strong> key/value pair. The first one <em>must not</em> have a <code>prefix_each</code> and the last one <em>must not</em> have a <code>suffix_each</code>.</p>
</blockquote>
<p>I also appreciate every other comment. Criticism will be taken as positive in any way.</p>
<p><strong>EDIT:</strong> I have to note, that I'm not using <code>http_build_query()</code>, as some APIs I'm dealing with, are using completely different strings, that don't use <code>=</code> as separator.</p>
|
[] |
[
{
"body": "<p>I'm not sure I entirely understand what this is doing. But I'll give you my two cents.</p>\n\n<p>If the scheme were HTTPS, would that instead append the <code>$request_uri</code> with \"HTTPSservice?\"? In which case you could do something like the following.</p>\n\n<pre><code>$this->scheme = 'http';//changed for ease\n$this->request_uri = '://example.com/' . strtoupper( $this->scheme ) . 'service?';\n</code></pre>\n\n<p>I don't know about everyone else, but to me it seems odd to see commas on the newline rather than the preceding one when you are defining multiline arrays or parameters, but that may just be a point of preference.</p>\n\n<p>I really want to bash that \"q\" parameter, but I've done it before too so I can't say much except that it should probably be more specific.</p>\n\n<p>The <code>sprintf()</code> function is usually pretty slow from my understanding, so it would probably be better to just concatenate the strings together manually. I'll leave this to you to profile and determine.</p>\n\n<p>What? What is this?</p>\n\n<pre><code>! $parts_count AND $parts_count = count( $this->query_parts ); \n</code></pre>\n\n<p>No! Don't do this! Its just confusing and abuses short circuiting in the worst way. Just use an if statement, yes its two more lines, but this is the only clean way to check if a variable is set then give it a default value. As it was I was left scratching my head for a moment or two trying to figure out what the hell was going on. Or, since you've already set it to static, you can just give it that count value upon initializing it.</p>\n\n<pre><code>if( ! isset( $parts_count ) ) {\n $parts_count = count( $this->query_parts );\n}\n</code></pre>\n\n<p>BTW: Use <code>&&</code> instead of <code>AND</code>. Short reason: They aren't the same thing. Long Reason: <code>AND</code> and <code>&&</code> have different precedences, therefore one supersedes the other so it could have unforeseen results. I can't give you a good example as I've never run across an issue with this before, however it is standard practice not to use this format unless specifically meant.</p>\n\n<p>Instead of using those ternary statements inline, as you are doing, I would assign a variable to them so that it is easier to determine their purpose.</p>\n\n<p>Also, don't create an array just to implode it, that's redundant. Just concatenate it. That's like saying, \"I'd like a burger, hold the patty and bun.\" Sure you will get a salad, but its an odd way to go about it.</p>\n\n<p>Might want to work on that legibility thing a little more before worrying about that counter, as I'm not sure what's going on anyways. But if I'm understanding this correctly, you can just shift and pop the array outside of the function to remove the first and last elements respectively and then append them manually outside of the function. The <code>$request_parts</code> array will no longer contain these values and it can be <code>implode()</code>'d like you are currently doing without change.</p>\n\n<pre><code>$keys = array_keys( $this->request_parts );\n$values = array_values( $this->request_values );\n\n$firstKey = array_shift( $keys );\n$firstValue = array_shift( $values );\n\n$lastKey = array_pop( $keys );\n$lastValue = array_pop( $values );\n\n$newRequestValues = array_combine( $keys, $values );\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T21:02:33.913",
"Id": "23275",
"Score": "0",
"body": "Thanks for your answer. I'm leaving all the preference stuff out, as it's ... preference and I'm aware of anything you wrote (incl. `&&` over `and/AND`). The point with your last argument is, that I'm using `array_map` for a reason: There can be _lots_ of key/value pairs and the order inside the assoc array. And the order is undefined - so using `array_pop/shift` may a) bring the wrong value and b) would pop/shift it permanently off the array and therefore wouldn't be available for the next key/val pair anymore. Then there's also the issue that I avoid assigning var, that are used only once..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T21:05:34.050",
"Id": "23276",
"Score": "0",
"body": "(...continue) ...as this would slow down stuff for no reason. The only reason why I'm assigning `$uri` is that in my \"real\" class, I log the output and return `$uri` _after_ that. Else I'd return immediately. The actual problem, that I've is that I want to avoid all the static counting and comparing inside the callback. I already tried several things incl. work arounds for `http_build_query()`. But `http_build_query()` lacks the possibility to replace the `=` connector and add leading/trailing chars like `[]` or similar (some APIs use such things)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T21:08:09.323",
"Id": "23277",
"Score": "0",
"body": "(...continue) It also lacks the main features I'm after: Adding a prefix that starts **after** the first key/value pair and adding a suffix that ends **before** the first key/value pair. For other things like the leading `?`, I got `prefix` and for stuff like `.json` (that some APIs got), I got `suffix`. My problems are **only** the `prefix_each/suffix_each` and the counting that comes with it. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T22:03:26.450",
"Id": "23279",
"Score": "0",
"body": "The difference between `&&` and `AND` is not a matter of preference. I said precedence. Sorry about final point, forgot I was looking at an associative array. You can still use suggested solution with `array_keys()` and `array_values()`, then combining with `array_combine()`. If this is not a feasible solution for you, you will have to deal with the counter as there is no other way. Except maybe with iterators, but I can't help you there. As far as order, that shouldn't matter, they all go to the same place, it only matters which one is first and gets the \"?\" instead of the \"&\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T22:03:52.333",
"Id": "23280",
"Score": "0",
"body": "Assigning variables for one time use should not hinder your program. If it does, then there is definitely something wrong. This is a simple task and should not cause any issues. If you are trying to optimize for performance, unnecessarily, then don't that's called premature optimization and makes horrible code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T22:13:04.887",
"Id": "23281",
"Score": "0",
"body": "Hey, thanks for your answer again :) I'm sorry, but I don't follow what you're trying to tell me with `array_values/_keys/_combine()`. Could you please add an example to your answer? Btw: You're right with `sprintf()`. I did profile it on 1.000.000 runs and simply building a string with `.` was about 25x faster - changed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T22:31:34.217",
"Id": "23283",
"Score": "0",
"body": "added to answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T23:56:50.153",
"Id": "23284",
"Score": "0",
"body": "That won't work that way you think (see the arrays). But I did some profiling on how much faster plain, simple, stupid string concatenating is and switched to it, after seeing it 4.2x faster than anything else I tried. So: thanks."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T20:38:53.057",
"Id": "14386",
"ParentId": "14381",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T17:48:33.627",
"Id": "14381",
"Score": "2",
"Tags": [
"php",
"performance"
],
"Title": "Improving a \"Http request URl builder\" to be shorter, faster, easier to read"
}
|
14381
|
<p>This downloads content from YouTube either as whole playlists or single videos. I find it very useful but would like to know if it's something close to a program that others could maintain. I also wanted to show it off a bit and get some feedback as I've been learning on my own from the net and would be helpful to know if I'm on a right track.</p>
<p>It works through the shell (Windows for now) and doesn't have a GUI. Because I made a custom command line interface it's very user-friendly so anyone can use it and has a few simple commands which are explained by typing "help". It also downloads the videos using an opensource command line script/program called youtube-dl.</p>
<p><img src="https://i.stack.imgur.com/ceo9R.gif" alt="enter image description here"></p>
<p><a href="http://sdrv.ms/OHdrjM" rel="nofollow noreferrer">Unfinished project outline</a></p>
<pre><code>import HTMLParser
import urllib2
import os
help_str = '''
* YouTube Offline can be used without these commands.
For single video downloads enter a valid YouTube username.
The users playlists will be shown if any in order by numbers
starting from 1. Select a playlist or video item by simply
entering the items number. When a video number is selected
the download will begin automatically.
Or add multiple items(playlists or videos) to the job queue
with these commands and use the start command to begin downloads.
List of commands:
add <item> Add playlist or videoitem to job queue.
eg. add 12
adds the 12th item in the list to job queue
start Executes tasks in job queue if any.
clear / clear all Clears last job from job queue or clears all jobs.
cancel Navigate backwards through prompts.
up Scroll up / previous page
<enter> Scroll down / next page
...hit <enter> to exit help...
'''
youtube_header = ['','',
' __ __ ______ __ ____ ________',
' \ \/ /__ __ _/_ __/_ __/ / ___ / __ \/ _/ _/ (_)__ ___ ',
' \ / _ \/ // // / / // / _ \/ -_) / /_/ / _/ _/ / / _ \/ -_)',
' /_/\___/\_,_//_/ \_,_/_.__/\__/ \____/_//_//_/_/_//_/\__/',
'','','']
screen = {'head':[''] * 3,
'body':[''] * 11,
'bar':[''],
'status':[''],}
data = {}
job_q = []
def comm_input(comm=None, comm_data=None):
'executes commands and returns False, or if no command returns comm'
global job_q
if comm == None:
comm = raw_input('>> ')
comm = comm.lower().strip()
if comm == 'help':
os.system('cls')
print help_str
raw_input()
print_screen('status')
return False
if comm_data:
user = comm_data[0]
# add <item>
if comm[:3] == 'add':
i = comm[3::].strip()
try:
i = int(i)
if len(comm_data) == 2:
# add video to job_q
playlist = data[comm_data[0]][comm_data[1]]
if 0 < i <= len(playlist[2]):
i -= 1
p_title = playlist[0]
y_id = playlist[2][i][2]
v_title = playlist[2][i][0]
path = 'videos/'+clean(user)+'/'+clean(p_title)+'/'+clean(v_title)+'.flv'
job_q.append((y_id, path))
prin_screen('status')
return False
else:
# Invalid range
print_screen('status', ['Invalid option. Valid options are from 1 to ' + str(len(playlist[2]))])
return False
else:
# add playlist to job_q
if 0 < i <= len(data[user]):
i -= 1
p_title = data[user][i][0]
if not data[user][i][3]:
get_all_vids(data[user][i])
for vid in data[user][i][4]:
v_title = vid[0]
y_id = vid[1]
path = 'videos/'+clean(user)+'/'+clean(p_title)+'/'+clean(v_title)+'.flv'
job_q.append((y_id, path))
print_screen('status')
return False
else:
# Invalid range
print_screen('status', ['Invalid option. Valid options are from 1 to ' + str(len(data[user]))])
return False
except ValueError:
print_screen('status', ['Invalid command for add <item>; type help'])
return False
# clear
elif comm == 'clear':
job_q.pop()
return False
# clear all
elif comm == 'clear all':
job_q = []
return False
# start
elif comm == 'start':
start_work(job_q)
job_q = []
return False
# not a command
return comm
def download(youtube_id, path):
os.system('python youtube-dl.py -f 18 -icw -o "' + path + '" http://www.youtube.com/watch?v=' + youtube_id)
def start_work(job_q):
for job in job_q:
download(job[0], job[1])
def get_source(url):
try:
source = urllib2.urlopen(url)
return source.read()
except:
return False
def unescape(string):
h = HTMLParser.HTMLParser()
return h.unescape(string)
def clean(title):
'replaces invalid filename chars with valid chars'
invalid_dir_chr = ['\\', '/', ':', '*', '?', '<', '>', '|']
title = unescape(title)
title = urllib2.unquote(title)
title = title.replace('"', "'")
title = title.replace('?', '.')
for c in invalid_dir_chr:
title = title.replace(c, '-')
return title
def print_screen(key=None, lines=None, disp=True):
'lines --> [str, ... ]'
global screen
if lines:
for i in range(len(screen[key])):
try:
if lines[i] != None:
screen[key][i] = lines[i]
except IndexError:
screen[key][i] = ''
elif key:
screen[key] = ['' for x in screen[key]]
if disp:
lines = ['head', 'body', 'bar', 'status']
os.system('cls')
for line in lines:
for subline in screen[line]:
print subline
if len(job_q) == 0:
print ''
else:
print 'jobs pending: ' + str(len(job_q))
def display_list(data, page):
'data --> list | page --> int, actual page not index num'
block = [line[0] for line in data]
start = (10 * (page - 1))
end = start + 10
if len(data) < 10:
pad = '%01d'
elif len(data) < 100:
pad = '%02d'
else:
pad = '%03d'
block = [(pad % (start+1+i)) + '.' + block[start+i] for i in range(len(block[start:end]))]
print_screen('body', block)
def browse(user, playlist_i=None):
'pages through data_list 10 lines at a time'
data_list = data[user]
if not data_list:
return False
if playlist_i != None:
print_screen('head', [None, data_list[playlist_i][0]])
data_list = data_list[playlist_i][5]
if len(data_list) <= 10:
pages = 1
else:
pages = len(data_list) / 10
if len(data_list) % 10:
pages += 1
page = 1
while True: # while paging
# Display
display_list(data_list, page)
# page number bar display
page_bar = [str(x) for x in range(1,pages+1)]
page_bar = [x if int(x) == page or int(x) == page+1 else ' '+x for x in page_bar]
page_bar[page-1] = '['+str(page)+']'
page_bar = ''.join(page_bar)
print_screen('bar', [page_bar])
while True: # while commands being executed, don't page
# comm_data parameter allows the option of either explicitly
# executing commands or following the prompt.
if playlist_i != None:
comm = comm_input(comm_data=(user, playlist_i))
else:
comm = comm_input(comm_data=(user,))
if comm == False: # A command was executed at comm_input()
print_screen()
continue
elif comm == '': # <enter>, next page
print_screen('status', disp=False)
if page == pages:
page = 1
else:
page += 1
break
elif comm == 'up': # prev page
print_screen('status', disp=False)
if page == 1:
page = pages
else:
page -= 1
break
elif comm.strip().lower() == 'cancel': # prev level
print_screen('status', disp=False)
print_screen('head', [None, ''])
print_screen('bar')
return
else: # possible selection
try:
comm = int(comm.strip())
if 0 < comm <= len(data_list):
if playlist_i != None:
comm_input('add ' + str(comm), (user, playlist_i))
break
else:
if not data_list[comm-1][6]:
get_all_vids(data_list[comm-1])
browse(user, comm-1)
break
else:
print_screen('status', ['Invalid option. Valid options are from 1 to ' + str(len(data_list))])
continue
except ValueError:
print_screen('status', ['Invalid command'])
continue
break
def get_all_vids(playlist):
url = playlist[1]
playlist_data = playlist[2]
print_screen('status', ['...fetching playlist data...'])
source = get_source(url)
while True:
# link
source = source[source.find('<li class="playlist-video-item')::]
# youtube id
a = source.find('data-video-ids')
a = source.find('"', a)
b = source.find('"', a + 1)
if a == -1 or b == -1:
break
yid = source[a+1:b]
source = source[b::]
# video title
source = source[source.find("title video-title")::]
a = source.find('>')
b = source.find('<')
if a == -1 or b == -1:
break
title = source[a+1:b]
source = source[b::]
playlist_data.append([title, yid])
print_screen('status', disp=None)
def get_playlists(source):
'returns --> [<playlist data>] or False'
playlist = []
while True:
# URL
source = source[source.find("yt-uix-tile-link")::]
a = source.find("href")
a = source.find('"', a)
b = source.find('"', a+1)
if a == -1 or b == -1:
break
url = "http://www.youtube.com" + source[a+1:b]
source = source[b::]
# playlist title
a = source.find(">")
b = source.find("<")
if a == -1 or b == -1:
break
title = source[a+1:b].strip()
source = source[b::]
if not title or not url:
break
title = unescape(title)
playlist.append([title, url, []])
return playlist
def get_all_playlists(user):
'returns --> [[<playlist data>], ... ] from online'
playlist = []
page = 0
while True:
page += 1
print_screen('status', ['...fetching page ' + str(page) + '...'])
source = get_source('http://www.youtube.com/user/' + user + '/videos?sort=dd&view=1&page=' + str(page))
p = get_playlists(source)
if p:
playlist += p
else:
print_screen('status')
return playlist
def set_username(user):
'returns --> user or False if not exist or False if no playlists'
global data
if user == False:
return False
print_screen('head', ['Username: ' + user])
user = user.strip().lower()
if not user:
print_screen('status')
return False
if user in data:
if data[user]:
return user
else:
print_screen('status', ['no playlists found for user: ' + user])
return False
else:
print_screen('status', ['...checking online for username: ' + user + '...'])
source = get_source('http://www.youtube.com/user/' + user)
if source:
data[user] = get_all_playlists(user)
if data[user]:
print_screen('status', False)
return user
else:
print_screen('status', ['no playlists found for user: ' + user], False)
return False
else:
print_screen('status', [user + ' does not exist'], False)
return False
def prompt():
user = False
while user == False:
print_screen('head', ['Username: ', ''])
print_screen('body', youtube_header)
user = set_username(comm_input())
browse(user)
while True:
prompt()
</code></pre>
|
[] |
[
{
"body": "<p>One suggestion I would make is to reduce the length of your functions, and reduce the amount of nesting / indentation. This will make your code easier to follow, and easier to maintain.</p>\n\n<p>As one example, you've got a function to respond to user commands. I would probably approach this by defining a new function to handle each command. You can then describe a mapping from command to function, and call the appropriate function.</p>\n\n<p>e.g.</p>\n\n<pre><code># Define some functions to handle various user commands.\ndef start():\n # do something\n pass\n\ndef add_item(item):\n # do something with the item\n pass\n\ndef show_help():\n # display help message\n pass\n\n# Map from command to the associated function.\nCOMMANDS = { 'help': show_help,\n 'add': add_item,\n 'start': start,\n } # etc\n\n# Given user input, split it into a command and its arguments, then call\n# the appropriate function.\ndef handle_command(user_input):\n command = user_input.split()[0]\n arguments = user_input.split()[1:]\n\n try:\n COMMANDS[command](*arguments)\n except KeyError:\n # command not recognised, so show help.\n show_help()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T04:22:19.740",
"Id": "23294",
"Score": "1",
"body": "nit-pick: you need to define those function before the dict."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T07:19:55.620",
"Id": "23300",
"Score": "0",
"body": "Thanks John Fouhy. I appreciate you taking the time. I'll spend the rest of today working on the comm_input function and definitively like the idea of mapping commands with a dict."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T21:57:05.097",
"Id": "23367",
"Score": "0",
"body": "Ahh, too much time recently on DotNet..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T19:09:14.743",
"Id": "23442",
"Score": "0",
"body": "Didn't have much time at work yesterday so not yet finished with the code cleanup."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T19:16:34.283",
"Id": "23443",
"Score": "0",
"body": "...However I did add some new functionality to this one as I needed to use it while I work on a better implementation using OO. Here is the source for the improvement. You can set the quality of vids or playlists and throttle the download speed. [Here's the source](http://pastebin.com/4fmAr39Y) make sure you put youtube-dl in the python folder to use it: [youtube-dl source](http://pastebin.com/H3mssge3)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T03:29:10.263",
"Id": "14396",
"ParentId": "14383",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "14396",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T18:12:02.073",
"Id": "14383",
"Score": "6",
"Tags": [
"python",
"youtube"
],
"Title": "Downloading content from YouTube"
}
|
14383
|
<p>I'm new to bash scripting and need some help improving a script I made for working with reverse-engineering Android applications.</p>
<p>I wrote comments in the script itself to explain what I want to do. Some of the code/functions are missing/broken, but I hope that you can help me out with it.</p>
<pre><code>#!/bin/bash
# Goal: Have a working folder with a source rom and work from there.
# process would be: unzip relevant apks, decompile, add translations, recompile and build, sign apks. In the end put the new apks in a lang-pack.zip
# In the future, i'd like to do more clever paths, so i don't write absolute pathnames to the different functions.
# So that i can "install" my script whereever i want and the functions still work.
#
#
# I'd like to have the script start with a menu, where user can select to:
# 1. select which input zip file to work with
# 2. ON/OFF options for: -"Decompile" (default on)
# -"Fix sources" part of script (default on)
# -"add translations" (default on)
# -"recompile" (default on)
# -"Re-sign files" (default on)
# -"create flashable zip" (default on)
# 3. exit
echo "This script is designed to create language packs for patchrom MIUI ICS Desire by Marange"
echo ""
echo "Created by 1982Strand :) - Inspired by XavierJohn, TommyTomatoe and Marange."
echo ""
# Make sure we are root
if [ `id | sed -e 's/(.*//'` != "uid=0" ]; then
echo "Sorry, you need super user privileges to run this script."
exit 1
fi
##### Functions
# Want the user to select which zip to work with and show the selected one one the main menu
# Keep version number for later use. the rom zips are named MIUI-x.x.x-y.yy.yy.zip and the version number needed is the y.yy.yy
function select_zip
{
echo ""
echo "[--- Select ROM zip to work with ----]"
echo ""
PS3="Enter a number or 'q' to quit: "
fileList=$(find . -maxdepth 1 -type f)
select fileName in $fileList; do
if [ -n "$fileName" ]; then
# then return to main menu, wait for user to make an input, but don't know how to do it :(
fi
break
done
}
# Unzip apks from source zip into "apk_in" directory
# Needs refining
# Has to pull every apk from the zip, then remove unwanted afterwards. (Or simply just pull the needed ones, perhaps by making a seperate file with a list of the files needed..?)
function unzip_apks
{
echo ""
echo "[--- Unzipping apks ----]"
echo ""
# clear apk_in and apk_out directory
rm -r ./apk_in
rm -r ./apk_out
# now unzip the apks from the file specified in select_zip.
unzip -j -u *.zip *.apk -d ./apk_in # the *.zip part needs to use the file specified
echo ""
echo "[--- Removing unneeded apks ---]"
echo ""
cd /root/buildtool/apk_in
rm Google*.apk
rm ChromeBookmarksSyncAdapter.apk
rm DefaultContainerService.apk
rm LatinIME.apk
rm MediaProvider.apk
rm PicoTts.apk
rm Provision.apk
rm UserDictionaryProvider.apk
rm Vending.apk
rm VisualizationWallpapers.apk
rm WAPPushManager.apk
rm WeatherProvider.apk
rm SuperMarket.apk
rm LatinImeDictionaryPack.apk
rm SharedStorageBackup.apk
rm Talk.apk
rm Gmail.apk
cd ..
}
function decompile_apks
{
echo ""
echo "[--- Installing frameworks ---]"
echo ""
apktool if ./apk_in/framework-res.apk
apktool if ./if_frameworks/2.apk
apktool if ./if_frameworks/3.apk
apktool if ./if_frameworks/4.apk
apktool if ./if_frameworks/5.apk
apktool if ./apk_in/framework-miui-res.apk
echo ""
echo "[--- Decompiling apks ---]"
echo ""
cd /root/buildtool/apk_in
for file in `dir -d *` ; do
echo "Decompiling $file " # for log: 2>&1 | tee -a /root/buildtool/log/decompile_log.txt
apktool -q d -f $file /root/buildtool/apk_in/decompiled/$file # for log: 2>&1 | tee -a /root/buildtool/log/decompile_log.txt
done
cd /root/buildtool
}
function fix_src
{
echo ""
echo "[--- Fix MIUI sources ---]"
echo ""
echo ""
echo "Fixing Email.apk"
echo ""
patch -i src_fix/Email/ids.diff apk_in/decompiled/Email.apk/res/values/ids.xml
patch -i src_fix/Email/public.diff apk_in/decompiled/Email.apk/res/values/public.xml
patch -i src_fix/Email/sw600dp-styles.diff apk_in/decompiled/Email.apk/res/values-sw600dp/styles.xml
patch -i src_fix/Email/sw800dp-port.diff apk_in/decompiled/Email.apk/res/values-sw800dp-port/styles.xml
echo ""
echo "Fixing framework-miui-res.apk"
echo ""
patch -i src_fix/framework-miui-res/apktool.diff apk_in/decompiled/framework-miui-res.apk/apktool.yml
echo ""
echo "Fixing MiuiCompass.apk"
echo ""
patch -i src_fix/MiuiCompass/apktool.diff apk_in/decompiled/MiuiCompass.apk/apktool.yml
#echo ""
#echo "Fixing Gmail.apk"
#echo ""
#
#patch -i src_fix/Gmail/AndroidManifest.diff apk_in/Gmail/AndroidManifest.xml
echo ""
echo "Fixing Mms.apk"
echo ""
patch -i src_fix/Mms/bools.diff apk_in/decompiled/Mms.apk/res/values/bools.xml
}
function add_translation
{
echo ""
echo "[--- Adding Danish Translations ---]"
echo ""
cd /root/buildtool/translations/ma-xml-4.0-danish/device/bravo
cp -r * /root/buildtool/apk_in/decompiled
cd /root/buildtool/apk_in/decompiled/framework-res.apk/res
rm -r values-da
cd /root/buildtool/translations/ma-xml-4.0-danish/main
cp -r * /root/buildtool/apk_in/decompiled
cd /root/buildtool
}
function recompile_apks
{
echo ""
echo "[--- Recompile apks ---]"
echo ""
cd /root/buildtool/apk_in/decompiled
for b in `find * -maxdepth 0 -type d`; do
echo "Recompiling $b" # for log: 2>&1 | tee -a /root/buildtool/log/recompile_log.txt
apktool -q b -f $b /root/buildtool/apk_out/$b # for log: 2>&1 | tee -a /root/buildtool/log/recompile_log.txt
done
cd /root/buildtool
}
function sign_apks
{
echo ""
echo "[--- Re-sign apks ---]"
echo ""
for apk in `find apk_out/ -name "*.apk"`
do
echo "Signing $apk..."
java -jar ./signing/signapk.jar ./signing/testkey.x509.pem ./signing/testkey.pk8 $apk $apk.signed
zipalign 4 $apk.signed $apk.signed.aligned
mv $apk.signed.aligned $apk
rm $apk.signed
done
}
# When creating flashable zip, the script should name the finished zip with
# the version number from the rom zip in select_zip function.
function create_zip
{
echo ""
echo "[--- Creating flashable zip ---]"
echo ""
cd /root/buildtool/flashable
mkdir ./system
cd ./system
mkdir ./app
mkdir ./framework
cd /root/buildtool
for C in /root/buildtool/apk_out/*;
do
cp -f $C /root/buildtool/flashable/system/app
done
mv -f /root/buildtool/flashable/system/app/framework-res.apk /root/buildtool/flashable/system/framework
mv -f /root/buildtool/flashable/system/app/framework-miui-res.apk /root/buildtool/flashable/system/framework
cp -f /root/buildtool/flashable/template.zip /root/buildtool/flashable/flashable.zip
7za a -tzip /root/buildtool/flashable/flashable.zip /root/buildtool/flashable/system -mx3
rm -r /root/buildtool/flashable/system
cd /root/buildtool
}
# When rom zip is selected and all on/off options are set, run the script.
function run_script
{
echo ""
echo "[--- Running script ----]"
echo ""
unzip_apks
# if all options ON:
if [ $decompile -eq 1 ] && [ $fix_src -eq 1 ] && [ $translation -eq 1 ] && [ $recompile -eq 1 ] && [ $sign -eq 1 ] && [ $flashable -eq 1 ]; then
decompile_apks
fix_src
add_translation
recompile_apks
sign_apks
create_zip
fi
}
# ON/OFF functions
function dec_onoff() {
[ $decompile -eq 1 ] && decompile=0 || decompile=1
}
function fix_onoff() {
[ $source_fix -eq 1 ] && source_fix=0 || source_fix=1
}
function tra_onoff() {
[ $translation -eq 1 ] && translation=0 || translation=1
}
function rec_onoff() {
[ $recompile -eq 1 ] && recompile=0 || recompile=1
}
function sig_onoff() {
[ $sign -eq 1 ] && sign=0 || sign=1
}
function fla_onoff() {
[ $flashable -eq 1 ] && flashable=0 || flashable=1
}
##### From prevoius script, needs to be incorporated at some point
###################################################
#
# Track processing time
#TIMES=$SECONDS
# use apktool 1.4.9
#echo ""
#echo "[--- Using apktool 1.4.9 and MIUI aapt ---]"
#echo ""
#cp ./apktool/1.4.9/apktool.jar /usr/local/bin
#cp ./apktool/1.4.9/aapt /usr/local/bin
#TIMEE=$SECONDS
#DIFF=$(echo "$TIMEE-$TIMES" | bc)
#printf ""%dh:%dm:%ds"\n" $(($DIFF/3600)) $(($DIFF%3600/60)) $(($DIFF%60))
#
###########################################
#Next part inspired by XJ's tool, not sure if commands are correct...
decompile=1
source_fix=1
translation=1
recompile=1
sign=1
flashable=1
while true; do
[ $decompile -eq 0 ] && tmpdecompile="OFF" || tmpdecompile="ON"
[ $source_fix -eq 0 ] && tmpsource_fix="OFF" || tmpsource_fix="ON"
[ $translation -eq 0 ] && tmptranslation="OFF" || tmptranslation="ON"
[ $recompile -eq 0 ] && tmprecompile="OFF" || tmprecompile="ON"
[ $sign -eq 0 ] && tmpsign="OFF" || tmpsign="ON"
[ $flashable -eq 0 ] && tmpflashable="OFF" || tmpflashable="ON"
clear
echo "--------------------------------------------------------------"
echo " Dans Build Tool for MIUI"
echo " -by Dan Strand-"
echo "--------------------------------------------------------------"
echo "SETTINGS:"
echo " Decompile apks : $tmpdecompile"
echo " Fix sources : $tmpsource_fix"
echo " Add translations : $tmptranslation"
echo " Recompile apks : $tmprecompile"
echo " Re-sign apks : $tmpsign"
echo " Create flashable zip : $flashable"
echo "-------------------------------------------------------------"
echo "TOGGLES:"
echo " 1 Decompile apks (ON/OFF)"
echo " 2 Fix sources (ON/OFF)"
echo " 3 Add translations (ON/OFF)"
echo " 4 Recompile apks (ON/OFF)"
echo " 5 Re-sign apks (APK OUT) (ON/OFF)"
echo " 6 Create flashable zip (ON/OFF)"
echo "--------------------------------------------------------------"
echo "ACTIONS:"
echo " 7 Select source ROM"
echo " 8 Run script"
echo " 9 Exit"
echo "--------------------------------------------------------------"
echo "CURRENT ROM:"
echo
echo -n "CHOOSE OPTION:"
read menunr
[ $menunr -eq 1 ] && dec_onoff
[ $menunr -eq 2 ] && fix_onoff
[ $menunr -eq 3 ] && tra_onoff
[ $menunr -eq 4 ] && rec_onoff
[ $menunr -eq 5 ] && sig_onoff
[ $menunr -eq 6 ] && fla_onoff
[ $menunr -eq 7 ] && select_zip
[ $menunr -eq 8 ] && run_script
[ $menunr -eq 9 ] && quit
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T03:10:24.580",
"Id": "23293",
"Score": "1",
"body": "The convention in cr.se is that the script in question is added inline. This protects us against the changes in the external hosting parties."
}
] |
[
{
"body": "<p>Good first effort, here are a few general comments.</p>\n\n<ul>\n<li><p>You can replace multiple echos with one cat. that is</p>\n\n<pre><code>echo \"one\"\necho \"two\"\n</code></pre>\n\n<p>is equivalent to</p>\n\n<pre><code>cat <<EOF\none\ntwo\nEOF\n</code></pre>\n\n<p>and is much more cleaner.</p></li>\n<li><p>you can replace </p>\n\n<pre><code>`id | sed -e 's/(.*//'` != \"uid=0\" \n</code></pre>\n\n<p>with </p>\n\n<pre><code>`$(id -g) -eq 0`\n</code></pre></li>\n<li><p>You can avoid</p>\n\n<pre><code>cd xxx\n...\ncd ..\n</code></pre>\n\n<p>by doing</p>\n\n<pre><code>(cd xxx\n...\n)\n</code></pre></li>\n</ul>\n\n<p>Also, as a general advice, try to use a consistent formatting.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-12T08:02:43.810",
"Id": "14575",
"ParentId": "14384",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T19:05:43.827",
"Id": "14384",
"Score": "1",
"Tags": [
"beginner",
"android",
"bash"
],
"Title": "Bash script for reverse-engineering Android applications"
}
|
14384
|
<p>I have written this sample code to fetch a web page in C++ using libcurl. Please review it.</p>
<pre><code>#include <iostream>
#include <iostream>
#include <string>
#include <exception>
extern "C"
{
#include <curl/curl.h>
#include <stdlib.h>
}
//Exception class for curl exception
class CurlException : std::exception
{
public:
CurlException(std::string message):m_message(message) { }
CurlException(CURLcode error)
{
m_message = curl_easy_strerror(error);
}
const char* what() throw()
{
return m_message.c_str();
}
~CurlException() throw() { }
private:
std::string m_message;
};
//A tiny wrapper around Curl C Library
class CppCurl
{
public:
CppCurl(std::string url) throw (CurlException)
{
m_handle = curl_easy_init();
if ( m_handle == NULL )
throw CurlException("Unable to initialize curl handler");
if ( url.length() == 0 )
throw CurlException("URL can't be of zero length");
m_url = url;
}
std::string Fetch() throw (CurlException)
{
SetOptions();
SendGetRequest();
return m_data;
}
~CppCurl() throw()
{
curl_easy_cleanup(m_handle);
}
private:
void SetOptions() throw (CurlException)
{
CURLcode res;
//set the url
res = curl_easy_setopt(m_handle, CURLOPT_URL, m_url.c_str());
if ( res != CURLE_OK)
throw CurlException(res);
//progress bar is not require
res = curl_easy_setopt(m_handle, CURLOPT_NOPROGRESS, 1L);
if ( res != CURLE_OK )
throw CurlException(res);
//set the callback function
res = curl_easy_setopt(m_handle, CURLOPT_WRITEFUNCTION,
CppCurl::WriteDataCallback);
if ( res != CURLE_OK )
throw CurlException(res);
//set pointer in call back function
res = curl_easy_setopt(m_handle, CURLOPT_WRITEDATA, this);
if ( res != CURLE_OK )
throw CurlException(res);
}
void SendGetRequest()
{
CURLcode res;
res = curl_easy_perform(m_handle);
if ( res != CURLE_OK )
throw CurlException(res);
}
static size_t WriteDataCallback(void *ptr, size_t size,
size_t nmemb, void* pInstance)
{
return (static_cast<CppCurl*>(pInstance))->write_data(ptr, size, nmemb);
}
size_t write_data(void* ptr, size_t size, size_t nmemb)
{
size_t numOfBytes = size * nmemb;
char *iter = (char*)ptr;
char *iterEnd = iter + numOfBytes;
//while ( iter != iterEnd )
//{
// cout<<*iter;
// iter ++;
//}
m_data += std::string(iter, iterEnd);
return numOfBytes;
}
CURL *m_handle;
std::string m_url;
std::string m_data;
};
int main()
{
try
{
CppCurl ob("http://kodeyard.blogspot.in/");
std::cout<<ob.Fetch();
std::cout<<std::endl;
}
catch ( CurlException e)
{
std::cerr<<"Exception thrown..."<<std::endl;
std::cerr<<e.what()<<std::endl;
}
return 0;
}
</code></pre>
<p>This is also here in the <a href="http://kodeyard.blogspot.in/2012/08/fetch-web-page-in-libcurl.html" rel="nofollow">blog</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-04T11:27:27.950",
"Id": "149564",
"Score": "0",
"body": "Good job guys! I put this code on\nhttps://github.com/asashnov/tinycurl So everyone can use the latest version and improve it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-04T11:50:52.650",
"Id": "149565",
"Score": "1",
"body": "@asashnov - you cannot take code licensed using the CC-by-SA license, and then put it in the public domain. You need to read up on how copyright works."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-05T22:35:48.367",
"Id": "149826",
"Score": "0",
"body": "@rolfl I think it's ok. I wrote that own(means I own it). So, I am ok with that code being in public domain."
}
] |
[
{
"body": "<p>You should probably derive from std::runtime_error.<br>\nIt takes a string in the constructor as the message and stored it for use with what() in a way that is safe even in low memory situations:</p>\n\n<p>Your exception class is then simplified too:</p>\n\n<pre><code>class CurlException : public std::runtime_error\n{\npublic:\n CurlException(std::string const& message): std::runtime_error(message) {}\n // ^^^^^^^ pass message by const reference.\n CurlException(CURLcode error): std::runtime_error(curl_easy_strerror(error)) {}\n};\n</code></pre>\n\n<p>The use of exception specifications in C++ was an experiment that ultimitely showed it was a bad idea. The only useful specification was the no throw specification (and then only when you made sure it really was no-throw).</p>\n\n<pre><code>void SetOptions() throw (CurlException)\n // ^^^^^^^^^^^^^^^^^^^^^ Get rid of this bit.\n</code></pre>\n\n<p>In C++11 exception specifications have been deprecated.</p>\n\n<p>The curl library is a C library. It only knows about C calling conventions. Thus you can <strong>NOT</strong> pass it C++ functions. If it works it is pure luck and definately non portable.</p>\n\n<pre><code> res = curl_easy_setopt(m_handle, CURLOPT_WRITEFUNCTION,\n CppCurl::WriteDataCallback);\n</code></pre>\n\n<p>Even though <code>CppCurl::WriteDataCallback</code> is a static function there is no guarantee that static methods have the same calling convention as a C function. Future versions of the compiler may break your code.</p>\n\n<p>You should do something like this:</p>\n\n<pre><code> extern \"C\" size_t WriteDataCallback(void *ptr, size_t size, size_t nmemb, void* pInstance)\n {\n CppCurl* obj = reinterpret_cast<CppCurl*>(pInstance);\n return obj->write_data(ptr, size, nmemb);\n }\n</code></pre>\n\n<p>Not a big deal but I would have used insert rather than +=.</p>\n\n<pre><code> m_data += std::string(iter, iterEnd);\n\n // -- or.\n\n m_data.insert(m_data.begin(), iter, iterEnd);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T23:01:54.583",
"Id": "14390",
"ParentId": "14389",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T21:53:23.463",
"Id": "14389",
"Score": "3",
"Tags": [
"c++",
"curl"
],
"Title": "Tiny Curl C++ wrapper"
}
|
14389
|
<p>I wrote a failback for the fairly new CSS <code>calc()</code> rule. It works fine but I want to use it in a production environment and would appreciate feedback. Please recommend anything regarding weird/wrong code, possible optimizations, or a way to reduce code size.</p>
<pre><code>// CSS calc() replacement
function calcfailback(){
var d = document.createElement('div');
var _body = document.getElementsByTagName('body') [0];
_body.appendChild(d);
d.style.visibility = 'hidden';
d.style.width = "-webkit-calc(10px)";
d.style.width = "-o-calc(10px)";
d.style.width = "-moz-calc(10px)";
d.style.width = "calc(10px)";
var newwidth = d.offsetWidth;
if (newwidth == "10"){}
else{
function resize(){
document.getElementById('content').style.height = window.innerHeight - 40 + 'px';
document.getElementById('content').style.width = window.innerWidth - 300 +'px';
document.getElementById('sidebar').style.height = window.innerHeight - 40 + 'px';
};
resize();
window.onresize = function (){
resize();
}
};
_body.removeChild(d)
};
window.onload = calcfailback;
</code></pre>
|
[] |
[
{
"body": "<p>Am not very familiar with CSS, but I have a few comments on strictly the JS related parts:</p>\n\n<hr>\n\n<p><strong>calcfailback</strong></p>\n\n<p>I would call this <code>calcFailback</code> or <code>calc_failback</code>.</p>\n\n<hr>\n\n<p><strong>one var statement</strong></p>\n\n<p>It's fairly standard practice to only have 1 var statement per scope. This is because JS does hoisting where it essentially pulls all variable declarations to the top of a scope anyway.</p>\n\n<pre><code>function f() {\n var x = 5;\n if (x == 5) {\n var y = 10;\n }\n}\n</code></pre>\n\n<p>Is actually silently equivalent to:</p>\n\n<pre><code>function f() {\n var x = 5;\n var y;\n if (x == 5) {\n y = 10;\n }\n}\n</code></pre>\n\n<p>For this reason (or more particuarly, the odd bugs this can lead to if you forget that it's silently interpretted as this), it's a fairly widespread practice to only use 1 var declaration per scope:</p>\n\n<pre><code>function f() {\n var x = 5,\n y;\n ...\n}\n</code></pre>\n\n<hr>\n\n<p><strong>There's no point in a no-op branch</strong></p>\n\n<pre><code>if (newwidth == \"10\") {}\n</code></pre>\n\n<p>That's fairly pointless. There are some border situations where having an empty branch can be useful, but for a trivial one like this, just do:</p>\n\n<pre><code>if (newwidth != \"10\") { ... }\n</code></pre>\n\n<hr>\n\n<p><strong>Variable naming</strong></p>\n\n<p>I would use either underscores or camelCase so that there's some kind of visual separation of words. <code>new_width</code> and <code>newWidth</code> are much easier to read and understand than <code>newwidth</code>.</p>\n\n<hr>\n\n<p><strong>Functions that call other functions are usually pointless</strong></p>\n\n<pre><code>var x = function () { f(); };\n</code></pre>\n\n<p>All this does is create a function bound to <code>x</code> that when called, calls <code>f</code>.</p>\n\n<p>Unless you specifically want to do this to hide the calling context, it's usually better to just write it as:</p>\n\n<pre><code>var x = f;\n</code></pre>\n\n<p>In this situation, <code>x()</code> still calls <code>f</code>, it just does it without the layer of indirection.</p>\n\n<p>On a technical note though, these are different. A function without a context defaults to the <code>window</code> object as the context (or <code>undefined</code> in strict mode).</p>\n\n<p>This means that <code>this</code> inside of f may be different depending on how <code>x</code> is called.</p>\n\n<p>For example:</p>\n\n<pre><code>function f() {\n console.log(this);\n}\nvar x = function() { f(); },\n obj = {foo: \"bar\"};\n\nx.call(obj); //The console.log will output either window or undefined depending on strict mode\n//('this' inside of the wrapper function, however, would be obj)\n</code></pre>\n\n<p>Compared to:</p>\n\n<pre><code>function f() {\n console.log(this);\n}\nvar x = f,\n obj = {foo: \"bar\"};\n\nx.call(obj); //The console.log will output obj (in other words, 'this' inside of 'f' would be 'obj'\n</code></pre>\n\n<hr>\n\n<p><strong>Your script clobbers any other scripts</strong></p>\n\n<p>When you assign the <code>window.onload</code> and <code>window.onresize</code> properties, you may be over writing old handlers.</p>\n\n<p>\"But this is the only script on my page!\" You say.</p>\n\n<p>Well, it's the only script <em>for now</em>.</p>\n\n<p>For the sake of avoiding odd future bugs, I might make a simple little function to stack binding instead:</p>\n\n<pre><code>function bindEvt(target, evt, func) {\n var prev = target[evt];\n if (typeof prev !== \"function\") {\n target[evt] = func;\n } else {\n target[evt] = function() {\n prev.apply(this, Array.prototype.slice.call(arguments));\n func.apply(this, Array.prototype.slice.call(arguments));\n };\n }\n return target[evt];\n}\n</code></pre>\n\n<p>It would be used like:</p>\n\n<pre><code>function f() { ... };\nbindEvt(window, \"onresize\", f);\n</code></pre>\n\n<p>(Note: this really should be used as an idea than an actual implementation. I'm entirely sure that there's at least one major problem with this function.)</p>\n\n<hr>\n\n<p><strong>Suggested implementation</strong></p>\n\n<p>I might write it something like this:</p>\n\n<pre><code>// CSS calc() replacement\nfunction calcFailback(){\n var d = document.createElement('div'),\n _body = document.getElementsByTagName('body')[0],\n newWidth;\n\n //functions are actually hoisted too, though in a silenty different way\n function resize() {\n document.getElementById('content').style.height = window.innerHeight - 40 + 'px';\n document.getElementById('content').style.width = window.innerWidth - 300 +'px';\n document.getElementById('sidebar').style.height = window.innerHeight - 40 + 'px';\n }; //You will not usuaully see a ; here. There's nothing wrong with it though.\n\n _body.appendChild(d);\n\n d.style.visibility = 'hidden';\n d.style.width = \"-webkit-calc(10px)\";\n d.style.width = \"-o-calc(10px)\"; \n d.style.width = \"-moz-calc(10px)\"; \n d.style.width = \"calc(10px)\"; \n\n newWidth = d.offsetWidth;\n\n if (newWidth != \"10\") { //I might use either !== \"10\" or !== 10 if you know the type\n\n resize();\n window.onresize = resize;\n\n //I might consider inlining the function defition since it's a simple function.\n //You could use a structure like:\n //window.onresize = function() { ... };\n //window.onresize();\n //This is not the same thing as a legitimate onresize event happening though, so you'd need to be\n //careful to make sure that your handler is capable of handling fake events like this.\n //A bit more 'authentic' way might be:\n //window.onresize.call(window); since the handler is probably (I'm not sure) called with window as the context\n //This would still neglect the parameters though.\n\n } //There was no reason for the ; here\n\n _body.removeChild(d); //This should have a ; here (mainly for styling purposes in this context, but it's a good habit for situations where it does matter)\n\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Edit</strong></p>\n\n<p>For what it's worth, here's a (very) crude example of using a bindEvt like function: <a href=\"http://jsfiddle.net/DcKPD/1/\" rel=\"nofollow\">jsfiddle</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T02:10:43.240",
"Id": "23289",
"Score": "0",
"body": "Amazing post! implemented everything :). Learned a lot about basic code structuring and although the code of the bindEvt itself goes over my head I understand its principle. How would you suggest the bindEvt function could be improved? As you made it it seems to run quite well :)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T04:41:53.947",
"Id": "23295",
"Score": "0",
"body": "@SnippetSpace It's not so much that I know there's a problem with it; it's just that I don't trust my DOM related JS skills very much :). In fact, this seems to be a better approach: http://stackoverflow.com/questions/5411055/javascript-multiple-event-listeners-handlers-on-the-same-element. That has the browser handle the multiple events instead of creating wrappers over and over again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T13:11:25.443",
"Id": "23324",
"Score": "0",
"body": "Here is the final code :) http://pastebin.com/Bdp7rbUa"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T01:35:16.730",
"Id": "14393",
"ParentId": "14392",
"Score": "2"
}
},
{
"body": "<p>It would probably be a good idea to generalize your code so you can use it with different values. I'm not suggesting you support the full <code>calc()</code> syntax, but making it configurable at least could be useful if you plan on using it in more than one place.</p>\n\n<p>For the code you have though, I just have a couple suggestions:</p>\n\n<ol>\n<li><p>I typically avoid underscores in variable names, but that's just a preference (although one that a lot of style guides I've seen share).</p></li>\n<li><p>Replace <code>if (newwidth == \"10\"){} else</code> with <code>if (newwidth !== 10) {</code>. Instead of doing nothing in the true case, switch the comparison and skip the else. You can also compare directly with the <em>number</em> 10 (using the strict equality operator) instead of doing a string comparison.</p></li>\n<li><p>Function declarations are technically not legal inside <code>if</code> statements in ECMAScript (they are only allowed at the global scope, or the top level of a function). Browsers tend to support it as an extension, but they behave differently and it can cause problems, so it's best to avoid that. Function expressions are fine, so I assigned an anonymous function directly to <code>window.onresize</code> and called it through that. You could also assign the function to a variable (replace <code>function resize() {...}</code> with <code>var resize = function() {...};</code>).</p></li>\n<li><p>Instead of calling <code>document.getElementById('content')</code> three times, store the style object in a variable and reference that. You'll gain a speed and file-size advantage.</p></li>\n<li><p>Semicolons aren't needed after function declarations or after an <code>if</code> statement block.</p></li>\n</ol>\n\n<p>Here's what I ended up with:</p>\n\n<pre><code>// CSS calc() replacement\nfunction calcfailback() {\n var d = document.createElement('div');\n\n // 1\n var body = document.getElementsByTagName('body')[0];\n body.appendChild(d);\n d.style.visibility = 'hidden';\n d.style.width = \"-webkit-calc(10px)\";\n d.style.width = \"-o-calc(10px)\"; \n d.style.width = \"-moz-calc(10px)\"; \n d.style.width = \"calc(10px)\"; \n var newwidth = d.offsetWidth;\n\n // 2\n if (newwidth !== 10) {\n // 3\n window.onresize = function() {\n // 4\n var contentStyle = document.getElementById('content').style;\n contentStyle.height = window.innerHeight - 40 + 'px';\n contentStyle.width = window.innerWidth - 300 +'px';\n contentStyle.height = window.innerHeight - 40 + 'px';\n };\n window.onresize();\n } // 5\n body.removeChild(d);\n} // 5\nwindow.onload = calcfailback;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T02:22:26.220",
"Id": "23291",
"Score": "0",
"body": "Thanks for the |var xxx = function| tip. I didn't know it was not \"allowed\" to use functions directly. :)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T02:28:13.173",
"Id": "23292",
"Score": "0",
"body": "@SnippetSpace Actually, I should clarify that (I left out some words when I was editing that sentence). Function declarations are only legal in the global scope, or directly inside another function. In other words, not inside `if`, `while`, etc. blocks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T13:12:13.583",
"Id": "23325",
"Score": "0",
"body": "Here is the final code :) http://pastebin.com/Bdp7rbUa"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-08-07T01:51:06.950",
"Id": "14394",
"ParentId": "14392",
"Score": "3"
}
},
{
"body": "<p>There's no reason to check for the <code>-o-</code> prefix. Opera under the Presto engine never had support for <code>calc()</code>, prefixed or otherwise. Opera under the Blink engine supports it without prefixes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-10T04:20:14.873",
"Id": "62486",
"ParentId": "14392",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "14393",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T00:50:07.130",
"Id": "14392",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"css"
],
"Title": "calc() fallback script"
}
|
14392
|
<p>I have written a small Windows application that draws India's flag in the window. I am very new to using Visual C++ and I want to understand if my code can be improved further.</p>
<pre><code>#include "afxwin.h"
#include <math.h>
class CMyApp : public CWinApp
{
public:
virtual BOOL InitInstance ();
};
class CMainWindow : public CFrameWnd
{
public:
CMainWindow();
protected:
afx_msg void OnPaint();
DECLARE_MESSAGE_MAP();
};
CMyApp myAPP;
BOOL CMyApp::InitInstance()
{
m_pMainWnd = new CMainWindow;
m_pMainWnd->ShowWindow(m_nCmdShow);
m_pMainWnd->UpdateWindow();
return TRUE;
}
BEGIN_MESSAGE_MAP (CMainWindow, CFrameWnd)
ON_WM_PAINT()
END_MESSAGE_MAP()
CMainWindow::CMainWindow ()
{
Create(NULL,_T("India's Flag"), WS_OVERLAPPEDWINDOW );
}
void IndiaFlag(CDC &dc, int x, int y)
{
dc.SetBkMode(TRANSPARENT);
CRect rect;
CPen pen(PS_SOLID, 1, RGB(0,0,0));
CPen *oldPen = dc.SelectObject(&pen);
{
CBrush brush(RGB(255,130,0));
CBrush *oldBrush = dc.SelectObject(&brush);
dc.Rectangle(x,y,x+200,(y+50));
}
{
CBrush brush(RGB(255,255,255));
CBrush *oldBrush = dc.SelectObject(&brush);
dc.Rectangle(x,(y+50),(x+200),(y+100));
CPen pen2(PS_SOLID, 1,RGB(0,0,255));
CPen *oldPen = dc.SelectObject(&pen2);
dc.Ellipse((x+75),(y+50),(x+125),(y+100));
double Nx,Ny;
for (int angle=0;angle<360; angle+=15)
{
int angle2 = angle;
double length = 25*(cos(double(angle2 *(3.14159265 / 180))));
double len2 = 25*(sin(double(angle2 *(3.14159265 / 180))));
int originX = (x+100);
int originY = (y+75);
Nx = originX + length;
Ny = originY - len2;
dc.MoveTo(originX,originY);
dc.LineTo(Nx,Ny);
}
}
{
CBrush brush(RGB(34,139,34));
CBrush *oldBrush = dc.SelectObject(&brush);
dc.Rectangle(x,(y+100),(x+200),(y+150));
}
}
void CMainWindow::OnPaint ()
{
CPaintDC dc(this);
IndiaFlag(dc, 150, 150);
}
</code></pre>
<hr>
<p>In case you wondered, this is what the Indian flag looks like:</p>
<p><img src="https://i.stack.imgur.com/F2mQW.png" alt="Indian flag"></p>
|
[] |
[
{
"body": "<p>IMO, this code seems ok!</p>\n\n<p>To have a better clarity, you could create some functions for the drawing parts so that you India flag is made of smaller function. For example, for the inda flag, I would create a \"drawColoredRectangle\" and \"drawCircleStar\" just to make in clearer.</p>\n\n<p>But for the rest, I think it's ok!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T17:36:17.523",
"Id": "23344",
"Score": "2",
"body": "For sure this code doesn't seem to be any OK."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T13:28:36.197",
"Id": "14406",
"ParentId": "14397",
"Score": "-3"
}
},
{
"body": "<p>Consider replacing any literal constants with symbols (macros, enums, functions).\nThis should help understand the code better.</p>\n\n<p>For example:</p>\n\n<pre><code>#define BLACK RGB(0,0,0)\n</code></pre>\n\n<p>In combination with:</p>\n\n<pre><code>CPen pen(PS_SOLID, 1, BLACK)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T15:00:27.337",
"Id": "23329",
"Score": "0",
"body": "Good point! Didn't notice that at first read."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T17:38:05.507",
"Id": "23345",
"Score": "0",
"body": "Why don't just use `CPen blackSolidPen(PS_SOLID, 1, BLACK)`? It's not the case for `#define`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T18:36:51.520",
"Id": "23350",
"Score": "0",
"body": "This might be a bad example. Frankly, I prefer to stay away from #define, but it's the first thing I could think of. And I'm a lousy C/C++ programmer. I like to read it though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T19:01:02.457",
"Id": "23351",
"Score": "0",
"body": "`#define PI (3.14)` is for C, because there is no `const` in C. In C++ there are real `const`s."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T19:08:42.010",
"Id": "23352",
"Score": "0",
"body": "@loki2302, what would be a good way of creating shortcuts for the different colors in C++?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T19:14:22.640",
"Id": "23353",
"Score": "2",
"body": "You don't need colors normally. You need \"tools for drawing colorful things\", like pencils and brushes (`blackSolidBrush`). Even in case you think you really want it, the \"more C++\" approach is like this: `COLORREF const blackColor = RGB(0, 0, 0);`. `COLORREF` is in fact just a number."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T14:18:27.137",
"Id": "14407",
"ParentId": "14397",
"Score": "1"
}
},
{
"body": "<p>Thanks to your method <code>IndiaFlag</code>, I guess you're drawing a flag of India. The problem is, I don't know what it looks like. OK, I gonna google it.</p>\n\n<p>It consists of 3 stripes: orange, white and green (top to bottom) and a sort of a wheel in the center. So, why don't you just say:</p>\n\n<pre><code>int const width = ...\nint const height = ...\nint const stripeHeight = height / 3;\n\ndrawStripe(0, 0, width, stripeHeight, Orange);\ndrawStripe(0, stripeHeight, width, 2 * stripeHeight, White);\ndrawStripe(0, 2 * stripeHeight, width, 3 * stripeHeight, Green);\ndrawWheel(width / 2, height / 2)\n</code></pre>\n\n<p>?</p>\n\n<p>This code describes what your're drawing in fact. There are no brushes or pencils here, because if I ask you what the flag looks like, for sure you're not going to tell me about pencils and brushes and how GDI works. You'll probably say there are 3 stripes and a wheel in the center and that's what I want to hear.</p>\n\n<p>So, why do you write the code like you're not going to tell anyone what happens in there?</p>\n\n<p>Looking at your code, I'd say that all the names you give are terrible:</p>\n\n<pre><code>CBrush brush(RGB(255,255,255));\n</code></pre>\n\n<p>What does it mean? You're only going to have a single brush, so that's why you call it a \"brush\"? Nothing specific about it? If I see a name <code>brush</code> 20 lines later, do you expect me to remember it is white or any specific at all?</p>\n\n<pre><code>CBrush *oldBrush = dc.SelectObject(&brush);\n</code></pre>\n\n<p>An old brush? When I see <code>oldBrush</code> 20 lines later, do you expect me to remember what this brush is? Do YOU know why you need this <code>oldBrush</code>? I see no code where you switch back to it, so why do you even do it?</p>\n\n<pre><code> dc.Rectangle(x,(y+50),(x+200),(y+100));\n</code></pre>\n\n<p>What is <code>x</code> here? Why <code>y+50</code>? What is <code>500</code>? What is <code>200</code>?</p>\n\n<pre><code> CPen pen2(PS_SOLID, 1,RGB(0,0,255));\n</code></pre>\n\n<p>And once again, something called <code>pen2</code>. Is this pen any specific, or you're just telling me you're using 2 pens? Should I care? Etc.</p>\n\n<p>P.S. Procedures/Functions/Methods describe actions, so their names are traditionally <code>DoWhat</code>. Your <code>IndiaFlag</code> violates the principle, because it says <code>What</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-01-25T10:05:28.023",
"Id": "290428",
"Score": "1",
"body": "*\"I see no code where you switch back to it, so why do you even do it?\"* That's a bug. You must reselect the original object into the DC before releasing it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T17:24:00.003",
"Id": "14415",
"ParentId": "14397",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "14415",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T04:45:42.520",
"Id": "14397",
"Score": "4",
"Tags": [
"c++",
"windows"
],
"Title": "Windows application that draws India's flag"
}
|
14397
|
<p>I'm one of those coder/designers that has been at it since day one, but is still getting the hang of several important coding nuances (e.g. OOP for PHP, and concepts such as <a href="http://nikic.github.com/2011/12/27/Dont-be-STUPID-GRASP-SOLID.html" rel="nofollow">this</a>).</p>
<p>In this case, I'm migrating my toolkit from MySQL to PDO. I had considered MySQLi, but a critical mass of stackoverflow leans towards PDO, so ... I defer to experience. I've spent a few weeks in search of the best PDO wrapper class, studying dozens of PDO db wrapper classes on github, sourceforge, google code, etc.</p>
<p>Most of what I found was either kind of absurd, or added excessive complexity, or was over my head. So I opted to cannibalize, recombine and redesign things to work with my coding flow. As I'm new to PHP OOP, and new to PDO, it's likely I'm overlooking major things here.</p>
<p>I'd be most grateful if anyone could help improve this, or shed light on anything I'm not seeing! Thanks :)</p>
<p>Rough docs and examples of use can be found here: <a href="http://www.designosis.com/PDO_class/" rel="nofollow">http://www.designosis.com/PDO_class/</a></p>
<pre><code>class db extends PDO {
private $error = '';
private $crypt_salt = 'somesillystringforsalt'; // min 22 chars alphanumeric
public $querycount = 0;
public function __construct($dsn, $user='', $passwd='') {
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => true
);
try {
parent::__construct($dsn, $user, $passwd, $options);
} catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
public function run($query, $bind=false, $handler=false) {
$this->querycount++;
try {
if ($bind !== false) {
$bind = (array) $bind;
$dbh = $this->prepare( trim($query) );
$dbh->execute( $bind );
} else {
$dbh = $this->query( trim($query) ); // because query is 3x faster than prepare+execute
}
if (preg_match('/^(select|describe|pragma)/i', $query)) {
// if $query begins with select|describe|pragma, either return handler or fetch
return ($handler) ? $dbh : $dbh->fetchAll();
} else if (preg_match('/^(delete|insert|update)/i', $query)) {
// if $query begins with delete|insert|update, return count
return $dbh->rowCount();
} else {
return true;
}
} catch (PDOException $e) {
$this->error = $e->getMessage();
return false;
}
}
private function prepBind($pairs, $glue) {
$parts = array();
foreach ($pairs as $k=>$v) { $parts[] = "`$k` = ?"; }
return implode($glue, $parts);
}
public function update($table, $data, $where, $limit=false) {
if (is_array($data) && is_array($where)) {
$dataStr = $this->prepBind( $data, ', ' );
$whereStr = $this->prepBind( $where, ' AND ' );
$bind = array_merge( array_values($data), array_values($where) );
$sql = "UPDATE `$table` SET $dataStr WHERE $whereStr";
if ($limit && is_int($limit)) { $sql .= ' LIMIT '. $limit; }
return $this->run($sql, $bind);
}
return false;
}
public function insert($table, $data) {
if (is_array($data)) {
$dataStr = $this->prepBind( $data, ', ' );
$bind = array_values( $data );
$sql = "INSERT `$table` SET $dataStr";
return $this->run($sql, $bind);
}
return false;
}
public function delete($table, $where, $limit=false) {
if (is_array($where)) {
$whereStr = $this->prepBind( $where, ' AND ' );
$bind = array_values( $where );
$sql = "DELETE FROM `$table` WHERE $whereStr";
if ($limit && is_int($limit)) { $sql .= ' LIMIT '. $limit; }
return $this->run($sql, $bind);
}
return false;
}
// crypt (one-way encryption)
public function crypt($str, $moresalt='') {
$salt = $moresalt . $this->crypt_salt;
if (CRYPT_BLOWFISH == 1) {
$presalt = (version_compare(PHP_VERSION,'5.3.7','<')) ? '2a' : '2y'; // PHP 5.3.7 fixed stuff
$blowfish_salt = '$'. $presalt .'$07$'. substr($salt, 0, CRYPT_SALT_LENGTH) .'$';
return crypt($str, $blowfish_salt);
}
return sha1($str . $salt);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T10:53:47.743",
"Id": "23315",
"Score": "0",
"body": "Some notes from the link above: I've made UTF8 and FETCH_ASSOC static because I've never needed anything else. Also, the run() function only works with un-named parameters. I really was going for simplicity here ... LESS TYPING :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T11:01:41.840",
"Id": "23316",
"Score": "1",
"body": "I'll come back to this in more detail later, but the first main problem I see is that this class probably shouldn't extend PDO. If you do decide to go that route though, your construtor should take $options as a parameter, not be hard coded. What if you don't even want to use MySQL in the future?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T11:20:48.327",
"Id": "23317",
"Score": "0",
"body": "@Corbin I noticed about half of the PDO wrappers out there extend PDO it one way, the rest use new classes. And I couldn't find any info on why one way was better. I'd be excited to learn *why* it would be preferable to make a new class instead of extending PDO ..."
}
] |
[
{
"body": "<p>I agree with Corbin, this probably shouldn't extend the PDO class. What he means by this is that its too limiting. You are using PDO now, but what if, as he asks, you don't want to use MySQL in the future? then you are stuck rewriting this entire database class because it is entirely hardcoded for MySQL. All databases share some common traits, they can add, remove, update, etc... So if you made this class a little more loosely it could be extended to use any database subtype. And that is the whole point of OOP: Creating reusable objects that can be extended past their initial purpose without refactoring. Now, on to review...</p>\n\n<p>This is purely preference, but for legibility I would consider adding spaces around your operators when doing comparisons. Its the same concept as adding spaces around the equals sign when defining variables.</p>\n\n<pre><code>if ($bind !== false) {\n</code></pre>\n\n<p>ALWAYS, ALLways, always use braces on your statements, even for one-liners. Yes PHP allows this, but even they say this is wrong. In other languages, such as Python, where the braces are not necessary or don't exist, this may be fine, but in PHP it can cause issues with your code. Its just two characters, and not only does it ensure your code doesn't have issues, but it helps with legibility as well. Or, if you fancy one-liners, you may think of using ternary (though some people frown on its use). BTW: you don't need parenthesis around the ternary statement.</p>\n\n<pre><code>if (!is_array($bind)) { $bind = array($bind); }\n//ternary\n$bind = is_array( $bind ) ? $bind : array( $bind );\n</code></pre>\n\n<p>Of course, I don't even think ternary is necessary. I believe you can just typecast it here. You can either do it right after checking if it is not FALSE, or you can do it when you initially set the parameter in the method. Then you should also give it a default array value so that you can check if it is empty instead of FALSE. Type hinting it in the parameter list is the preferred method because PHP wont allow you to use anything else other than the specified parameter type, this will make all of your <code>is_array()...return FALSE</code> checks unnecessary.</p>\n\n<pre><code>$bind = ( array ) $bind;\n//Or\npublic function run( $sql, Array $bind = array(), $handler = FALSE ) {\n</code></pre>\n\n<p>Variable names should almost always be specific and descriptive. There are some exceptions, such as for throw away variables such as iterator counters <code>$i</code> and exceptions <code>$e</code>. There are probably more, but these are two major ones. So a variable, <code>$q</code>, is not descriptive enough.</p>\n\n<p>Consider documenting your REGEX. Not everyone can read it, so trying to figure out what it does can be difficult. For instance, I can't read this alien script, so I have no idea what this does. So I can't tell you if there is some better way that doesn't use REGEX. Typically the tasks I find people using REGEX for can be accomplished more quickly and efficiently with non-REGEX functions, so this is something to consider. If you comment this REGEX, I'll come back and take another look.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>I didn't test this, but it reads right. So admitedly, this is probably not any easier, nor shorter, but it may be faster. Probably not due to all the function calls, I didn't profile it. But this is something you have to keep in mind when using REGEX. REGEX is usually slower than a single string function, or sometimes multiple string functions. This would be a preference call here. Which do you find easier? Which do you find faster? Do you need to worry about speed? Which do you find more legible? Which, taking all of these questions into mind, best fits your requirements? Probably here it will be the REGEX function, but its entirely up to you, just figured I'd show you another way :)</p>\n\n<pre><code>$pointers = array( 'select', 'describe', 'pragma' );\n$editors = array( 'delete', 'insert', 'update' );\n\n$mods = array_merge( $pointers, $editors );\n$lengths = array_map( 'strlen', $mods );\n$max = max( $lengths );\n\n$first = substr( $query, 0, $max );\n\nif( in_array( $first, $pointers ) ) {\n return $handler ? $dbh : $dbg->fetchAll();\n} else if( in_array( $first, $editors ) ) {\n return $dbh->rowCount();\n} else {\n return TRUE;\n}\n</code></pre>\n\n<p><strong>END OF UPDATE</strong></p>\n\n<p>I notice that you are not appending to your <code>$error</code> property but are overwriting it each time. Are you handling the errors as they come up, or are you just ignoring all but the last one? Not that you should be try/catching inside these methods, this is typically done in implementation of the class to avoid repetition.</p>\n\n<p>The <code>&&</code> and <code>AND</code> operators are not the same. You should use <code>&&</code> over <code>AND</code> due to its precedence. But even if you were to use the later rather than the former, it should be in all-caps <code>AND</code> instead of <code>and</code>.</p>\n\n<pre><code>if (is_array($data) && is_array($where)){\n</code></pre>\n\n<p>I would consider using PHP's escape string for the following line. It will enhance legibility in this instance, as the back ticks wont be competing with the single quotes. Also, why <code>$sql1</code> and <code>$sql2</code>? These aren't SQL statements, they are parameters. I would call them <code>$whereParams</code> and <code>$dataParams</code>.</p>\n\n<pre><code>$sql1[] = \"`$k` = ?\";\n</code></pre>\n\n<p>And where did these arrays come from? You are using this variable as an array without ever having declared it. What if this variable had been defined as a string earlier, or, god forbid, it was a global with a string value? Then you would be appending data onto the end of a string instead of the end of an array, and then <code>implode()</code> would not work properly, and then the world would come to a fiery end! Always define your arrays before using them to ensure that they aren't already being used for something else. PHP does allow array syntax to be used on strings.</p>\n\n<pre><code>$sql1 = array();\n$sql2 = array();\n$bind = array();\n</code></pre>\n\n<p>BTW: You seem to be doing this foreach loop quite a bit, even twice is enough to warrant a function/method. This follows the \"Don't Repeat Yourself\" (DRY) Principle, which is a key part of OOP, that and the \"Single Responsibility\" Principle. I use <code>compact()</code> and <code>extract()</code> here, though you may want to consider other methods. Not everyone approves of this method because there is no way to tell that these variables were used, therefore your IDE will not be able to track them and may even throw up some warnings. Its probably best to have it return an array with those two arrays imploded appropriately anyways to avoid having to repeat that task.</p>\n\n<pre><code>private function _getParams( $array ) {\n $params = array();\n $bind = array();\n\n foreach( $array as $k => $v ) {\n $params[] = \"`$k` = ?\";\n $bind[] = $v;\n }\n\n return compact( 'params', 'bind' );\n}\n\nextract( $this->_getParams( $where ) );//$params, $bind\n</code></pre>\n\n<p>Would consider removing all of those <code>implode()</code>s from inline and assigning them to variables to enhance legibility. Lines of code should not become so long, or convoluted, that they become difficult to read. Even the below is starting to look sketchy because of all of the concatenations going on. I would consider using double quotes here or dropping this down to multiple lines.</p>\n\n<pre><code>$dataString = implode( ', ', $sql1 );\n$whereString = implode( ' AND ', $sql2 );\n$sql = 'UPDATE `'. $table .'` SET '. $dataString .' WHERE '. $whereString;\n</code></pre>\n\n<p>Unless this is a version number you are checking for, or there is some other reason that the <code>CRYPT_BLOWFISH</code> constant is set to one \"1\", then it should really use the TRUE/FALSE switch that PHP already provides, then you can just ask about the constant directly. However, this constant came out of nowhere. What if its not been defined? It's not part of either class, so it can't be guaranteed to exist. This method should really be done elsewhere, where this constant, and the others it uses, make more sense in the local scope.</p>\n\n<pre><code>if( CRYPT_BLOWFISH ) {\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T16:49:30.180",
"Id": "23333",
"Score": "0",
"body": "Wow! A buffet of stylistic food for thought. Excellent ideas, well written. Strunk && White material :) Some of the readability issues seem somewhat subjective ... for example, I find `if( blah ) {` much less readable than `if (blah) {` ... but you clearly know what the hell you're talking about. Braces = always, got it, great advice. I commented the REGEX, which basically just checks the first word the query. You said `The && and AND operators are not the same.` ... Huh?? I gotta look into that. Totally agree that those `foreach`s should be a function, I'll edit that tomorrow. THANK YOU!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T17:39:42.370",
"Id": "23346",
"Score": "0",
"body": "@neokio: Stylistics will always be subjective :) I find spaces within the parenthesis makes it easier to distinguish their contents, especially with brace highlighting, but that particular one was unintentional. I wasn't trying to press that style, or any, upon you. Figured I would point them out and let you make that decision."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T17:40:34.850",
"Id": "23347",
"Score": "1",
"body": "I used, more or less, the same explanation that PHP uses for the `&&` and `AND` difference. It's not very helpful. I have yet to come across code where this would be an issue, but it is documented as being different and the community at large uses the `&&` format, so I point it out. **BTW:** I updated the answer for the REGEX. Not really better, but something to look at."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T06:48:33.050",
"Id": "23393",
"Score": "0",
"body": "I've edited the code again to solve DRY principle offenders with `$db->prepBind()`. Thanks again for all the great info and suggestions!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T14:55:07.373",
"Id": "14408",
"ParentId": "14402",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "14408",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T10:51:36.310",
"Id": "14402",
"Score": "1",
"Tags": [
"php",
"pdo"
],
"Title": "PHP PDO wrapper class"
}
|
14402
|
<p><a href="http://projecteuler.net/problem=11" rel="nofollow">Project Euler #11</a> asks to find the largest product of four numbers of a grid, where the four numbers occur consecutive to each other vertically, horizontally, or diagonally.</p>
<p>Here is my solution in Python. In addition to the usual code review, I have 2 extra questions (actually confessions of my laziness):</p>
<ol>
<li><p>Would it be better if I compared products as in traditional way instead of using max(list)? Like:</p>
<pre><code>if (current > max_product):
max_product = current
</code></pre></li>
<li><p>Would it be better if I used proper <code>for</code> loops instead of relying on <code>try</code>? Because in certain cases it gives <code>KeyError</code>. </p></li>
</ol>
<p>Because of these two shortcuts, I feel like I have cheated. Shall I worry about them or just ignore them?</p>
<pre><code>yy = """08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48"""
rows = yy.splitlines()
d = {}
x = 0
for row in rows:
row_cels = row.split()
y = 0
d[x] = {}
for cell in row_cels:
d[x].update({y: int(cell)})
y+=1
x+=1
def product(a, b, al="hori", r=4):
try:
res = 1
for xx in xrange(r):
if al == "hori": # -
res *= d[a][b+xx]
elif al == "verti": # |
res *= d[b+xx][a]
elif al == "dia": # \
res *= d[a+xx][b+xx]
elif al == "diarev": # /
res *= d[a+xx][19-(b+xx)]
return res
except:
return 0
hori = []
verti = []
dia = []
diarev = []
for x in xrange(0, 20):
for y in xrange(0, 20):
hori.append(product(x,y))
verti.append(product(x, y, "verti"))
dia.append(product(x, y, "dia"))
diarev.append(product(x, y, "diarev"))
print max(max(hori), max(verti), max(dia), max(diarev))
</code></pre>
|
[] |
[
{
"body": "<p>The problem is pretty trivial and you should only check the index ranges and don't use </p>\n\n<pre><code>for x in xrange(0, 20):\n for y in xrange(0, 20):\n</code></pre>\n\n<p>but </p>\n\n<pre><code>for x in xrange(16):\n for y in xrange(16):\n</code></pre>\n\n<p>My version:</p>\n\n<pre><code>d = [map(int, row.split()) for row in open('20x20.txt').read().splitlines()]\nvalue = 0\nfor m in xrange(16):\n for n in xrange(16):\n value = max(value,\n # rows\n d[m][n] * d[m][n + 1] * d[m][n + 2] * d[m][n + 3],\n d[m + 1][n] * d[m + 1][n + 1] * d[m + 1][n + 2] * d[m + 1][n + 3],\n d[m + 2][n] * d[m + 2][n + 1] * d[m + 2][n + 2] * d[m + 2][n + 3],\n d[m + 3][n] * d[m + 3][n + 1] * d[m + 3][n + 2] * d[m + 3][n + 3],\n # cols\n d[m][n] * d[m + 1][n] * d[m + 2][n] * d[m + 3][n],\n d[m][n + 1] * d[m + 1][n + 1] * d[m + 2][n + 1] * d[m + 3][n + 1],\n d[m][n + 2] * d[m + 1][n + 2] * d[m + 2][n + 2] * d[m + 3][n + 2],\n d[m][n + 3] * d[m + 1][n + 3] * d[m + 2][n + 3] * d[m + 3][n + 3],\n # diag\n d[m][n] * d[m + 1][n + 1] * d[m + 2][n + 2] * d[m + 3][n + 3],\n d[m + 3][n] * d[m + 2][n + 1] * d[m + 1][n + 2] * d[m][n + 3])\nprint('Max value = %d' % value)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T14:26:26.827",
"Id": "23406",
"Score": "0",
"body": "Hmm. Hardcoding all these calculations looks icky. I’d write a tiny helper functions do do the calculation given a 4-tuple of offsets in a 4x4 field (call as e.g. `get(m, n, 1, 4, 9, 13)` to get the second row in row-major layout)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T16:05:38.397",
"Id": "23412",
"Score": "0",
"body": "May be your idea is correct for a huge code, but such hardcoding makes the code very fast (I would bet that a code optimizer just loves that :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-03T08:53:34.987",
"Id": "39901",
"Score": "0",
"body": "Upvoted, it's a great answer, even though a version without the unrolled loops would have been nice."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T12:44:50.693",
"Id": "14449",
"ParentId": "14405",
"Score": "1"
}
},
{
"body": "<ol>\n<li>It's OK to use <code>max()</code>, reimplementing it yourself won't save time, especially since the Python version is possibly faster if it's written in C. It's possible to be more concise and clearer though: <code>max(hori + verti + dia + diarev)</code>.</li>\n<li>You should use a list of list to represent a matrix, not a list of dictionaries. As <code>cat_baxter</code> points out, <code>d = [map(int, row.split()) for row in open('20x20.txt').read().splitlines()]</code> is enough to populate <code>d</code>. However if you're not familiar with list comprehensions and map, it's OK to use normal loops.</li>\n<li>Python doesn't really have constants, but a convention is to do <code>VERTI = \"verti\"</code> and then use <code>VERTI</code> everywher, denoting that it is a constant (\"verti\" is not a good name, by the way, \"vertical\" is better. Use code completion.)</li>\n<li><code>try: ... except: ...</code> is bad practice, you need to catch specific exceptions (<code>KeyError</code> in this case). And you need to understand why those errors are thrown! This could be a bug in your code.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-03T08:52:54.843",
"Id": "25759",
"ParentId": "14405",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T11:30:40.377",
"Id": "14405",
"Score": "5",
"Tags": [
"python",
"programming-challenge",
"matrix"
],
"Title": "Finding the largest product of four consecutive numbers in a grid"
}
|
14405
|
<p>As a beginner, I wrote the following python script that solves warrant 1 of <a href="http://mutcd.fhwa.dot.gov/pdfs/2009r1r2/part4.pdf" rel="nofollow">this document - pp 436-438</a>.</p>
<p>My solution, although works, seems to me as poorly designed and highly unmaintanable. I was thinking of putting talbe 4C-1 condition A/B as numpy arrays and use mapping to interpolate. I would also like to get rid of my "standard" ifs in the document.</p>
<p>How would you recommend I refactor the code so it is "professionally", more eficient, shorter, and of all correctly done.</p>
<p>Thanks</p>
<pre><code>"""
Traffic Warrant 1
"""
def is_warranted_1(pop, spd_maj, vph_maj, vph_min,
lanes_maj, lanes_min, standard):
if standard == 1:
#Standard 1: (condition A) or (Condition B)
#8 hours used for condition a could be different than condition B
if lanes_maj == lanes_min == 1:
return (vph_maj >= 500 and vph_min >= 150) or (vph_maj >= 750 and vph_min >= 75)
if lanes_maj >= 2 and lanes_min == 1:
return (vph_maj >= 600 and vph_min >= 150) or (vph_maj >= 900 and vph_min >= 75)
if lanes_maj >= lanes_min >= 2:
return (vph_maj >= 600 and vph_min >= 200) or (vph_maj >= 900 and vph_min >= 100)
if lanes_maj == 1 and lanes_min >= 2:
return (vph_maj >= 500 and vph_min >= 200) or (vph_maj >= 750 and vph_min >= 100)
if standard == 2:
#Standard 2: (condition A) and (Condition B)
if lanes_maj == lanes_min == 1:
return (vph_maj >= 400 and vph_min >= 120) and (vph_maj >= 600 and vph_min >= 60)
if lanes_maj >= 2 and lanes_min == 1:
return (vph_maj >= 480 and vph_min >= 120) and (vph_maj >= 720 and vph_min >= 60)
if lanes_maj >= lanes_min >= 2:
return (vph_maj >= 480 and vph_min >= 160) and (vph_maj >= 720 and vph_min >= 80)
if lanes_maj == 1 and lanes_min >= 2:
return (vph_maj >= 500 and vph_min >= 160) and (vph_maj >= 600 and vph_min >= 80)
if standard == 3:
#Standard 3: rural area / Condition A or condition B
if pop <= 10000 or spd_maj >= 40:
if lanes_maj == lanes_min == 1:
return (vph_maj >= 350 and vph_min >= 105) or (vph_maj >= 525 and vph_min >= 53)
if lanes_maj >= 2 and lanes_min == 1:
return (vph_maj >= 420 and vph_min >= 105) or (vph_maj >= 630 and vph_min >= 53)
if lanes_maj >= lanes_min >= 2:
return (vph_maj >= 420 and vph_min >= 140) or (vph_maj >= 630 and vph_min >= 70)
if lanes_maj == 1 and lanes_min >= 2:
return (vph_maj >= 350 and vph_min >= 140) or (vph_maj >= 525 and vph_min >= 70)
if standard == 4:
#Standard 4: rural area / last measure / Condition A and Condition B
if pop <= 10000 or spd_maj >= 40:
if lanes_maj == lanes_min == 1:
return (vph_maj >= 280 and vph_min >= 84) and (vph_maj >= 420 and vph_min >= 42)
if lanes_maj >= 2 and lanes_min == 1:
return (vph_maj >= 336 and vph_min >= 84) and (vph_maj >= 504 and vph_min >= 42)
if lanes_maj >= lanes_min >= 2:
return (vph_maj >= 336 and vph_min >= 112) and (vph_maj >= 504 and vph_min >= 56)
if lanes_maj == 1 and lanes_min >= 2:
return (vph_maj >= 280 and vph_min >= 112) and (vph_maj >= 420 and vph_min >= 56)
import random
def test():
for i in range(1, 20):
pop = random.choice(range(5000,100000, 500))
spd_maj = random.choice(range(35,65, 5))
vph_maj = random.choice(range(200,2000, 50))
vph_min = random.choice(range(20,1000, 25))
lanes_maj = random.choice(range(1,4))
lanes_min = random.choice(range(1,4))
standard = random.choice(range(1,4))
result = is_warranted_1(pop, spd_maj, vph_maj, vph_min,
lanes_maj, lanes_min, standard)
print "pop: %s, spd_mmaj: %s, vph_maj: %s, vph_min: %s, lanes_maj: %s, \
lanes_min: %s, stnadard: %s. the result is %s" % (pop, spd_maj,
vph_maj, vph_min, lanes_maj, lanes_min, standard, result)
if __name__ == "__main__":
test()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T16:42:33.347",
"Id": "23332",
"Score": "0",
"body": "Well, I like the functional style. The only question is - can one use less code to compute the same result."
}
] |
[
{
"body": "<p><code>lanes_maj >= lanes_min >= 2</code> means <code>lanes_maj >= lanes_min and lanes_min >= 2</code> and it is different from <code>lanes_maj >= 2 and lanes_min >= 2</code>.</p>\n\n<p>You should probably raise ValueError if none of the conditions met instead of returning None implicitly.</p>\n\n<p>Tests should not require a human i.e., supply both input and expected output. You could use a random input if you compare two different implementations of the same function.</p>\n\n<p>Don't optimize for speed unless your profiler says so.</p>\n\n<p>There is no need to repeat the same code four times. You could put the limits into a nested list/tuple/namedtuple (don't repeat the same limit more more than once). To simplify <code>warranted()</code> function you could generate an additional data from it. Given generated data the implementation could look like:</p>\n\n<pre><code>lanes_limits = standard_limits[standard-1]\nif lanes_maj == lanes_min == 1:\n limits = lanes_limits[0]\nelif lanes_maj >= 2 and lanes_min == 1:\n limits = lanes_limits[1]\nelif ...\n# don't forget to check `if pop <= 10000 or spd_maj >= 40:` for standard 3,4\nand_or = op[standard-1]\nreturn and_or((vph_maj >= limits.a.maj and vph_min >= limits.a.min), \n (vph_maj >= limits.b.maj and vph_min >= limits.b.min))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T22:34:07.110",
"Id": "14427",
"ParentId": "14409",
"Score": "2"
}
},
{
"body": "<p>This is the first long answer I've ever written, so bear with me if the writing isn't the best. I've tried to convey my thought process and analysis of the problem.</p>\n\n<p>First, notice that each of the two values you're comparing against (Vehicles per hour on major street, Vehicles per hour on higher-volume\nminor-street approach) depend ONLY on the respective number of lanes. For example, in standard one, condition A, if lanes_maj == 1, then we only care about vph_maj >= 500. You don't need four separate conditions for this; just figure out what your limits are and then do one comparison:</p>\n\n<pre><code>vph_maj_limit_a = 500 if lanes_maj == 1 else 600\nvph_min_limit_a = 150 if lanes_min == 1 else 200\nvph_maj_limit_b = 750 if lanes_maj == 1 else 900\nvph_min_limit_b = 75 if lanes_min == 1 else 100\n... etc ...\nreturn (vph_maj >= vph_maj_limit_a and vph_min >= vph_min_limit_a) and ... etc ...\n</code></pre>\n\n<p>Next, since all the logic that checks if the vph's are above their limits is the same for all standards, we could use an array instead of a literal value, and index on the standard. This requires that we turn the standard into a 0-based index, which isn't hard, we just subtract 1. Also, in the example I gave, each entry in the list is a 2-tuple; the first one for if the number of lanes is 1, the second if the number of lanes is greater than 1. So we need to calculate the index, which is also easy, and we only need to do it once at the top of the function:</p>\n\n<pre><code>condition_a_maj_limits = ((500, 600), (400, 480), (350, 420), (280, 336))\n\ndef blah(...whatever...):\n\n maj_index = 0 if lanes_maj == 1 else 1\n standard_index = standard - 1\n ...\n vph_maj_limit_a = condition_a_maj_limits[standard_index][maj_index]\n ... etc ...\n return (vph_maj >= vph_maj_limit_a and vph_min >= vph_min_limit_a) and ... etc ...\n</code></pre>\n\n<p>Now, I only wrote out the limits for vph on the major street for condition A, and that was a pain. But notice that the percentages for each limit in the chart are literally percentages of the max limit. I.e., the 80% limit is 80% of the 100% limit. So we could programmatically create the chart. This might be problematic if the chart changes to add an exception or something, but for now, it's regular.</p>\n\n<pre><code>percentages = (1, 0.8, 0.7, 0.56)\ncondition_a_maj_limits = [(500*percentage, 600*percentage) for percentage in percentages]\n</code></pre>\n\n<p>I've used a list comprehension to quickly create the list based on the percentages and the 100% value. Notice that the only difference between each limits list is the condition and whether or not it's major/minor. And all that's really used to generate that list is the pair of values for 100%; first the one where lanes_maj == 1 and then the one for more than 1 lane. So we should write a function to reuse the code instead of copy/pasting it:</p>\n\n<pre><code>def gen_limit_list(one_lane_limit, multi_lane_limit):\n return [(one_lane_limit*p, multi_lane_limit*p) for p in percentages]\n\n...\ncondition_a_maj_limits = gen_limit_list(500, 600)\n</code></pre>\n\n<p>We might as well make a function for each of the conditions, which only depend on the standard, the number of lanes, and the vph's:</p>\n\n<pre><code>def condition_a(standard, vph_maj, vph_min, lanes_maj, lanes_min):\n maj_index = 0 if lanes_maj == 1 else 1\n min_index = 0 if lanes_min == 1 else 1\n standard_index = standard - 1\n maj_limit = condition_a_maj_limits[standard_index][maj_index]\n min_limit = condition_a_min_limits[standard_index][min_index]\n return vph_maj >= maj_limit and vph_min >= min_limit\n</code></pre>\n\n<p>Each different standard has a unique combination of whether or not we check pop, etc, and whether or not we need both conditions or at least one (and vs or). So let's make a separate function for each.</p>\n\n<pre><code>def standard_1(pop, spd_maj, vph_maj, vph_min, lanes_maj, lanes_min):\n cond_a = condition_a(1, vph_maj, vph_min, lanes_maj, lanes_min)\n cond_b = condition_b(1, vph_maj, vph_min, lanes_maj, lanes_min)\n return cond_a or cond_b\n\ndef standard_4(pop, spd_maj, vph_maj, vph_min, lanes_maj, lanes_min):\n if pop <= 10000 or spd_maj >= 40:\n cond_a = condition_a(1, vph_maj, vph_min, lanes_maj, lanes_min)\n cond_b = condition_b(1, vph_maj, vph_min, lanes_maj, lanes_min)\n return cond_a and cond_b\n else:\n return False\n</code></pre>\n\n<p>Might as well get those conditions from a function to avoid having those long ugly lines in four places:</p>\n\n<pre><code>def get_conditions(standard, vph_maj, vph_min, lanes_maj, lanes_min):\n cond_a = condition_a(standard, vph_maj, vph_min, lanes_maj, lanes_min)\n cond_b = condition_b(standard, vph_maj, vph_min, lanes_maj, lanes_min)\n return cond_a, cond_b\n\ndef standard_1(pop, spd_maj, vph_maj, vph_min, lanes_maj, lanes_min):\n cond_a, cond_b = get_conditions(1, vph_maj, vph_min, lanes_maj, lanes_min)\n return cond_a or cond_b\n</code></pre>\n\n<p>Since all our standard functions have the same parameter list, we can put them in a list and dynamically select the right one:</p>\n\n<p>standards_list = (standard_1, standard_2,...etc)</p>\n\n<p>Then our whole warrant function ends up looking like this:</p>\n\n<pre><code>def is_warranted_1(pop, spd_maj, vph_maj, vph_min,\n lanes_maj, lanes_min, standard):\n\n return standards_list[standard-1](pop, spd_maj, vph_maj, vph_min, lanes_maj, lanes_min)\n</code></pre>\n\n<p>Here's the final code after some more reductions. This approach is better because it captures the process of looking up the values in the table and comparing them to your parameters rather than just writing out every possibility. It's also much easier to maintain, because if one of the values in the table changes, you only need to change it in one place. Also, very little code is repeated; code duplication is evil.</p>\n\n<pre><code>from collections import namedtuple\n\n# Each standard uses a different set of pairs of vehicle per hour limits, \n# each of which are a certain percentage of a base limit pair.\n\npercentages = (1.00, .80, .70, .56)\n\ndef gen_limit_list(single_lane_limit, multi_lane_limit):\n return tuple((single_lane_limit*p, multi_lane_limit*p) for p in percentages)\n\n# Each condition has a different pair of limits for major and minor streets depending on the standard.\nlimits_a_major = gen_limit_list(500, 600)\nlimits_a_minor = gen_limit_list(150, 200)\nlimits_b_major = gen_limit_list(750, 900)\nlimits_b_minor = gen_limit_list(75, 100)\n\nParams = namedtuple(\"Params\", (\"standard\", \"vph_major\", \"vph_minor\", \"lanes_major\", \"lanes_minor\", \"pop\", \"spd_major\"))\n\ndef get_limit(num_lanes, limits, standard):\n # Arrays are 0-indexed, so Standard 1 is at index 0 and so on.\n standard_index = p.standard - 1\n # Limits is a list of pairs of limits, such as what gen_limit_list returns.\n index = 0 if num_lanes == 1 else 1\n limit = limits[standard_index][index]\n return limit\n\ndef get_condition(p, limits_major, limits_minor):\n major_limit = get_limit(p.lanes_major, limits_major, p.standard)\n minor_limit = get_limit(p.lanes_minor, limits_minor, p.standard)\n return p.vph_major >= major_limit and p.vph_minor >= minor_limit\n\ndef is_warranted_1(p):\n cond_a = get_condition(p, limits_a_major, limits_a_minor)\n cond_b = get_condition(p, limits_b_major, limits_b_minor)\n # If standard is 1 or 2, then we ignore whether or not it's rural.\n # Standards 1 and 3 require either condition to be true; standards 2 and 4 require both conditions to be true.\n is_rural = p.pop <= 10000 or p.spd_major >= 40\n if p.standard in (1, 2) or is_rural: \n if p.standard in (1, 3):\n return cond_a or cond_b\n else:\n return cond_a and cond_b\n else:\n # This is reached only when the city is not rural AND we're applying standard 3 or 4.\n return False\n\ndef test():\n from random import randrange\n for i in range(1, 20):\n p = Params(\n pop = randrange(5000, 100000, 500),\n spd_major = randrange(35, 65, 5),\n vph_major = randrange(200, 2000, 50),\n vph_minor = randrange(20, 1000, 25),\n lanes_major = randrange(1, 4),\n lanes_minor = randrange(1, 4),\n standard = randrange(1, 4)\n )\n print \"Test %d:\\n\" % i\n\n for key, value in p._asdict().iteritems():\n print \"%s: %s\" % (key, value)\n print \"The warrant is satisfied.\" if is_warranted_1(p) else \"The warrant is not satisfied.\"\n\n print \"\"\n\nif __name__ == \"__main__\":\n test()\n</code></pre>\n\n<p>Note that I haven't touched on object oriented programming at all. Another approach would be to create a Standard class with objects that know about the relevant limits and how to check if they're satisfied.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T20:21:11.520",
"Id": "14509",
"ParentId": "14409",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "14509",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T15:39:35.963",
"Id": "14409",
"Score": "2",
"Tags": [
"python",
"numpy"
],
"Title": "Simple arithmetic in Python"
}
|
14409
|
<p>I'm working on a simple time sheet webapp. I have created the following query (simplified - I actually have several mapped columns of a similar type to <code>project_id</code>) to generate test data:</p>
<pre><code>INSERT INTO `entries` (`entry_id`, `user_id`, `project_id`, `date`, `comment`, `hours`)
VALUES
( null,
0,
(SELECT `project_id` FROM projects ORDER BY RAND() LIMIT 1),
CURRENT_DATE(),
'# TEST DATA #',
(SELECT ROUND((0.25 + RAND() * (24 - 0.24)), 2))
);
</code></pre>
<p>I'm currently running this query inside a PHP loop.</p>
<p>This code is currently adequate for my needs <em>now</em>, as I can iterate 50 loops in 0.3037 seconds. However, I fear that when it comes time to test large data sets (searching and report generation for <code>rows > 1 000 000</code>), I may run into problems creating them.</p>
<p>How can I optimize this algorithm? Should I consider using a stored procedure? Or should I just not worry about it, and run the loop to longer iterations, more times?</p>
<pre><code>DROP PROCEDURE IF EXISTS `create_test_entries`;
DELIMITER //
CREATE PROCEDURE `create_test_entries` (IN number INT)
LANGUAGE SQL
DETERMINISTIC
SQL SECURITY INVOKER
COMMENT 'Creates `number` of random test entries in the timesheet'
BEGIN
DECLARE i INT;
SET i = 0;
WHILE i < number DO
INSERT INTO `entries` (`entry_id`, `user_id`, `project_id`, `department_id`, `task_id`, `date`, `comment`, `hours`)
VALUES
( null,
0,
(SELECT `project_id` FROM projects ORDER BY RAND() LIMIT 1),
CURRENT_DATE(),
'# TEST DATA #',
(SELECT ROUND((0.25 + RAND() * (24 - 0.24)), 2))
);
SET i = i + 1;
END WHILE;
END //
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T17:12:22.653",
"Id": "23341",
"Score": "0",
"body": "Stored procedures? http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T18:43:05.690",
"Id": "23437",
"Score": "0",
"body": "So, what's about your original question? Is this approach any faster? :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T18:56:07.720",
"Id": "23438",
"Score": "0",
"body": "@loki2302 I've never run long queries like this before, so basically: is running this type of stored procedure a million times a bad idea, is there a more efficient way to do it, or anything else that jumps out?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T18:59:03.210",
"Id": "23440",
"Score": "0",
"body": "Accessing database million times is always bad idea. If you need to have a million of entries, just make this SP generate you all these entries at once and then call it once."
}
] |
[
{
"body": "<p>It feels like <code>(SELECT project_id FROM projects ORDER BY RAND() LIMIT 1)</code> stands for \"get random but still valid project_id\". You could probably just iterate over all of your projects (with no randomness) and for every project add a random number of records. I don't think it affects your intention but this will probably work faster.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T18:51:19.967",
"Id": "14463",
"ParentId": "14411",
"Score": "2"
}
},
{
"body": "<h3>Performance</h3>\n\n<p>How does this query work?</p>\n\n<blockquote>\n<pre><code>SELECT `project_id` FROM projects ORDER BY RAND() LIMIT 1\n</code></pre>\n</blockquote>\n\n<p>The database will assign a random number to every single record,\nand then find the first.\nSo even though only one record gets selected,\nall records get assigned a random value.\nThis could be expensive when you have a lot of records.</p>\n\n<p>If it's not a problem to load all project ids to memory,\nthen it will be much more efficient.</p>\n\n<h3>Logic in code or database</h3>\n\n<p>Keeping logic in code is a lot easier to manage than keeping it in a stored procedure,\nbecause you can easily add it to version control and track changes to it.\nSo I think stored procedures should be a last resort,\nand only in performance-critical situations.</p>\n\n<p>You could run a million INSERT queries fast if you stick all of them into a single string, and use the <a href=\"https://dev.mysql.com/doc/apis-php/en/apis-php-mysqli.multi-query.html\" rel=\"nofollow noreferrer\">multi_query API</a>.\nBut even a simple loop might be good enough,\nif you use prepared statements.</p>\n\n<h3>Suspicious code in the stored procedure</h3>\n\n<p>In the posted stored procedure,\nthe columns in the <code>INSERT</code> and in the <code>SELECT</code> sub-query don't match:\nit looks like <code>CURRENT_DATE()</code> comes in the place of <code>department_id</code>.\nI guess it was a copy-paste error in the question,\nbut I think it's worth pointing out anyway.</p>\n\n<blockquote>\n<pre><code> INSERT INTO `entries` (`entry_id`, `user_id`, `project_id`, `department_id`, `task_id`, `date`, `comment`, `hours`)\n VALUES\n ( null,\n 0,\n (SELECT `project_id` FROM projects ORDER BY RAND() LIMIT 1),\n CURRENT_DATE(),\n '# TEST DATA #',\n (SELECT ROUND((0.25 + RAND() * (24 - 0.24)), 2))\n );\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-29T19:31:05.147",
"Id": "176820",
"ParentId": "14411",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "14463",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T16:41:11.527",
"Id": "14411",
"Score": "3",
"Tags": [
"performance",
"sql",
"mysql",
"unit-testing"
],
"Title": "Creating many random test database entries"
}
|
14411
|
<p>I wrote a script to remove .vb code files when there are corresponding .cs files in a certain directory structure. But I felt like there were some extra statements that I had to put in there that didn't feel natural. Is there a better way to do this check and then action?</p>
<p>Specifically, having to do the <code>foreach</code> at the end didn't seem right to me. I also didn't know if there was a more PowerShell-y way to do the change extension and test-path.</p>
<pre><code>ls . -include *.vb -recurse
| ? { $cs = [System.IO.Path]::ChangeExtension($_.FullName, ".cs"); Test-Path $cs }
| % { rm $_ -force }
</code></pre>
|
[] |
[
{
"body": "<p>You could <a href=\"http://rkeithhill.wordpress.com/2007/11/24/effective-powershell-item-10-understanding-powershell-parsing-modes/\" rel=\"nofollow\">combine expression vs. command mode</a> in PowerShell, process only files (<code>!$_.PSIsContainer</code>) and use regex instead of <code>ChangeExtension</code>:</p>\n\n<pre><code>gci -include *.vb -Recurse |\n ? { (!$_.PSIsContainer) -and (Test-Path ($_.FullName -replace \"\\.vb$\", \".cs\") } |\n % { rm $_ -force } \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T17:05:17.280",
"Id": "23337",
"Score": "0",
"body": "That's a big one, I couldn't figure out why I needed the temporary `$cs` variable; just wrapping it in parens fixes it from encountering \"parameter cannot be found that accepts argument 'System.Object[]'\" (and makes sense now that I look though that article and see the fix). Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T17:07:20.040",
"Id": "23338",
"Score": "1",
"body": "And it looks like I don't need to specify `$_.FullPath`, but can just use `$_` (with either the `ChangeExtension` or `-replace` method)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T17:11:32.890",
"Id": "23340",
"Score": "0",
"body": "It doesn't look like `gci *.vb -recurse` actually recurses. I think I have to specify current directory as the path, then `*.vb` as the filter for recursing to work correctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T17:13:25.930",
"Id": "23342",
"Score": "0",
"body": "you are right: `gci -include *.vb -Recurse` — works much _better_"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T17:19:17.013",
"Id": "23343",
"Score": "0",
"body": "Actually, removing `FullPath` breaks it once you get into the deeper folders, since you're only getting the name by default, not the full path."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T16:53:42.983",
"Id": "14414",
"ParentId": "14412",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "14414",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T16:44:45.683",
"Id": "14412",
"Score": "3",
"Tags": [
"powershell"
],
"Title": "Script to remove .vb files from a directory"
}
|
14412
|
<p>Anyone can play Google Hurdles today. Here is my score: 1.1 second. Is there are way of improving this score and running faster than a second?</p>
<p><a href="http://www.google.com/doodles/hurdles-2012" rel="nofollow">http://www.google.com/doodles/hurdles-2012</a></p>
<pre><code>import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class RunOlim {
private volatile static boolean run=true;
public static void main(String[] args) {
Robot robot = null;
Thread th = new Thread(new Runnable(){
@Override
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
run=false;
}
}
});
th.start();
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
while(run){
robot.keyPress(KeyEvent.VK_RIGHT);
robot.keyRelease(KeyEvent.VK_RIGHT);
robot.keyPress(KeyEvent.VK_LEFT);
robot.keyRelease(KeyEvent.VK_LEFT);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T16:55:48.707",
"Id": "23334",
"Score": "1",
"body": "OK, this was originally [on StackOverflow](http://stackoverflow.com/questions/11850048/google-hurdles-game-gold-medal), and I asked the same thing there: what does the sentence \"Everyone could be played google hurdles today\" mean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T16:58:55.740",
"Id": "23335",
"Score": "0",
"body": "It emphasizes the target in order to make the question clear. I think giving real world example is best way of asking something? Sentences has to be like: \"Everyone must have played google hurdles today\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T17:00:59.637",
"Id": "23336",
"Score": "0",
"body": "I mean that the sentence itself is not even close to an English sentence. Do you mean \"Anyone can play Google Hurdles today\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T20:24:26.140",
"Id": "23358",
"Score": "0",
"body": "I'm confused. How does your code example correlate to Google Doodle for hurdles? And what are you looking to do?"
}
] |
[
{
"body": "<p>There are some general notes about the code, not really performance improvements (however, I have not tested their performance). I guess the real bottleneck could be in the browser/OS/hardware which can't handle more key events.</p>\n\n<p>Anyway, these do not need any other thread:</p>\n\n<ol>\n<li><pre><code>final long endTime = System.nanoTime() \n + TimeUnit.NANOSECONDS.convert(10, TimeUnit.SECONDS);\nwhile (endTime > System.nanoTime()) {\n robot.keyPress(KeyEvent.VK_RIGHT);\n robot.keyRelease(KeyEvent.VK_RIGHT);\n\n robot.keyPress(KeyEvent.VK_LEFT);\n robot.keyRelease(KeyEvent.VK_LEFT);\n}\n</code></pre></li>\n<li><pre><code>final long endTime = System.nanoTime() \n + TimeUnit.NANOSECONDS.convert(10, TimeUnit.SECONDS);\nwhile (endTime > System.nanoTime()) {\n for (int i = 0; i < 100; i++) {\n robot.keyPress(KeyEvent.VK_RIGHT);\n robot.keyRelease(KeyEvent.VK_RIGHT);\n\n robot.keyPress(KeyEvent.VK_LEFT);\n robot.keyRelease(KeyEvent.VK_LEFT);\n }\n}\n</code></pre></li>\n</ol>\n\n<p>Maybe these were your first tries too.</p>\n\n<p>Here is a 3rd one with a <code>ScheduledExecutorService</code>:</p>\n\n<pre><code>public static void main(final String[] args) throws AWTException {\n\n final ScheduledExecutorService scheduledExecutorService = \n Executors.newScheduledThreadPool(1);\n final Runnable stopCommand = new Runnable() {\n @Override\n public void run() {\n run = false;\n }\n };\n scheduledExecutorService.schedule(stopCommand, 10, TimeUnit.SECONDS);\n\n final Robot robot = new Robot();\n\n while (run) {\n robot.keyPress(KeyEvent.VK_RIGHT);\n robot.keyRelease(KeyEvent.VK_RIGHT);\n\n robot.keyPress(KeyEvent.VK_LEFT);\n robot.keyRelease(KeyEvent.VK_LEFT);\n }\n scheduledExecutorService.shutdown();\n}\n</code></pre>\n\n<p>A final note from <em>Clean Code</em>, page 25: </p>\n\n<blockquote>\n <p>Classes and objects should have noun or noun phrase names like <code>Customer</code>, <code>WikiPage</code>,\n <code>Account</code>, and <code>AddressParser</code>. [...] A class name should not be a verb.</p>\n</blockquote>\n\n<p>I'd name it <code>HurdleRunner</code>, for example.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T17:06:48.837",
"Id": "14457",
"ParentId": "14413",
"Score": "2"
}
},
{
"body": "<p>First off, this may not really be an answer to your question. You want to play it fast, but I can tell you how you get a great score. Good enough for showing off, if that's what you're after!</p>\n\n<p>You can vastly improve your score, even on a very slow network.\nAnd you could even gain even more (secret) medals.</p>\n\n<p>Just play Hurdles once so it shows your score, then - e.g. using jQuery - have fun with the DOM:</p>\n\n<pre><code>$('#hplogo_sbt').html('0.1');\n$('#hplogo_sb').find('.hplogo_smh').removeClass('hplogo_smh').addClass('hplogo_smg');\n</code></pre>\n\n<p>That's about it, 0.1 seconds and 3 gold medals (you could get up to 9 without breaking the layout if you have a 0.1 second time, just insert more \"medal\" dom nodes).</p>\n\n<p><img src=\"https://i.stack.imgur.com/oEJfg.png\" alt=\"enter image description here\"></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-24T12:23:09.640",
"Id": "15026",
"ParentId": "14413",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "15026",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T16:45:59.577",
"Id": "14413",
"Score": "2",
"Tags": [
"java",
"performance"
],
"Title": "Can this Google Hurdles code be made to run any faster?"
}
|
14413
|
<p>I am writing a lightweight JSON API, and I come from a PHP background, so I have some questions/reviews about async node.js code.</p>
<p>This is my code so far:</p>
<p><strong>main.js</strong></p>
<pre><code>var http = require('http');
var api = require('./api.js');
api.addRoute({
'method': 'POST',
'url': '/users',
'input': {
'fullName': {
type: String,
required: true,
min: 2,
max: 64
},
'email': {
type: String,
required: true,
match: /^(.*)@(.*).(.*)$/,
min: 2,
max: 64
},
'password': {
type: String,
required: true,
min: 2,
max: 64
}
},
'description': 'Create an user account.'
});
var server = http.createServer(api.handleRequest).listen(3000);
</code></pre>
<p><strong>api.js</strong></p>
<pre><code>var api = exports;
var routes = [];
var postMaxSize = 1000;
var postTotalReceived = 0;
function getInput(req, res, callback){
if(req.method === 'POST' || req.method === 'PUT'){
var queryString = require('querystring');
var inputData = '';
req.on('data', function(data){
if(data.length < postMaxSize && postTotalReceived < postMaxSize){
inputData += data;
postTotalReceived += data.length;
} else {
res.statusCode = 413;
res.end('max-size');
}
});
req.on('end', function(){
callback(queryString.parse(inputData));
});
} else {
callback(false);
}
};
api.addRoute = function(route){
routes.push(route);
}
function getRoute(req, res, callback){
for(var i = 0; i < routes.length; i++){
if(routes[i]['method'] === req.method){ // If the request method matches.
if(typeof(routes[i]['url'] === 'string') && routes[i]['url'] === req.url){
callback(routes[i]);
}
} else {
var matches = req.url.match(routes[i]['url']);
if(matches){
req.urlParameters = [];
for(var j = 1; j < matches.length; j++){ // Skip the first match, which is the url.
req.urlParameters.push(matches[j]);
}
callback(routes[i]);
}
}
}
};
api.handleRequest = function(req, res){
res.setHeader('Content-Type', 'application/json'); // Always return JSON since this is a rest JSON api.
getInput(req, res, function(inputData){
getRoute(req, res, function(route){
if(route){
// Do something.
res.end();
} else {
res.statusCode = 404;
res.end('not-found');
}
});
});
};
</code></pre>
<p>I am just wondering, Node.js sells itself with "Non-blocking", but if on each request I have to do a regex to match the route for example:</p>
<pre><code>/^\/users\/(.*)\//$ -> /users/mike
</code></pre>
<p>The regex has to be executed since Node.js is single threaded. How does it do Regex non blocking? The CPU has to execute the Regex, right?</p>
<p>About the code, my idea was: </p>
<ul>
<li><p>I don't want to use any framework like express, since routing etc. can be done
much more lightweight and I can customize everything, full control etc.</p></li>
<li><p>Each route has automatic input validation, which can be combined with auto generating documentation, for example if a user would request 'GET /' he would get a list of all the routes fully documented with required parameters, optional parameters, description, authentication requirements etc.</p></li>
</ul>
<p>Please take a look at the <code>api.handleRequest</code> function. Am I correctly using callbacks at <code>getInput</code> and <code>getRoute</code>? Or should I <em>only</em> use callbacks at I/O, db calls etc?</p>
<p>The API I am about the build is basically a simple wrapper around Amazon Web Services, MongoDb and maybe later Redis or some other message queue.</p>
|
[] |
[
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li>Not sure why you are not parsing the querystring for <code>GET</code> requests? It seems wrong</li>\n<li><code>if(data.length < postMaxSize && postTotalReceived < postMaxSize)</code> could be <code>if(data.length + postTotalReceived < postMaxSize)</code></li>\n<li>Not sure what happens in your code after setting the <code>413</code>, it seems you have some loose ends there. You could consider redefining callback to <code>function(){}</code></li>\n<li><p>I would not store the routes as an array, the lookup time is too slow in my mind, instead I would store the routes in an object like this:<br></p>\n\n<pre><code>api.addRoute = function(route){\n routes[route.method][route.url] = route;\n}\n</code></pre></li>\n<li>I read your code several times, it seems as if even if the <code>method</code> of a route does not match you will still execute the <code>route</code> if the <code>url</code> matches through a regex. If so, then that is completely wrong.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T15:48:09.960",
"Id": "68725",
"Score": "0",
"body": "Point 2 is not correct"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T15:55:24.950",
"Id": "68727",
"Score": "0",
"body": "@megawac Why do you think so?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T15:59:05.183",
"Id": "68728",
"Score": "0",
"body": "I haven't read his code but the first case will be true for `data.length = postTotalReceived = postMaxSize - 1` while yours will be false or am I missing something"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T16:02:45.977",
"Id": "68729",
"Score": "2",
"body": "You are correct, in my mind that is a bug in the OP code. The OP code will allow the size to be larger than postMaxSize. My suggestion does not allow it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T15:43:15.517",
"Id": "40749",
"ParentId": "14416",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T17:39:26.827",
"Id": "14416",
"Score": "3",
"Tags": [
"javascript",
"regex",
"node.js",
"asynchronous"
],
"Title": "Asynchronous lightweight JSON API"
}
|
14416
|
<p>I have a shell script to mount different remote systems. While it does work, the area I struggle with (not being a programmer) is the logic of the script: it feels quite stilted and there seems to be some unnecessary duplication.</p>
<p>I would appreciate any comments as to how I could improve it - both in terms of the logic, but also any other tips about style or approach.</p>
<pre><code>#!/bin/sh
# mount boxes by SSHFS
usage () {
cat <<EOF
sshmnt -[c,s,u,h]
-c Box1
-s Box2
-u unmount
-h print this message
EOF
}
mnt(){
sshfs jason@"$host":/home/jason /media/"$dir" \
-C -p "$port" \
-o reconnect,IdentityFile=/home/jason/.ssh/id_rsa \
&& ls /media/"$dir"
}
umnt(){
fusermount -u /media/"$dir"
}
# unmounting
if [ "$1" = "-u" ]; then
box=$(mount | grep Box1)
if [ -n "$box" ]; then
dir=Box1
else
dir=Box2
fi
umnt && exit
fi
# check if on LAN
lan="$(ip addr | grep .102/)"
if [ -n "$lan" ]; then
case "$1" in
-c) int=100
;;
-s) int=200
;;
esac
host="192.168.1.$int"
else
host="XXX.XXX.XXX.XXX"
fi
# box specifics
case "$1" in
-c) dir=Box1 port="XXXX"
mnt
;;
-s) dir=Box2 port="XXXX"
mnt
;;
*) usage && exit
;;
esac</code></pre>
<p>I have obscured the relevant ports and hostnames.</p>
|
[] |
[
{
"body": "<p>Your functions shouldn't depend on variables but use specified\nparameters. You always specified variables before calling your function instead of just specifying them as parameters, e.g:</p>\n\n<pre><code>DIR=Box1\nHost=192.168.1.100\nmnt\n</code></pre>\n\n<p>but you can easily write it as</p>\n\n<pre><code>mnt Box1 192.168.1.100\n</code></pre>\n\n<p>I would also only parse your command line arguments in one place and create\na dedicated function for determine the appropriate ip address for your hosts.</p>\n\n<p>I would also remove the ls call from your <code>mnt</code> function as mnt doesn't do what the name suggests. But this is a rather minor issue and I didn't change it in my code.</p>\n\n<pre><code>#!/bin/sh\n# mount boxes by SSHFS\n\nusage () {\n cat <<EOF\nsshmnt -[c,s,u,h]\n -c Box1\n -s Box2\n -u unmount\n -h print this message\n\nEOF\n}\n\nmnt(){\n\n if [ $# -ne 3 ] ; then\n echo \"Wrong parameters for mnt - host dir port\" >&2\n return 1\n fi\n\n host=\"$1\"\n dir=\"$2\"\n port=\"$3\"\n sshfs jason@\"$host\":/home/jason /media/\"$dir\" \\\n -C -p \"$port\" \\\n -o reconnect,IdentityFile=/home/jason/.ssh/id_rsa \\\n && ls /media/\"$dir\"\n}\n\numnt(){\n dir=\"$1\"\n fusermount -u /media/\"$dir\"\n}\n\nget_host(){\n # check if on LAN\n lan=\"$(ip addr | grep .102/)\"\n\n if [ -z \"$lan\" ] ; then\n echo XXX.XXX.XXX.XXX\n return 0\n fi\n\n case \"$1\" in\n Box1) echo 192.168.1.100 ;;\n Box2) echo 192.168.1.200 ;;\n *) echo \"Unknown Parameter\" >&2 && return 1 ;;\n esac\n}\n\ncase \"$1\" in\n -c) mnt $(get_host Box1) Box1 port ;;\n -s) mnt $(get_host Box2) Box2 port ;;\n -u)\n mount | grep Box1 && umnt Box1\n mount | grep Box2 && umnt Box2\n ;;\n *) usage && exit 1;;\nesac\n</code></pre>\n\n<p>Another suggestion is to get rid of all your hard coded paths and texts like, <code>/media/</code>, <code>/home/jason/</code> and <code>jason</code> and replace them with variables, e.g:</p>\n\n<pre><code>MOUNT_PREFIX=/media/\nSSH_KEY=/home/jason/.ssh/id_rsa\nMOUNT_SOURCE=/home/jason\n</code></pre>\n\n<p>and just specify the user for your hosts in <code>~/.ssh/config</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T00:12:35.997",
"Id": "23374",
"Score": "0",
"body": "Thanks Ulrich: that is very helpful. Would you mind expanding on your comment that \"functions shouldn't depend on environment variables but use specified parameters\"? I don't quite follow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T00:20:41.017",
"Id": "23375",
"Score": "0",
"body": "@jasonwryan ok updated the answer - also have a look at the last paragraph about your hard coded values"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T00:37:22.963",
"Id": "23386",
"Score": "0",
"body": "thank you for the added detail; it was a lightbulb moment. The extra variables are also a good suggestion."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T23:54:33.140",
"Id": "14428",
"ParentId": "14424",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "14428",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T21:50:37.180",
"Id": "14424",
"Score": "4",
"Tags": [
"shell",
"sh"
],
"Title": "Mount different remote systems"
}
|
14424
|
<p>This is really not a question. I was looking up this solution but couldn't find it anywhere. Thought of posting it here so it may save someone's time.</p>
<p>Here was my issue: I had a JSON coming from server which was not nested. Lets take example of Movies:</p>
<pre><code>var movies = [
{"name":"Ice Age 3", "language":"English", "year":"2012"},
{"name":"Ice Age 3", "language":"French", "year":"2011"},
{"name":"Ice Age 3", "language":"German", "year":"2013"}
];
</code></pre>
<p>Now effectively speaking, there is no need for server to return it like this, however this was my case and since I was using <code>jquery-template</code> I wanted to have it as a nested JSON object. Something like this:</p>
<pre><code>var movies = [{
"name": "Ice Age 3",
"details": [
{"language": "English", "year": "2012"},
{"language": "French", "year": "2011"},
{"language": "German", "year": "2013"}
]
}];
</code></pre>
<p>Here is the code which I wrote to convert it:</p>
<pre><code>function convert(arr) {
var convertedArray = [];
$(arr).each(function () {
var found = false;
for (var i = 0; i < convertedArray.length; i++) {
if (convertedArray[i].name === this.name) {
found = true;
convertedArray[i].details.push({
"language": this.language,
"year": this.year
});
break;
}
}
if (!found) {
convertedArray.push({
"name": this.name,
"details": [{
"language": this.language,
"year": this.year
}]
});
}
});
return convertedArray;
}
</code></pre>
<p>I am sure there would be a better approach for this. But for me it worked.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T19:39:18.773",
"Id": "23368",
"Score": "0",
"body": "details: { languages: [{}], other: undefined }"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T19:39:49.897",
"Id": "23369",
"Score": "2",
"body": "It's okay to answer your own question, but please pose the question as a question, and post a separate, actual answer. http://meta.stackexchange.com/q/17463/133242"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T19:42:32.077",
"Id": "23370",
"Score": "1",
"body": "\"This is really not a question.\" Cool story bro?"
}
] |
[
{
"body": "<pre><code>var found = false;\n</code></pre>\n\n<p>Using flag is not good practice. </p>\n\n<p>This is better solution:</p>\n\n<pre><code>var movies = [\n {\"name\":\"Ice Age 3\", \"language\":\"English\", \"year\":\"2012\"},\n {\"name\":\"Ice Age 3\", \"language\":\"French\", \"year\":\"2011\"},\n {\"name\":\"Ice Age 3\", \"language\":\"German\", \"year\":\"2013\"},\n {\"name\":\"Ice Age 4\", \"language\":\"German\", \"year\":\"2013\"}\n];\n\nfunction convert(arr) {\n return $.map(unique(arr), function(name){\n return {\n name: name,\n details: $.grep(arr, function(item){\n return item.name == name\n })\n } \n });\n}\n\nfunction unique(arr) {\n var result = [];\n $.map(arr, function(item){\n if ($.inArray(item.name, result))\n result.push(item.name);\n })\n return result;\n}\n\nconsole.log(convert(movies));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T20:34:24.393",
"Id": "23446",
"Score": "0",
"body": "Hi Ivan, Thanks for the wonderful code. However the following input displays the data incorrectly:\nvar movies = [\n {\"name\":\"Ice Age 3\", \"language\":\"English\", \"year\":\"2012\"},\n {\"name\":\"Ice Age 4\", \"language\":\"French\", \"year\":\"2011\"},\n {\"name\":\"Ice Age 3\", \"language\":\"German\", \"year\":\"2013\"},\n {\"name\":\"Ice Age 4\", \"language\":\"German\", \"year\":\"2013\"},\n {\"name\":\"Ice Age 3\", \"language\":\"German\", \"year\":\"2014\"}\n ];"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T20:29:39.033",
"Id": "14431",
"ParentId": "14429",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "14431",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T19:37:58.143",
"Id": "14429",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"json"
],
"Title": "Convert JSON to a different format (nested json)"
}
|
14429
|
<p>I have 4 text columns, a mix of Varchar and Text. I need to find rows in a table where all words searched for are present across the 4 columns.</p>
<p>The 4 columns are:</p>
<ul>
<li>name</li>
<li>type</li>
<li>keywords</li>
<li>description</li>
</ul>
<p>So if someone searches for "london wildlife museum", it would only return rows where all words were found across the 4 columns.</p>
<p>Current code for managing the multiple words:</p>
<pre><code>$words = $_GET['freetext'];
if(empty($words)){
//redirect somewhere else!
}
$parts = explode(" ",trim($words));
$clauses1=array();
foreach ($parts as $part){
//function_description in my case , replace it with whatever u want in ur table
$clauses1[]="vname LIKE '%" . mysql_real_escape_string($part) . "%'";
}
$clause1=implode(' OR ' ,$clauses1);
$parts = explode(" ",trim($words));
$clauses2=array();
foreach ($parts as $part){
//function_description in my case , replace it with whatever u want in ur table
$clauses2[]="vtype LIKE '%" . mysql_real_escape_string($part) . "%'";
}
$clause2=implode(' OR ' ,$clauses2);
$parts = explode(" ",trim($words));
$clauses3=array();
foreach ($parts as $part){
//function_description in my case , replace it with whatever u want in ur table
$clauses3[]="vdesc LIKE '%" . mysql_real_escape_string($part) . "%'";
}
$clause3=implode(' OR ' ,$clauses3);
$parts = explode(" ",trim($words));
$clauses4=array();
foreach ($parts as $part){
//function_description in my case , replace it with whatever u want in ur table
$clauses4[]="vkeywords LIKE '%" . mysql_real_escape_string($part) . "%'";
}
$clause4=implode(' OR ' ,$clauses4);
//select your condition and add "AND ($clauses)" .
$sql="SELECT vid, vname, vsuburb, vtype, vlogo, suburb.sname
FROM venue, suburb
WHERE
venue.vsuburb = suburb.sid
AND (($clause1) OR ($clause2) OR ($clause3) OR ($clause4))";
</code></pre>
<p>Obviously this creates a long list of <code>OR</code>s, but I can't see how to only choose the rows where all words appear.</p>
|
[] |
[
{
"body": "<p>Easy! Change your ORs to ANDs so that the final statement reads:</p>\n\n<p>Your statement essentially needs to look like this:</p>\n\n<p>SELECT * FROM table </p>\n\n<p>WHERE (vname LIKE '%value1%' OR vtype LIKE '%value1%' OR vdesc LIKE '%value1%')</p>\n\n<p>AND (vname LIKE '%value2%' OR vtype LIKE '%value2%' OR vdesc LIKE '%value2%')</p>\n\n<p>AND (vname LIKE '%value3%' OR vtype LIKE '%value3%' OR vdesc LIKE '%value3%')</p>\n\n<p>so it ensures that value1 exists in one of the 4 fields, that value2 exists in one of the 4 fields, and value3 exists in one of the 4 fields, etc.</p>\n\n<p>If that's not sufficient, use PHP to iterate a larger number of results and filter down the results.</p>\n\n<pre><code>$words = $_GET['freetext'];\nif(empty($words)){\n//redirect somewhere else!\n}\n$parts = explode(\" \",trim($words));\n$clauses1=array();\nforeach ($parts as $part){\n //function_description in my case , replace it with whatever u want in ur table\n $clauses1[]=\"vname LIKE '%\" . mysql_real_escape_string($part) . \"%'\";\n}\n$clause1=implode(' AND ' ,$clauses1);\n\n$parts = explode(\" \",trim($words));\n$clauses2=array();\nforeach ($parts as $part){\n //function_description in my case , replace it with whatever u want in ur table\n $clauses2[]=\"vtype LIKE '%\" . mysql_real_escape_string($part) . \"%'\";\n}\n$clause2=implode(' AND ' ,$clauses2);\n\n$parts = explode(\" \",trim($words));\n$clauses3=array();\nforeach ($parts as $part){\n //function_description in my case , replace it with whatever u want in ur table\n $clauses3[]=\"vdesc LIKE '%\" . mysql_real_escape_string($part) . \"%'\";\n}\n$clause3=implode(' AND ' ,$clauses3);\n\n$parts = explode(\" \",trim($words));\n$clauses4=array();\nforeach ($parts as $part){\n //function_description in my case , replace it with whatever u want in ur table\n $clauses4[]=\"vkeywords LIKE '%\" . mysql_real_escape_string($part) . \"%'\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T00:16:52.293",
"Id": "23378",
"Score": "0",
"body": "Wouldn't this make it so it returns only when a single column has every word in the search query, not where every search query is found in a whole row?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T00:17:07.237",
"Id": "23379",
"Score": "0",
"body": "Hi there, thanks for the response, but that requires that all words appear in one column together rather than spanned over all columns."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T00:18:32.053",
"Id": "23380",
"Score": "0",
"body": "Hi @Johnnyoh yes, that's the problem"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T00:19:27.753",
"Id": "23381",
"Score": "0",
"body": "Look at my answer Deepweb."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T00:11:27.320",
"Id": "14433",
"ParentId": "14432",
"Score": "1"
}
},
{
"body": "<p>Change the ORs to ANDs on the final SQL statement. </p>\n\n<pre><code>$sql=\"SELECT vid, vname, vsuburb, vtype, vlogo, suburb.sname \n FROM venue, suburb \n WHERE\n venue.vsuburb = suburb.sid\n AND (($clause1) AND ($clause2) AND ($clause3) AND ($clause4))\";\n</code></pre>\n\n<p>This would make the final query look something like this:</p>\n\n<pre><code>SELECT vid, vname, vsuburb, vtype, vlogo, suburb.sname \nFROM venue, suburb \nWHERE\nvenue.vsuburb = suburb.sid\nAND\n(vname = 'london' OR vname = 'wildlife' OR vname='museum') AND (vtype = 'london' OR vtype = 'wildlife' OR vtype ='museum') AND (vkeywords='london' OR vkeywords='wildlife' OR vkeywords='museum') AND (vdescription='london' OR vdescription='wildlife' OR vdescription='museum')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T00:55:03.860",
"Id": "23388",
"Score": "0",
"body": "Sorry, @johnnyoh this means that one word of the phrase must appear in all columns"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T00:14:13.050",
"Id": "14434",
"ParentId": "14432",
"Score": "0"
}
},
{
"body": "<p>I would suggest you have a look at MySQL's full-text search. Its a better approach then just combining each criteria. It do think it only works on MyISAM.</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/fulltext-natural-language.html\" rel=\"nofollow\">http://dev.mysql.com/doc/refman/5.0/en/fulltext-natural-language.html</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T00:20:12.927",
"Id": "23382",
"Score": "0",
"body": "and for innodb stuff look here: http://stackoverflow.com/questions/1381186/fulltext-search-with-innodb"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T08:46:45.190",
"Id": "23395",
"Score": "0",
"body": "Hi @Rogier, I had tried with this with no success, but went back and have managed to get it working. Major issue getting the Fulltext indexes across the columns but ended up working"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T00:14:51.820",
"Id": "14435",
"ParentId": "14432",
"Score": "2"
}
},
{
"body": "<p>+1 to <em>@Rogier</em>, full-text search seems the best solution. Another idea could be concatenating the <code>name</code>, <code>type</code>, <code>keywords</code> and <code>description</code> attributes and searching in the concatenated attribute:</p>\n\n<pre><code>SELECT ..., CONCAT_WS(' ', name, type, keywords, description) AS c\nFROM ...\nWHERE c LIKE '%value1%' AND c LIKE '%value2%' ...\n</code></pre>\n\n<p>It may possible to store the result of concatenation in a persistent attribute etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T08:47:18.247",
"Id": "23396",
"Score": "0",
"body": "Concat is a good idea, fulltext using MATCH is working now"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T07:25:49.027",
"Id": "14437",
"ParentId": "14432",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "14435",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T23:55:39.173",
"Id": "14432",
"Score": "2",
"Tags": [
"php",
"sql",
"mysql",
"search"
],
"Title": "Multi column search"
}
|
14432
|
<p>I am new to modular JavaScript code, and after reading an article on the Internet, I wrote a very basic calculator. This works fine, but due to some unknown reason, I feel that this code is not well written. I will appreciate it if someone could improve my code below so that it will be helpful with learning modular JavaScript.</p>
<pre><code>$(function () {
$('.button').on('click', function() {
var operator = $(this).attr('name'),
calc = new Calculator('output', 'valOne', 'valTwo', operator);
calc.init();
});
});
</code></pre>
<p><strong>calculator.js</strong></p>
<pre><code>var Calculator = function(eq, valone, valtwo, operator) {
var eqCtl = document.getElementById(eq),
valone = document.getElementById(valone),
valtwo = document.getElementById(valtwo),
op = operator,
init = function() {
op = operator;
val1 = parseInt($(valone).val());
val2 = parseInt($(valtwo).val());
calculation();
},
setVal = function(val) {
eqCtl.innerHTML = val;
},
calculation = function() {
if(op == 'add') {
addition(val1, val2);
}
else if(op == 'sub') {
subtract(val1, val2);
}
else if(op == 'mult') {
multiply(val1, val2);
}
else {
division(val1, val2);
}
},
addition = function(x,y) {
return setVal(x + y);
},
subtract = function(x,y) {
return setVal(x - y);
},
multiply = function(x,y) {
return setVal(x * y);
},
division = function(x,y) {
if( y == 0 ) {
return setVal('cannot divide by 0');
} else {
return setVal(x / y);
}
};
return {
init: init
};
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T03:17:45.947",
"Id": "23559",
"Score": "0",
"body": "Why are you checking for `y == 0` in `division`? Javascript's Numbers can have a value of `Infinity` (or `-Infinity`), which is returned when you divide by 0 and works as you'd expect it to work. It doesn't throw an error."
}
] |
[
{
"body": "<p>I've done this only for addition to make it more readable -</p>\n\n<pre><code>var Calculator = function() { \n\n this.calculate = function(eq, valone, valtwo, op) {\n\n var val1 = parseInt($(valone).val());\n var val2 = parseInt($(valtwo).val()); \n\n var eqCtl = $('#' + eq),\n var operation;\n\n switch(op){\n case 'add' : \n operation = addition;\n break;\n case 'sub':\n //same here\n break;\n default :\n operation = division;\n }\n\n this.addition = function(){\n //for those who could not read the question\n }\n\n return operation.apply(null, [val1, val2]); // to setVal()\n },\n\n addition = function() {\n return setVal(arguments[0] + arguments[1]);\n }\n\n return this;\n};\n</code></pre>\n\n<p>And then use as..</p>\n\n<pre><code>var calc = new Calculator();\n\ncalc.calculate('output', 'valOne', 'valTwo', operator);\n//call as many times as required\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T19:17:59.883",
"Id": "23444",
"Score": "3",
"body": "Why `val1`, `val2` and `addition` are global?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T09:44:59.203",
"Id": "23517",
"Score": "2",
"body": "@RobinMaben You also forgot the `break;` in the switch. Please don't be sloppy when proposing improvements."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T03:28:55.217",
"Id": "23560",
"Score": "0",
"body": "This post introduces a staggering number of errors. Some lines before `var` statements are terminated with commas, which is invalid syntax. `addition` is a leaked global variable. `parseInt`, as written, will fail for input like \"010\". The switch statement is broken. `addition` is much slower due to an entirely unnecessary use of `arguments`. `operator` is a reserved word, so the entire program won't run on some engines. The entire structure is needlessly complex. And the spacing is off in a few places."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T04:45:14.420",
"Id": "23564",
"Score": "0",
"body": "Don't be like that. Keep the OP's code in context."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-11T03:39:42.550",
"Id": "23609",
"Score": "0",
"body": "@RobinMaben I'm sorry if I offended you; my goal was to prevent readers from learning bad habits by assuming accepted answers are always correct, and to help you improve your answer. If you'd like help fixing your code, tell me what part you want help with and I'd be glad to write a more thorough explanation. (also, please start your reply with `@st-boost`, so it appears in my inbox and I don't have to manually check back)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-11T06:53:19.720",
"Id": "23611",
"Score": "0",
"body": "@st-boost: I should apologize for my lack of attention to detail too."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T09:07:29.987",
"Id": "14439",
"ParentId": "14438",
"Score": "-1"
}
},
{
"body": "<p>You should construct the object only once, and then re-use it. (That, or use a \"static\" method.)</p>\n\n<pre><code>$(function () {\n \"use strict\";\n var calculator = new Calculator('output', 'valOne', 'valTwo');\n $('.button').on('click', function() {\n var operator = $(this).attr('name');\n calculator.calculate(operator);\n });\n});\n</code></pre>\n\n<p>Then, inside the <code>Calculator</code> you would initialize the HTML elements for operand1/operand2/output and provide a method that reads the values and outputs the result.</p>\n\n<p>I would just do the operation directly in the switch. Alternatively, you can do something like: <code>var method, result; if(...) {method = add;} ...; result = method(x, y);</code></p>\n\n<pre><code>var Calculator = function (outputId, firstOperandId, secondOperandId) {\n \"use strict\";\n\n var output = document.getElementById(outputId),\n firstOperand = document.getElementById(firstOperandId),\n firstOperand = document.getElementById(secondOperandId);\n return {\n calculate: function (operator) {\n var num1 = +firstOperand.getAttribute('value'),\n num2 = +secondOperand.getAttribute('value'),\n result;\n switch (operator) {\n case 'add':\n result = x + y;\n break;\n case 'sub':\n result = x - y;\n break;\n case 'mult':\n result = x * y;\n break;\n case 'div':\n if (y === 0) {\n //throw new Error('cannot divide by 0');\n result = 'cannot divide by 0';\n } else {\n result = x / y;\n }\n break;\n default:\n // throw new Error(\"invalid operator '\" + operator + \"'\");\n result = \"invalid operator '\" + operator + \"'\";\n }\n output.innerHTML = result;\n return result;\n }\n };\n};\n</code></pre>\n\n<p>Other remarks:</p>\n\n<ul>\n<li>Use <code>===</code> instead of <code>==</code>.</li>\n<li>Inside the if-chain (or switch, YMMV) I would just do the operation directly, instead of calling a one-liner method for it - why make it more complicated than it needs to be?</li>\n<li>I wouldn't default to division, but throw an error instead - maybe write <code>error</code> to the output element?</li>\n<li>The <code>+</code> coerces a numeric value. It's not bullet-proof (<code>\" \" === 0</code>), but it's better than using <code>parseInt</code>, because with parseInt you need to remember to always send a second param <code>10</code> - try <code>parseInt('010')</code> and <code>parseInt('008')</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T05:41:33.647",
"Id": "23567",
"Score": "0",
"body": "Regarding your comments about `parseInt()`, it's worse than that. Even when you remember the radix with `parseInt(val,10)` it still ignores any non-numeric characters at the end of the string, and obviously it doesn't do decimals. So if the user tries to calculate `2.8 + 2.8` they get an answer of `4` because `parseInt(\"2.8\",10)` returns `2` (ignoring everything from the decimal point). If the user enters `\"2abc\"` I think it would be better to explicitly report an error than to just use the `2` returned from `parseInt(\"2abc\",10)`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T12:48:51.557",
"Id": "14482",
"ParentId": "14438",
"Score": "2"
}
},
{
"body": "<p>The concept of creating a <code>new Calculator()</code> with a specified operator and then calling <code>calc.init()</code> to actually perform the operation seems a bit strange. I'd probably have any initialisation built into the constructor, and then have a <code>calc.calculate()</code> method that takes the operation as a parameter.</p>\n\n<p>I don't have time now for a detailed analysis of your code, but one thing I would probably do is make the different operation functions methods of an object:</p>\n\n<pre><code>var operations = {\n \"addition\" : function(x,y) { return setVal(x + y); },\n \"subtract\" : function(x,y) { return setVal(x - y); },\n \"multiply\" : function(x,y) { return setVal(x * y); },\n // etc\n}\n</code></pre>\n\n<p>Because then you can eliminate the if/else structure that decides what function to call and just do this:</p>\n\n<pre><code>calculation = function() {\n if (op in operations)\n operations[op](val1, val2);\n else\n // invalid op requested, so show message, throw exception, whatever\n}\n</code></pre>\n\n<p>If you add more operations in the future, say a <code>toThePowerOf()</code> operation, you'd add it to the <code>operations</code> object but wouldn't need to change the <code>calculation()</code> function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T05:37:01.720",
"Id": "14521",
"ParentId": "14438",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "14439",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T08:57:57.967",
"Id": "14438",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"jquery",
"calculator"
],
"Title": "Basic modular calculator"
}
|
14438
|
<p>I am maintaining an application and have seen something like this</p>
<pre><code>Permission p = new UserModel().GetPermission(userToTestPerrmission, permissionWeCheck);
if(p.CanChange)
//sometihing
else
//something else
</code></pre>
<p>This approach looks a little "dirty" to me. The part I have problems with is this <code>new UserModel().GetPermission()</code>. Is this a typical way to write something like this or should it be like:</p>
<pre><code>var model = new UserModel();
model.GetPermissions(...);
...
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>Is this a typical way to write something like</p>\n</blockquote>\n\n<p>If that’s all the information that is required – yes, why not? I see no problem at all with this approach.</p>\n\n<p>On the other hand, if code lik this is prolific this is a sure sign that the original class design is broken. But from your code it looks like this is outside of your control anyway, since <code>UserModel</code> is a framework class.</p>\n\n<p>In general, if a class is used in such a fashion then it is over-engineered: a static method could have been used just as well (on the other hand, this may make unit testing harder because it prevents mocking).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T17:55:47.900",
"Id": "23432",
"Score": "0",
"body": "Nicely said. If a class is used for initialization and a method call, why is it a class in the first place? (of course, this is harder to obey in a purely OO language, which quite further proves that OOP is not a silver bullet)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T10:57:04.637",
"Id": "14443",
"ParentId": "14440",
"Score": "5"
}
},
{
"body": "<p>Sometimes this does stink. Consider the following:</p>\n\n<pre><code>byte[] data = { ... };\n\nFile.OpenWrite(\"filename.dat\").Write(data, 0, data.Length);\n</code></pre>\n\n<p><code>File.OpenWrite</code> implements <code>IDisposable</code> and therefore should be deterministically disposed as such:</p>\n\n<pre><code>byte[] data = { ... };\n\nusing (var stream = File.OpenWrite(\"filename.dat\"))\n{\n stream.Write(data, 0, data.Length);\n}\n</code></pre>\n\n<p>So, keep an eye out.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-01T21:59:39.413",
"Id": "55823",
"ParentId": "14440",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "14443",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T09:49:37.700",
"Id": "14440",
"Score": "2",
"Tags": [
"c#"
],
"Title": "new Class().Function() pattern"
}
|
14440
|
<p>This is an OOP Rock, Paper, Scissors program I wrote in Python. I am just learning about using classes and I'd appreciate some advice on improving it.</p>
<pre><code># rock.py
# example of OOP
import random
class Rock:
def main(self):
self.Make_players()
print("Best of Five - Let's play!\n")
done = False
while done == False:
self.p1.go_player()
self.p2.go_player()
print()
if self.p2.go == self.p1.go:
print("No winner!\n")
continue
else:
temp = self.check(self.p1, self.p2)
if temp == False:
temp = self.check(self.p2, self.p1)
print(self.message, end = " ")
print(temp.name + " won this round.")
temp.scored()
print(self.p1.name + ": " + str(self.p1.score))
print(self.p2.name + ": " + str(self.p2.score))
if self.p1.score == 3:
self.winner = self.p1
done = True
elif self.p2.score == 3:
self.winner = self.p2
done = True
else:
done = False
input()
print("The winner was " + self.winner.name + "!")
def __init__(self):
print("**** Welcome to Rock, Paper, Scissors!****\n")
self.winner = False
self.main()
def Make_players(self):
temp = (input("What shall we call Player 1? "))
self.p1 = Player(temp)
temp = (input("What shall we call Player 2? "))
self.p2 = Player(temp)
def check(self, p_a, p_b):
if p_a.go == "rock" and p_b.go == "scissors":
self.message = "Rock breaks scissors."
return p_a
elif p_a.go == "paper" and p_b.go == "rock":
self.message = "Paper wraps stone."
return p_a
elif p_a.go == "scissors" and p_b.go == "paper":
self.message = "Scissors cut paper."
return p_a
else:
return False
class Player:
def __init__(self, name):
self.choices = ["rock", "paper", "scissors"]
self.score = 0
self.name = name
print("Player:", self.name, "created!\n")
def go_player(self):
self.go = random.choice(self.choices)
print(self.name + " chose " + self.go, end = ". ")
return self.go
def scored(self):
self.score += 1
# Main
game = Rock()
</code></pre>
|
[] |
[
{
"body": "<p>I would change <code>check</code> to this</p>\n\n<pre><code>def check(self, p_a, p_b):\n messages = {\"rock\":\"Rock breaks scissors.\",\n \"paper\":\"Paper wraps stone.\",\n \"scissors\":\"Scissors cut paper.\",\n }\n if p_a.go == p_b.go:\n return False\n elif p_a.go == \"rock\" and p_b.go == \"scissors\":\n self.message = messages[p_a.go]\n return p_a\n elif p_a.go == \"paper\" and p_b.go == \"rock\":\n self.message = messages[p_a.go]\n return p_a\n elif p_a.go == \"scissors\" and p_b.go == \"paper\":\n self.message = messages[p_a.go]\n return p_a\n else:\n # if moves are not same and player1 couldn't win than it should be\n # player2 who wins that round\n self.message = messages[p_b.go]\n return p_b\n</code></pre>\n\n<p>And the part where you check moves:</p>\n\n<pre><code>temp = self.check(self.p1, self.p2)\nif not temp: \n print(\"No winner!\\n\")\n continue\n</code></pre>\n\n<p>Edit after antiloquax's comment:</p>\n\n<p>Even it will work that way I don't like it. you can use a class variable <code>messages = {\"rock\":\"...\",}</code> as I did in <code>check</code> method. While printing you just say</p>\n\n<pre><code>print(self.messages[temp.go])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T13:14:45.527",
"Id": "23400",
"Score": "0",
"body": "Thanks savruk. I was thinking about something like that - but the \"else:\" here would just return the player without printing the message \"Paper wraps stone\" etc. I think."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T13:29:07.890",
"Id": "23402",
"Score": "0",
"body": "antiloquax, you are right. I didn't think about it. See my edited answer. As a move can only win against a certain move(rock can only beat scissors, scissors can only beat paper ...), it is easy to use a dictionary to define a message for the move."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T12:28:01.570",
"Id": "14448",
"ParentId": "14441",
"Score": "0"
}
},
{
"body": "<p>The best OOP advice I can give for this code is: <a href=\"http://pyvideo.org/video/880/stop-writing-classes\" rel=\"nofollow\">stop writing classes</a>.</p>\n\n<p>Ideally, watch the video first (it’s not that long) and come back later. But here’s the gist:</p>\n\n<blockquote>\n <p>A class that has only one publicly called method (or less) isn’t a legitimate class. It should be a method.</p>\n</blockquote>\n\n<p>Consequently, <code>Rock</code> shouldn’t be a class. It should be a method.</p>\n\n<p>The rest is detail criticism. Most importantly, <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">read PEP8 (the Python style guide)</a> and adhere to it. Notably, this includes naming conventions, and using <em>meaningful</em> names.</p>\n\n<p>Next, separate concerns clearly. <code>go_player</code> shouldn’t print text, its sole task should be to generate a random game choice. The printing should happen elsewhere.</p>\n\n<p>Similarly (i.e. still a separation-of-concerns problem), neither all possible choices (i.e. <code>choices</code>) nor the <em>current choice</em> (i.e. <code>go</code>) logically belong in the <code>Player</code>. They are separate entities.</p>\n\n<p><code>self.winner = False</code> is logically wrong. The variable doesn’t contain a boolean value later on, why does it contain one now? Same goes for <code>check</code> – it should return <code>None</code>, not <code>False</code>.</p>\n\n<p>Next, use a standard entry point. The following is pretty much an established pattern in Python that all code should follow:</p>\n\n<pre><code>def main():\n …\n\nif __name__ == '__main__':\n sys.exit(main())\n</code></pre>\n\n<p>This way, the code can be executed directly or reused as a module.</p>\n\n<p>And a check like <code>while done == False</code> is like fingernails across a blackboard for professional programmers: explicit checks against boolean literals <strong>never</strong> (!) make sense. Use <code>while not done</code> instead.</p>\n\n<p>In summary, here’s how I’d do it:</p>\n\n<pre><code>#!/usr/bin/env python\n\nimport sys\nimport random\n\n# The extended, cool rules:\n# http://en.wikipedia.org/wiki/Rock-paper-scissors-lizard-Spock\nCHOICES = ['rock', 'paper', 'scissors', 'lizard', 'Spock']\n\nRULES = {\n 'rock': {\n 'scissors': 'blunts',\n 'lizard': 'crushes'},\n 'paper': {\n 'rock': 'covers',\n 'Spock': 'disproves'},\n 'scissors': {\n 'paper': 'cuts',\n 'lizard': 'decapitates'},\n 'lizard': {\n 'paper': 'eats',\n 'Spock': 'poisons'},\n 'Spock': {\n 'rock': 'vaporizes',\n 'scissors': 'smashes'}\n}\n\n\nclass Player:\n def __init__(self, name):\n self.name = name\n self.score = 0\n\n @classmethod\n def create(cls, num):\n name = raw_input('What shall we call player {}? '.format(num))\n return cls(name)\n\n def go(self):\n return random.choice(CHOICES)\n\n def scored(self):\n self.score += 1\n\n def __str__(self):\n return self.name\n\n\ndef get_winner(players, choices):\n \"\"\"\n Determine winner of a rock-paper-scissors round.\n\n Returns a tuple of (winner, winning move) if exists, else None.\n \"\"\"\n def get_rule(cs):\n return RULES[cs[0]].get(cs[1], None)\n\n move = get_rule(choices)\n\n if move is not None:\n winner = players[0]\n else:\n choices = choices[::-1]\n move = get_rule(choices)\n winner = players[1]\n\n if move is None:\n return None\n\n return (winner, (choices[0], move, choices[1]))\n\n\ndef game(how_many_rounds):\n if how_many_rounds % 2 == 0:\n raise RuntimeError('Rounds must be an uneven number')\n\n players = [Player.create(1), Player.create(2)]\n winning_score = how_many_rounds // 2 + 1\n\n print('Best of {} - let\\'s play!\\n'.format(how_many_rounds))\n\n while True:\n choices = [p.go() for p in players]\n for p, c in zip(players, choices):\n print p, c\n win = get_winner(players, choices)\n\n if win is None:\n print('No winner.\\n')\n continue\n\n winner, move = win\n winner.scored()\n print('{} {} {}. {} won this round.'.format(\n move[0].capitalize(), move[1], move[2], winner))\n for p in players:\n print('{}: {}'.format(p, p.score))\n\n if winner.score == winning_score:\n break\n\n raw_input()\n\n print('The winner was {}!'.format(winner))\n\n\ndef main():\n game(99)\n\n\nif __name__ == '__main__':\n sys.exit(main())\n</code></pre>\n\n<p>To be honest, I’m not entirely satisfied with this since I prefer having immutable objects as much as possible, and the player objects here are <em>not</em> immutable. In fact, I’d probably get rid of the <code>Player</code>s entirely and store the game state inside the game, where it belongs.</p>\n\n<p>(Proper documentation is left as an exercise for the reader. I’ve only documented <code>get_winner</code> since it would be incomprehensible without documentation.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T13:52:59.263",
"Id": "23404",
"Score": "1",
"body": "`score` isn't an attribute on `Player`; you should have a `scoreboard := map(Player, int)` or even `:= Counter(Player)`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T13:44:19.547",
"Id": "14452",
"ParentId": "14441",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T10:29:59.037",
"Id": "14441",
"Score": "2",
"Tags": [
"python",
"object-oriented",
"game",
"rock-paper-scissors"
],
"Title": "OOP in Rock, Paper, Scissors program"
}
|
14441
|
<p>For <a href="http://projecteuler.net/problem=14" rel="nofollow">Project Euler problem 14</a> I wrote code that runs for longer than a minute to give the answer. After I studied about <a href="http://en.wikipedia.org/wiki/Memoization" rel="nofollow">memoization</a>, I wrote this code which runs for nearly 10 seconds on Cpython and nearly 3 seconds on PyPy. Can anyone suggest some optimization tips?</p>
<pre><code>import time
d={}
c=0
def main():
global c
t=time.time()
for x in range(2,1000000):
c=0
do(x,x)
k=max(d.values())
for a,b in d.items():
if b==k:
print(a,b)
break
print(time.time()-t)
def do(num,rnum):
global d
global c
c+=1
try:
c+=d[num]-1
d[rnum]=c
return
except:
if num==1:
d[rnum]=c
return
if num%2==0:
num=num/2
do(num,rnum)
else:
num=3*num+1
do(num,rnum)
if __name__ == '__main__':
main()
</code></pre>
|
[] |
[
{
"body": "<p>I think you're over complicating your solution, my approach would be something along these lines:</p>\n\n<pre><code>def recursive_collatz(n):\n if n in collatz_map:\n return collatz_map[n]\n if n % 2 == 0:\n x = 1 + recursive_collatz(int(n/2))\n else:\n x = 1 + recursive_collatz(int(3*n+1))\n collatz_map[n] = x\n return x\n</code></pre>\n\n<p>Basically define a memoization map (collatz_map), initialized to <code>{1:1}</code>, and use it to save each calculated value, if it's been seen before, simply return.</p>\n\n<p>Then you just have to iterate from 1 to 1000000 and store two values, the largest Collatz value you've seen so far, and the number that gave you that value.</p>\n\n<p>Something like:</p>\n\n<pre><code>largest_so_far = 1\nhighest = 0\nfor i in range(1,1000000):\n temp = recursive_collatz(i)\n if temp > largest_so_far:\n highest = i\n largest_so_far = temp\n</code></pre>\n\n<p>Using this approach I got:</p>\n\n<p>Problem 14's answer is: 837799.\nTook 1.70620799065 seconds to calculate.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T11:25:55.080",
"Id": "14446",
"ParentId": "14442",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "14446",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T10:33:42.567",
"Id": "14442",
"Score": "5",
"Tags": [
"python",
"optimization",
"project-euler"
],
"Title": "Optimizing Code for Project Euler Problem 14"
}
|
14442
|
<p>I created a simple todo kind of app using JavaScript. It is working fine but the code which I wrote is not proper. Please review my code and improve it if it is needed.</p>
<pre><code>$(function () {
var todo = new Todo('contents');
$('.addBtn').on('click', function() {
var name = $(this).parent().find('input[type="text"]').val();
todo.add(name);
});
$('.contents').on('click', '.remove', function() {
var el = $(this).parent();
todo.remove(el);
});
$('.contents').on('click', '.update', function() {
var dom = $(this);
todo.addUpdateField(dom);
});
$('.contents').on('click', '.updateBtn', function() {
var el = $(this);
todo.update(el);
});
});
</code></pre>
<p>Here is my todo.js file</p>
<pre><code>var Todo = function(c) {
var contents = $('.' + c),
name;
add = function (name) {
if(name != "") {
var div = $('<div class="names"></div>');
div.append('<span>' + name + '</span>');
div.append("<button class='update' class='update'>Edit</button>");
div.append("<button class='remove' name='remove'>Remove</button>");
contents.prepend(div);
$('.name').val('').focus();
}
return;
},
addUpdateField = function (dom) {
var name = dom.parent().find('span').text(),
field = $('<input type="text" value="' + name + '" />'),
update = $('<button class="updateBtn">Update</button>');
return dom.parent().html('').append(field).append(update);
},
update = function(el) {
var val = el.parent().find('input').val();
el.parent().html('<span>' + val + '</span>')
.append('<button class="update" class="update">Edit</button>')
.append('<button class="remove" class="remove">Remove</button>');
},
remove = function (el) {
return el.remove();
};
return {
add : add,
update : update,
remove : remove,
addUpdateField : addUpdateField
};
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T12:43:21.613",
"Id": "23523",
"Score": "2",
"body": "You have leaking globals because of the semi-colon after `name;` (replace it with `,`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T03:12:54.457",
"Id": "23558",
"Score": "0",
"body": "Is this a homework assignment?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T06:05:21.990",
"Id": "23568",
"Score": "0",
"body": "@st-boost No it is not homework assignment. I am learning modular javascript and want to improve my coding. Since here are professional javascript developer on this forum so I thought this would be the best place for me to ask for improvement in my code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T16:32:55.947",
"Id": "23582",
"Score": "0",
"body": "@al0neevenings You forgot to share the HTML."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-11T03:23:03.023",
"Id": "23608",
"Score": "0",
"body": "@al0neevenings Ok, just asking because your wording reminded me of a homework assignment. I hope you find what you're looking for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-15T13:27:43.750",
"Id": "140535",
"Score": "0",
"body": "I would suggest possibly putting all instances of hard-coded html like this: `'<button class=\"update\" class=\"update\">Edit</button>'` into their own variables at the top. This way, if you ever need to make a change to all of the 'Edit' buttons you can do this with one simple line change instead of multiple. This isn't a big concern with this project since the most one of these buttons are used is twice, but I think you can see the benefit to this."
}
] |
[
{
"body": "<p>As I read it, you want:</p>\n\n<ul>\n<li>one <code><div class=\"names\"></code> per todo (in this case inside <code>.contents</code>) surrounding the todo text in a <code>span</code> and the buttons \"Edit\" / \"Remove\"</li>\n<li>on clicking \"Edit\", the <code>span</code> is exchanged for an <code>input</code> field and an \"Update\" button, \"Edit\" and \"Remove\" are removed.</li>\n<li>on clicking \"Update\", the prior state with the new text is recreated (<code>span</code>, Edit, Remove)</li>\n</ul>\n\n<p>After you follow <a href=\"https://codereview.stackexchange.com/users/14938/inkbug\">Inkbug</a>`s advice from his comment, you should probably do this:</p>\n\n<ul>\n<li>cache the todo root element (<code>var todoRoot = $(...);</code>)</li>\n<li>rename <code>addUpdateField</code>/<code>.update</code> to <code>edit</code>/<code>.edit</code> and <code>updateBtn</code> to <code>update</code> - consistent with the button texts and easier to read</li>\n<li><p>change the api of your todo.js functions. For update / edit / remove, just use the dom node of the div as the argument:</p>\n\n<pre><code>function(target, action) {\n todoRoot.on('click', target, function(e) {\n e.preventDefault();\n e.stopPropagation();\n action.call(todo, $(this).parents('.names').first());\n });\n}\n\nbindClick('.remove', todo.remove);\nbindClick('.edit', todo.edit);\nbindClick('div', todo.update);\n</code></pre></li>\n<li><p>don't use that many appends. Put it all in a string (that can contain more than one DOM node!)</p></li>\n<li>don't create / delete all the nodes. Create all three buttons, use <a href=\"http://api.jquery.com/toggleClass/\" rel=\"nofollow noreferrer\"><code>.toggleClass(...)</code></a> and CSS to make all buttons/fields disappear that you don't need. That moves all your HTML into the <code>add</code> function and goes easy on the DOM</li>\n<li>move the bindings into the <code>Todo</code> function. You don't want to have to remember to bind these events for every Todo list you create</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T14:03:08.483",
"Id": "14529",
"ParentId": "14444",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T11:13:36.660",
"Id": "14444",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"to-do-list"
],
"Title": "To-do list app using jQuery"
}
|
14444
|
<p>I'm new to coding and have written a script from scratch to do an auto-correlation function. It's too slow and I have to run it on a few thousand files over the next few days. I'm sure it's terribly written (and you can see my brain ticking in basic ways through it) and can be faster.</p>
<p>I know that Python has an inbuilt autocorrelation function, but I think it's restricted to the sense that they use the word in physics. This is for checking residency times of a molecule in a biomolecule simulation and I couldn't see how to apply the default.</p>
<pre><code>import sys
import time
start = time.time()
fileName = sys.argv[1]
time = []
water = []
#make two 1d arrays for time and water
with open(fileName, "r") as input:
for line in input:
time.append(line.split()[0])
water.append(line.split()[1])
# define a totaltimescale in picoseconds - the minus 1 is
# because of the zero index
# windowsize is 2 ns
totaltimescale = 50000 - 1
windowsize = 2000
# endtau should take into consideration the multiplier
# below so 400 with a multiplier of 5 gives us
endtau = 400
alltau = range(1, endtau)
for tau in alltau:
# there is a tau multiplier (i.e. use every 5th tau
# or every 5 picoseconds to speed up calculation)
tau = 5*tau
print tau
# these three values just start counters
counter = 0
noncounter = 0
output = 0
# to set up a value for total number of windows we're interested in,
# leave off 2 times the windowsize at the end arbitrarily so it doesn't
# jump too far, may get errors eventually for this so may have to be wary
numberofwindows = totaltimescale - 2*windowsize
listofwindowstartingpoints = range(0, numberofwindows)
# outer iterator which ensures the window (of size start - start + windowsize)
# is moved down one unit each time, i.e. starts at the next picosecond
for startingpoint in listofwindowstartingpoints:
window = range(startingpoint, startingpoint + windowsize)
for a in window:
if a + tau < totaltimescale:
if water[a] == water[a + tau]:
counter = float(counter + 1)
else:
noncounter = noncounter + 1
totaljumpsanalysed = float(counter + noncounter)
output = counter/totaljumpsanalysed
else:
pass
# counters should have kept values
print counter
print totaljumpsanalysed
print output
with open(fileName + '.autocorrelate', "a") as outfile:
outfile.writelines('{0} {1}{2}'.format(tau, output, '\n'))
print 'It took', time.time()-start, 'seconds.'
</code></pre>
<p>It's running on files that look like this (but the time column, the first one, goes up to 50000, the second column is the index of the molecule that goes into the spot).</p>
<blockquote>
<pre><code>1.0 24561 0.1255
2.0 24561 0.1267
3.0 -1 0.2265
4.0 24561 0.1095
5.0 24561 0.1263
6.0 -1 0.1598
7.0 -1 0.2024
8.0 -1 0.1798
9.0 -1 0.1823
10.0 24409 0.1291
11.0 24409 0.1288
12.0 -1 0.1537
13.0 -1 0.1853
14.0 -1 0.1625
15.0 24561 0.1300
16.0 24561 0.1342
17.0 24221 0.1294
18.0 24561 0.1165
19.0 24561 0.0611
20.0 24561 0.1259
21.0 6345 0.1284
22.0 -1 0.1421
23.0 -1 0.1435
24.0 -1 0.2599
25.0 -1 0.2659
26.0 -1 0.1961
27.0 24213 0.1398
28.0 24213 0.1325
29.0 -1 0.1809
30.0 -1 0.2044
</code></pre>
</blockquote>
<p>The output typically looks a bit something like this where the first column is tau and the second 'output' or the probability that it's the molecule with the same index at that point tau.</p>
<blockquote>
<pre><code>5 0.674404921846
10 0.59412323094
15 0.543056729494
20 0.503867421031
25 0.470009065414
30 0.442317789517
35 0.417826474489
40 0.398214015522
45 0.379222841801
50 0.360768038436
55 0.344779093024
60 0.330382117003
65 0.316864844888
70 0.306959596948
75 0.29386854062
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T14:19:39.673",
"Id": "23405",
"Score": "0",
"body": "For a beginner this is incredibly well-written, clean code. I see very few points that can be trivially improved, besides the suggestions made in the answers below."
}
] |
[
{
"body": "<p>My first suggestion is to look into parallelization. I believe your problem is one that can be made <a href=\"http://en.wikipedia.org/wiki/Embarrassingly_parallel\" rel=\"nofollow\">embarassingly parallel</a>. Each iteration of your loop is independent of each other iteration, so you could run all of them simultaneously. With sufficiently beefy hardware you could get an increase in efficiency proportional to <code>len(alltau) * len(window)</code>.</p>\n\n<p>Also, you're doing some unnecessary work in your big loop. </p>\n\n<ul>\n<li>You're calculating <code>output</code> fifty thousand times, when you could just calculate it exactly once after the loop ends. </li>\n<li>You can keep track of <code>totaljumpsanalysed</code> by incrementing it once per loop. No <code>noncounter</code> needed.</li>\n<li>You don't necessarily need to convert <code>counter</code> to a float. Remember, python supports integers of arbitrary size, so you don't need to worry about overflow.</li>\n<li><code>else: pass</code> does nothing, so you can remove it.</li>\n</ul>\n\n<p> </p>\n\n<pre><code>totaljumpsanalysed = 0\nfor startingpoint in listofwindowstartingpoints:\n window = range(startingpoint, startingpoint + windowsize)\n for a in window:\n if a + tau < totaltimescale:\n if water[a] == water[a + tau]:\n counter += 1\n totaljumpsanalysed += 1\n\noutput = float(counter)/float(totaljumpsanalysed)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T15:16:46.357",
"Id": "23409",
"Score": "0",
"body": "Thanks very much for the help! Now I'm getting an overflow error though\n\n`code`Traceback (most recent call last):\n File \"autocorrelationbatchtesting_08_08_2012_codereview.py\", line 54, in <module>\n if water[a] == water[a + tau]:\nIndexError: list index out of range`code` \n\nIt happens at 40000 now, I wrote a temp file to check, I can't think why that would be given there is the if clause in there?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T15:34:49.373",
"Id": "23410",
"Score": "0",
"body": "How many lines are in your input file? If `len(water)` is less than `totaltimescale`, then your `if` guard won't prevent you from going beyond the end of the list."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T12:45:48.490",
"Id": "14450",
"ParentId": "14447",
"Score": "3"
}
},
{
"body": "<p>If you are dead-set on writting your own AC function, there is one suggestion that is better than any of those below or those by Kevin in the other post. <strong>USE NUMPY</strong>. The code is begging for the speedups by the numpy indexing properties. If pure Python speed is a concern there a couple of simple things to note:</p>\n\n<ul>\n<li>Since it looks like Python < 3.0, change <code>range</code> -> <code>xrange</code>. The former creates the list, the latter creates an iterator.</li>\n<li><code>a + tau</code> is computed multiple times every cycle of the inner loop.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T13:40:19.413",
"Id": "14451",
"ParentId": "14447",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "14450",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T11:43:18.607",
"Id": "14447",
"Score": "4",
"Tags": [
"python",
"optimization"
],
"Title": "Optimisation of auto-correlation function"
}
|
14447
|
<p>I have following code on my login page (now i use it for preventing POST variable resubmit on page refresh):</p>
<pre><code><?php
$cleaner = md5(uniqid(rand(), TRUE));
$_SESSION["cleaner"]=(empty($_SESSION["cleaner"])) ? $cleaner : $_SESSION["cleaner"];
if($_POST['login_button'] && !empty($_POST['cleaner']) && $_SESSION['cleaner'] == $_POST['cleaner']){
$cleaner = md5(uniqid(rand(), TRUE));
$_SESSION['cleaner'] = $cleaner;
//all other verification/login code
}
?>
<form method="POST" action="">
<input type="hidden" name="cleaner" value="<?php echo $_SESSION['cleaner']; ?>" />
<--! all other login html code and fields -->
</form>
</code></pre>
<p>Can this code make some attacks harder to do, or if not - what to change?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T17:49:37.860",
"Id": "23539",
"Score": "1",
"body": "This looks like the OWASP \"Synchronizer Token Pattern\", which should help against CSRF attacks. But because you're using session you may run into problems if the user uses the \"Back\" button. \n\nhttp://owasp.com/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet"
}
] |
[
{
"body": "<p>I haven't had the need to worry about this kind of thing before, so I can't claim that this will answer your question, but maybe it will help. It looks simple enough, but <code>rand()</code> may not be the best tool here. I know that, at least with Java, the random function is easily beaten because it starts with a number from a list and then iterates over that list each time you call it, and the list is always the same. So maybe this is something to look at in PHP too. Also, I was here anyways and I couldn't help but notice a few things.</p>\n\n<p>A couple of minor notes first. One line of code should only do one thing. This helps with legibility, which is a real problem the deeper you nest functions. And what is \"cleaner\" by the way? This is a really odd name. Would expect \"id\" or something else, but anyways.</p>\n\n<pre><code>$id = uniqid( rand(), TRUE );\n$cleaner = md5( $id );\n</code></pre>\n\n<p>You should check if the variable is set, not empty. Unless you already know it is set, which you don't because it hasn't been done in this document. Also, the extra parenthesis are unnecessary in this ternary operation.</p>\n\n<pre><code>$_SESSION[ 'cleaner' ] = isset( $_SESSION[ 'cleaner' ] ) ? $cleaner : $_SESSION[ 'cleaner' ];\n</code></pre>\n\n<p>A more efficient way, instead of creating something you will now never use, is to only create it if you have to. So...</p>\n\n<pre><code>if( isset( $_SESSION[ 'cleaner' ] ) ) {\n $cleaner = $_SESSION[ 'cleaner' ];\n} else {\n $id = uniqid( rand(), TRUE );\n $cleaner = md5( $id );\n}\n\n$_SESSION[ 'cleaner' ] = $cleaner;\n</code></pre>\n\n<p>You may notice that I'm now modifying the session variable no matter what. Its not really necessary, but it keeps the session fresh which is sometimes nice.</p>\n\n<p>With this next line I'm assuming that you are checking if the form has been submitted (\"login_button\" seems kind of obvious). This is a really debatable subject. Many people still do this, I think because they think it ensures that the user is actually using their form instead of their own, but its not that hard to look at the source and create POST parameters with the same keys, so I don't know how much truth there is in that. I personally find it better to just check the request method, or, if I'm feeling particularly lazy, to see if the POST array is empty. As I said, its really debatable, so you can take it or leave it.</p>\n\n<pre><code>if( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' ) {\n//Or the hack\nif( $_POST ) {\n</code></pre>\n\n<p>Next you check for the POST version of \"cleaner\", this should be another <code>isset()</code> check rather than an <code>empty()</code> check by the way, then you compare the session version to the POST version. So then, this would only be possible, theoretically, if we didn't use the cleaner we created earlier because the session version was set. Think I'm with you so far... But why not then use that earlier version we didn't use instead of creating a new one? To illustrate, a full rewrite might look something like this:</p>\n\n<pre><code>$id = uniqid( rand(), TRUE );\n$cleaner = md5( $id );\n\nif( isset( $_SESSION[ 'cleaner' ] ) ) {\n $temp = $_SESSION[ 'cleaner' ];\n if( ! $_SERVER[ 'REQUEST_METHOD' ] || $temp != $_POST[ 'cleaner' ] ) {\n $cleaner = $temp;\n }\n}\n\n$_SESSION[ 'cleaner' ] = $cleaner;\n</code></pre>\n\n<p>Hopefully this helps somewhat, sorry I couldn't really answer your question.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T19:47:11.497",
"Id": "14501",
"ParentId": "14453",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T13:54:55.890",
"Id": "14453",
"Score": "2",
"Tags": [
"php",
"security"
],
"Title": "Will this code make some attacks (XSS, CSRF...) harder to do?"
}
|
14453
|
<p>Currently on my ASP.NET website when I define a new user I write their data to a .txt file like this:</p>
<pre><code>public class User
{
public string UserName;
public string PassWord;
public string Email;
public string FirstName;
public string LastName;
public string Twitter;
public string FaceBook;
public int Age;
public DateTime DateCreated;
public User(string username, string password, string email, string facebook, string twitter, string firstname, string lastname, int age, DateTime datecreated)
{
UserName = username;
PassWord = password;
Email = email;
FirstName = firstname;
LastName = lastname;
Age = age;
DateCreated = datecreated;
Twitter = twitter;
FaceBook = facebook;
AddToTextFile();
}
public bool CheckUsername(string username, List<User> users)
{
for (int i = 0; i < users.Capacity; i++)
{
if (users[i].UserName == username) return true;
else return false;
}
return false;
}
public bool CheckPassword(string username, string password, List<User> users)
{
for (int i = 0; i < users.Capacity; i++)
{
if (users[i].UserName == username)
{
if (users[i].PassWord == password) return true;
else return false;
}
else return false;
}
return false;
}
private void AddToTextFile()
{
string file = "../users-information.txt";
StreamWriter sw = new StreamWriter(@file);
sw.WriteLine("{0} {1} {2} {3} {4} {5} {6} {7} {8}", UserName, PassWord, FirstName, LastName, Email, FaceBook, Twitter, Age, DateCreated);
}
</code></pre>
<p>Then on my C# app I use <code>WebClient.DownloadData</code> to get the data and write it to a file.</p>
<pre><code> private void GetUsers()
{
//JavaScriptSerializer serializer = new JavaScriptSerializer();
//users = serializer.Deserialize<User[]>(Request.Form["users"]);
WebClient client = new WebClient();
byte[] file = client.DownloadData("http://kinected-security.com/users-information.txt");
File.WriteAllBytes(@"../user-information/user-information.txt", file);
string[] lines = File.ReadAllLines("../user-information/user-information.txt");
if (lines.Length != 0)
{
foreach (string line in lines)
{
string[] splited = new string[]{ };
splited = line.Split(new Char[] {' ' });
users.Add(new User(splited[0], splited[1], splited[2], splited[3], splited[4], splited[5], splited[6], int.Parse(splited[7]), DateTime.Parse(splited[8])));
}
}
}
</code></pre>
<p>Should I be using <code>WebClient.DownloadString</code>? Is there a more efficient way to do this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-14T01:45:47.637",
"Id": "23752",
"Score": "3",
"body": "Public fields are an idiomatic no-no: http://stackoverflow.com/a/379058/3312"
}
] |
[
{
"body": "<p>You don't have to write the file and read it again. You can change the byte array to a string internally using an Encoding and GetString() and split it by new line. Or you can do DownloadString directly and split by line. Reading/writing seems wasteful. Note that you might want to have some security around downloading user information from your server.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T17:28:04.700",
"Id": "23414",
"Score": "0",
"body": "I do have security I just didn't post it, and can you show an example of the encoding? Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T17:28:59.473",
"Id": "23415",
"Score": "0",
"body": "Sure, you can do something like: string Contents = Encoding.UTF8.GetString(byte_array_here). Then, you can split it, like so: string[] lines = Contents.split(\"\\r\\n\")."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T17:29:23.343",
"Id": "23416",
"Score": "0",
"body": "I will try it and accept if it works"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T17:33:43.710",
"Id": "23430",
"Score": "0",
"body": "I'm sorry, it should be Regex.Split(Contents, \"\\r\\n\")."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T17:34:52.557",
"Id": "23431",
"Score": "0",
"body": "Oh also I understand the \"\\n\" but why \"\\r\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T21:12:57.937",
"Id": "23448",
"Score": "0",
"body": "\\n is a new line, while \\r is a carriage return. In Linux, a new line is separated with just a \\n, while on Windows the default new line is a \\r\\n. If you download a text file made on Linux and open it in Windows notepad, you will not see lines, but everything on one line. This is why."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T17:25:43.253",
"Id": "14459",
"ParentId": "14458",
"Score": "2"
}
},
{
"body": "<p>Here is my cleanup of the <code>User</code> class. Note that there is a world of a <a href=\"https://stackoverflow.com/questions/2485139/list-capacity-has-more-items-than-added\">difference between the <code>.Count</code> and the <code>.Capacity</code> properties of a list</a>. Look them up! Your <code>CheckUsername</code> and <code>CheckPassword</code> methods were broken in more than one way.</p>\n\n<pre><code>namespace Foo\n{\n using System;\n using System.Collections.Generic;\n using System.Diagnostics.Contracts;\n using System.IO;\n using System.Linq;\n\n public class User\n {\n private static readonly string filePath = \"../users-information.txt\"; // Or not readonly if you wish to set it at run time.\n\n public User(IList<string> tokens)\n {\n Contract.Requires(tokens.Count == 9, \"Expected exactly 8 tokens but got \" + tokens.Count + \" of them.\");\n int age = Convert.ToInt32(tokens[7]);\n DateTime dateCreated = Convert.ToDateTime(tokens[8]);\n\n this.Init(\n userName : tokens[0],\n password: tokens[1],\n email: tokens[2],\n facebook: tokens[3],\n twitter: tokens[4],\n firstName: tokens[5],\n lastName: tokens[6],\n age: age,\n dateCreated: dateCreated);\n }\n\n public User(\n string username,\n string password,\n string email,\n string facebook,\n string twitter,\n string firstname,\n string lastname,\n int age,\n DateTime dateCreated)\n {\n this.Init(username, password, email, facebook, twitter, firstname, lastname, age, dateCreated);\n }\n\n public string UserName\n {\n get;\n private set;\n }\n\n public string PassWord\n {\n get;\n private set;\n }\n\n public string Email\n {\n get;\n private set;\n }\n\n public string FirstName\n {\n get;\n private set;\n }\n\n public string LastName\n {\n get;\n private set;\n }\n\n public string Twitter\n {\n get;\n private set;\n }\n\n public string FaceBook\n {\n get;\n private set;\n }\n\n public int Age\n {\n get;\n private set;\n }\n\n public DateTime DateCreated\n {\n get;\n private set;\n }\n\n private void Init(\n string userName,\n string password,\n string email,\n string facebook,\n string twitter,\n string firstName,\n string lastName,\n int age,\n DateTime dateCreated)\n {\n this.UserName = userName;\n this.PassWord = password;\n this.Email = email;\n this.FirstName = firstName;\n this.LastName = lastName;\n this.Age = age;\n this.DateCreated = dateCreated;\n this.Twitter = twitter;\n this.FaceBook = facebook;\n\n this.AddToTextFile();\n }\n\n /***** These methods are not great:\n A) It is not safe to send plain-text passwords over the wire as well as well as store them as such. You would want to compare a very well crafted and tested \"hash code\"/checksum.\n B) This has O(n) run time. Dictionary or a set would be a better data structure. You probably want a dictionary that maps a user name to a pair `[userName, hash]` and a dictionary that maps `hash` to the same pair. Maybe you will need a database, but a linear list is not as great.\n\n // Unused?\n public static bool CheckUsername(string username, IList<User> users)\n {\n return users.Any(user => user.UserName.Equals(username, StringComparison.Ordinal)); // Case-sensitive?\n }\n\n // Unused? Not the best method name - CheckCredentials perhaps?\n public static bool CheckPassword(string username, string password, List<User> users)\n {\n return users.Any(user => user.UserName.Equals(username, StringComparison.Ordinal) // Case-sensitive?\n && user.PassWord.Equals(password, StringComparison.Ordinal));\n }\n */\n\n private void AddToTextFile()\n {\n using (var sw = new StreamWriter(filePath))\n {\n sw.WriteLine(\n \"{0} {1} {2} {3} {4} {5} {6} {7} {8}\",\n this.UserName,\n this.PassWord,\n this.FirstName,\n this.LastName,\n this.Email,\n this.FaceBook,\n this.Twitter,\n this.Age,\n this.DateCreated);\n }\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-13T23:31:06.567",
"Id": "14638",
"ParentId": "14458",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "14459",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T17:21:20.153",
"Id": "14458",
"Score": "2",
"Tags": [
"c#",
"asp.net"
],
"Title": "Is WebClient.DownloadData acceptable for getting data from a website?"
}
|
14458
|
<p>I'm sorry if I have not worded the question title to well, so let me explain.</p>
<p>I am creating a game, actually a few and I see that most of the time when painting ect I use a JPanel, so I went and found a good method of painting (i.e it has great performance when multiple sprites etc are being painted) see here: <a href="https://stackoverflow.com/questions/1963494/java-2d-game-graphics">https://stackoverflow.com/questions/1963494/java-2d-game-graphics</a>. I implemented that into my own kind of <em>GameJPanel</em> which will allow me to always have performance when painting on my games <code>JPanel</code>s. Now to that I have added the methods like <code>setDoubleBuffered(true)</code> and <a href="http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/RenderingHints.html" rel="nofollow noreferrer">RenderHints</a> on when drawing:</p>
<pre><code> if (isTextRenderHintsOn()) {
bg.setRenderingHints(textRenderHints);
}
if (isImageRenderHintsOn()) {
bg.setRenderingHints(imageRenderHints);
}
if (isColorRenderHintsOn()) {
bg.setRenderingHints(colorRenderHints);
}
if (isInterpolationRenderHintsOn()) {
bg.setRenderingHints(iterpolationRenderHints);
}
if (isRenderHintsOn()) {
bg.setRenderingHints(renderHints);
}
</code></pre>
<p>now without going to other libraries etc what more can I do to adjust the quality and or performance of whats being drawn on the <code>JPanel</code>s?</p>
<p>It might also help to know that I use the <code>GraphicsEnviroment</code> and set the <code>JFrame</code> with the <code>JPanel</code> to full screen to gain a <em>hardware accelerated image via a Buffer Strategy</em> (not the linked performance drawing in swing also used some great techniques as is) below is an example of my <code>GameDrawLibrary</code> which implements the <em>Java2D game graphics links'</em> method and the rendering hints, the <code>FullScreen</code> class will be used for setting to and from full screen mode and the Test driver is just that:) :</p>
<p>Test Driver:</p>
<pre><code>import java.awt.BorderLayout;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
/**
* Test Driver
*
* @author David
*/
public class PureSwingPaintingTest extends JFrame {
static GameDrawLibrary gdl;
static Image image;
static final FullScreen fs = new FullScreen();
static int width = fs.getWidth(), height = fs.getHeight();
public PureSwingPaintingTest() {
setSize(width, height);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gdl.createPanel();//create the panel
JPanel panel = gdl.getPanel();
JButton button = new JButton("Exit");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
getContentPane().add(button, BorderLayout.SOUTH);
getContentPane().add(panel, BorderLayout.CENTER);
}
public static void main(String[] args) {
try {
image = ImageIO.read(new File("c:/chess.jpg")).getScaledInstance(width, height, Image.SCALE_SMOOTH);
} catch (IOException ex) {
ex.printStackTrace();
}
gdl = new GameDrawLibrary(width, height, true, true, true, true, true, true) {
@Override
void updateGame() {
//update logic here
}
@Override
void renderGame(Graphics2D g) {
g.drawImage(image, 0, 0, this);
}
};
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (fs.isSupported()) {
fs.setFullScreen(new PureSwingPaintingTest());
} else {
fs.emulateFullScreen(new PureSwingPaintingTest());
}
gdl.showPanel();
}
});
}
}
</code></pre>
<p>Game JPanel library of sorts:</p>
<pre><code>import java.awt.*;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
abstract class GameDrawLibrary extends JPanel {
private int width;
private int height;
private int scale;
private boolean isRunning = true;
private Canvas canvas;
private BufferStrategy strategy;
private BufferedImage background;
private Graphics2D backgroundGraphics;
private Graphics2D graphics;
private GraphicsConfiguration config = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
//graphics quaultiy settings
private boolean textRenderHintsOn;
private boolean imageRenderHintsOn;
private boolean colorRenderHintsOn;
private boolean interpolationRenderHintsOn;
private boolean renderHintsOn;
private RenderingHints textRenderHints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
private RenderingHints imageRenderHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
private RenderingHints colorRenderHints = new RenderingHints(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
private RenderingHints iterpolationRenderHints = new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
private RenderingHints renderHints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
public GameDrawLibrary() {
setIgnoreRepaint(true);
this.textRenderHintsOn = false;
this.imageRenderHintsOn = false;
this.colorRenderHintsOn = false;
this.interpolationRenderHintsOn = false;
this.renderHintsOn = false;
}
GameDrawLibrary(int width, int height) {
setIgnoreRepaint(true);
this.width = width;
this.height = height;
this.scale = 1;
this.textRenderHintsOn = false;
this.imageRenderHintsOn = false;
this.colorRenderHintsOn = false;
this.interpolationRenderHintsOn = false;
this.renderHintsOn = false;
}
GameDrawLibrary(int width, int height, int scale) {
setIgnoreRepaint(true);
this.width = width;
this.height = height;
this.scale = scale;
this.textRenderHintsOn = false;
this.imageRenderHintsOn = false;
this.colorRenderHintsOn = false;
this.interpolationRenderHintsOn = false;
this.renderHintsOn = false;
}
public GameDrawLibrary(int width, int height, boolean textRenderHintsOn, boolean imageRenderHintsOn, boolean colorRenderHintsOn, boolean interpolationRenderHintsOn, boolean renderHintsOn, boolean isDoubleBuffered) {
super(isDoubleBuffered);
setIgnoreRepaint(true);
this.width = width;
this.height = height;
this.scale = 1;
this.textRenderHintsOn = textRenderHintsOn;
this.imageRenderHintsOn = imageRenderHintsOn;
this.colorRenderHintsOn = colorRenderHintsOn;
this.interpolationRenderHintsOn = interpolationRenderHintsOn;
this.renderHintsOn = renderHintsOn;
}
public GameDrawLibrary(int width, int height, int scale, boolean textRenderHintsOn, boolean imageRenderHintsOn, boolean colorRenderHintsOn, boolean interpolationRenderHintsOn, boolean renderHintsOn, boolean isDoubleBuffered) {
super(isDoubleBuffered);
this.width = width;
this.height = height;
this.scale = scale;
this.textRenderHintsOn = textRenderHintsOn;
this.imageRenderHintsOn = imageRenderHintsOn;
this.colorRenderHintsOn = colorRenderHintsOn;
this.interpolationRenderHintsOn = interpolationRenderHintsOn;
this.renderHintsOn = renderHintsOn;
}
// Screen and buffer stuff
private Graphics2D getBuffer() {
if (graphics == null) {
try {
graphics = (Graphics2D) strategy.getDrawGraphics();
} catch (IllegalStateException e) {
return null;
}
}
return graphics;
}
private boolean updateScreen() {
graphics.dispose();
graphics = null;
try {
strategy.show();
Toolkit.getDefaultToolkit().sync();
return (!strategy.contentsLost());
} catch (NullPointerException | IllegalStateException e) {
return true;
}
}
// update game logic here
abstract void updateGame();
//paint stuff here
abstract void renderGame(Graphics2D g);
//create and return the already sized JFrame
public void createPanel() {
setSize(getRealWidth(), getRealHeight());
}
public void showPanel() {
// Canvas
canvas = new Canvas(config);
canvas.setSize(width * scale, height * scale);
add(canvas, 0);
// Background & Buffer
background = create(width, height, false);
canvas.createBufferStrategy(2);
do {
strategy = canvas.getBufferStrategy();
} while (strategy == null);
startThread();//start thread to draw to the canvas
}
private void startThread() {
new Thread(new Runnable() {
@Override
public void run() {
backgroundGraphics = (Graphics2D) background.getGraphics();
long fpsWait = (long) (1.0 / 30 * 1000);
main:
while (isRunning) {
long renderStart = System.nanoTime();
updateGame();
// Update Graphics
do {
Graphics2D bg = getBuffer();
if (isTextRenderHintsOn()) {
bg.setRenderingHints(textRenderHints);
}
if (isImageRenderHintsOn()) {
bg.setRenderingHints(imageRenderHints);
}
if (isColorRenderHintsOn()) {
bg.setRenderingHints(colorRenderHints);
}
if (isInterpolationRenderHintsOn()) {
bg.setRenderingHints(iterpolationRenderHints);
}
if (isRenderHintsOn()) {
bg.setRenderingHints(renderHints);
}
if (!isRunning) {
break main;
}
renderGame(backgroundGraphics); // this calls your draw method
// thingy
if (scale != 1) {
bg.drawImage(background, 0, 0, width * scale, height * scale, 0, 0, width, height, null);
} else {
bg.drawImage(background, 0, 0, null);
}
bg.dispose();
} while (!updateScreen());
// Better do some FPS limiting here
long renderTime = (System.nanoTime() - renderStart) / 1000000;
try {
Thread.sleep(Math.max(0, fpsWait - renderTime));
} catch (InterruptedException e) {
Thread.interrupted();
break;
}
// renderTime = (System.nanoTime() - renderStart) / 1000000;
}
}
}).start();
}
public JPanel getPanel() {
return this;
}
// create a hardware accelerated image
public final BufferedImage create(final int width, final int height, final boolean alpha) {
return config.createCompatibleImage(width, height, alpha ? Transparency.TRANSLUCENT : Transparency.OPAQUE);
}
public void setColorRenderHintsOn(boolean colorRenderHintsOn) {
this.colorRenderHintsOn = colorRenderHintsOn;
}
public void setRenderHintsOn(boolean renderHintsOn) {
this.renderHintsOn = renderHintsOn;
}
public void setInterpolationRenderHintsOn(boolean interpolationRenderHintsOn) {
this.interpolationRenderHintsOn = interpolationRenderHintsOn;
}
public void setImageRenderHintsOn(boolean imageRenderHintsOn) {
this.imageRenderHintsOn = imageRenderHintsOn;
}
public void setTextRenderHintsOn(boolean textRenderHintsOn) {
this.textRenderHintsOn = textRenderHintsOn;
}
public boolean isColorRenderHintsOn() {
return colorRenderHintsOn;
}
public boolean isInterpolationRenderHintsOn() {
return interpolationRenderHintsOn;
}
public boolean isTextRenderHintsOn() {
return textRenderHintsOn;
}
public boolean isImageRenderHintsOn() {
return imageRenderHintsOn;
}
public boolean isRenderHintsOn() {
return renderHintsOn;
}
public int getRealHeight() {
return height * scale;
}
public int getRealWidth() {
return width * scale;
}
@Override
public int getHeight() {
return height;
}
@Override
public int getWidth() {
return width;
}
public int getScale() {
return scale;
}
public void setHeight(int height) {
this.height = height;
}
public void setWidth(int width) {
this.width = width;
}
public void setScale(int scale) {
this.scale = scale;
}
}
</code></pre>
<p>Fullscreen class:</p>
<pre><code>import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import javax.swing.JFrame;
/**
*
* @author David
*/
public class FullScreen {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gs = ge.getDefaultScreenDevice();
Dimension screenSize;
public FullScreen() {
screenSize = Toolkit.getDefaultToolkit().getScreenSize();
}
public void setFullScreen(JFrame frame) {
if (gs.getFullScreenWindow() == null) {
frame.dispose();
frame.setUndecorated(true);
gs.setFullScreenWindow(frame);
frame.setVisible(true);
} else {// back to windowed mode
emulateFullScreen(frame);
}
}
public void emulateFullScreen(JFrame frame) {
frame.dispose();
frame.setUndecorated(false);
gs.setFullScreenWindow(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(screenSize);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public int getWidth() {
return gs.getDisplayMode().getWidth();
}
public int getHeight() {
return gs.getDisplayMode().getHeight();
}
public boolean isSupported() {
return gs.isFullScreenSupported();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T14:18:26.367",
"Id": "23417",
"Score": "0",
"body": "I may be wrong, but this seems more of a code-review type question than a specific single answer stackoverflow type question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T14:20:46.700",
"Id": "23418",
"Score": "0",
"body": "can you put a picture?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T14:20:49.050",
"Id": "23419",
"Score": "0",
"body": "@HovercraftFullOfEels Not really? I want to know what other ways the painting quality can be improved? maybe I'm missing something that can make quality better so I put specific code so that others may see what I have already impelemented for quality drawing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T14:22:04.217",
"Id": "23420",
"Score": "0",
"body": "a picture could be more readable than lots of code"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T14:22:59.767",
"Id": "23421",
"Score": "0",
"body": "@tuğrulbüyükışık I havent really got anything to compare it to as I havent implemented the drawing etc fully (I just use a simple `Image` for now) but I'd like to know besides the techniques already used how else can quality be improved"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T14:27:19.543",
"Id": "23422",
"Score": "0",
"body": "if doublebuffer clears the dirty line traces of fast-changing shapes, then quality is up to your imagination ."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T15:10:37.790",
"Id": "23423",
"Score": "0",
"body": "@David: you're asking in effect, \"please review this code and see how it can be improved.\" Sorry, but this is a code review question, whether you agree or not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T16:02:39.710",
"Id": "23425",
"Score": "0",
"body": "@mKorbel well seen as you both say it is I have flagged it to be moved sorry for any inconvenience caused"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T16:05:58.227",
"Id": "23427",
"Score": "0",
"body": "@mKorbel I knew there had to be a downside! :(.. I havent heard of the Code Review site myself til today"
}
] |
[
{
"body": "<p>It's a rather interesting piece of code, I'm going to enjoy reading it further when I have more time ;)</p>\n\n<p>About the only things that jump out at me is how you are scaling your graphics. I'd suggest having a read through <a href=\"http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html\">http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html</a> as it discuss <code>getScaledInstance</code> and some alternative algorithms.</p>\n\n<p>That aside, I was told, some years ago, you can fake anti aliasing by scaling a image down by 4. That is, if you want an output of a image at 800*600, you need to start with an image 4 times that size and scaling it down, which will produce a \"fake\" anti aliasing that does not rely on the hardware to render.</p>\n\n<p>This may no longer hold true, but it might be of some worth to you</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T16:13:05.007",
"Id": "23428",
"Score": "0",
"body": "+1 Thank you...ah i always forget about the scaling downfalls. And thank you for the tips i might give it a try."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T16:10:27.850",
"Id": "14461",
"ParentId": "14460",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "14461",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T14:16:03.953",
"Id": "14460",
"Score": "8",
"Tags": [
"java",
"performance",
"swing"
],
"Title": "What more can be done to add quality to Swing JPanel drawings?"
}
|
14460
|
<p>I have an array of values of the form:</p>
<pre><code>configs = ["26W", "27W", "28W"...]
</code></pre>
<p>They correspond to <em>some</em> of the <code>a</code> elements in a list:</p>
<pre><code><ul id="value-list"><li><a data-value="26W">...</a></li>
<li><a data-value="27W">...</a></li>...</ul>
</code></pre>
<p>When the data in the list <em>does</em> correspond to an existing <code>a</code>, I need to set the parent <code>li</code> class to "available" and not "unavailable". If there is an <code>a</code> with a value not in the list, I need to set the class to "unavailable" and not "available". (Edit: I realize that having <em>both</em> classnames is redundant, but I don't have the option to change that right now.)</p>
<p>I can think of two ways to do this:</p>
<h3>Iterate</h3>
<pre><code>var $allSwatchItems = $("#value-list > li");
$allSwatchItems.each(function () {
var $this = $(this);
var $a = $this.children("a");
if (configs.indexOf($a.attr("data-value")) === -1) {
$this.addClass("unavailable").removeClass("available");
} else {
$this.addClass("available").removeClass("unavailable");
}
});
</code></pre>
<h3>Two-step</h3>
<pre><code>var $allSwatchItems = $("#value-list > li");
// Set everything to unavailable at first.
$allSwatchItems.removeClass("available").addClass("unavailable");
// Build the selector for the swatch anchors.
var swatchSelector = configs.map(function (val, idx, arr) {
return "a[data-value='" + val + "']";
}).join(", ");
// Set the matching list items to available.
var $availSwatchItems = $allSwatchItems.children(swatchSelector).parent();
$availSwatchItems.removeClass("unavailable").addClass("available");
</code></pre>
<p>I know there are pros and cons to both approaches, but is one <em>significantly</em> better than the other (and how), or is there a third approach I should consider?</p>
<p>Update: Here's how I finally did it:</p>
<pre><code>function checkAvailable() {
if (-1 !== $.inArray($(this).children("a").attr("data-value"), configs)) {
return "available";
} else {
return "unavailable";
};
}
$("ul#value-list > li").removeClass("unavailable available").addClass(checkAvailable);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T21:38:46.627",
"Id": "23450",
"Score": "0",
"body": "What's `configs`? Do you mind about cross browser compatiblity?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T21:57:31.573",
"Id": "23457",
"Score": "0",
"body": "`configs` is the name of the array I mentioned at the very beginning. I have polyfilled `Array.prototype.map` for old browsers. What other cross-browser issues are there?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T18:33:50.083",
"Id": "23596",
"Score": "1",
"body": "`indexOf` works on arrays starting IE9 only :) https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf"
}
] |
[
{
"body": "<p>A good general performance rule of thumb is to avoid hitting the DOM (the HTML-manipulating stuff) more than necessary. Most DOM properties aren't just static properties that get set from somewhere else as things change. Invoking them tends to involve buildup and tear-down and examining of internal state, etc. Anything that actually alters HTML is 99.99% likely to cause reflow calculations.</p>\n\n<p>Why have two classes? Just let the lack of an 'available' when checked for with <code>.hasClass('available')</code> represent 'unavailable'. That way you only hit the DOM when you add 'available' and do the attribute checks with both of those className changes setting off reflow calculations.</p>\n\n<p>A note on the second approach. It looks more concise but it's doing a lot of looping and DOM access under the hood. It's important to understand what JQuery does when invoking it. In this line for instance,</p>\n\n<p><code>$allSwatchItems.removeClass(\"available\").addClass(\"unavailable\");</code></p>\n\n<p>JQ is going to have to run down the collection of DOM elements with an internal loop access the className property, do a replace operation on it, set the className property, then access the className property again match for 'unavailable' and add it on if it isn't there.</p>\n\n<p>People tend to shy away from using the class attribute as a place to tie things to data but I'm of the opinion that you're always binding to something in the HTML. Why not use the most efficient thing that's easiest to share with other concerns? And no, I do not consider HTML an exclusive property of the view in MVC and similar patterns. It also represents content and document structure. Leave HTML out of your JavaScript modeling conventions. It has too much overlap with other concerns and other domains. Think of DOM API stuff as low-level and view modeling as higher-level stuff that buries the DOM stuff.</p>\n\n<p><strong>Here's how I'd do it</strong> - I'll let you sort out what's worth haggling over with your team/tools where control over HTML/CSS is concerned but by baking things into your HTML structure the right way, it can save a lot of work.</p>\n\n<p>HTML like this with unavailable as default sharing with class with data_val classes if needed (classes can have multiple properties separated by spaces):</p>\n\n<pre><code><ul id=\"value-list\">\n<li class=\"data_val_26W\"><a >...</a></li>\n<li class=\"data_val_27W\"><a>...</a></li>...\n</ul>\n</code></pre>\n\n<p>build your available selector:</p>\n\n<pre><code>var swatchSelector = '.data_val_' + config.join(', .data_val_'),\n//#value-list step to reduce brutal IE8 DOM tomfoolery\n$availableSwatchItems = $('#value-list').find(swatchSelector);\n\n$availableSwatchItems.addClass('available'); //.remove('unavailable') if you must\n</code></pre>\n\n<p>It's not a minor thing to not have control over your HTML and CSS. By structuring to your advantage, you can drastically reduce code and improve performance. Any tool or back-end dev who makes this impossible is like a stick in the eye for a client-side dev. That's your domain. You should have control over it. As for custom attributes, when browsers have access methods as fast as className and ID for other attributes I don't really care what people use for attributes in HTML5 but for now, it's a pointless performance-hamperer, IMO.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T21:56:38.617",
"Id": "23456",
"Score": "0",
"body": "Heh, I should've mentioned I don't get to pick the classnames. Anyway, +1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T22:00:00.543",
"Id": "23458",
"Score": "0",
"body": "By the way, could you be more explicit about not hitting the DOM more often than necessary? I would think my *two-step* approach hits the DOM less often, but what do you think?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T22:10:24.123",
"Id": "23461",
"Score": "0",
"body": "At a glance I'd say you're hitting the DOM properties more in the second one. Also, attribute selectors `'a[data-value=something]'` are much slower than ID, tag, and class selectors. (although class selectors stink in IE<9)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T22:11:07.417",
"Id": "23462",
"Score": "0",
"body": "I'll add some to think in terms of what JQ is actually doing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T22:52:02.253",
"Id": "23486",
"Score": "0",
"body": "NM. I'll just show how I'd do it under ideal circumstances."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T21:27:23.520",
"Id": "14466",
"ParentId": "14465",
"Score": "5"
}
},
{
"body": "<p>I prefer the idea of the second approach, but I think the code in the first is less complicated. The second approach is too hard to understand it at a glance. Therefore the first is significantly better. Clarity is a prerequisite for maintainability.</p>\n\n<p>You don't specify but it looks like there is only a single <code>A</code> per each <code>LI</code>. I'm going on that assumption.</p>\n\n<p>What the selector build does can be written in a more traditional manner:</p>\n\n<pre><code>$(\"#value-list > li > a[data-value]\")\n // assume unavailability\n .parent()\n .removeClass(\"available\")\n .addClass(\"unavailable\")\n .end()\n .filter(function () {\n // is item available?\n return $.inArray( $.attr( this, 'data-value' ), configs ) !== -1;\n })\n // whatever remains is available\n .parent()\n .removeClass(\"unavailable\")\n .addClass(\"available\")\n ;\n</code></pre>\n\n<p>But I think this is even more elegant and succinct:</p>\n\n<pre><code>$(\"#value-list > li > a[data-value]\")\n // remove all availability classes\n .parent()\n .removeClass(\"unavailable available\")\n .end()\n // add availability classes\n .each(function () {\n // is item available? (avoiding query construction)\n var is_available = $.inArray( $.attr( this, \"data-value\" ), configs ) !== -1;\n // add appropriate class depending on availability\n $( this.parentNode ).addClass( is_available ? \"available\" : \"unavailable\" );\n });\n</code></pre>\n\n<p>I usually try to keep DOM alterations and query construction to a minimum as these are the most costly things to do. Also <code>Array.indexOf</code> is not available on older MSIE so use $.inArray if you need support for those.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T22:28:51.007",
"Id": "23469",
"Score": "0",
"body": "+1 because I really like your last approach, but the `.removeClass` is removing the classname from the wrong elements."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T22:38:07.423",
"Id": "23475",
"Score": "0",
"body": "Did you test it? There may be something I am missing from the description? I am assuming you only need one or the other of these classes per `li` and the loop should be reassigning the correct one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T15:29:20.800",
"Id": "23531",
"Score": "0",
"body": "Yes, but the `.removeClass` applies to the `a`, not the `li`. I'll post an edit to the question showing how I finally did it. It was heavily influenced by your answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T00:07:02.700",
"Id": "23557",
"Score": "0",
"body": "*\\*Facepalm!\\** I knew I should have set up a test case. I have fixed the logic so that it works correctly now (or I would not be able to sleep peacefully)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T22:01:13.460",
"Id": "14467",
"ParentId": "14465",
"Score": "3"
}
},
{
"body": "<p>The solution you edited into your question can be improved upon (shortened and sped up) by using an object for <code>configs</code> instead of an array. After all, you're just using it as a lookup now - and an array is one of the worst ways to store a simple lookup.</p>\n\n<p>Here's a complete implementation.</p>\n\n<pre><code>var configs = {'26W':1, '27W':1, '28W':1, ...};\n$(\"ul#value-list > li\").removeClass(\"unavailable available\").addClass(function () {\n return configs[$(this).children('a').attr('data-value')] ? 'available' : 'unavailable';\n});\n</code></pre>\n\n<p>Alternatively, use <code>configs.hasOwnProperty(x) ? y : z;</code> if you're concerned about <code>Object.prototype</code> being modified.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T03:08:30.420",
"Id": "14518",
"ParentId": "14465",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "14467",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T21:18:43.423",
"Id": "14465",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"iteration"
],
"Title": "jQuery iterate or two-step?"
}
|
14465
|
<p>Can anyone refactor this code without the for loop?</p>
<pre><code><?php
function lorem($paragraph_count = 1, $times = 1, $content = '')
{
$paragraph = array(
"Lorem ipsum dolor sit amet ......... Fusce a ante.",
"Praesent sit amet est. Vestibulum quis elit ......... consectetuer quis, quam.",
"Suspendisse ac eros. Morbi ......... feugiat at, tincidunt eget, ante.",
"Proin sit amet ......... nisi lacinia tristique.",
"Vivamus eu nisl sit amet tortor euismod venenatis ......... Proin tortor. Integer pulvinar."
);
for($i = 0; $i <= $paragraph_count; $i++) $content .= "<p>{$paragraph[$i]}</p>\n";
return str_repeat($content, $times);
}
?>
<?= lorem(2,2); ?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T01:34:33.923",
"Id": "23500",
"Score": "0",
"body": "Is your end goal readability/maintainability, or performance (or both)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T02:58:01.650",
"Id": "23501",
"Score": "0",
"body": "Performance but condensed code... ruby oneliner style!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T13:01:42.290",
"Id": "23524",
"Score": "0",
"body": "possible duplicate of [Can anyone better refactor this php lorem generator?](http://codereview.stackexchange.com/questions/14417/can-anyone-better-refactor-this-php-lorem-generator)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-01T20:49:04.323",
"Id": "149097",
"Score": "0",
"body": "The title of your post should be the function/purpose of your code."
}
] |
[
{
"body": "<p>Use <code>array_slice</code> to return a narrow selection from an array:</p>\n\n<pre><code>function random_paragraphs (array $chunks, $length=1) {\n shuffle($chunks);\n return '<p>'.\n implode(\n '</p><p>',\n array_slice(\n $chunks, \n 0,\n (count($chunks) > $length ? $length : count($chunks))\n )\n ).\n '</p>';\n}\n\necho random_paragraphs($paragraph, 5);\n</code></pre>\n\n<p><strong>Documentation</strong></p>\n\n<ul>\n<li><a href=\"http://www.php.net/manual/en/function.array-slice.php\" rel=\"nofollow\">http://www.php.net/manual/en/function.array-slice.php</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T00:21:24.637",
"Id": "23496",
"Score": "0",
"body": "Another alternative I'm trying is array_filter() with a closure or lamba but not working yet"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T00:59:55.200",
"Id": "23498",
"Score": "0",
"body": "For an ugly 1 liner: return array_reduce( array_slice($paragraph, 0, $paragraph_count), function ($a, $b) { return \"<p>{$a}{$b}</p>\\n\"; } );"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T01:08:38.657",
"Id": "23499",
"Score": "1",
"body": "`array_filter` is not an appropriate function for this use. What exactly are you trying to accomplish here?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T03:01:55.470",
"Id": "23502",
"Score": "0",
"body": "I deal with arrays seemingly every 2nd line, from MySQL results, mongo sets etc... and always using foreach to iterate/modify/parse array keys/elements... I'm looking for alternative functions/ways of doing it so not always using the foreach albeit it's fit. I know it does what it says on the tin but it's getting like rape trains in COD Zombies! Just looking for slick alternatives... yeah array_filter wudn't work unless array_filter( array_flip($array) ). I really appreciate the feedback and Thanks :) Just trying to accomplish alternatives that are viable."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T23:46:35.693",
"Id": "14471",
"ParentId": "14468",
"Score": "1"
}
},
{
"body": "<p>As a general rule, any iterative loop can be recreated using recursion, and vice-versa. That said, you don't necessarily want to use recursion to solve most problems. Here is the recursive form, however:</p>\n\n<pre><code>function lorem($paragraph_count = 1, $times = 1, $content = '') {\n $paragraph = array(\n \"Lorem ipsum dolor sit amet ......... Fusce a ante.\",\n \"Praesent sit amet est. Vestibulum quis elit ......... consectetuer quis, quam.\",\n \"Suspendisse ac eros. Morbi ......... feugiat at, tincidunt eget, ante.\",\n \"Proin sit amet ......... nisi lacinia tristique.\",\n \"Vivamus eu nisl sit amet tortor euismod venenatis ......... Proin tortor. Integer pulvinar.\"\n );\n\n // Build a base body of text with the desired number of entries from lorem ipsum\n if ($paragraph_count > 0) {\n $content = \"<p>{$paragraph[$paragraph_count-1]}</p>\\n\"+ $content;\n return lorem($paragraph_count-1, $times, $content);\n }\n\n // Regular base case\n if ($times <= 1) {\n return $content;\n }\n\n // Repeat the base body of text we built\n return $content + lorem($paragraph_count, $times-1, $content);\n}\n\necho lorem(2,2);\n</code></pre>\n\n<p>I'd stick with the iterative version.</p>\n\n<p>p.s. sorry if there are any typos, I typed it up in python then changed to php syntax : (</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T00:18:16.493",
"Id": "23494",
"Score": "0",
"body": "Thanks for the reply James... definitely a contender... never thought of calling the __ FUNCTION __ again with new arg values"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T00:12:19.257",
"Id": "14473",
"ParentId": "14468",
"Score": "0"
}
},
{
"body": "<p>The following replaces the loop using higher-order functions:</p>\n\n<pre><code>$para = function($p) { return \"<p>$p</p>\\n\"; };\n$content = implode('', array_map($para, array_slice($paragraphs, 0, $paragraph_count)));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T09:47:47.550",
"Id": "14479",
"ParentId": "14468",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T22:19:45.440",
"Id": "14468",
"Score": "0",
"Tags": [
"php"
],
"Title": "Can anyone take the for loop out of this code?"
}
|
14468
|
<p>Yes, I'm bad at conditionals. I don't use them so much and I feel a bit lost with them. How would you (if possible) refactor or change this little piece of code?</p>
<p><strong>Second improved version</strong>:</p>
<pre><code>$MAX_FNAME_LEN = 255;
$clientFilename = $this->file->getClientOriginalName();
$clientExtension = $this->file->guessExtension();
// Assume a failure in reading client filename
$defFilename = $defRandFilename = uniqid('fid_', true);
if(!is_null($clientFilename))
{
$clientFilenameLength = strlen($clientFilename);
$hasClientExtension = !is_null($clientExtension);
$removeFromEnd = $hasClientExtension ? - (1 + strlen($clientExtension)) : 0;
$appendAtEnd = $hasClientExtension ? ".$clientExtension" : '';
if($clientFilenameLength > $MAX_FNAME_LEN) // Truncate original filename
{
$excessFromEnd = $MAX_FNAME_LEN - $clientFilenameLength - $removeFromEnd;
$defFilename = substr($clientFilename, 0, $excess) . $appendAtEnd;
}
else
$defFilename = $clientFilename; // User original filename
if(strlen($defRandFilename) + abs($removeFromEnd) > $MAX_FNAME_LEN) // Truncate sanitized
$defRandFilename = substr($defRandFilename, 0, $removeFromEnd) . $appendAtEnd;
else
$defRandFilename .= $appendAtEnd; // Use sanitized plus extension
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T04:29:50.670",
"Id": "23503",
"Score": "0",
"body": "is this php? wow, i've never used endif; before, I've always traditionally used { braces and if else statements. What are the benefits to this approach? (this is just a general review comment really)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T05:36:04.780",
"Id": "23504",
"Score": "0",
"body": "@dreza yes, PHP. I like \"explicit end\" cause it clearly states where conditional/loop ends, instead of having too much `}}}}`. I'll do all the time :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T09:53:04.603",
"Id": "23519",
"Score": "1",
"body": "@dreza It’s pretty much discouraged in normal code. It can be tremendously helpful when mixed with a lot of HTML though. When using PHP to create templates, I invariably use this style (otherwise, the braces)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T10:34:06.077",
"Id": "23521",
"Score": "0",
"body": "Cheers guys, good to know about this feature of PHP"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-20T12:04:11.300",
"Id": "24121",
"Score": "1",
"body": "Gremo, I’ve rolled back your edit because it changed the question completely and led to confusion (see showerhead’s answer and my comment below that). If you want to show your code progress, either *add* the new code in the question instead of replacing the old code, or ask a new question if the scope has changed noticeably."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-20T13:04:35.840",
"Id": "24122",
"Score": "0",
"body": "@KonradRudolph you're right, my bad. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T22:51:40.073",
"Id": "466769",
"Score": "0",
"body": "This question title might be one of the worst titles on CodeReview."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T13:10:19.683",
"Id": "466839",
"Score": "0",
"body": "@mickmackusa yes, after 8 years, I agree."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T23:47:57.793",
"Id": "467111",
"Score": "0",
"body": "Feel free to edit your question so that this page can be more easily searched for. @gremo"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-05T12:16:31.473",
"Id": "467585",
"Score": "0",
"body": "@mickmackusa no more the worst title on CodeReview :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-05T12:29:18.053",
"Id": "467586",
"Score": "0",
"body": "Some sample input strings and desired outputs would complete your question and make it upvote-worthy by providing context. @gremo Yes, this is an old question. Yes, I intend to post a review."
}
] |
[
{
"body": "<p>Use early exit: reverse the null-checking conditional and return.</p>\n\n<pre><code>if(is_null($clientFilename))\n return;\n</code></pre>\n\n<p>If your code isn’t in a function, <em>change that</em>.</p>\n\n<p>Next, use consistent indentation for the <code>else</code>: it belongs on the same level as the <code>if</code>, <em>not</em> as the content of the <code>if</code>.</p>\n\n<p>I’d also encourage you to follow general usage in PHP, i.e. to use the braced <code>if</code> style even though I agree with you that the other style is fundamentally more readable.</p>\n\n<p>I’d also get rid of unnecessary variables such as <code>$clientFilenameLength</code>, and of magic constants (<code>255</code>). And as a small clean-up, use string interpolation instead of concatenation where it makes sense.</p>\n\n<p>That leaves us with:</p>\n\n<pre><code>define('MAX_LENGTH', 255);\n$clientFilename = $this->file->getClientOriginalName();\n$clientExtension = $this->file->guessExtension();\n\n// Assume a failure in reading client filename\n$defFilename = $defRandFilename = uniqid('fid_', true);\n\nif(is_null($clientFilename))\n return;\n\n// Remove strlen($clientExtension) + 1 chars from the end\n$hasClientExtension = !is_null($clientExtension);\n$removeFromEnd = $hasClientExtension ? 1 + strlen($clientExtension) : 0;\n$appendAtEnd = $hasClientExtension ? \".$clientExtension\" : '';\n\nif(strlen($clientFilename) > MAX_LENGTH)\n $defFilename = substr($clientFilename, 0, -$removeFromEnd) . $appendAtEnd;\nelse\n // User original upload name\n $defFilename = $clientFilename;\n\nif(strlen($defRandFilename) + $removeFromEnd > MAX_LENGTH) \n $defRandFilename = substr($defRandFilename, 0, -$removeFromEnd) . $appendAtEnd;\nelse\n // Use random file name plus .ext\n $defRandFilename .= $appendAtEnd;\n</code></pre>\n\n<p>But this code probably doesn’t do what you want: the whole check for <code>strlen($clientFilename)</code> is a red herring because the result will <em>not</em> be truncated. It will remove (a string of the length of) the client extension, and subsequently replace it. Is that really what you intended?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T12:20:34.983",
"Id": "23522",
"Score": "0",
"body": "Thanks for your suggestions. Can't use early check (i usually do early check/exit) because this is part of a function. And yes, you're right, this is not the intended behavior. I should remove `strlen($clientFilename) - MAX_LENGTH + strlen($appendAtEnd)`, if i'm right."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T10:05:32.603",
"Id": "14480",
"ParentId": "14474",
"Score": "3"
}
},
{
"body": "<p>Don't really agree with Konrad on a couple of points. First, <code>$clientFilenameLength</code>, while a bit far from where it is actually used and a bit lengthy for such a simple variable name, is not unnecessary. This variable prevents you from having to call a function, <code>strlen()</code>, twice on the same information. Its better to only have to run it once, and therefore the variable is necessary. Even if you only used that variable once, it would still be ok because sometimes it can enhance legibility or efficiency. This is especially the case when defining parameters for a for or while loop, because assigning functions as parameters in them will cause those functions to be called on every iteration, which is much less efficient than assigning a variable beforehand instead.</p>\n\n<p>Again, I have to disagree with Konrad. \"255\" is not a magic constant. First of all, because magic constants, at least in PHP, define constants that are available in every script without you needing to do anything special to get them, such as the file name <code>__FILE__</code>. What I think he meant to say is magic number, but even then, this can't be considered a magic number because you did indeed define it before using it. If however you just did something like the following, then THAT would have been considered a magic number. What you have is fine.</p>\n\n<pre><code>if( $clientFilenameLength > 255 ) {//this is a magic number\n</code></pre>\n\n<p>Why not <code>isset()</code> instead of <code>! is_null()</code>? <code>isset()</code> has the added benefit of also checking for a null value and means you don't have to use the \"not\" syntax.</p>\n\n<pre><code>if( isset( $clientFilename ) ) {\n $hasClientExtension = isset( $clientExtension );\n</code></pre>\n\n<p>Make sure you use the proper variables! You've created an <code>$excessFromEnd</code> variable and then use <code>$excess</code> instead, so this wont work. This is why long variable names aren't always good. Be descriptive, but not excessive. God, I'm full of puns today, first lengthy then excessive :) Don't worry, I'll leave shortly. Speaking of names, all-caps separated by underscores should only really be used for constants, which <code>$MAX_FNAME_LEN</code> can, and probably should, be.</p>\n\n<p>Subtracting a negative, at least if I remember highschool well enough, results in addition, so why not just make <code>$removeFromEnd</code> positive and add it? This will also mean that you can remove that <code>abs()</code> function.</p>\n\n<pre><code>$removeFromEnd = $hasClientExtension ? 1 + strlen($clientExtension) : 0;\n//rest of code\n$excessFromEnd = $MAX_FNAME_LEN - ( $clientFilenameLength + $removeFromEnd );\n//rest of code\nif( strlen( $defRandFilename ) + $removeFromEnd > $MAX_FNAME_LEN ) {\n</code></pre>\n\n<p>Always use braces! For languages, such as Python, that don't use braces, this is fine. But with PHP, even though they allow it, this is bad. PHP even agrees this is bad as it can cause issues with your code. Another good reason is to enhance legibility. I'm pretty sure this is similar for a lot of people, but I always expect the braces. So when I'm reading some code and it doesn't have them I have to go back to the beginning because when I got to the end the braces didn't match up. I don't always believe indentation, especially on CR, because sometimes its lost in the transfer process. It's just two little characters but they do so much.</p>\n\n<pre><code>else {\n $defFilename = $clientFilename; // User original filename\n}\n</code></pre>\n\n<p>Wow, just noticed this, and that should be a flag right there. Don't assign a variable to a variable you are just defining! They are hard to spot, and therefore hard to debug. As I just pointed out, I JUST found this while I was nearing the end of your script when I found <code>$defRandFilename</code> and was trying to figure out where it came from (answer: the beginning of the script). I had to use my IDE's highlighting to help me. If you need a copy of a variable, make one after you've made the original. But, from what I can tell from your code, this is just unnecessary. Just remove <code>$defFilename</code> here, you have it being reassigned no matter what later and you never use it before that. Actually, you just never really use it at all. You define <code>$defFilename</code> but its never used after that, I'm assuming because this is only partial code, but figured I'd point it out just in case.</p>\n\n<pre><code>$defFilename = $defRandFilename = uniqid('fid_', true);// this === bad\n</code></pre>\n\n<p>Alright, so if I'm reading this right, you just want to create a filename with a maximum of 255 characters, including extension. There is a problem. You are not comparing both the filename length AND extension length to the maximum allowed. At least not for <code>$defFilename</code>. You do, however, do it for <code>$defRandFilename</code>, but for <code>$defFilename</code> you are just comparing the filename's length. When you create the <code>$removeFromEnd</code> variable, you add the clause for the extension being removed as well, but you don't ever check it. BTW: What is the purpose of having both <code>$defFilename</code> AND <code>$defRandFilename</code>?</p>\n\n<p>Now, you were asking for an easier way to do this. You could just use <code>substr()</code> from the beginning. If the length parameter passed to <code>substr()</code> is larger than the length of the supplied string it will only go to the original string's length, with no out of bounds errors or anything. So....</p>\n\n<pre><code>if( isset( $clientFilename ) ) {\n $newFilename = substr( $clientFilename, 0, $MAX_FNAME_LEN - strlen( $clientExtension ) );\n $newFilename .= $clientExtension;\n}\n</code></pre>\n\n<p>I hope that's what you were looking for, and I hope the rest helps too :) The best advice I can give you right now is to make sure you define your variables close to where they are actually going to be used, rather than four or five lines away, or multiple indentations away. This was the biggest issue I had with reading this code. Well that and the braces. Good luck!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-20T12:00:17.580",
"Id": "24119",
"Score": "0",
"body": "Magic number – yes. However, OP edited his post. In the original version he *did* use a magic number without defining a constant/variable. As for the redundant variable `$clientFilenameLength`: you claim that it’s good because it removes a redundant call to `strlen`. But have a look at my code: there is no redundant call."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-20T13:33:53.010",
"Id": "24123",
"Score": "0",
"body": "@KonradRudolph: I apologize if that's the case, I don't remember seeing an edited tag. Its been more than a week, and my memory is horrible. As for the variable, that's not the only reason I gave. However, yes, in your code it is unnecessary. I don't know if I just didn't notice, or what. Mostly I just try focusing on the OP's code rather than answers that already exist. I read them to make sure I'm not repeating them, but more or less I skim and leave it to the OP to read them fully and glean the best information."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T15:06:05.273",
"Id": "14485",
"ParentId": "14474",
"Score": "2"
}
},
{
"body": "<p>For anyone who \"is bad at conditionals\", the good news is that this script can be sensibly written with only one conditional. I am electing to use a ternary expression in my custom function -- this avoids all of the debate around preferred control structure syntax.</p>\n\n<ol>\n<li><p>If the filename has length, use that string (doesn't matter if it is an empty string or null or false). Otherwise generate the random prefixed string.</p></li>\n<li><p>Prepend a dot to the extension value. By unconditionally trimming the dots from the right side of the string, the prepended dot will be removed. This spares having to writing a condition and saving the extension length to a variable.</p></li>\n<li><p>Unconditionally truncate the filename before appending the extension.</p></li>\n</ol>\n\n<p>This helper function has default values for every parameter so its utility is maximized for your application.</p>\n\n<p>Code: (<a href=\"https://3v4l.org/F5p5b\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>function prepareClientFilename($filename = '', $extension = '', $maxLength = 255) {\n $filename = strlen($filename) ? $filename : uniqid('fid_', true);\n $extension = rtrim(\".{$extension}\" , '.');\n return substr($filename, 0, $maxLength - strlen($extension)) . $extension;\n}\n\n$tests = [\n prepareClientFilename('this_is_a_string', 'txt'),\n prepareClientFilename(str_repeat(implode(range('a','z')), 9), 'pdf'),\n prepareClientFilename(str_repeat(implode(range('a','z')), 10), ''),\n prepareClientFilename(str_repeat(implode(range('a','z')), 10), 'csv'),\n prepareClientFilename('', 'jpeg', 10),\n prepareClientFilename('', 'mp4'),\n prepareClientFilename(),\n];\n\nvar_export(array_combine($tests, array_map('strlen', $tests)));\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>array (\n 'this_is_a_string.txt' => 20,\n 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz.pdf' => 238,\n 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstu' => 255,\n 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopq.csv' => 255,\n 'fid_5.jpeg' => 10,\n 'fid_5e610132001487.17408713.mp4' => 31,\n 'fid_5e6101320014a8.21403474' => 27,\n)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-05T22:25:41.417",
"Id": "238455",
"ParentId": "14474",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "14485",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-08-09T01:36:41.897",
"Id": "14474",
"Score": "2",
"Tags": [
"php",
"php5"
],
"Title": "Conditionally truncating a filename to a max length without damaging the file extension"
}
|
14474
|
<p>As a learn-by-doing project to learn Java webapps, I'm creating a website for registering and displaying happenings using JSP/Servlets, Apache Tomcat server, JDBC and a MySQL database.</p>
<p>I use JSP for views, Servlets for controller functionality and business logic, and I've created ONE DBManager.java class (my only DAO) to abstract SQL statements from my Servlets and JSPs. In my Servlets, I use the <code>DBManager</code> class by declaring a new instance and calling its public methods.</p>
<p>For instance:</p>
<pre><code>DBManager dbm = new DBManager();
Boolean userIsUpdated = dbm.updateUserInDB(user);
</code></pre>
<p>My DAO looks briefly like this:</p>
<pre><code>public class DBManager {
final String DATABASE_URL = "NOPE, I won't give you this one ;)";
Connection connection = null;
PreparedStatement pstmt = null;
public DBManager() {
//Nothing in constructor yet.
}
public ArrayList<Happening> getAllActivatedHappenings() {
//code removed for readability
}
public User logInAndGetUserByEmailAndPassword(String email, String password) {
//code removed for readability
}
public User insertUserIntoDB(User user) {
//code removed for readability
}
public boolean updateUserInDB(User user) {
//code removed for readability
}
public boolean insertHappeningIntoDB(Happening happening) {
//code removed for readability
}
public boolean deleteHappeningFromDB(int happeningId, int userId) {
//code removed for readability
}
public ArrayList<HappeningType> getAllHappeningTypes() {
//code removed for readability
}
public ArrayList<Happening> getAllHappeningsByUserId(int userid) {
//code removed for readability
}
public byte[] getPhotoByHappeningId(int happeningId, String imageType) {
//code removed for readability
}
public Map<Integer, String> getCountiesMap() {
//code removed for readability
}
public Boolean userIsHappeningOwner(int userId, int happeningId) {
//code removed for readability
}
public Happening getHappeningByHappeningId(int happeningId) {
//code removed for readability
}
public boolean updateHappening(Happening happeningDummy, String updateImage) {
//code removed for readability
}
public ArrayList<Happening> getFilteredActivatedHappenings(HttpServletRequest request) {
//code removed for readability
}
public boolean activateHappening(int happeningId) {
//code removed for readability
}
public boolean updateEmailNotificationForUser(User user, String emailnotificationhappeningtypeids, String emailnotificationcountyids) {
//code removed for readability
}
public User getUserByEmail(String email) {
//code removed for readability
}
}
</code></pre>
<p>As you can see, my DAO handles quite a lot of different transfer objects (happenings, users, cities, happening types etc.). Should I break this DAO into several smaller DAO classes (like <code>HappeningDAO</code>, <code>UserDAO</code>, etc.)? Any other reasons for doing this than readability?</p>
<p>Also, is this approach thread-safe as long as I declare a new instance of <code>DBManager</code> within my <code>doGet</code>/<code>doPost</code> methods in the servlets?</p>
|
[] |
[
{
"body": "<p>Just a quick note: <code>ArrayList<...></code> return types should be simply <code>List<...></code>. See: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T04:34:36.593",
"Id": "14476",
"ParentId": "14475",
"Score": "2"
}
},
{
"body": "<p>I would use an Object-Relational Map package, such as Hibernate. Almost all of the object specific logic could then be moved to the DAO objects themselves and the DBManager would only have to worry about database transactions - fetching, updating, inserting, and deleting objects.</p>\n\n<p>Even if you do not choose to use such a package, the logic for each object type should still be moved somewhere else - either to the DAO class itself or to some kind of DB helper object that would translate high level actions into low level DB calls/SQL.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T04:39:27.383",
"Id": "14477",
"ParentId": "14475",
"Score": "2"
}
},
{
"body": "<p>Unless it is a professional project, I suggest, for study before beginning a long work, you look before in <a href=\"http://community.versant.com/Downloads.aspx\" rel=\"nofollow\">Quick download db4o</a> (you can load 8.1)<br></p>\n\n<p>Inside zip file, you have doc directory with a tutorial for learn, and a reference for browser with index and search tool (very complete and uptodate doc).</p>\n\n<p>First work with EmbeddedObjectContainer, have a look to</p>\n\n<ul>\n<li>SODA query,</li>\n<li>Transparent Activation and Transparent Persistence to understand OODB powerfulness,</li>\n<li>After you can configure a Server.</li>\n<li>Don't forget OME the integrated manager, it can be a model for your project.</li>\n<li>You will forget 'select/join' SQL burden for a light/fast 'choose and navigate' in OODB.</li>\n<li>Do not imagine table for data but graph : some fields are ActivatableArry[Set|List|..] linking instances, as internal indexes.</li>\n</ul>\n\n<p>Have in mind that db4o can be migrated to Versant professional for huge databases.</p>\n\n<p>If you are aware, this will take few time, and with a couple of hour you will be able to see OODB functionnality, then you will be able to test some tools.</p>\n\n<p>You can try to work with JSON (<a href=\"https://vaadin.com/demo/\" rel=\"nofollow\">Vaadin</a>) for Web with Tomcat.\nIf you want to go further look <a href=\"http://www.jease.org/\" rel=\"nofollow\">Jease</a> to avoid some pitfalls, and more stressed web conections</p>\n\n<p>All those tools are Eclipse compatible </p>\n\n<p>So you will be able if it is worth to continue in your first way or choose another perspective, but SGBDR will give you more problems, more works, more issues, and SQL is not powerfull for OO code, even if Hibernate is powerfull it is complicated, SQL have no future for OO languages, and JSON is more now mature.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T14:37:23.343",
"Id": "23528",
"Score": "0",
"body": "I wouldn't necessarily agree that Hibernate is complicated. Yes, there are many features and it can do some complicated things, but if you ignore most of it and just stick to what you need, it can be very simple - especially with JPA annotations. Nor do I necessarily agree that OODBs are the answer for every problem. Yes, they are good answers for many problems, but no solution is universally best."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T15:31:19.393",
"Id": "23532",
"Score": "0",
"body": "@Donald.McLean - As SGBDR DBA (Sybase/Oracle), I can understand your point of view. - Yes OODB are not universal, but they are now mature ... I can say that I'll never more code request/join. For me SQL is dead (even if many API work with it [as on Cobol], and many peoples will be paid for it). So, I just gave new orientations to look inside, before coding a new project. Thanks for attention you paid for my post."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T08:02:24.180",
"Id": "14478",
"ParentId": "14475",
"Score": "-1"
}
},
{
"body": "<p>Yes, I would split the one DAO object onto several separated one, because yours is going to grow and soon you'll realise that it has become a mess.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-19T08:40:34.490",
"Id": "14825",
"ParentId": "14475",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T19:24:01.510",
"Id": "14475",
"Score": "4",
"Tags": [
"java",
"database"
],
"Title": "DAO for happenings registration website"
}
|
14475
|
<p>I'm doing exercise 11.8 from Scala for impatient, asking to write a matrix class: </p>
<blockquote>
<p>Provide a class <code>Matrix</code> - you can choose whether you want to implement 2
x 2 matrices, square matrices of any size, or m x n matrices. Supply operations + and *. The latter should also work with scalars, for example mat * 2. A single element should be accessible as <code>mat(row, col)</code>.</p>
</blockquote>
<p>The code is working, but may be there can be improvements to make code more functional or more stable:</p>
<pre><code>class Matrix(val n: Int, val m: Int, fun: (Int, Int) => Double) {
private val matrix = Array.tabulate[Double](n,m)(fun)
def +(another: Matrix) = {
if (n != another.n || m != another.m)
throw new IllegalArgumentException("Sizes of arrays don't match.")
else
new Matrix(n, m, (i, j) => this(i)(j) + another(i)(j))
}
def *(another: Matrix) = {
if (m != another.n)
throw new IllegalArgumentException("Sizes of arrays don't match.")
else
new Matrix(n, another.m, (i,j) => { var sum = 0.0;
for (k <- matrix(i).indices) sum += matrix(i)(k) * another(k)(j);
sum }
)
}
def *(k: Int) = new Matrix(n, m, k * matrix(_)(_) )
def apply(i: Int)(j: Int) = matrix(i)(j)
override def toString = {
var result = ""
for (row <- matrix) {
for (value <- row)
result += value + " "
result += "\n"
}
result
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T18:11:02.287",
"Id": "23590",
"Score": "0",
"body": "It's curious how you use a function as part of the constructor parameters. Is that proposed by the book? If so, could you give more details? If not, then I think you went the wrong way. No clue why the `tabulate` is in there either, and I'm not sure if it's something the book said that you didn't mention, or something you came up with for reasons I don't understand."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T19:54:59.173",
"Id": "23599",
"Score": "0",
"body": "Hi, thanks for response. I updated the question. No, it was not part of task, I used it by myself. What's wrong with function in constructor and tabulate, could you please explain? May be Array in constructor would be better, I just decided that it's quicker to generate values with function, than create 2-dimensional array."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T20:32:48.327",
"Id": "23601",
"Score": "0",
"body": "There should be a way to update individual values in the matrix, I think. The use of the function is clever, but won't work if you are allowed to update (create a new matrix with updated) individual values. I suggest you redo the problem with that additional (implicit?) requisite."
}
] |
[
{
"body": "<p>Remove all <code>var</code>. Doesn't the book show <code>for...yield</code> by that point? For example:</p>\n\n<pre><code>(i,j) => { \n var sum = 0.0; \n for (k <- matrix(i).indices) sum += matrix(i)(k) * another(k)(j); \n sum \n}\n</code></pre>\n\n<p>Can be replaced with:</p>\n\n<pre><code>(i,j) => (for (k <- matrix(i).indices) yield matrix(i)(k) * another(k)(j)).sum\n</code></pre>\n\n<p>The <code>var</code> on <code>toString</code> can be replaced by using <code>mkString</code>. I'll let you work out for yourself how to do that, now that I called your attention to that method. And, yes, it that method works on <code>Array</code> as well, though it doesn't appear on Scaladoc for Scala up to 2.9.2 because it is added implicitly. I suggest you use the <a href=\"http://www.scala-lang.org/archives/downloads/distrib/files/nightly/docs/library/index.html\" rel=\"nofollow\">nightly scaladoc</a> to look things up -- the documentation there is better, though it may show things not available on release versions, and so is the tool itself.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T20:39:28.243",
"Id": "14537",
"ParentId": "14483",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "14537",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T13:42:36.020",
"Id": "14483",
"Score": "4",
"Tags": [
"scala",
"matrix"
],
"Title": "Producing a matrix class that supports any size"
}
|
14483
|
<p>Is there a better way to do this? I'm kinda ending up having a lot of <code>if</code> statements.</p>
<pre><code>if params[:custom_url] || params[:user_id]
if !params[:user_id].blank?
@user = User.find(params[:user_id]).first
@url = @user.custom_url
else
@url = params[:custom_url]
@user = User.where(:custom_url => @url).first
end
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-11T12:23:17.017",
"Id": "23617",
"Score": "1",
"body": "instead of `!params[:user_id].blank?`, you can write `params[:user_id].present?` which reads more nicely."
}
] |
[
{
"body": "<p>Not a big fan of <code>case..when</code>:</p>\n\n<pre><code>@user = User.find_first(params[:user_id]) if params[:user_id]\n@user ||= User.find_by_custom_url(@url)\n\n@url = params[:custom_url] || @user.custom_url\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-11T20:32:07.873",
"Id": "23634",
"Score": "2",
"body": "At line 2, @url is going to be nil, so there's no sense using it as a param."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T19:32:08.360",
"Id": "34688",
"Score": "0",
"body": "Line 1, wouldn't it be better to use `if params[:user_id].present?`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T22:49:31.120",
"Id": "14541",
"ParentId": "14487",
"Score": "1"
}
},
{
"body": "<p>I typically chain scopes together like this:</p>\n\n<p>Model:</p>\n\n<pre><code>def self.by_user_and_url(user_id, custom_url)\n by_user(user_id).by_custom_url(custom_url)\nend\n\ndef self.by_user(user_id)\n user_id ? where(user_id: user_id) : scoped\nend\n\ndef self.by_custom_url(custom_url)\n custom_url ? where(custom_url: custom_url) : scoped\nend\n</code></pre>\n\n<p>Controller:</p>\n\n<pre><code>if params[:custom_url].present? || params[:user_id].present?\n @user = User.by_user_and_url(params[:user_id], params[:custom_url]).first\nend\n</code></pre>\n\n<p>I'm not sure why you had two instance variables. The url can be pulled from the @user instance variable if you need it in your view.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-23T06:11:36.407",
"Id": "14975",
"ParentId": "14487",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T15:34:36.987",
"Id": "14487",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Checking custom URLs and user IDs"
}
|
14487
|
<p>I calculate a highscore and find the users current rank like shown <a href="https://stackoverflow.com/questions/2195257/ranking-entries-in-mysql-table">here</a>. This is the query:</p>
<pre><code>SELECT * FROM (SELECT q.*, @r := @r + 1 AS rank
FROM ( SELECT @r := 0 ) vars,
(
SELECT p.*, MAX(punkte) AS max_points
FROM olympia_punkte_alle p
WHERE markt_id = 1
GROUP BY fb_id
ORDER BY max_points DESC
) q) AS q2 WHERE fb_id = '26950' ORDER BY max_points DESC LIMIT 1
</code></pre>
<p>Problem is that the table has many rows (~8,5 Mio) and so this query is very slow. I could cache the sub select but than the highscore is always kind of old.</p>
<p>Any thoughts on how to make this faster?</p>
<p>EXPLAIN:</p>
<pre><code>id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY <derived2> ALL NULL NULL NULL NULL 1352 Using where; Using filesort
2 DERIVED <derived3> system NULL NULL NULL NULL 1
2 DERIVED <derived4> ALL NULL NULL NULL NULL 1352
4 DERIVED p ref markt_id 4 2055 Using where; Using temporary; Using filesort
3 DERIVED NULL NULL NULL NULL NULL NULL NULL No tables used
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T16:12:23.370",
"Id": "23533",
"Score": "0",
"body": "Since rank is calculated on the outer query, is it really necessary here? Could this be calculated in php instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T16:15:14.407",
"Id": "23534",
"Score": "1",
"body": "@Waygood: You want to load 8,5 millions records to memory in php script?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T16:19:40.230",
"Id": "23535",
"Score": "0",
"body": "After re-reading, the OP just wants the current rank, not a list of rankings, which would have been row number (in php). +1'd @ŁukaszW.pl (you LOL)"
}
] |
[
{
"body": "<p>What about this query:</p>\n\n<pre><code>SELECT COUNT(*) + 1 as user_rank\n FROM olympia_punkte_alle p\n WHERE markt_id = 1\n GROUP BY fb_id\n HAVING \n MAX(punkte) > (SELECT MAX(punkte)\n FROM olympia_punkte_alle\n WHERE markt_id = 1\n GROUP BY fb_id\n HAVING fb_id = 2950)\n</code></pre>\n\n<p>We are getting the count of users that have better score then users with id <code>2950</code>.\nThe count of better users + 1 is rank of your user.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-13T11:22:44.107",
"Id": "23691",
"Score": "0",
"body": "Nice, this query is 1 second faster! But still takes 6 seconds. I am trying to store max_points, that should make it faster."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T16:12:46.480",
"Id": "14489",
"ParentId": "14488",
"Score": "1"
}
},
{
"body": "<p>This is the only refactoring that I can come up with:</p>\n\n<pre><code>SET @r = 0;\nSELECT * FROM (\n SELECT q.*, @r := @r + 1 AS rank\n FROM\n (\n SELECT p.*, MAX(punkte) AS max_points\n FROM olympia_punkte_alle p\n WHERE markt_id = 1\n GROUP BY fb_id\n ) q\n ORDER BY q.max_points DESC\n) AS q2\nWHERE fb_id = '26950'\nLIMIT 0,1\n</code></pre>\n\n<p>A possible caching optimization that you could implement is to add a <code>max_points</code> column in some users table somewhere. Then every time a user changes his score, you calculate <code>MAX(punkte)</code> and store that in the <code>max_points</code> column. That way you could save time calculating the maximum points for every query. It would end up something like:</p>\n\n<pre><code>SET @r = 0;\nSELECT * FROM (\n SELECT u.*, @r := @r + 1 AS rank\n FROM users u\n ORDER BY u.max_points DESC\n) AS q\nWHERE q.fb_id = '26950'\nLIMIT 0,1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-13T13:19:55.557",
"Id": "23702",
"Score": "0",
"body": "Storing max_points is a great idea. Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T16:34:18.747",
"Id": "14490",
"ParentId": "14488",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "14489",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T16:01:44.030",
"Id": "14488",
"Score": "2",
"Tags": [
"php",
"mysql",
"optimization"
],
"Title": "Speed up highscore rank calculation"
}
|
14488
|
<p>I wrote a quick function to create a set of radio buttons, three per table row. I would like some feedback about how I can shorten this bit of code using algebraic functions, or different jQuery functionality.</p>
<pre><code>var arr = [ "earth", "mars", "jupiter", "saturn", "venus", "argus", "pluto", "janus", "canary", "orange", "butter pineapple", "eventual bliss"];
var obj = { one:"earth", two:"mars", three:"jupiter", four:"saturn", five:"venus" };
var start = ""; end = "";
var count = 0;
$("#radio_container").append("<table>");
$.each(arr, function(i, val) {
if(count == 3)
{
start = "<tr>";
end = "</tr>"
count= 0;
}
$("#radio_container").append(start);
$("#radio_container").append("<td><input name='finalcategory' type='radio' value='"+val+"'></input></td><td class='style3'>"+val+"</td>");
$("#radio_container").append(end);
count++;
start = "";
end = "";
});
$("#radio_container").append("</table>");
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T19:59:30.177",
"Id": "23545",
"Score": "0",
"body": "Is this question suitable for CR.se? The code as is does not produce the intended result."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T20:08:30.310",
"Id": "23546",
"Score": "0",
"body": "The code was originally in a fiddle, and someone pulled it out of the fiddle and changed my CR question. Fiddle: http://jsfiddle.net/KNseM/1/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T20:10:43.530",
"Id": "23547",
"Score": "1",
"body": "Like I said, this code does not produce the intended result. Inspect the rendered DOM and you'll see what I mean."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T16:45:46.400",
"Id": "23584",
"Score": "1",
"body": "I cannot stress this enough: **add labels** to the text next to the radio buttons: `<label><input type=\"radio\" name=\"foo\"> You can click the text to pick</label>`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-16T17:04:58.600",
"Id": "23985",
"Score": "0",
"body": "You should definitely follow @ANeves' advice. I added the code to my answer."
}
] |
[
{
"body": "<p>Here are some points to consider:</p>\n\n<ol>\n<li><p>Your <code>end</code> variable is declared without a <code>var</code>, so that it's leaking into the global namespace. Don't do that.</p></li>\n<li><p>As it stands now, your <code>obj</code> isn't used anywhere in the code. I'll assume it's not applicable here.</p></li>\n<li><p>Instead of manually keeping <code>count</code> of your iteration, use the <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Arithmetic_Operators#.C2.A0.25_%28Modulus%29\" rel=\"nofollow\">% (Modulus) operator</a> to calculate your rows.</p></li>\n<li><p>jQuery's <code>append</code> method doesn't deal with code fragments the way you seem to think it does. <code>append(\"<table>\")</code> actually appends a whole table, not just an opening tag (that's not even possible).</p></li>\n<li><p>Access to the DOM is not free. Every time you hit the DOM you incur some overhead. Try keeping DOM modification to a minimum.</p></li>\n<li><p>Unlike others, when dealing with a simple HTML construct such as this, I prefer to build my fragment from a concatenated string since <a href=\"http://jsperf.com/dom-vs-concatentation\" rel=\"nofollow\">it's much faster</a>.</p></li>\n</ol>\n\n<hr>\n\n<p>With all that in mind, here's how I would do it:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var arr = [\"earth\", \"mars\", \"jupiter\", \"saturn\", \"venus\", \"argus\", \"pluto\", \"janus\", \"canary\", \"orange\", \"butter pineapple\", \"eventual bliss\"],\n snippet = '<table><tr>';\n\n$.each(arr, function(i, val) {\n\n if (i % 3 == 0) snippet += '</tr><tr>';\n\n snippet += '<td><input name=\"finalcategory\" type=\"radio\" value=\"' + val + '\" /></td>' +\n '<td class=\"style3\">' + val + '</td>';\n});\n\nsnippet += '</tr></table>';\n\n$(\"#radio_container\").append( snippet );\n</code></pre>\n\n<p>See it here in action: <a href=\"http://jsfiddle.net/DWcSN/\" rel=\"nofollow\">http://jsfiddle.net/DWcSN/</a></p>\n\n<hr>\n\n<p>The code above works, but the text is not associated with the radio button in any way.</p>\n\n<p>To remedy that, consider wrapping labels around your radio buttons:</p>\n\n<pre><code>snippet += '<td><label class=\"style3\">' +\n '<input name=\"finalcategory\" type=\"radio\" value=\"' + val + '\" />' +\n val +\n '</label></td>';\n</code></pre>\n\n<p>See it here in action: <a href=\"http://jsfiddle.net/DWcSN/1/\" rel=\"nofollow\">http://jsfiddle.net/DWcSN/1/</a> (clicking the text activates the corresponding button).</p>\n\n<hr>\n\n<p><strong>P.S.</strong> <code>style3</code> is not very descriptive. You should consider coming up with a more intuitive naming convention.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-21T22:24:26.793",
"Id": "24204",
"Score": "0",
"body": "You know i learned alot from asking this one question. There is so much knowledge on this board, i cannot not begin to express how much i appreciate all the help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-21T22:33:09.187",
"Id": "24205",
"Score": "0",
"body": "@AntonioHerrera - Glad you're learning! That's what we're all here for."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T19:44:51.873",
"Id": "14499",
"ParentId": "14497",
"Score": "4"
}
},
{
"body": "<p>Here's how I would probably tackle this:</p>\n\n<pre><code>var arr = [ \"earth\", \"mars\", \"jupiter\", \"saturn\", \"venus\", \"argus\", \"pluto\", \"janus\", \"canary\", \"orange\", \"butter pineapple\", \"eventual bliss\"];\nvar obj = { one:\"earth\", two:\"mars\", three:\"jupiter\", four:\"saturn\", five:\"venus\" };\n\n// Create the table here and attach it to your document.\nvar $table = $('<table>').appendTo('#radio_container'),\n // also, create the scope of $tr so we can keep using it.\n $tr;\n$.each(arr, function(k,v){\n // if it's a multiple of 3, create a new row and attach\n // it to the table\n if ((k % 3) == 0){\n $tr = $('<tr>').appendTo($table);\n }\n // create the data cell\n $('<td>',{\n // add a radio input element within\n 'html':$('<input>',{\n 'name':'finalcategory',\n 'type':'radio',\n 'value':v\n })\n }).appendTo($tr); // attach it to the row\n\n // create the second cell, style and populate it,\n // and also attach it to the row.\n $('<td>',{\n 'class':'style3'\n }).text(v).appendTo($tr);\n});\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/PdFaX/\" rel=\"nofollow\">Working example</a>, and the notes:</p>\n\n<ol>\n<li>Use jQuery to build the objects, don't use <code>\"<html>\"</code> strings.</li>\n<li>With a little refactoring, you can use the pre-created objects to your advantage and rid yourself of a counter variable.</li>\n<li>You can also use modulo (<code>%</code>) to figure out which row you're on.</li>\n</ol>\n\n<p>Some other things:</p>\n\n<ol>\n<li>jQuery allows you to specify an object (<code>{}</code>) as a second parameter which will set the attributes of the object it's creating (see how I've done it to mimic your code).</li>\n<li>Use <code>.text()</code> whenever possible to avoid injecting foul information in to the markup. <code>.text()</code> will sanitize the data for you--let it.</li>\n</ol>\n\n<p><strong>EDIT</strong> Feel free to also heed the advice of a comment about not showing the table until it has completed rendering. This can be done very simply using <code>.hide()</code> and <code>.show()</code> as shown in <a href=\"http://jsfiddle.net/PdFaX/1/\" rel=\"nofollow\">this example</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T19:57:12.147",
"Id": "23544",
"Score": "0",
"body": "We can argue about whether string concatenation is the way to go, but regardless, you shouldn't be appending that table to the DOM until you're done messing around with it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T20:23:15.620",
"Id": "23551",
"Score": "1",
"body": "I can't stress this enough: messing with the DOM is *extremely* expensive. Here's a performance test comparing both our methods: http://jsperf.com/dom-vs-concatentation"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T20:27:28.750",
"Id": "23552",
"Score": "0",
"body": "Hiding and then showing the table doesn't help much. You're still messing with the live DOM! (Hiding/Showing might actually make it worse). I added your other method to the performance test: http://jsperf.com/dom-vs-concatentation"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T20:30:05.133",
"Id": "23553",
"Score": "0",
"body": "@JosephSilber: Acknowledged. I'm not arguing performance, at all. I am however arguing against directly inserting textual information through concatenation. I just don't feel comfortable with `\"+v+\"`. And, FWIW, my same code could handle a lot more variations in `arr` where as yours would fail."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T19:46:45.637",
"Id": "14500",
"ParentId": "14497",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "14500",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T18:56:21.440",
"Id": "14497",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "Set of radio buttons"
}
|
14497
|
<p>I was asked to implement a hash map in this phone interview (screen-share), so time was limited and this is what I came up with. I'd appreciate if someone can take a minute to critique/review it and help me improve.</p>
<p><a href="http://rextester.com/YJX95968" rel="nofollow">Here</a> is an online version of the code.</p>
<pre><code>#include <list>
#include <iostream>
using namespace std;
const int SIZE = 10;
class Node{
public:
Node(){}
Node(int k, int v):key(k), value(v){}
int key, value;
};
class HashMap {
private:
list<Node*> data[SIZE];
public:
~HashMap();
Node* get(int key);
void put(int key, int value);
int hashFn(int val){ return val % 13; }
};
Node* HashMap::get(int key){
int hashValue = hashFn(key);
int bucket = hashValue % SIZE;
list<Node*>::iterator it = data[bucket].begin();
while(it != data[bucket].end()){
Node ** d = &(*it);
if((*d)->key == key){
return *d;
}
it++;
}
return NULL;
}
void HashMap::put(int key, int value){
int hashValue = hashFn(key);
int bucket = hashValue % SIZE;
Node* node = this->get(key);
if(node == NULL){
data[bucket].push_front(new Node(key, value));
}
else{
node->value = value;
}
}
HashMap::~HashMap(){
for(int i = 0; i < SIZE; ++i){
list<Node*>& val = data[i];
for(list<Node*>::iterator it = val.begin(); it != val.end(); it++){
Node* n = *it;
delete n;
}
}
}
int main(){
HashMap map;
cout << "Finding 5: " << map.get(5) << endl; // -1
map.put(5, 10);
map.put(5, 11);
cout << "Finding 5: " << map.get(5)->value; // 11
return 1;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T10:14:27.267",
"Id": "23570",
"Score": "3",
"body": "A destructor is not enough. You have forgotten the rule of three."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T10:39:05.723",
"Id": "23571",
"Score": "0",
"body": "Well, as I mentioned this was a part of telephonic interview and the focus here was on implementing get() and put(). However, I do agree with you and this definitely lacks the rule of three!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T11:09:38.287",
"Id": "23572",
"Score": "0",
"body": "You have not declared the destructor in the class body."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T11:16:42.990",
"Id": "23573",
"Score": "0",
"body": "Yea, I posted the code on Mat's request. Forgot to update both the places."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T11:17:17.420",
"Id": "23574",
"Score": "0",
"body": "Probably I should have also implemented the rules of three for the interviewer."
}
] |
[
{
"body": "<p><strong>Some obvious problems</strong></p>\n\n<ol>\n<li>It leaks memory (every <code>new</code>ly allocated <code>Node</code>) when the Hashmap leaves the scope.</li>\n<li>A delete/remove function is missing.</li>\n<li><strike>It doesn't replace the value within the existing <code>Node</code> on repeated <code>put</code>s with the same key but instead adds an additional <code>Node</code> every time.</strike></li>\n<li>The size is fixed and therefore the hashmap <code>get</code> quickly degenerates into linked list search.</li>\n<li>Key and value types aren't generic.</li>\n</ol>\n\n<p><strong>Some positive things</strong></p>\n\n<ul>\n<li>It implements a hashmap </li>\n<li>uses hash-lookup for search </li>\n<li>returns correct results</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T04:44:05.187",
"Id": "23562",
"Score": "0",
"body": "1. when hashmap leaves the scope, destructor would be called upon its members, aka list and when it gets destroyed, it would call the destructor on its members and hence it won't be a memory leak ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T04:45:07.510",
"Id": "23563",
"Score": "0",
"body": "3. In fact it does replace the value. I see if a node exists in the map, I return that instead and modify the value of that node."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T04:46:35.090",
"Id": "23565",
"Score": "0",
"body": "4. Yes, size is fixed, but a lot depends on the hashFunction to distribute the elements properly. What I wrote was a dummy function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T05:02:27.337",
"Id": "23566",
"Score": "0",
"body": "@brainydexter: For 1., no. The destructor for a `List<T*>` (or any other standard container) doesn't call delete on the pointers it contains."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T09:15:33.547",
"Id": "23569",
"Score": "0",
"body": "@Mat Added destructor code also."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T17:07:56.277",
"Id": "23585",
"Score": "0",
"body": "@brainydexter: Yes, I was wrong about 3., too late yesterday evening..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T17:14:16.847",
"Id": "23586",
"Score": "0",
"body": "@brainydexter: You'd have to enlargen the HashMap and rehash all entries at a certain filling-factor to prevent degeneration to linked list search with lots of entries. With the given hash it's pointless though, you'd use at most 13 buckets even if you allocate more than that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T17:20:51.673",
"Id": "23587",
"Score": "0",
"body": "@Patrick : agreed."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T21:27:52.290",
"Id": "14510",
"ParentId": "14498",
"Score": "4"
}
},
{
"body": "<pre><code>int hashValue = hashFn(key);\nint bucket = hashValue % SIZE;\n</code></pre>\n\n<p>I'd suggest having a <code>bucket(key)</code> function that returns the bucket rather then repeating this piece of code. I'd also create a Bucket class to handle the per-bucket logic. Then your get function would look like:</p>\n\n<pre><code>Node * HashMap::get(int key)\n{\n return bucket(key).get(key);\n}\n</code></pre>\n\n<p>Of course, Bucket::get would have more complicated logic than here, but I think it would simplify your code overall. </p>\n\n<pre><code> Node ** d = &(*it); \n</code></pre>\n\n<p>Its not clear this helps over using the iterator directly in the following lines.</p>\n\n<pre><code>list<Node*>::iterator it = data[bucket].begin();\n\nwhile(it != data[bucket].end()){\n</code></pre>\n\n<p>Why not use a standard for loop here?</p>\n\n<pre><code>list<Node*> data[SIZE];\n</code></pre>\n\n<p>Linked lists are almost always the wrong choice. There are slower for every case except inserting/deleting in the middle. You don't use that here, so you should probably use a <code>vector</code> not a <code>list</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T18:08:36.310",
"Id": "23589",
"Score": "0",
"body": "I agree with creating a bucket function but not quite sure if I understood making a Bucket class ? As for using a while loop over for loop, there was no particular reason, just a style of accessing iterators I prefer. And, though I agree with your suggestion of `vector<Node*> data`, but I also think, whenever we do a lookup based on a key, we have to loop through each element to find it and hence O(n) time. Similarly for insert, I am just inserting this at the beginning which is O(1), so I am not sure how would a vector be better in this case ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T18:11:11.393",
"Id": "23591",
"Score": "0",
"body": "If I were to store elements in a sorted manner, I could use binary search on the vector to reduce lookup time to O(lg n) from O(n) where n is the size of vector. This would increase the insertion time though. Inserting element in a sorted array would take O(n) time. So am not sure if we are actually gaining that much"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T18:26:21.453",
"Id": "23592",
"Score": "1",
"body": "@brainydexter, A Bucket Class would hold your list<> of Nodes and provide `get` and `set` methods just for items which fit into that list."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T18:27:56.117",
"Id": "23593",
"Score": "1",
"body": "@brainydexter, lookup on a vector and list will both be O(n), but vector has a smaller O(n). A vector just to move forward in memory to iterate, but a list has to read a pointer and jump to a completely different memory location."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T18:29:20.903",
"Id": "23594",
"Score": "1",
"body": "@brainydexter, both list and vectors keep track of the location of the last element, so both have O(1) insert at the end. You aren't gaining anything by inserting at the beginning. I'm not exactly sure how the insertion time itself compares between the two methods. Inserting a vector is usually faster, because there is less to do, but if it runs out of capacity it can be more expensive."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T18:31:05.207",
"Id": "23595",
"Score": "0",
"body": "@brainydexter, yes you could do a sorted vector. But then the idea in a hash is that you could get speed by not putting things into the same bucket, so I wouldn't focus on optimizing hash collisions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T18:40:53.090",
"Id": "23597",
"Score": "0",
"body": "About sorted vector, here is what I meant: `vector<Node*> data[SIZE]`. Now, after finding the right bucket, one can search on the vector at this bucket `data[bucket]` (which is a type of vector<Node*>). This lookup can be brought down to O(lg N). I'm not sure what you meant there by putting things into the same bucket."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T18:42:32.040",
"Id": "23598",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/4454/discussion-between-brainydexter-and-winston-ewert)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T17:50:39.673",
"Id": "14534",
"ParentId": "14498",
"Score": "2"
}
},
{
"body": "<p>The first two things I noticed:</p>\n\n<ol>\n<li>Drop the pointers. They give you no advantage. Use value objects.</li>\n<li>Drop the linked list. It’s <em>sluggishly</em> slow. I have no idea why hash maps collision resolution, when taught in class, always mentions lists – probably because it makes the asymptotic runtime analysis easier. They are almost <em>always</em> slower.</li>\n</ol>\n\n<p>Dropping pointers has the nice effect of plugging the leaks and making the code easier – in particular, the rule of three is then trivially satisfied – and more efficient.</p>\n\n<p>Then, since <code>Node</code> is just an aggregate, I’d use <code>std::pair</code>.</p>\n\n<p>For a real implementation, <code>hashFn</code> shouldn’t be a function inside the hash map, it should be a user-supplied function, depending on the type of data (potentially even if the type is not generic, since different data has different characteristics). But a real implementation also would need to be resizable and configurable by load factor.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T20:42:45.290",
"Id": "14538",
"ParentId": "14498",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T19:24:11.130",
"Id": "14498",
"Score": "7",
"Tags": [
"c++",
"interview-questions",
"hash-map"
],
"Title": "Implementation of hash map"
}
|
14498
|
<p>I saw <a href="https://stackoverflow.com/questions/11886977/how-to-wait-current-thread-execution-and-execute-another-thread-completedly">How to wait current thread execution and execute another thread completedly?</a> on StackOverflow, and I <a href="https://stackoverflow.com/questions/6058395/how-to-pause-thread-execution/6058532#6058532">answered it there</a>, but would like more eyes on the code I posted.</p>
<p>The requirement is to pause one thread whilst a different thread is running.</p>
<p>Could you please review and comment on this implementation?</p>
<pre><code>public class App {
public static void main(String[] args) {
Thread1 thread1 = new Thread1();
Thread2 thread2 = new Thread2();
try {
thread1.start();
Thread.sleep(500);
synchronized (thread1) {
thread1.waiting = true;
thread2.start();
thread2.join();
thread1.waiting = false;
thread1.notify();
}
} catch (Exception e) {
//TODO actually handle exception
}
}
}
</code></pre>
<p>Class Thread1.java</p>
<pre><code>public class Thread1 extends Thread {
boolean waiting = false;
public void run() {
testFun1();
}
public void testFun1() {
for (int i = 1; i < 10; i++) {
synchronized (this) {
while (waiting) {
try {
wait();
} catch (Exception e) {
//TODO Handle exception
}
}
}
try {
Thread.sleep(100);
System.out.println("From testFun1() = " + i);
} catch (Exception e) {
//TODO Handle exception
}
}
}
}
</code></pre>
<p>Class Thread2.java</p>
<pre><code>public class Thread2 extends Thread {
public void run() {
testFun2();
}
public void testFun2() {
try {
for (int i = 20; i <= 25; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
//catch
}
System.out.println("From testFun2() = " + i);
}
} catch (Exception e) {
//TODO do something
}
}
}
</code></pre>
<p>Output:</p>
<pre><code>C:\Java\jdk1.6.0_25\bin\java -Didea.launcher.port=7543 "-Didea.launcher.bin.path=C:\Program Files\JetBrains\IntelliJ IDEA 10.5.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Java\jdk1.6.0_25\jre\lib\alt-rt.jar;C:\Java\jdk1.6.0_25\jre\lib\alt-string.jar;C:\Java\jdk1.6.0_25\jre\lib\charsets.jar;C:\Java\jdk1.6.0_25\jre\lib\deploy.jar;C:\Java\jdk1.6.0_25\jre\lib\javaws.jar;C:\Java\jdk1.6.0_25\jre\lib\jce.jar;C:\Java\jdk1.6.0_25\jre\lib\jsse.jar;C:\Java\jdk1.6.0_25\jre\lib\management-agent.jar;C:\Java\jdk1.6.0_25\jre\lib\plugin.jar;C:\Java\jdk1.6.0_25\jre\lib\resources.jar;C:\Java\jdk1.6.0_25\jre\lib\rt.jar;C:\Java\jdk1.6.0_25\jre\lib\ext\dnsns.jar;C:\Java\jdk1.6.0_25\jre\lib\ext\localedata.jar;C:\Java\jdk1.6.0_25\jre\lib\ext\sunjce_provider.jar;C:\Java\jdk1.6.0_25\jre\lib\ext\sunmscapi.jar;C:\Java\jdk1.6.0_25\jre\lib\ext\sunpkcs11.jar;C:\IdeaProjects\PracticeModule\target\classes;C:\Program Files\JetBrains\IntelliJ IDEA 10.5.1\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain jmhp.core.App
From testFun1() = 1
From testFun1() = 2
From testFun1() = 3
From testFun1() = 4
From testFun1() = 5
From testFun2() = 20
From testFun2() = 21
From testFun2() = 22
From testFun2() = 23
From testFun2() = 24
From testFun2() = 25
From testFun1() = 6
From testFun1() = 7
From testFun1() = 8
From testFun1() = 9
</code></pre>
<p>Thanks!</p>
|
[] |
[
{
"body": "<p>The implementation looks fine. Some small notes:</p>\n\n<ol>\n<li>Consider using <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/util/concurrent/Uninterruptibles.html#sleepUninterruptibly%28long,%20java.util.concurrent.TimeUnit%29\" rel=\"nofollow noreferrer\">Guava's Uninterruptibles</a> class if you don't want to handle <code>InterruptedException</code>s.</li>\n<li>The default access <code>waiting</code> flag in <code>Thread1</code> is makes the code hard to read/follow and results tight coupling.</li>\n<li>Consider using <code>Runnable</code>s instead of <code>Thread</code>s. See: <a href=\"https://stackoverflow.com/q/541487/843804\">Java: “implements Runnable” vs. “extends Thread”</a></li>\n<li>Consider synchronizing on a separate lock object: <a href=\"https://stackoverflow.com/q/442564/843804\">Avoid synchronized(this) in Java?</a></li>\n</ol>\n\n<p>Anyway, it would be much easier, less error-prone and more readable with a fair <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Semaphore.html\" rel=\"nofollow noreferrer\"><code>Semaphore</code></a> (from the <a href=\"http://docs.oracle.com/javase/6/docs/technotes/guides/concurrency/overview.html\" rel=\"nofollow noreferrer\">concurrency utilities package</a>):</p>\n\n<p><code>App.java</code>:</p>\n\n<pre><code>public class App {\n\n public static void main(final String[] args) throws InterruptedException {\n final Semaphore control = new Semaphore(1, true);\n\n final Thread1 thread1 = new Thread1(control);\n final Thread2 thread2 = new Thread2();\n\n thread1.start();\n Uninterruptibles.sleepUninterruptibly(500, TimeUnit.MILLISECONDS);\n control.acquireUninterruptibly();\n thread2.start();\n thread2.join();\n control.release();\n }\n}\n</code></pre>\n\n<p><code>Thread1.java</code>:</p>\n\n<pre><code>public class Thread1 extends Thread {\n private final Semaphore control;\n\n public Thread1(final Semaphore control) {\n this.control = control;\n }\n\n @Override\n public void run() {\n for (int i = 1; i < 10; i++) {\n control.acquireUninterruptibly();\n try {\n Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);\n System.out.println(\"From testFun1() = \" + i);\n } finally {\n control.release();\n }\n }\n }\n}\n</code></pre>\n\n<p><code>Thread2.java</code>:</p>\n\n<pre><code>public class Thread2 extends Thread {\n\n public void run() {\n for (int i = 20; i <= 25; i++) {\n Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);\n System.out.println(\"From testFun2() = \" + i);\n }\n\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T22:14:25.670",
"Id": "23556",
"Score": "1",
"body": "Wow! Thanks a lot, threads is a extensive theme with lots of things that can be learned! like i just did! :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T22:08:11.220",
"Id": "14511",
"ParentId": "14502",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-08-09T19:52:55.697",
"Id": "14502",
"Score": "1",
"Tags": [
"java",
"multithreading"
],
"Title": "Thread pausing/resuming implementation"
}
|
14502
|
<p>I'm very very fresh to programming. This is one of my first experiments with Python and I'm wondering in what ways I could have made this program less clunky. Specifically, is there a way that I could have used classes instead of defining my x, y, and z variables globally?</p>
<pre><code>def getx():
try:
global x
x = float(raw_input("Please give your weight (pounds): "))
return x
except ValueError:
print("Use a number, silly!")
getx()
def gety():
try:
global y
y = float(raw_input("what is your current body fat percentage? (>1): "))
return y
except ValueError:
print("Use a number, silly!")
gety()
def getz():
try:
global z
z = float(raw_input("What is your desired body fat percentage? (>1): "))
return z
except ValueError:
print("Use a number, silly!")
getz()
def output():
getx()
gety()
getz()
A = (x*(y/100-z/100))/(1-z/100)
B = x - A
print("Your necessary weight loss is %.1f pounds, and \
your final weight will be %.1f pounds" % (A,B))
more()
def more():
again = raw_input("Calculate again? ")
if again.lower() == "yes" or \
again.lower() == "y" or \
again.lower() == "sure" or \
again.lower() == "ok" or \
again.lower() == "" or \
again.lower() == "okay":
output()
elif again.lower() == "no" or \
again.lower() == "n" or \
again.lower() == "nah" or \
again.lower() == "nope":
end()
else:
more()
def end():
print("Ok, see ya later!")
output()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T19:50:05.233",
"Id": "23548",
"Score": "1",
"body": "This belongs on codereview, but I don't see how classes would help. You might want to get rid of the global variables, however and just pass things in via function arguments."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T19:56:38.307",
"Id": "23549",
"Score": "0",
"body": "since all three \"get\" functions are almost identical, you can reduce them to one that takes a parameter for the input prompt. For the if statements, you can say ... if again.lower() in [\"yes\", \"y\", ...]:"
}
] |
[
{
"body": "<p>Do you have objects, \"things\" that have state and behaviour? I don't see any. So use functions as you do (perhaps improve the code format).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T19:48:52.267",
"Id": "14504",
"ParentId": "14503",
"Score": "1"
}
},
{
"body": "<p>all of your functions seem to do the same thing with a different message, so why not condense them and take the message as a parameter?</p>\n\n<pre><code>def get_num(msg):\n num = None\n while num is None:\n try:\n num = float(raw_input(msg))\n except ValueError:\n print(\"Use a number, silly!\")\n\n return num\n</code></pre>\n\n<p>and then</p>\n\n<pre><code>def output():\n x = get_num('Please give your weight (pounds): ')\n y = get_num('what is your current body fat percentage? (>1): ')\n z = get_num('What is your desired body fat percentage? (>1): ')\n A = (x*(y/100-z/100))/(1-z/100)\n B = x - A\n print(\"Your necessary weight loss is %.1f pounds, and \\\nyour final weight will be %.1f pounds\" % (A,B))\n more()\n</code></pre>\n\n<p>in your more function you can condense your ifs with the <code>in</code> operator</p>\n\n<pre><code>def more():\n again = raw_input(\"Calculate again? \")\n\n if again.lower() in [\"yes\", \"y\", \"sure\" , \"ok\", \"\", \"okay\"]:\n output()\n elif again.lower() in [\"no\", \"n\", \"nah\", \"nope\"]:\n end()\n else:\n more()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T19:50:26.100",
"Id": "14505",
"ParentId": "14503",
"Score": "4"
}
},
{
"body": "<p>In <code>getx</code>, <code>gety</code> and <code>getz</code> there's no need to use <code>global</code> <em>and</em> <code>return</code>. Also, it would be better to use iteration rather than recursion, like this:</p>\n\n<pre><code>def getx():\n while True:\n try:\n return float(raw_input(\"Please give your weight (pounds): \"))\n except ValueError:\n print(\"Use a number, silly!\")\n</code></pre>\n\n<p>You might also want to use better function and variable names.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T19:51:18.200",
"Id": "14506",
"ParentId": "14503",
"Score": "1"
}
},
{
"body": "<p>Yes, you definitely can. You can try something in the lines of:</p>\n\n<pre><code>class PersonData(object):\n def __init__(self):\n pass\n\n\n def getx(self):\n try:\n self.x = float(raw_input(\"Please give your weight (pounds): \"))\n except ValueError:\n print(\"Use a number, silly!\")\n self.getx()\n</code></pre>\n\n<p>.. and so on.</p>\n\n<p>And then in your main program:</p>\n\n<pre><code>if __name__ == \"__main__\":\n person = PersonData()\n person.getx()\n person.gety()\n\n... \n\n A = (person.x * (person.y / 100 - person.z / 100))/(1 - person.z / 100)\n</code></pre>\n\n<p>If you get my drift. This is generally if you want to use classes. Otherwise see other answers :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T19:54:04.527",
"Id": "14507",
"ParentId": "14503",
"Score": "0"
}
},
{
"body": "<p>The code below condenses your script (fewer lines and redundancy when you remove the triple quote explanations). Honestly, using classes would complicate your function, so unless you need the classes for something else, just do all in the function. Also, typically it is better to not call globals unless you need to. For your purpose, unless there is more to the script, use local variables. </p>\n\n<p>Your script suffers a lot from redundancy. It works fine, but there are easier ways to do it. Instead of reusing again.lower() ==, put all the desired responses into a list. Using 'is...in' checks if your variable is in you list (or string, etc). For example, if var in [\"y\", \"yes\"]: </p>\n\n<p>You can further reduce your redundancy by making a function to do your try/except statements, but I used while statements to show another way to do it. You can then use continue (which resets back to the beginning) if there is an exception and use break to exit the loop if you try statement succeeds. </p>\n\n<p>Note: I tested this on Pythonista for iOS using 2.7. I added in the triple quotes as explanations after confirming the script worked and using as is may throw an indentation error. Removing the triple quote explanations should run it properly. </p>\n\n<pre><code>\"\"\" Unless you are reusing variables, but it all in \nthe same function\"\"\"\n\ndef output():\n\"\"\" Put your inputs in a while statement. Continue on\nexception and break otherwise\"\"\"\n while True:\n try:\n x = float(raw_input(\"Please give your weight (pounds): \"))\n except ValueError:\n print(\"Use a number, silly!\")\n continue\n break\n while True:\n try:\n y = float(raw_input(\"what is your current body fat percentage? (>1): \"))\n except ValueError:\n print(\"Use a number, silly!\")\n continue\n break\n while True:\n try:\n z = float(raw_input(\"What is your desired body fat percentage? (>1): \"))\n except ValueError:\n print(\"Use a number, silly!\")\n continue\n break\n A = (x*(y/100-z/100))/(1-z/100)\n B = x - A\n print(\"Your necessary weight loss is %.1f pounds, and \\\nyour final weight will be %.1f pounds\" % (A,B))\n\n\"\"\" Like before put input into while statement\"\"\"\n\n while True:\n again = raw_input(\"Calculate again? \")\n\n\"\"\" Condense your input options into an if in statement\"\"\"\n if again.lower() in [\"yes\", \"y\", \"sure\", \"ok\", \"\", \"okay\"]:\n output()\n\n\"\"\" Unless No response is important, just use else\ncatchall\"\"\"\n else:\n print(\"Ok, see ya later!\")\n break\noutput()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-19T17:36:06.507",
"Id": "305711",
"Score": "1",
"body": "How and why does this *condense* the original script? Can you explain why you did the things you did?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-19T18:13:45.800",
"Id": "305730",
"Score": "0",
"body": "Also, please verify your indentation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-19T18:51:27.013",
"Id": "305746",
"Score": "0",
"body": "@StephenRauch It's fewer lines and less redundancy. For example, instead of rewriting each \"again.lower() ==\" line, it puts all desirable responses into a list and checks if the response is in the list. Unless 'No' is very important, any answer that isn't yes can be 'No' - otherwise, put in a list and check. I explained my changes inside of the script. The while statements removes the need for separate functions. Continue runs the previous try and break ends the statement. This can be further condensed, but I wanted to show the while/continue/break combination with try/except."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-19T18:53:49.337",
"Id": "305750",
"Score": "0",
"body": "@200_success I wrote this on Pythonista on my phone, so indentation may be off compared to desktop version. Also, I added the notes explaining changes after I verified the function worked and the notes are throwing me the indentation errors. Remove the triple quote notes and it all runs fine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-19T18:56:38.707",
"Id": "305751",
"Score": "0",
"body": "Thanks for the feedback, but you should edit this explanation into the answer so that it is helpful for future readers. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-19T20:11:59.233",
"Id": "305769",
"Score": "0",
"body": "@StephenRauch I fixed the response to explain better"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-19T17:28:21.173",
"Id": "161238",
"ParentId": "14503",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T19:46:02.923",
"Id": "14503",
"Score": "1",
"Tags": [
"python",
"beginner",
"calculator"
],
"Title": "Python beginner's body fat calculator"
}
|
14503
|
<p>I'd like to use lock objects that are specific to the person I'm updating. In other words, if thread A is updating Person 1, thread B is blocked from also updating Person 1, but thread C is not blocked from updating Person 2.</p>
<p>99% of the time, I don't really need the locks since I'm working with different Person.Id values. In the occasional situations when I am working with the same Person.Id value, I want to lock around some read/write code.</p>
<p>The following code is working as I expect. I'm looking for any "gotcha's" I may have missed, or better ways of accomplishing the same thing. I decided to use the .NET Cache to store the lock objects so I don't need to worry about cleaning them up later (the lock objects are removed from cache when they haven't been used for a certain TimeSpan).</p>
<p>This code provides the object to lock on</p>
<pre><code>public static class PersonLocks
{
private static readonly object CacheLock = new object();
private const string KeyPrefix = "LockForPersonID:";
public static object GetPersonLock(long personId)
{
lock (CacheLock)
{
string key = BuildCacheKey(personId);
object cachedItem = HttpRuntime.Cache[key];
if (cachedItem == null)
{
cachedItem = new object();
HttpRuntime.Cache.Insert(key, cachedItem, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 5, 0));
}
return cachedItem;
}
}
private static string BuildCacheKey(long personId)
{
return KeyPrefix + personId.ToString();
}
}
</code></pre>
<p>This is how I'm using the code</p>
<pre><code>object padlock = PersonLocks.GetPersonLock(person.Id);
lock (padlock)
{
//do read
//do some data mapping
//do write
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-17T19:27:48.610",
"Id": "24061",
"Score": "0",
"body": "Are the person objects stored in some data structure that all threads have access to? If they are, then can't you just lock the person object itself?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-22T00:10:58.207",
"Id": "25754",
"Score": "0",
"body": "No, the person objects have a very short lifetime, so they're not stored in a common data structure. I think your suggestion would work, but I generally prefer to use separate objects to lock on in order to avoid confusion about what the lock keyword is doing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-14T05:01:49.160",
"Id": "430087",
"Score": "0",
"body": "@tgriffin Acquiring an outer lock `lock (CacheLock)` to get a person lock is expensive. I would use an atomic operation to get the person lock, rather than a lock. `ConcurrentDictionary`is the way to go for me. The only downside is that you have to implement expiration yourself."
}
] |
[
{
"body": "<p>Your code would do just fine, in terms of functionality.</p>\n\n<p>However, note that such design holds as long as everybody knows that they should acquire the lock before performing any process on the person object.</p>\n\n<p>Perhaps you should consider re-design your data objects (such as the person class) so that there's an explicit method for any update process. Perhaps something like <code>BeginEdit</code> and <code>EndEdit</code>, or, even better, a method that returns an <code>IDisposable</code> object that acquires the lock and releases it in its <code>Dispose</code> implementation. Example:</p>\n\n<pre><code>public class Person {\n public IDisposable AcquireLock() {\n // ...\n }\n\n // ...\n}\n\n// usage:\nvar aPerson = GetPerson(1234);\nusing (aPerson.AcquireLock()) {\n aPerson.LastName = \"abcd\";\n SavePerson(aPerson);\n // ...\n}\n</code></pre>\n\n<p>This way the locking is made more explicit.</p>\n\n<p>Just a suggestion, though...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-22T00:11:41.513",
"Id": "25755",
"Score": "0",
"body": "I like this. I've upvoted your answer. I implemented the original code, but will consider doing something like this in the future."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-20T21:32:57.903",
"Id": "14876",
"ParentId": "14519",
"Score": "5"
}
},
{
"body": "<p>Use double check lock:</p>\n\n<pre><code>public static object GetPersonLock(long personId) \n{ \n var key = BuildCacheKey(personId);\n object cachedItem = HttpRuntime.Cache[key];\n\n if (cachedItem != null) {\n return cachedItem;\n }\n\n lock (CacheLock) \n {\n cachedItem = HttpRuntime.Cache[key];\n if (cachedItem != null) {\n return cachedItem;\n }\n\n cachedItem = new object(); \n HttpRuntime.Cache.Insert(key, cachedItem, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 5, 0)); \n\n return cachedItem; \n } \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-22T00:16:02.663",
"Id": "25756",
"Score": "0",
"body": "Thanks. I've upvoted your answer. I considered doing this, but decided not to since 99% of the time the lock object won't be in cache (updates for the same person normally come infrequently, but on rare occassions I'll get 2 updates within a few milliseconds). I'm probably not saving much time, but decided to skip the initial \"unlocked\" read from cache."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-22T10:59:19.183",
"Id": "25770",
"Score": "0",
"body": "If you are not using correct locking you have big chance to end up within a deadlock situation."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-20T07:58:22.840",
"Id": "15759",
"ParentId": "14519",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T03:40:43.483",
"Id": "14519",
"Score": "11",
"Tags": [
"c#",
".net",
"multithreading",
"cache"
],
"Title": "Using different instances of an object to lock threads"
}
|
14519
|
<p>I've just finished a week long adventure of creating an <a href="http://jsfiddle.net/MtypZ/64/" rel="nofollow">HTML5 Drag and Drop scheduler</a>. As the prototype stands it works fine, but I'm curious if some of the code can be optimized. I mostly focused on it being readable and well documented, but I'm curious if someone can come up with any optimizations.</p>
<p>I've noticed that when Firefox is used there is some "twitching" that occurs when the cells are updated. Here's the code (minus the comments that are available on the fiddle):</p>
<pre><code>var unscheduledTbody = null,
scheduledTbody = null,
isDroppable = true;
var dataTransferValue = null;
var Indecies = function (td) {
var tr = td.parent(),
tbody = tr.parent();
var row = tbody.children().index(tr),
column = tr.children().index(td);
return [row, column];
};
var CheckCellRowspan = function (options) {
var element = null;
for (var i = 1; i < options.rows; i++) {
element = scheduledTbody.find("tr:eq(" + (options.row + i) + ") td." + options.column);
if (element.attr("id") != null) {
isDroppable = false;
return;
};
};
element = null;
isDroppable = true;
};
var ToggleCellVisibility = function (options) {
var selectors = "",
i = 1;
for (i; i < options.rows; i++) {
if (options.hide) {
selectors = (selectors + ("tr:eq(" + (options.row + i) + ") td." + options.column + ","));
} else {
selectors = (selectors + ("tr:eq(" + (options.row + i) + ") td." + options.column + ":hidden,"));
};
};
selectors = selectors.substring(0, (selectors.length - 1));
if (selectors.length > 0) {
scheduledTbody.find(selectors).css({
display: (options.hide ? "none" : "table-cell")
});
};
};
$(function () {
$("#Unscheduled tbody td,#Scheduled tbody td").prop("draggable", true);
unscheduledTbody = $("#Unscheduled tbody");
scheduledTbody = $("#Scheduled tbody");
unscheduledTbody.find("td").data("scheduled", false);
var scheduledTds = scheduledTbody.find("td");
$("[draggable]").live("dragstart", function (e) {
e.originalEvent.dataTransfer.effectAllowed = "move";
e.originalEvent.dataTransfer.setData("text/plain", this.id);
}).live("drag", function (e) {
}).live("dragend", function (e) {
var dropEffect = e.originalEvent.dataTransfer.dropEffect;
switch (dropEffect) {
case "copy":
case "move":
if (isDroppable) {
var source = $(this),
target = $("#" + dataTransferValue);
if (source.data("scheduled")) {
var sourceIndecies = Indecies(source),
sourceRow = sourceIndecies[0],
sourceColumn = sourceIndecies[1],
rows = target.data("rows");
ToggleCellVisibility({
rows: rows,
row: sourceRow,
column: sourceColumn,
hide: false
});
sourceIndecies = null;
sourceRow = null;
sourceColumn = null;
rows = null;
} else {
source.parent().remove();
};
dataTransferValue = null;
source = null;
target = null;
};
break;
case "link":
case "none":
default:
break;
};
});
scheduledTds.each(function () {
var td = $(this);
td.addClass("" + Indecies(td)[1]);
}).data("scheduled", true).live("dragenter", function (e) {
e.originalEvent.dataTransfer.dropEffect = "move";
$(this).addClass("Droppable");
}).live("dragover", function (e) {
e.preventDefault();
}).live("dragleave", function (e) {
$(this).removeClass("Droppable");
}).live("drop", function (e) {
e.preventDefault();
dataTransferValue = e.originalEvent.dataTransfer.getData("text/plain");
var source = $("#" + dataTransferValue),
target = $(this),
targetIndecies = Indecies(target),
targetRow = targetIndecies[0],
targetColumn = targetIndecies[1],
rows = source.data("rows");
CheckCellRowspan({
rows: rows,
row: targetRow,
column: targetColumn
});
if (isDroppable) {
var sourceIndecies = Indecies(source),
sourceRow = sourceIndecies[0],
sourceColumn = sourceIndecies[1],
url = source.data("url");
target.removeClass("Droppable")
.html(source.html())
.attr("id", source.attr("id"))
.attr("rowspan", rows)
.data("rows", rows)
.data("url", url);
source.html("")
.removeAttr("id")
.removeAttr("rowspan")
.removeData("rows")
.removeData("url");
ToggleCellVisibility({
rows: rows,
row: targetRow,
column: targetColumn,
hide: true
});
sourceIndecies = null;
sourceRow = null;
sourceColumn = null;
} else {
$("b").text("The cell could not be dropped at the target location. It conflicted with an existing cell in its path.");
target.removeClass("Droppable");
};
source = null;
target = null;
targetIndecies = null;
targetRow = null;
targetColumn = null;
rows = null;
}).find("a").live("click", function (e) {
e.preventDefault();
var source = $(this).closest("td"),
sourceIndecies = Indecies(source),
sourceRow = sourceIndecies[0],
sourceColumn = sourceIndecies[1],
rows = source.data("rows");
unscheduledTbody
.append($("<tr />")
.append($("<td draggable=\"true\" data-scheduled=\"false\" />")
.html(source.html())
.attr("id", source.attr("id"))
.data("rows", rows)));
source.html("")
.removeAttr("id")
.removeAttr("rowspan")
.removeData("rows");
ToggleCellVisibility({
rows: rows,
row: sourceRow,
column: sourceColumn,
hide: false
});
source = null;
sourceIndecies = null;
sourceRow = null;
sourceColumn = null;
rows = null;
});
scheduledTds = null;
});
</code></pre>
|
[] |
[
{
"body": "<p>I don't really address the concrete questions you made; I hope someone else does. :)</p>\n\n<hr>\n\n<blockquote>\n <p>As the prototype stands it works fine</p>\n</blockquote>\n\n<p>Famous last words! You have at least two bugs:</p>\n\n<ol>\n<li>Drag D on top of B, and B is lost forever.</li>\n<li>Now drag A on top of D, and not only D disappears but the layout is ruined.</li>\n</ol>\n\n<p>You will get some good tips by running your code through JSLint.<br>\nSome quick and non-exaustive remarks:</p>\n\n<ul>\n<li>You can avoid escaping quotes by alternating between single and double quotes, which both JavaScript and HTML use interchangeably: use <code>str = \"<foo bar='nix' />\"</code> instead of <code>str = \"<foo bar=\\\"nix\\\" />\"</code>;</li>\n<li>Do not pollute the global namespace: encapsulate the code in a self-executing function;</li>\n<li>Starting the code with <code>\"use strict\";</code> will really help with identifying many problems early;</li>\n<li>Use <code>===</code> to compare, and not <code>==</code>;</li>\n<li><code>indecies</code> should be called <code>indexes</code> (actually, <code>getIndexesOf</code>);</li>\n<li>Constructors start with a capital letter - all those methods are not constructors, so they should not start with a capital letter;</li>\n<li>Use <code>.on('event', ...)</code> instead of live, and maybe even use the <a href=\"http://api.jquery.com/on/\" rel=\"nofollow\">.on</a> overload that takes an \"event-map\".</li>\n</ul>\n\n<p>Note that <code>.on</code> will not bind to objects that are later loaded into the DOM. <strong>But</strong> you can bind to a parent element, and provide a selector to filter which children elements to catch the event on. This not only catches events on such children that might be later attached (same as live), but also attaches a single event handler instead of a million. Take heed not to use <code>document</code> to attach these, or similar elements high in the DOM tree - read the API: <a href=\"http://api.jquery.com/on/\" rel=\"nofollow\">http://api.jquery.com/on/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T13:33:51.490",
"Id": "14527",
"ParentId": "14522",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T07:04:43.687",
"Id": "14522",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"html5"
],
"Title": "Drag and drop script"
}
|
14522
|
<p>I an a newcomer in the Scala world, and I would like some advice from more experienced people to find out whether what I am writing goes in the direction of idiomatic code.</p>
<p>In particular, I have to write a simple algorithm that will do the following. We are given an integer number of, say, candies to be distributed, and a list of proportions, which are also integers. We should split the candies into groups, such that the proportions are respected as accurately as possible, given that a single candy cannot be broken up.</p>
<p>For instance, given <code>17</code> candies to distribute in proportions of <code>(3, 2, 5)</code> we should obtain <code>(5, 4, 8)</code>.</p>
<p>Here is my code, including a quick ScalaCheck test.</p>
<pre><code>import org.scalacheck.Prop._
import org.scalacheck.Gen
object Distribution {
private class IntWithDivision(val self: Int) {
def @/(other: Int): Float = self.toFloat / other
}
private implicit def divisibleInt(int: Int) = new IntWithDivision(int)
def distribute(amount: Int, proportions: Seq[Int]): Seq[Int] = {
val sum = proportions.sum
val byDifect = proportions map { x => (amount * x @/ sum).toInt }
val approximations = (byDifect, proportions).zipped map { (x, y) => x @/ y }
val lowValuesIndices = (
approximations.view.zipWithIndex
sortBy { _._1 }
take (amount - byDifect.sum)
map { _._2 }
).force
val remainders = (
approximations.view.zipWithIndex
map { x => if (lowValuesIndices contains x._2) 1 else 0 }
).force
(byDifect, remainders).zipped map { _ + _ }
}
def main(args: Array[String]) {
val pos = Gen.choose(1, 50000)
val posList = Gen.containerOf[List, Int](pos)
val propSum = forAll(pos, posList) { (amount: Int, proportions: List[Int]) =>
(proportions.size > 0) ==> (amount == distribute(amount, proportions).sum)
}
propSum.check
}
}
</code></pre>
<p>In particular, I would like advice on the following points:</p>
<ul>
<li>The algorithm goes over the list of proportions and derived lists a few times. I would like to use more laziness, but using <code>proportions.view</code> at the beginning and then returning a <code>force</code> gives a type error.</li>
<li>The code is more convoluted than I would like. I think it may be simplified knowing the Collections API better.</li>
</ul>
<p>Any help or suggestion is welcomed.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T14:52:43.207",
"Id": "23575",
"Score": "0",
"body": "Arguably it should be 5, 3, 9 -- the second group has a smaller piece than the last one, so it should be the last one to get it. What's the criteria for distributing remains?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T16:27:26.167",
"Id": "23579",
"Score": "0",
"body": "Well, the criterion I have adopted is to compute the ratio between the original proportions and the computed proportions and minimize the variability (max - min)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T16:30:34.183",
"Id": "23580",
"Score": "0",
"body": "In practice this means that I distribute the candies computing the exact proportion and rounding by difect. Then I distribute the leftovers starting from the kid for which the ratio `assignedCandies/assignedProportion` is lowest, and repeat. It is easy to see that in this way, the no kid will get more than one leftover, so I directly compute those kids having the lowest value and assing one candy to all of them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T16:31:19.563",
"Id": "23581",
"Score": "0",
"body": "I hope now the algorithm makes a little more sense."
}
] |
[
{
"body": "<p>Ok, I'm changing the answer now that I understand what you are doing.</p>\n\n<p>The main problem here is <code>@/</code> -- while Scala people, in general, don't mind special operators, they don't add operators just because they can either. You can replace <code>@/</code> with the existing <code>/</code> just by adding <code>.toFloat</code> to any one of the terms. </p>\n\n<p>Views aren't often used either, and it's important to have a very good understanding of how they work if you are going to use them, and it's not that easy to gain performance with them, since the machinery they use to support non-strictness is quite heavy, and not everything takes advantage of it. For example, <code>sortBy</code> will create a new collection before <code>take</code> and <code>map</code> are applied.</p>\n\n<p>Views can gain when you have many mapping/slicing steps, and few elements of it are ever used. Most of the time, iterators will gain you much more performance, at the cost of the mutability problems iterators have.</p>\n\n<p>If you want to reduce the number of times you iterate through the list of proportions, there's at least one place where you can simplify:</p>\n\n<pre><code> val remainders = (\n approximations.view.zipWithIndex\n map { x => if (lowValuesIndices contains x._2) 1 else 0 }\n ).force\n\n (byDifect, remainders).zipped map { _ + _ }\n</code></pre>\n\n<p>Can be reduced to</p>\n\n<pre><code> byDifect.zipWithIndex map {\n case (bd, i) => bd + (if (lowValuesIndices contains i) 1 else 0)\n }\n</code></pre>\n\n<p>One could also keep <code>byDifect</code> a <code>Float</code>, then either use it alone when computing <code>approximation</code> (instead of zipping stuff), or skip that altogether and put that computation on <code>sortBy</code> -- incurring the cost of computation O(nlogn) times instead of O(n) times. It would make the code shorter, but whether it would be faster or not is something I'd leave to a benchmark with a real application -- I'm guessing it would depend on actual sizes for <code>proportions</code>.</p>\n\n<p>So, let's talk a bit about performance. Before Scala 2.10, if you want performance you should avoid methods added through implicits on critical paths. The code you wrote will <em>probably</em> get inlined by JIT. You can also reduce the number of computations by pre-computing <code>amount / sum</code>, and if you make that <code>amount.toFloat / sum</code>, then you don't need <code>/@</code>.</p>\n\n<p>More specifically, views are not guarantees of speed, particularly if the computations are light, such as here. I'd not use them at all, unless I'm specifically optimizing the code.</p>\n\n<p>Doing a fixed size of multiple passes on small data structures is often not a problem. You are not changing the complexity, just losing memory locality. If the data is bigger, you can incur in gc overheads, which are more substantial. If maximum performance is required, just drop immutability and go to mutable arrays.</p>\n\n<p>Finally, <code>contains</code> is faster on <code>Set</code> than <code>Seq</code> -- and, in this particular case, a <code>BitSet</code> would be way faster. Call it <code>apply</code>, however, since <code>contains</code> is a general method on traversables, while set's apply is a fundamental operation. If one of them is less than optimized, it will be <code>contains</code>.</p>\n\n<p>This is the most idiomatic beginner's code I have ever seen... do you come from another functional language?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T16:33:07.470",
"Id": "23583",
"Score": "0",
"body": "Of course we are not allowed to leave any candies, otherwise the problem would be trivial. In any case, I would be happy to know whether the way I have written the algorithm in Scala is idiomatic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T20:29:21.027",
"Id": "23600",
"Score": "0",
"body": "@Andrea Ok, revised the answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-11T09:38:21.730",
"Id": "23612",
"Score": "0",
"body": "Thank you very much for your advice! I also do not like an exceeding use of operators in public APIs, but I figured in this case it was all kept private, just make some lines more readable. As you suggest, it is better to keep `amount/sum` as a float and avoid the issue altogether. As for my background, I mostly come from Python and Javascript, but I have dabbled with Clojure, Scheme and Haskell before."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-28T01:55:51.590",
"Id": "186975",
"Score": "0",
"body": "@DanielC.Sobral, I'd like to abuse of that answer to bring this question to your attention: http://codereview.stackexchange.com/questions/101339/kosaraju-in-scala. Thanks in advance if you have any time for that :-)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T15:04:03.133",
"Id": "14531",
"ParentId": "14524",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "14531",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T10:12:32.407",
"Id": "14524",
"Score": "2",
"Tags": [
"algorithm",
"scala",
"beginner"
],
"Title": "First steps in Scala: does this look idiomatic?"
}
|
14524
|
<p>I have been writing a jQuery widget for a couple of days now. Originally I needed this functionality for something I am writing at work, but I felt like I could abstract it a little more so here I am. I think it's about finished for now, I may add some features depending on how It gets used (if it does).</p>
<p>This is my first jQuery widget and I have been programming in JavaScript for just over a month now, so I don't think the code will be particularly great, but I've tried my hardest.</p>
<p>I have done some vague testing and it does seem to work in all browsers.</p>
<p>My main gripes are validation of the options, of which I don't really know how to do, however, I am going to do some proper research on this and come back to it.</p>
<p>There a few other problems with it but I think that this is not the right place to ask about those, so will leave it for now.</p>
<p>I would just like some feedback on my coding, how to improve/do it better, now and in the future. It's quite a big chunk of code but I didn't see anything in the FAQ about length of code.</p>
<p>I've also attached a jsFiddle so you can mess with it: <a href="http://jsfiddle.net/jCVzp/2/" rel="nofollow">http://jsfiddle.net/jCVzp/2/</a></p>
<p>I've tried to comment as best as I can and have noted all the options in the file description, and more guidance needed, just ask.</p>
<p>All the CSS is present in the jsFiddle, didn't think it was necessary to post it here.</p>
<p>Any time and help is greatly appreciated.</p>
<pre><code>(function($) {
/*
* Document : list-widget-0.1
* Created on : 06-Aug-2012, 20:53:49
* Author : aydin hassan
* Description:
* This widget is designed to be attatched to a div
*
* Using the options you can specify one of three list types:
* 1.) a normal list if items (normal)
* 2.) a list of items with a cross/tick img depending on its status (act-deact)
* ---Clicking the image will toggle its status (change the img and class) and run a provided callback
* 3.) a list of items with a trash can icon (remove)
* ---Click the image will run a supplied calback and then remove the item
*
* Each of the lists has various callbacks:
* 1.) The global click callback (selectabble.clickCallBack), if passed, will launch on clicked an element for any list type
* 2.) The global click off callback (selectable.clickOffCallBack), if passed, will launch when an item is clicked off.
* ---Works in conjuction with selectable.sticky - if this is set to true elements will stay higlighted until they are clicked off
* ---NOTE: click off callback will not be processed if selectable.sticky is set to true
* 3.) The act-deact callback, if passed, will run after a user has clicked the img, or, if there is no global click callback (selectabble.clickCallBack) it will
* run when the li element is clicked
* 4.) The remove callback, if passed, will run after the user clicks on the trash-can icon
* 5.) The add button callback, if passed, will run when a user clicks the add button
*
* List data:
* The list data must be an object of the following form:
* act-deact:
* var data = {
* "0":{"name":"list item 1","activated":true},
* "1":{"name":"list item 2","activated":true},
* "2":{"name":"list item 3","activated":false}
* };
*
* normal/remove:
* var data = {
* "0":{"name":"list item 1"},
* "1":{"name":"list item 2"},
* "2":{"name":"list item 3"}
* };
*
* Other options:
* title: ---The title of the list box
* description: ---Some description of the data
* searchBar: ---BOOL - To display a filter box
* addButton: ---BOOL - To display an add button
* idStyle: ---A string to prepend to the id of the item id in the data object to use as the li element id attribute
*
*/
$.widget( "widgets.adminList", {
// These options will be used as defaults
options: {
list: null,
title: "Title",
description: "Some description",
searchBar: true,
addButton: false,
addCallBack: null,
listType: "normal",
idStyle: "li-id-",
removeCallBack: null,
toggleCallBack: null,
selectable: null
},
// Set up the widget
_create: function() {
},
_init: function() {
var options = this.options;
//Build the container elements
this._buildTableHead();
//switch type of list and run setup function for specified type
switch (options.listType) {
case "normal": this._setUpNormal();
break;
case "act-deact": this._setUpActDeact();
break;
case "remove": this._setUpRemove();
break;
}
//If the selectable options are configured then we may want sticky elements (hover css stays until clciked again, or another elements is clicked)
//And there may also be click on and click off callbacks
if(options.selectable != null) {
$(".list-widget-list-container .list-widget-list li a").live('click',(function(e) {
//prevent the href("") from being followed, href is needed for IE to display hover
e.preventDefault();
//If we want elements to stick
if(options.selectable.stick) {
//If this element is stuck already
//unstick it and run click off call back if supplied
if($(this).hasClass("selected")) {
$(this).removeClass("selected");
if(options.selectable.clickOffCallBack != null){
options.selectable.clickOffCallBack(this);
}
//Else unstick any other elements
//Stick this element
//and run click callback
} else {
$(".list-widget-list-container .list-widget-list").find(".selected").removeClass("selected");
$(this).addClass("selected");
if(options.selectable.clickCallBack != null){
options.selectable.clickCallBack(this);
}
}
//If we don't want to stick just run click on callback if supplied
} else {
if(options.selectable.clickCallBack != null){
options.selectable.clickCallBack(this);
}
}
}));
}
//If add callback is supplied
//create click event
if(options.addButton && options.addCallBack != null) {
$(".list-widget-head-div .header-table .add-but").click(function() {
options.addCallBack(this);
});
}
//create event for filter box
var that = this;
$(".list-widget-head-div .header-table .list-search-box").bind("keyup",function(){
that._listFilter(this);
});
//Add the list elements
this.add(options.list);
},
_listFilter:function(e){
var filter = $(e).val(); // get the value of the input, which we filter on
var list = $(".list-widget-list-container .list-widget-list");
//only filter if value exists
if(!filter || filter.length < 1 ){
list.find("li").show();
}
else{
list.find("li").each(function(){
//if a element text contains the filter value, hide it
if($("a", this).text().toLowerCase().indexOf(filter.toLowerCase()) == -1 ){
$(this).hide();
}
else{
//else show it
$(this).show();
}
});
}
},
_buildTableHead:function(){
//get the current options
var options = this.options;
//get the div the widget has been attatched to
var self = this.element;
//build table header
var headCells = $("<tr />")
.append($('<td />')
.attr("width","33%")
.attr("height","45px")
.append($('<p />')
.addClass("title")
.text(options.title)
)
);
//depending on the options;
//add a search bar and add button
//if we want searchbar and add button..
if(options.searchBar && options.addButton) {
headCells.append($('<td />')
.attr("width","33%")
.attr("height","45px")
.attr("text-align","center")
.append($('<img />')
.addClass("add-but")
.attr("src","add-image.png")
)
)
.append($('<td />')
.attr("width","33%")
.attr("height","45px")
.append($('<input />')
.attr("type","text")
.addClass("list-search-box")
)
);
//if we only want add button
} else if (!options.searchBar && options.addButton) {
headCells.append($('<td />')
.attr("width","50%")
.attr("align","center")
.append($('<img />')
.addClass("add-but")
.attr("src","add-image.png")
)
);
//if we only want search bar
} else if (options.searchBar && !options.addButton) {
headCells.append($('<td />')
.attr("width","50%")
.append($('<input />')
.attr("type","text")
.addClass("list-search-box")
)
);
}
//Build the tables and append the cells
self.append($('<div />')
.addClass("list-widget-head-div")
.addClass("ui-corner-top")
.append($('<table />')
.addClass("header-table")
.append(headCells)
)
//Add the description if present
.append($("<p />")
.addClass("descript")
.text(options.description)
)
);
//Add the actual list element
self.append($("<div />")
.addClass("list-widget-list-container")
.addClass("ui-corner-bottom")
.append($("<ul />")
.addClass("list-widget-list")
)
);
},
_setUpNormal:function(){
//get the current options
var options = this.options;
},
_setUpActDeact:function(){
//get the current options
var options = this.options;
//click event upon clicking the item image
//Changes the status and can be provided with a call back
//which has access to the clicked element
//If there is no clickCallBack supplied, we apply the toggle action to the whole li element
if(options.selectable.clickCallBack == null) {
$(".list-widget-list-container .list-widget-list li").live('click',function(e){
//get the clicked element
var imgElem = $(this).find("img.list-img");
//var to store status
var active;
//get status of item
//and remove the class
if(imgElem.hasClass("deactivated")) {
active = false;
imgElem.removeClass("deactivated");
} else {
active = true;
imgElem.removeClass("activated");
}
//add the loading class
imgElem.addClass("loading");
imgElem.attr("src","ajax-loader.gif")
//if callback has been provided, run it
if(options.toggleCallBack != null) {
options.toggleCallBack(this)
}
//remove loading class
imgElem.removeClass("loading");
//add the oposite class(item has been toggled)
if(active) {
imgElem.addClass("deactivated");
imgElem.attr("src","cross.png")
} else {
imgElem.addClass("activated");
imgElem.attr("src","tick.png")
}
});
//if there is a clickCallBack then we just apply the toggle event to the image
} else {
$(".list-widget-list-container .list-widget-list li img.list-img").live('click',function(e){
//get the clicked element
var imgElem = $(this);
//var to stored status
var active;
//get status of item
//and remove the class
if(imgElem.hasClass("deactivated")) {
active = false;
imgElem.removeClass("deactivated");
} else {
active = true;
imgElem.removeClass("activated");
}
//add the loading class
imgElem.addClass("loading");
imgElem.attr("src","ajax-loader.gif")
//if callback has been provided, run it
if(options.toggleCallBack != null) {
options.toggleCallBack(this)
}
//remove loading class
imgElem.removeClass("loading");
//add the oposite class(item has been toggled
if(active) {
imgElem.addClass("deactivated");
imgElem.attr("src","cross.png")
} else {
imgElem.addClass("activated");
imgElem.attr("src","tick.png")
}
});
}
},
_setUpRemove:function(){
//get the current options
var options = this.options;
//click event upon clicking the delete image
//runs a provided callback and the removes item
$(".list-widget-list-container .list-widget-list li img.list-img").live('click',function(e){
//if callback has been provided, run it
if(options.removeCallBack != null) {
options.removeCallBack(this)
}
//remove element
$(this).parent().remove();
});
},
// Use the _setOption method to respond to changes to options
_setOption: function( key, value ) {
switch( key ) {
case "clear":
// handle changes to clear option
break;
}
// In $ UI 1.8, you have to manually invoke the _setOption method from the base widget
$.Widget.prototype._setOption.apply( this, arguments );
// In $ UI 1.9 and above, you use the _super method instead
this._super( "_setOption", key, value );
},
// Use the destroy method to clean up any modifications your widget has made to the DOM
destroy: function() {
// In $ UI 1.8, you must invoke the destroy method from the base widget
$.Widget.prototype.destroy.call( this );
// In $ UI 1.9 and above, you would define _destroy instead of destroy and not call the base method
},
/* This fuction when presented with an object in the following format
* var data = {
* "0":{"name":"list item 1","activated":true},
* "1":{"name":"list item 2","activated":true},
* "2":{"name":"list item 3","activated":false}
* };
* Will append the items to the bottom of the list
*/
add: function(list) {
//Pick add function depending on listType
switch(this.options.listType) {
case "normal":this._addNormal(list);
break;
case "act-deact":this._addActDeact(list);
break;
case "remove":this._addRemove(list);
break;
}
},
_addNormal: function(list) {
var options = this.options;
//Get the list elemenent
var ulElem = $(".list-widget-list-container .list-widget-list");
//For each list item
$.each(list, function(key,val){
//Append the item to the list
ulElem.append($("<li />")
.attr("id",options.idStyle + key)
.append($("<a />")
.text(val.name)
)
);
});
},
_addActDeact: function(list) {
var options = this.options;
//Get the list elemenent
var ulElem = $(".list-widget-list-container .list-widget-list");
//For each list item
$.each(list, function(key,val){
//creat li element
var li = $("<li />")
.attr("id",options.idStyle + key)
.append($("<img />")
.addClass("list-img")
)
.append($("<a />")
.text(val.name)
.attr("href","")
.addClass("actdeact")
);
//add activated/deactivated class
//depending on item status
if(val.activated === true) {
li.find("img").addClass("activated");
li.find("img").attr("src","tick.png");
} else {
li.find("img").addClass("deactivated");
li.find("img").attr("src","cross.png");
}
//Append the list item to the list
ulElem.append(li);
});
},
_addRemove: function(list) {
var options = this.options;
//Get the list elemenent
var ulElem = $(".list-widget-list-container .list-widget-list");
//For each list item
$.each(list, function(key,val){
//Append the item to the list
ulElem.append($("<li />")
.append($("<img />")
.addClass("list-img")
.attr("src","trash_can.png")
)
.attr("id",options.idStyle + key)
.append($("<a />")
.text(val.name)
.addClass("remove")
)
);
});
},
//Function to empty the list
empty: function() {
$(".list-widget-list-container .list-widget-list").empty();
}
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-13T10:49:11.017",
"Id": "29556",
"Score": "1",
"body": "Just skimmed through it, and it seems well-structured and nicely commented. Kudos! I also tried running it through [jshint](http://jshint.com/) which found a few things like missing semicolons and such. Try it out; it's a good way to catch the small stuff. Oh, and for checking callbacks, use `typeof someCallback === 'function'` rather than `someCallback != null`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-13T11:02:37.767",
"Id": "29558",
"Score": "0",
"body": "Thankyou, I will make those changes and checkout jshint!"
}
] |
[
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li><p>Do not do this:<br></p>\n\n<pre><code>if(options.selectable != null)\n</code></pre>\n\n<p>do either</p>\n\n<pre><code>if(options.selectable)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if(options.selectable !== null) //Notice the ==\n</code></pre></li>\n<li>You are not consistent with semicolons, use jshint.com to fix your code</li>\n<li>Extract some constants out, particularly widths and heights in your element building code</li>\n<li>You use both single and double quotes to delimit strings, pick one, preferably single quotes</li>\n<li>Considering using <code>$().toggleClass()</code>, you seem to be toggling a few times classnames yourself</li>\n<li>I would allow <code>toggleCallBack</code> to cancel the toggeling so that I could use it validate the toggle </li>\n</ul>\n\n<p>Other than that I think your code is solid.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T20:17:32.550",
"Id": "41427",
"ParentId": "14525",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T12:34:33.993",
"Id": "14525",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "jQuery list widget"
}
|
14525
|
<p>I find this code quite ugly, but in fact, I can't find a finer way of achieving the goal.</p>
<pre><code>private static final String TABLE_NAME = "table_name";
private static final String[] allNeededColumns = {"col_id","col_one","col_two"};
public int[] getItemIds(int category_id) {
ArrayList<Integer> ids = new ArrayList<Integer>();
Cursor c = getDatabase().query(TABLE_NAME, allNeededColumns, CATEGORY_ID + "=" + category_id, null, null, null, null);
c.moveToFirst();
while(!c.isAfterLast()){
ids.add(Integer.valueOf(c.getInt(2)));
c.moveToNext();
}
return convertIntegers(ids);
}
public static int[] convertIntegers(ArrayList<Integer> integers)
{
int[] ret = new int[integers.size()];
Iterator<Integer> iterator = integers.iterator();
for (int i = 0; i < ret.length; i++)
{
ret[i] = iterator.next().intValue();
}
return ret;
}
</code></pre>
<p>The purpose is to get out of table <code>int array, where IDs are item IDs from category by</code>category_id`.</p>
<p>The problem is, I need some kind of expandable collection to add DB result ID to, and return primitives array, and I find it prettier than creating new <code>int[]</code> variable for each iteration on <code>Cursor</code>.</p>
<p>Can you think of a prettier solution?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-12T10:07:28.527",
"Id": "23647",
"Score": "0",
"body": "blame java for the way primitives are handled. you can use a library such as [Guava](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/primitives/Ints.html#toArray(java.util.Collection)) to get around that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-13T15:50:35.247",
"Id": "23707",
"Score": "0",
"body": "Have you considered using Cursor.getCount() to find out how many ids is here? Then you can allocate an array of the needed size in advance and avoid using an expandable collection."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-13T16:32:48.823",
"Id": "23709",
"Score": "0",
"body": "@DarthBeleg good point good sir :) Thank you"
}
] |
[
{
"body": "<p>If you were going to use the above you could still utilise Java's autoboxing feature, but there is a shorter form as hinted at by Darth Beleg.</p>\n\n<p>Untested:</p>\n\n<pre><code>int[] ret = new int[c.getCount()];\nif (c.moveToFirst())\n for (int i = 0; i < c.getCount();) {\n ids[i++] = c.getInt(2);\n c.moveToNext();\n }\n}\n</code></pre>\n\n<p>Although it is not pertinent to your case it is worth remembering that</p>\n\n<pre><code>ret[i] = iterator.next().intValue();\n</code></pre>\n\n<p>could throw a NPE.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T13:47:55.407",
"Id": "30035",
"ParentId": "14526",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T13:06:54.937",
"Id": "14526",
"Score": "2",
"Tags": [
"java",
"array",
"android",
"collections",
"integer"
],
"Title": "Get int array from database Cursor"
}
|
14526
|
<p>Inspired by another thread on here I was wondering if I could have an expert eye passed over this script?</p>
<p>If I run the script with App1, App2 or App3 individually it takes about 3 mins per run. However when I invoke the ALL option that time increases to an hour. I'm no doubt managing my memory awfully so any advise would be great.</p>
<p>I'm new to this so getting this far has been good; my customer is happy running the 3 separately but I like to finish things properly.</p>
<pre><code># Get Domain State
import sys,os
from weblogic.management.security.authentication import UserEditorMBean
from time import strftime, sleep
today = strftime('%Y%m%d %H:%M.%S')
#import wlstutility
#wlstutility.initialise(globals())
#from wlstutility import *
#from wlstutility.constructors import *
from java.io import FileInputStream
environment = []
component = []
adminURL = ""
adminServerName = ""
configFile = ""
userKeyFile = ""
userConfigFile = ""
keyFile = ""
adminServersFail = 0
adminServersErrorCapture = []
adminServerRunning = 0
adminServerLog = []
connectToAdminServerFail = 0
setEnvironmentPropertiesFail = 0
managedServersFail = 0
managedServersErrorCapture = []
managedServerRunning = 0
managedServerState = []
otherErrorCount = 0
otherErrorCapture = []
exitCode = 255
def setEnvironmentProperties(environment, component):
try:
global setEnvironmentPropertiesFail
setEnvironmentPropertiesFail = 0
print "Checking and connecting to " + component
print strftime('%Y%m%d %H:%M.%S') + " INFO: environment: " + environment
domainPFile = environment + "/" + component+ ".properties"
print strftime('%Y%m%d %H:%M.%S') + " INFO: domainPFile: " + domainPFile
print strftime('%Y%m%d %H:%M.%S') + " INFO: component: " + component
loadProperties(domainPFile)
dpInputStream = FileInputStream(domainPFile)
domainProps = Properties()
domainProps.load(dpInputStream)
global configFile
configFile = "./"+environment+"/"+component+"configFile"
print strftime('%Y%m%d %H:%M.%S') + " INFO: configFile: " + configFile
global userConfigFile
userConfigFile=configFile
global keyFile
keyFile = "./"+environment+"/"+component+"keyFile"
print strftime('%Y%m%d %H:%M.%S') + " INFO: keyFile: " + keyFile
global userKeyFile
userKeyFile=keyFile
global adminUrl
adminUrl="t3://" + adminListenAddress + ":" + adminListenPort
print strftime('%Y%m%d %H:%M.%S') + " INFO: adminUrl: " + adminUrl
global adminServerName
adminServerName = adminServerName
global clusterAddress
clusterAddress = clusterName
print strftime('%Y%m%d %H:%M.%S') + " INFO: clusterAddress: " + clusterAddress
except:
print " FATAL: Could NOT set properties for " + environment + " " + component
global setEnvironmentPropertiesFail
setEnvironmentPropertiesFail += 1
global otherErrorCount
otherErrorCount += 1
global otherErrorCapture
otherErrorCapture.append(" WARNING: Properties Could Not Be Set For " + environment + " " + component)
global adminServerLog
adminServerLog.append(environment + ";" + adminServerName + ";" + " " + ';' + " " + ';' + component + ';' + "PROPSNOTFOUND")
def connectToAdmin():
try:
global connectToAdminServerFail
connectToAdminServerFail = 0
print strftime('%Y%m%d %H:%M.%S') + " INFO: Connecting to running AdminServer"
connect(userConfigFile=configFile, userKeyFile=keyFile, url=adminUrl)
print strftime('%Y%m%d %H:%M.%S') + " INFO: Getting " + adminServerName + " Server Status"
domainRuntime()
cd('/ServerRuntimes/' + adminServerName)
ss = cmo.getState()
hs = cmo.getHealthState()
x = hs.toString().split(',')[1].split(':')[1]
print strftime('%Y%m%d %H:%M.%S') + " INFO: " + adminServerName + ': ' + ss + ': ' + x
cd('../..')
global adminServerLog
adminServerLog.append(environment + ";" + adminServerName + ";" + ss + ';' + x + ';' + component + ';')
except:
global connectToAdminServerFail
connectToAdminServerFail += 1
print strftime('%Y%m%d %H:%M.%S') + " FATAL: Cannot connect to " + adminUrl + " ensure property files are correct"
global adminServersErrorCapture
adminServersErrorCapture.append(environment + ";" + adminUrl + ";" + component)
global adminServerLog
adminServerLog.append(environment + ';' + adminServerName + ';' + "" + ';' + " " + ';' + component + ';' + 'FAILEDCONNECTADMIN')
def findManagedServers():
print strftime('%Y%m%d %H:%M.%S') + " INFO: Finding Managed Servers"
try:
global findManagedServerFail
findManagedServerFail = 0
domainConfig()
print "CD to cluster" + clusterAddress
cd('Clusters/' +clusterAddress)
global managedServers
managedServers=cmo.getServers()
global numberofManagedServers
numberofManagedServers=`len(managedServers)`
print strftime('%Y%m%d %H:%M.%S') + " INFO: Found " + numberofManagedServers + " Managed Servers"
except:
global findManagedServerFail
findManagedServerFail += 1
print strftime('%Y%m%d %H:%M.%S') + " FATAL: Error navigating DomainConfig MBean tree for managed servers"
global managedServerState
managedServerState.append(environment + ';' + "Managed Server Name NOT Found" + ';' + " " + ';' + " " + ';' + component + ';' + "FAILEDMSMBEAN")
def getManagedServerState():
domainRuntime()
for servers in managedServers:
managedServerName=servers.getName()
print "Checking MS State of " + managedServerName
try:
print strftime('%Y%m%d %H:%M.%S') + " INFO: Getting " + managedServerName + " Server Status"
cd('/ServerRuntimes/' + managedServerName)
ss = cmo.getState()
hs = cmo.getHealthState()
x = hs.toString().split(',')[1].split(':')[1]
print strftime('%Y%m%d %H:%M.%S') + " INFO: " + managedServerName + ': ' + ss + ': ' + x
cd('../..')
global managedServerState
managedServerState.append(environment + ';' + managedServerName + ';' + ss + ';' + x + ';' + component + ';')
except:
print strftime('%Y%m%d %H:%M.%S') + " WARNING: " + managedServerName + " could NOT be contacted please investigate!"
global managedServersFail
managedServersFail =+ 1
global managedServersErrorCapture
managedServersErrorCapture.append(environment + ';' + managedServerName + ';' + " " + ';' + " " + ';' + component)
global managedServerState
managedServerState.append(environment + ';' + managedServerName + ';' + " " + ';' + " " + ';' + component + ';' + "FAILEDCONNECTMANAGED")
if managedServersFail == numberofManagedServers:
print strftime('%Y%m%d %H:%M.%S') + " FATAL: No Managed Servers Can Be Contacted in Cluster " + clusterAddress
exitCode = -1
def internalServiceBus(component):
if component == INTSB:
try:
domainRuntime()
for server in serverNames:
cd ('ServerRuntimes/intsb_ms1/JMSRuntime/intsb_ms1.jms/JMSServers/idecideserver_1/Destinations/idecideresources!idecideserver_1@idecide.commonerror')
except:
print strftime('%Y%m%d %H:%M.%S') + " Warning: Unable to connect to " + managedServerName
managedServersFail += 1
managedServersErrorCapture.append(server + " Unable to navigate domainRuntime MBean tree, please investigate")
exitCode = -1
def exitDomainState():
print ""
print "---------------------------------------------------"
print " Domain State Checks Complete"
print "---------------------------------------------------"
print ""
print ""
print "The Following Services are Running Without Issue:"
print ""
for smallsEnv in environments:
print smallsEnv
for smallsComponents in components:
for keys in adminServerLog:
key=keys.split(";")
if key[0] == smallsEnv:
if key[4] == smallsComponents:
if key[5] != "FAILEDCONNECTADMIN" and key[5] != "PROPSNOTFOUND":
printcount = 0
while printcount < 1:
print "-" + smallsComponents
print "--Administration Server"
printcount += 1
if key[2] == "RUNNING":
print " INFO: Weblogic Server " + key[1] + " is currently " + key[2] + " " + key[3]
global msprintcount
msprintcount = 0
for keys in managedServerState:
key=keys.split(";")
if key[0] == smallsEnv:
if key[4] == smallsComponents:
if key[5] != "FAILEDCONNECTMANAGED":
while msprintcount < 1:
print "--Managed Servers"
global msprintcount
msprintcount += 1
if key[2] == "RUNNING":
print " INFO: Weblogic Server " + key[1] + " is currently " + key[2] + " " + key[3]
print "---------------------------------------------------"
print ""
print ""
print "---------------------------------------------------"
print "The Following Services have issues :"
print "---------------------------------------------------"
print ""
for smallsEnv in environments:
global smallscount
smallscount = 0
for smallsComponents in components:
for keys in adminServerLog:
key=keys.split(";")
if key[0] == smallsEnv:
if key[4] == smallsComponents:
if key[5] == "FAILEDCONNECTADMIN" or key[5] == "PROPSNOTFOUND" or key[2] != "RUNNING" or key[3] != "HEALTH_OK":
printcount = 0
while printcount < 1:
while smallscount < 1:
print smallsEnv
smallscount += 1
print "-" + smallsComponents
print "--Administration Server"
printcount += 1
if key[5] == "FAILEDCONNECTADMIN":
print " FATAL: Could NOT Connect to " + key[1] + " Administration Server - Check Properties and/or server logs"
if key[5] == "PROPSNOTFOUND":
print " FATAL: Properties NOT found for " + smallsComponents + " Please Check Files"
if (key[2] != "RUNNING") and `len(key[2])` < 1:
print " WARNING: Weblogic Server " + key[1] + " is communicating but has a state of " + key[2] + " check log files"
if (key[3] != "HEALTH_OK") and `len(key[2])` < 1:
print " WARNING: Weblogic Server " + key[1] + " is " + key[2] + " but has a bad health status"
global msprintcount
msprintcount = 0
for keys in managedServerState:
key=keys.split(";")
if key[0] == smallsEnv:
if key[4] == smallsComponents:
if key[5] == "FAILEDMSMBEAN" or key[5] == "FAILEDCONNECTMANAGED" or key[2] != "RUNNING" or key[3] != "HEALTH_OK":
while msprintcount < 1:
while smallscount < 1:
print smallsEnv
print "-" + smallsComponents
smallscount += 1
print "--Managed Servers"
global msprintcount
msprintcount += 1
if key[5] == "FAILEDCONNECTMANAGED":
print " FATAL: Could NOT Connect to Managed Server: " + key[1] + " - server state " + key[2] + " check console and logfiles"
if key[5] == "FAILEDMSMBEAN":
print " ERROR: Failed to traverse Managed Server MBEAN Tree in domainConfig() - Check Admin server health and properties, this error can also be generated if the domain has NO managed servers"
if (key[2] != "RUNNING") and `len(key[2])` < 1:
print " WARNING: Weblogic Server " + key[1] + " is communicating but has a state of " + key[2] + " check log files"
if (key[3] != "HEALTH_OK") and `len(key[2])` < 1:
print " WARNING: Weblogic Server " + key[1] + " is " + key[2] + "but has a bad health status"
global smallscount
smallscount = 0
disconnect()
exit()
try:
environment=sys.argv[1]
component=sys.argv[2]
print "Environment " + environment
if environment == "App1":
global environments
environments = []
environments.extend(["SM1","SM2","SM3",])
global components
components = []
components.extend(["IL2CMS","IL2FORMS","IL2PORTAL","IL3FORMS","IL3COMMS",])
if environment == "App2":
global environments
environments = []
environments.extend(["SM1","SM2","SM3","SM4",])
global components
components = []
components.extend(["BPM","INTSB","EXTSB","OPA","VRD","BULKINTSB","BULKEXTSB",])
if environment == "App3":
global environments
environments = []
environments.extend(["SM1","SM2","SM3",])
global components
components = []
components.extend(["ETL","PORTAL","SB","SP",])
if environment == "ALL":
global environments
environments = []
environments.extend(["SM1","SM2","SM3","SM4"])
global components
components = []
components.extend(["IL2CMS","IL2FORMS","IL2PORTAL","IL3FORMS","IL3COMMS","BPM","INTSB","EXTSB","OPA","VRD","BULKINTSB","BULKEXTSB","ETL","PORTAL","SB","SP",])
for environmentState in environments:
print "Checking and connecting to " + environmentState
for componentState in components:
environment = environmentState
component = componentState
setEnvironmentProperties(environment, component)
if setEnvironmentPropertiesFail == 0:
connectToAdmin()
if connectToAdminServerFail == 0:
findManagedServers()
if findManagedServerFail == 0:
getManagedServerState()
disconnect()
# if setEnvironmentPropertiesFail > 0:
# global managedServerState
# managedServerState.append(environment + ';' + managedServerName + ';;;' + component + ';' + "FAILED")
exitDomainState()
# environments = [environment]
# components = [component]
# setEnvironmentProperties(environment, component)
# connectToAdmin()
# findManagedServers()
# getManagedServerState()
# exitDomainState()
# exit()
finally:
exit()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T15:27:13.607",
"Id": "23576",
"Score": "1",
"body": "Where is the profiler output?"
}
] |
[
{
"body": "<p>This may not account for everything, but notice that you're doing more work in <code>ALL</code> than in the sum of the other options.</p>\n\n<p>See <code>App1</code> for example - you iterate over [SM1, SM2, SM3] x [IL2CMS, IL2FORMS, IL2PORTAL, IL3FORMS, IL3COMMS] which is 15 combinations of (environment, component) in total.</p>\n\n<p>Now, look at <code>ALL</code>. Every component is checked in <em>every</em> environment, so now the five components from <code>App1</code> are also combined with SM4, which they never were before. That's 5 more iterations for the <code>App1</code> components that you don't run for <code>App1</code> alone.</p>\n\n<p>Similarly, <code>App3</code>'s four components are evaluated for <code>SM4</code>, which they weren't before.</p>\n\n<p>That's only nine more combinations in total than running the three options sequentially - perhaps those combinations take more time to complete because they don't really exist, and the connections time out?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-13T10:58:46.350",
"Id": "23689",
"Score": "0",
"body": "Thanks for the reply. The connections do exist it just slows down as the script progresses. \n\nI'll try changing the ALL segment to break the array into smaller chunks.\n\nThanks!\nDave"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-13T11:13:22.467",
"Id": "23690",
"Score": "0",
"body": "I'd suggest breaking the environment-specific branches out into functions returning a flat list of `(environment,component)` tuples: then the `ALL` branch can just call each function and cat the lists together"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T16:11:29.987",
"Id": "14533",
"ParentId": "14528",
"Score": "2"
}
},
{
"body": "<p><code>except</code> followed by nothing is like running with scissors: any kind of error will be 'swallowed' (deleted forever) and you will never know if you have a bug, instead do:</p>\n\n<pre><code>try:\n some_code\nexcept ExpectedException:\n other_code\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-04T19:04:55.303",
"Id": "88807",
"ParentId": "14528",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T13:41:04.437",
"Id": "14528",
"Score": "1",
"Tags": [
"python",
"ant"
],
"Title": "Ant database and configuration manager"
}
|
14528
|
<p>I like the modular aspect of AMDs (Asynchronous Module Definition; see this <a href="https://stackoverflow.com/a/8127152/270274">Stack Overflow reply</a>) and it's quite neat to structure JS.</p>
<p>But I typically compile all my JS files into one JS file. Therefore I don't really need the asynchronous part. So I thought I could quickly write such "infile" Module Loader.</p>
<pre><code>var load=(function()
{
var modules={};
return function(moduleName,dependencies,module)
{
if(moduleName.constructor===Array)
{
module=dependencies;
dependencies=moduleName;
moduleName=undefined;
}
if(!((moduleName&&moduleName.constructor===String||moduleName===undefined)
&& dependencies&&dependencies.constructor===Array
&& module&&module.constructor===Function))
throw "wrong usage";
var ret = module.apply(null,
dependencies.map(function(d){return modules[d]||(function(){throw "no module "+d})()})
);
if(moduleName)
{
if(!ret||ret.constructor!==Object) throw "module should be an object";
modules[moduleName]=ret;
}
}
})();
load('utils',[],function(){return {veryUseful:function(){alert('hey')}}});
load(['utils'],function(utils){utils.veryUseful()});
</code></pre>
<p><code>load</code> is used on one way to define a module and on an other way to call a function with the required modules passed as function arguments.</p>
<p><a href="http://jsfiddle.net/suKXm/" rel="nofollow noreferrer">Demo</a></p>
<p>The goal here is to allow one to have two pieces of code written in the same file that are guaranteed to be independent.</p>
<p>I'm curious if you have any suggestions on any level. From the concept of such "infile" Module Loader to a hidden neat little JS feature.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T15:41:18.203",
"Id": "23577",
"Score": "0",
"body": "\"see this StackOverflow reply\" -> That's not a reply. That's an user profile."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T21:37:31.800",
"Id": "68796",
"Score": "0",
"body": "I quite like it. To anyone that has used `require.js` your module definitions will feel natural."
}
] |
[
{
"body": "<p>I re-read your code several things, I can't say I would want to use it.</p>\n\n<ul>\n<li><p>Requiring the parameters to be modules seems neat with 1 module or 2. For larger applications, that would become silly.</p></li>\n<li><p>The most common use case with require is <code>var xxx = load(\"Xxx\")</code> but you do not provide anything of the sort, in fact, <code>load</code> does not return anything</p></li>\n<li><p>Having <code>load</code> being called in 2 different ways with 2 different ways of execution is wrong, I would suggest to simply use 2 different functions.</p></li>\n<li><p>Consider rewriting the <code>if</code> block for <code>\"wrong usage\"</code> with falsey values and/or add some comment, it is pretty much unreadable now</p></li>\n</ul>\n\n<p>At the very least I would modify the <code>apply</code> call to a <code>call</code> call, so that <code>this</code> has all the modules :</p>\n\n<p><code>var ret = module.call(modules);</code></p>\n\n<p>which makes for </p>\n\n<pre><code>load('utils',[],function(){return {veryUseful:function(){alert('hey')}}});\nload(['utils'],function(){this.utils.veryUseful()});\n</code></pre>\n\n<p>and return <code>ret</code> in case the caller wants to work with the module directly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T21:35:19.353",
"Id": "68795",
"Score": "0",
"body": "Not sure I agree with using `this` to access the modules. It doesn't feel very 'modular'."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T23:12:44.293",
"Id": "68811",
"Score": "0",
"body": "Agreed, but if I had to choose between parameters or `this`.."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T20:46:49.723",
"Id": "40779",
"ParentId": "14530",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T14:49:44.190",
"Id": "14530",
"Score": "3",
"Tags": [
"javascript",
"asynchronous"
],
"Title": "A little \"infile\" Asynchronous Module Definition"
}
|
14530
|
<p>I'm wrote a simple function <code>isBalanced</code> which takes some code and returns <code>true</code> if the brackets in the code are balanced and <code>false</code> otherwise:</p>
<pre><code>function isBalanced(code) {
var length = code.length;
var delimiter = '';
var bracket = [];
var matching = {
')': '(',
']': '[',
'}': '{'
};
for (var i = 0; i < length; i++) {
var char = code.charAt(i);
switch (char) {
case '"':
case "'":
if (delimiter)
if (char === delimiter)
delimiter = '';
else delimiter = char;
break;
case '/':
var lookahead = code.charAt(++i);
switch (lookahead) {
case '/':
case '*':
delimiter = lookahead;
}
break;
case '*':
if (delimiter === '*' && code.charAt(++i) === '/') delimiter = '';
break;
case '\n':
if (delimiter === '/') delimiter = '';
break;
case '\\':
switch (delimiter) {
case '"':
case "'":
i++;
}
break;
case '(':
case '[':
case '{':
if (!delimiter) bracket.push(char);
break;
case ')':
case ']':
case '}':
if (!delimiter && bracket.length && matching[char] !== bracket.pop())
return false;
}
}
return bracket.length ? false : true;
}
</code></pre>
<p>The function must not operate on brackets inside strings and comments. I wanted to know if my current implementation will work correctly for all test cases. I also wanted to know whether brackets may be used in any other context beside strings and comments in a language like JavaScript (AFAIK this is not the case).</p>
|
[] |
[
{
"body": "<p><code>The function must not operate on brackets inside strings and comments.</code></p>\n<p>If that's the case then why not just compare the number of opened vs closed symbols?</p>\n<p>Example:</p>\n<pre><code>var haveSameLength = function(str, a, b){\n return (str.match(a) || [] ).length === (str.match(b) || [] ).length;\n};\nvar isBalanced = function(str){\n var arr = [ \n [ /\\(/gm, /\\)/gm ], [ /\\{/gm, /\\}/gm ], [ /\\[/gm, /\\]/gm ] \n ], i = arr.length, isClean = true;\n \n while( i-- && isClean ){\n isClean = haveSameLength( str, arr[i][0], arr[i][1] );\n }\n return isClean;\n};\n</code></pre>\n<p>Simple Testcases.</p>\n<pre><code>console.log( isBalanced( "var a = function(){return 'b';}" ) === true ); \nconsole.log( isBalanced( "var a = function(){return 'b';" ) === false ); \nconsole.log( isBalanced( "/*Comment*/var a = function(){ \\n // coment again \\n return 'b';" ) === false ); \nconsole.log( isBalanced( "var a = function(){return 'b';" ) === false ); \n</code></pre>\n<p>Here's a demo:\n<a href=\"http://jsfiddle.net/9esyk/\" rel=\"noreferrer\">http://jsfiddle.net/9esyk/</a></p>\n<h1>Update</h1>\n<p>Your code is optimal if performance is the main consideration, but the complexity is too high.\nHere are a few tips.</p>\n<h1>1)</h1>\n<p>Split up your function into smaller methods to reduce the complexity. One way to do this would be to have functions to filter your string so that you only analyze the meaningful characters.</p>\n<h1>2)</h1>\n<p>Avoid using the keyword <code>char</code> since it's a java reserved keyword.</p>\n<h1>Final Result:</h1>\n<pre><code>var removeComments = function(str){\n var re_comment = /(\\/[*][^*]*[*]\\/)|(\\/\\/[^\\n]*)/gm;\n return (""+str).replace( re_comment, "" );\n};\nvar getOnlyBrackets = function(str){\n var re = /[^()\\[\\]{}]/g;\n return (""+str).replace(re, "");\n};\nvar areBracketsInOrder = function(str){\n str = ""+str;\n var bracket = {\n "]": "[",\n "}": "{",\n ")": "("\n },\n openBrackets = [], \n isClean = true,\n i = 0,\n len = str.length;\n \n for(; isClean && i<len; i++ ){\n if( bracket[ str[ i ] ] ){\n isClean = ( openBrackets.pop() === bracket[ str[ i ] ] );\n }else{\n openBrackets.push( str[i] );\n }\n }\n return isClean && !openBrackets.length;\n};\nvar isBalanced = function(str){\n str = removeComments(str);\n str = getOnlyBrackets(str);\n return areBracketsInOrder(str);\n};\n</code></pre>\n<p>Testcases</p>\n<pre><code>test("test isBalanced for good values", function(){\n var func = isBalanced;\n ok(func( "" ));\n ok(func( "(function(){return [new Bears()]}());" ));\n ok(func( "var a = function(){return 'b';}" ));\n ok(func( "/*Comment: a = [} is bad */var a = function(){return 'b';}" ));\n ok(func( "/*[[[ */ function(){return {b:(function(x){ return x+1; })('c')}} /*_)(([}*/" ));\n ok(func( "//Complex object;\\n a = [{a:1,b:2,c:[ new Car( 1, 'black' ) ]}]" ));\n});\ntest("test isBalanced for bad values", function(){\n var func = isBalanced;\n ok(!func( "{" ));\n ok(!func( "{]" ));\n ok(!func( "{}(" ));\n ok(!func( "({)()()[][][}]" ));\n ok(!func( "[//]" ));\n ok(!func( "[/*]*/" ));\n ok(!func( "(function(){return [new Bears()}())];" ));\n ok(!func( "var a = [function(){return 'b';]}" ));\n ok(!func( "/*Comment: a = [} is bad */var a = function({)return 'b';}" ));\n ok(!func( "/*[[[ */ function(){return {b:(function(x){ return x+1; })'c')}} /*_)(([}*/" ));\n ok(!func( "//Complex object;\\n a = [{a:1,b:2,c:[ new Car( 1, 'black' ) ]]" ));\n});\n</code></pre>\n<p>Demo: <a href=\"http://jsfiddle.net/9esyk/3/\" rel=\"noreferrer\">http://jsfiddle.net/9esyk/3/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T14:32:30.873",
"Id": "24950",
"Score": "0",
"body": "When you check for balanced brackets you must ensure that an opening bracket comes before a closing bracket. Your code doesn't take that into account and fails if say a function is declared with a closing brace before an opening brace (which is invalid) but your code passes it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T21:33:37.863",
"Id": "24969",
"Score": "0",
"body": "@AaditMShah Updated my answer. Thanks for the response."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T22:32:01.993",
"Id": "15339",
"ParentId": "14532",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "15339",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T15:38:34.833",
"Id": "14532",
"Score": "7",
"Tags": [
"javascript",
"balanced-delimiters"
],
"Title": "Checking for balanced brackets in JavaScript"
}
|
14532
|
<p>Example of a C++ function which removes duplicates from a string:</p>
<pre><code>string remove_duplicates(string subject)
{
string no_duplicates("");
for(int i = 0; i < (int) subject.length(); i++) {
bool found = false;
for(int j = 0; j < (int) no_duplicates.length(); j++) {
if (no_duplicates[j] == subject[i]) {
found = true;
break;
}
}
if (!found) no_duplicates += subject[i];
}
return no_duplicates;
}
</code></pre>
<p>I often find myself writing the subroutine inside which loops through and checks if something is found, if it is NOT found, I need to execute some action. Another approach would be to check if <code>j == no_duplicates.length()</code>, but this doesn't seem optimum as well. </p>
<p>Any suggestions on how to optimize this?</p>
|
[] |
[
{
"body": "<p>If you don't need to modify a parameter always use <code>const</code> and try to take references. For your exact problem try to create a simple boolean function, e.g. which checks if a character is already in the string. This simplifies things a lot and improves the readability.</p>\n\n<p>In your case there is fortunately already a function for checking if a char is present, <a href=\"http://www.cplusplus.com/reference/string/string/find/\" rel=\"nofollow\">std::string find</a>. You can easily use it, e.g:</p>\n\n<pre><code>std::string remove_duplicates(const std::string& subject) {\n std::string no_duplicates;\n\n for(std::string::const_iterator it = subject.begin(); it != subject.end(); ++it) {\n\n if (no_duplicates.find(*it) == std::string::npos) // char not found\n no_duplicates += *it;\n\n }\n\n return no_duplicates;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T22:34:46.427",
"Id": "23603",
"Score": "0",
"body": "Thanks! This helped a lot. :-) Any specific reason for always using const for references? Passing by address I guess is because it is cheaper, since C++ by default copies the string, which is not required."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T22:50:45.940",
"Id": "23604",
"Score": "0",
"body": "@Sirupsen you don't use always const for references only if you don't want to modify it. This make sure you don't change it by accident and may also allow additional optimization"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-12T20:51:15.747",
"Id": "23670",
"Score": "0",
"body": "Why are you using const_iterator rather than a normal iterator?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-12T21:35:10.463",
"Id": "23671",
"Score": "0",
"body": "@Sirupsen because i don't need to modify subject, see [const vs. non-const iterators](http://stackoverflow.com/questions/309581/const-and-nonconst-stl-iterators)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T22:32:23.700",
"Id": "14540",
"ParentId": "14539",
"Score": "2"
}
},
{
"body": "<p>This is a well know problem:<br>\nOpen up one of Knuths book (I hope you have the set lying around).</p>\n\n<p>Anyway a string is a set of char.<br>\nchar only has 256 values (assuming 8 bits). So you set up an array of 256 counters (set to zero). Then you just start counting how many of each letter there is. The first element that exceeds 1 means you have duplicates:</p>\n\n<pre><code>bool checkduplicates(string const& subject) \n{\n char no_duplicates[256] = {0}; // initialize counts to zero.\n\n for(std::size_t i = 0; i < subject.length(); i++)\n {\n // need the static cast to make sure the character\n // is not signed and thus potentially negative.\n std::size_t index = static_cast<unsigned char>(subject[i])\n ++no_duplicates[index];\n\n if (no_duplicates[index] > 1)\n { return true;\n // I know this changes the meaning of your code.\n // I am just using it as an example of optimal check-duplicates.\n // It would be easy to convert to your code to use this technique.\n }\n }\n\n return false;\n}\n</code></pre>\n\n<p>Code review:</p>\n\n<p>The function is called remove duplicates.<br>\nBut that is not what it does. Use names that reflect the actual action.</p>\n\n<pre><code>string remove_duplicates(string subject) \n</code></pre>\n\n<p>Given that the function actually only checks for duplicates I would return a bool as a result (unless the output here is being used for other purposes) and I would pass the parameter by const reference. This prevents a copy (if the compiler is feeling sloppy) but more importantly is an indication that it will not be modified.</p>\n\n<p>Avoid C style casts in C++ code. There is absolutely no need for them. There are a whole set of new C++ casts that are designed to be much more easily seen.</p>\n\n<p>Avoid C++ style casts as much as possible. They are an indication that you are overriding the compiler because it can not do something you want it to do.</p>\n\n<pre><code> for(int i = 0; i < (int) subject.length(); i++) {\n</code></pre>\n\n<p>In this case you are using the wrong type and you are just asking the compiler to stop complaining. But this makes code harder to maintain. What happens if a maintainer change types of some variable will the cast still hold true? The compiler will still keep quite about any errors as you have indicated with a cast that you know what you are doing and have told it to shut up.</p>\n\n<p>Use the correct type (or one the compiler will not complain about).</p>\n\n<p>Also prefer pre-increment. It does not make any difference for POD types. But it can and usually does make a difference for class types (potentially container iterators). By using pre-increment your code will still work optimally when the types are changed (and it required no other code changes to keep the code working optimally).</p>\n\n<p>Why are you marking work to be done in one location:</p>\n\n<pre><code> found = true;\n break;\n</code></pre>\n\n<p>Then doing the work in another?</p>\n\n<pre><code> if (!found) no_duplicates += subject[i];\n</code></pre>\n\n<p>It would be easier to read to move the work to the point where it is needed.</p>\n\n<pre><code>for(int j = 0; j < (int) no_duplicates.length(); j++) {\n if (no_duplicates[j] == subject[i]) {\n no_duplicates += subject[i];\n break;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-11T15:29:32.933",
"Id": "23622",
"Score": "0",
"body": "1) Why not pass simply by reference? 2) Why the explicit (int) for subject.length()? 3) This doesn't do the same as my own function (although could easily be modified to)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-11T15:46:08.727",
"Id": "23623",
"Score": "0",
"body": "1) Because const& reference is an indication you are not going to modify it allowing the compiler more freedom."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-11T15:46:54.437",
"Id": "23624",
"Score": "0",
"body": "2) I am saying **don't** use (int)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-11T15:47:39.957",
"Id": "23625",
"Score": "0",
"body": "3) I am just showing the optimal solution for detecting duplicates. Which can be modified easily and adapted fro removing dupes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-11T15:51:34.590",
"Id": "23626",
"Score": "0",
"body": "“I hope you have the set [of Knuth’s books] lying around” – are you mad? In what Universe is that a reasonable assumption? I *do* happen to have the set lying around, and although I’ve used them occasionally they are far from an ideal reference, and a particularly poor educational tool. Other algorithms books are easier to approach, reasonably complete, and far cheaper."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-11T15:52:48.143",
"Id": "23627",
"Score": "0",
"body": "@KonradRudolph: It was a joke. Nobody has a set lying around (apart from you and me)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-11T15:53:16.117",
"Id": "23628",
"Score": "0",
"body": "@LokiAstari … ah. OK, that was actually a good one then."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-12T20:30:34.243",
"Id": "23666",
"Score": "0",
"body": "I do actually have a set lying around. Hah."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-12T20:38:19.460",
"Id": "23668",
"Score": "0",
"body": "Thanks for the thorough review. What's size_t? Why not just use int? What does the static cast stuff do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-13T00:06:12.837",
"Id": "23673",
"Score": "0",
"body": "`std::size_t` is a type used for measuring size (thus can not be negative). It is used by all the container types. It is guaranteed to be able to hold a number large enough to measure any object used by the computer. `static_cast<>()` is a C++ cast for converting between similar types."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-11T15:18:15.953",
"Id": "14557",
"ParentId": "14539",
"Score": "2"
}
},
{
"body": "<p>In C++11, avoid loops. In addition to what Loki said, avoiding loops would yield the following concise code:</p>\n\n<pre><code>std::string remove_duplicates(std::string const& subject) {\n std::string result;\n char duplicates[std::numeric_limits<char>::max()] = { };\n\n std::copy_if(begin(subject), end(subject), std::back_inserter(result),\n [&](char c) { return duplicates[c]++ == 0; });\n\n return result;\n}\n</code></pre>\n\n<p>This advice is not just an arbitrary preference: avoiding loops removes whole classes of potential errors (especially overflows and off-by-one errors) which are fundamentally impossible to make in the above code.</p>\n\n<p>But like Loki’s, this code assumes unsigned characters. Unfortunately, this is far from given; therefore, instead of relying on an implicit conversion between characters and integers, an explicit conversion would be required.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-12T20:31:13.757",
"Id": "23667",
"Score": "0",
"body": "This is a good tip. Practically all C++ I do is for competitive programming, where off-by-one errors can /not/ happen."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-12T20:39:04.730",
"Id": "23669",
"Score": "0",
"body": "Although C++11 is not allowed in most competitions..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-11T15:44:53.663",
"Id": "14558",
"ParentId": "14539",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "14540",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-10T21:54:27.663",
"Id": "14539",
"Score": "5",
"Tags": [
"c++"
],
"Title": "Optimize loop check"
}
|
14539
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.