body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I wrote this because I need to store an unknown bundle to a database. Most everyone suggested to <code>Parcel</code> it. The problem is the android docs specifically say not to use <code>parcel</code> for persistent storage. With some help from <code>palacsint</code> I was able to refactor my original code to the following:</p>
<pre><code>public class AndroidBundleSerializer {
public final Map<String, DataTypeHandler> dataTypeHandlers;
public AndroidBundleSerializer() {
final Map<String, DataTypeHandler> dataTypeHandlers =
new HashMap<String, DataTypeHandler>();
register(dataTypeHandlers, new BooleanHandler());
register(dataTypeHandlers, new BooleanArrayHandler());
// Register other handlers here
this.dataTypeHandlers = Collections.unmodifiableMap(dataTypeHandlers);
}
private void register(final Map<String, DataTypeHandler> dataTypeHandlers,
final DataTypeHandler type) {
final String name = type.getName();
dataTypeHandlers.put(name, type);
}
public interface DataTypeHandler {
String getName();
void write(ObjectOutputStream out, Bundle bundle, String key) throws IOException;
void read(ObjectInputStream in, Bundle bundle, String key) throws IOException;
}
private final static String TYPE_BOOLEAN = "Boolean";
private final static String TYPE_BOOLEAN_ARRAY = "boolean.array";
private final static String TYPE_STRING_ARRAY = "String.array";
private final static String TYPE_STRING_ARRAY_LIST = "String.array.list";
private class StringArrayHandler implements DataTypeHandler {
public StringArrayHandler() {
}
public String getName() {
return TYPE_STRING_ARRAY;
}
public void write(final ObjectOutputStream out, final Bundle bundle,
final String key) throws IOException {
final String[] array = bundle.getStringArray(key);
out.writeInt(array.length);
for (String item : array) out.writeUTF(item);
Log.v("SERIALIZE", key + "[" + getName() + "][" + array.length + "]");
}
public void read(final ObjectInputStream in, final Bundle bundle,
final String key) throws IOException {
final int length = in.readInt();
final String[] data = new String[length];
for (int i = 0; i < length; i++) data[i] = in.readUTF();
bundle.putStringArray(key, data);
Log.v("DE-SERIALIZE", key + "[" + getName() + "][" + length + "]");
}
}
private class StringArrayListHandler implements DataTypeHandler {
public StringArrayListHandler() {
}
public String getName() {
return TYPE_STRING_ARRAY_LIST;
}
public void write(final ObjectOutputStream out, final Bundle bundle,
final String key) throws IOException {
final String[] array = (String[]) bundle.getStringArrayList(key).toArray();
out.writeInt(array.length);
for (String item : array) out.writeUTF(item);
Log.v("SERIALIZE", key + "[" + getName() + "][" + array.length + "]");
}
public void read(final ObjectInputStream in, final Bundle bundle,
final String key) throws IOException {
final int length = in.readInt();
final ArrayList<String> data = new ArrayList<String>();
for (int i = 0; i < length; i++) data.add(in.readUTF());
bundle.putStringArrayList(key, data);
Log.v("DE-SERIALIZE", key + "[" + getName() + "][" + length + "]");
}
}
</code></pre>
<p>And here is the code (in my SQLiteDataBaseManager class) that serializes the bundle:</p>
<pre><code>private byte[] bundleToByteArray(Bundle bundle){
AndroidBundleSerializer serializer = new AndroidBundleSerializer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ObjectOutputStream out = new ObjectOutputStream(baos);
for (final String key: bundle.keySet()) {
final Object obj = bundle.get(key);
String type = obj.getClass().getSimpleName();
if(obj.getClass().isArray()) type = type + ".array";
out.writeUTF(key);
out.writeUTF(type);
final DataTypeHandler dataTypeHandler = serializer.dataTypeHandlers.get(type);
if (dataTypeHandler != null) {
dataTypeHandler.write(out, bundle, key);
} else {
Log.v("DEBUG", key + "[" + type + "]");
}
}
byte[] buffer = baos.toByteArray();
return buffer;
} catch (IOException ioe) {
Log.i("BundleToByteArray","IOException");
return null;
}
}
</code></pre>
<p>I have a couple of questions regarding the above code. </p>
<ol>
<li><p>Does anyone see any oportunites to improve this code. I found it very repetative to write (I believe this is often an indicator that refactoring would help).</p></li>
<li><p>I have 21 posible types that could be in the bundle. I have included code for 2 handlers (StringArray and StringArrayList that are almost identical. Does anyone see any way to do away with all this boiler plate code and combining similar handlers. </p></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-01T11:29:02.100",
"Id": "21397",
"Score": "0",
"body": "Could you edit the question in a way that does not make existing answers meaningless, please? I think it would be better to ask a new question with the refactored code. Maybe somebody has another idea for the original question especially if you link it from the new one.\n\n\n\nhttp://meta.stackexchange.com/questions/94446/editing-a-question-and-asking-a-completely-different-question\n\nhttp://meta.stackexchange.com/questions/64459/rolling-back-a-completely-changed-question"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-24T23:48:46.813",
"Id": "186337",
"Score": "0",
"body": "There is a PersistableBundle class in Android. There might be something useful there, though I haven't checked."
}
] |
[
{
"body": "<ol>\n<li><p>Try to minimize the scope of local variables. It's not necessary to declare them at the beginning of the method, declare them where they are first used.</p>\n\n<p>See <em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>. (Google for \"minimize the scope of local variables\", it's on Google Books too.))</p></li>\n<li><p>You could replace the <code>Iterator</code> and the <code>while</code> loop with a <a href=\"http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html\" rel=\"nofollow\">foreach loop</a>:</p>\n\n<pre><code>for (final String key: bundle.keySet()) \n</code></pre></li>\n<li><p>The same <code>if-else</code> structure is repeating in both methods. It's not too safe and error-prone since there is no compile time check that you provided both serialize and deserialize logic for the same type. You should replace them with polymorphism. Here is a common interface for every data type:</p>\n\n<pre><code>public interface DataTypeHandler {\n\n String getName();\n\n void write(ObjectOutputStream out, Bundle bundle, String key) throws IOException;\n\n void read(ObjectInputStream in, Bundle bundle, String key) throws IOException;\n}\n</code></pre>\n\n<p>A sample implementation for the <code>boolean[]</code> type:</p>\n\n<pre><code>public class BooleanArrayHandler implements DataTypeHandler {\n\n public BooleanArrayHandler() {\n }\n\n @Override\n public String getName() {\n return \"boolean.array\";\n }\n\n @Override\n public void write(final ObjectOutputStream out, final Bundle bundle, \n final String key) throws IOException {\n final boolean[] array = (boolean[]) bundle.get(key);\n final int len = array.length;\n out.writeInt(len);\n for (int i = 0; i < len; i++) {\n out.writeBoolean(array[i]);\n }\n Log.v(\"SERIALIZE\", key + \"[\" + getName() + \"][\" + len + \"]\");\n }\n\n @Override\n public void read(final ObjectInputStream in, final Bundle bundle, \n final String key) throws IOException {\n final int length = in.readInt();\n final boolean[] data = new boolean[length];\n for (int i = 0; i < length; i++) {\n data[i] = in.readBoolean();\n }\n bundle.putBooleanArray(key, data);\n Log.v(\"DE-SERIALIZE\", key + \"[\" + getName() + \"][\" + length + \"]\");\n }\n}\n</code></pre>\n\n<p>The code won't compile if you don't implement both <code>read</code> and <code>write</code> methods.</p>\n\n<p>Here is a constructor which fills a map with the available handler objects:</p>\n\n<pre><code>private final Map<String, DataTypeHandler> dataTypeHandlers;\n\npublic AndroidBundleSerializer() {\n final Map<String, DataTypeHandler> dataTypeHandlers = \n new HashMap<String, DataTypeHandler>();\n register(dataTypeHandlers, new BooleanHandler());\n register(dataTypeHandlers, new BooleanArrayHandler());\n // ... more register calls here\n this.dataTypeHandlers = Collections.unmodifiableMap(dataTypeHandlers);\n}\n\nprivate void register(final Map<String, DataTypeHandler> dataTypeHandlers, \n final DataTypeHandler type) {\n final String name = type.getName();\n dataTypeHandlers.put(name, type);\n}\n</code></pre>\n\n<p>And the code which uses it for writing and replaces the one of big <code>if-else</code> conditionals:</p>\n\n<pre><code>final DataTypeHandler dataTypeHandler = dataTypeHandlers.get(type);\nif (dataTypeHandler != null) {\n dataTypeHandler.write(out, bundle, key);\n} else {\n Log.v(\"DEBUG\", key + \"[\" + type + \"]\");\n}\n</code></pre>\n\n<p>The replacement of the read <code>if-else</code> conditionals should be similar.</p>\n\n<p>References:</p>\n\n<ul>\n<li><em>Refactoring: Improving the Design of Existing Code</em> by <em>Martin Fowler</em>: <em>Replacing the Conditional Logic on Price Code with Polymorphism</em></li>\n<li><a href=\"http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism\" rel=\"nofollow\">Replace Conditional with Polymorphism</a></li>\n</ul></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-30T00:47:51.780",
"Id": "21373",
"Score": "1",
"body": "Thanks for your input. Item 1 I will have to try out. Its been a while since I hashed this out. I remember moving them up there as there was an error (I think it was due to the try block). Item 2: definitly. I am new to java so I wasn't aware of this construct. Item 3: This one is going to take some research. I will update my code when I get a minute to look at this. Thanks again for the input."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-01T04:07:49.733",
"Id": "21395",
"Score": "0",
"body": "Ok... I have implemented your suggestions (see edited question). Did I miss anything?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-01T11:29:48.153",
"Id": "21398",
"Score": "0",
"body": "@cstrutton: I'll check it soon."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-29T22:30:38.630",
"Id": "13205",
"ParentId": "12305",
"Score": "3"
}
},
{
"body": "<p>For the update:</p>\n\n<ol>\n<li><p></p>\n\n<pre><code>private final static String TYPE_BOOLEAN = \"Boolean\";\nprivate final static String TYPE_BOOLEAN_ARRAY = \"boolean.array\";\nprivate final static String TYPE_STRING_ARRAY = \"String.array\";\nprivate final static String TYPE_STRING_ARRAY_LIST = \"String.array.list\";\n</code></pre>\n\n<p>These constants are useful during the refactoring but as far as I see, since their values are used only once, I'd remove them and use their values inside the <code>getName()</code> methods.</p></li>\n<li>\n\n<pre><code>for (String item : array) out.writeUTF(item);\n</code></pre>\n\n<p>According to the <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-142311.html#454\" rel=\"nofollow\">Code Conventions for the Java Programming Language, 7.5 for Statements</a> you should use braces here. Omitting braces is error-prone.</p></li>\n<li>\n\n<pre><code>final ArrayList<String> data = new ArrayList<String>();\n</code></pre>\n\n<p>It's type could and should be simply <code>List<String></code>:</p>\n\n<pre><code>final List<String> data = new ArrayList<String>();\n</code></pre>\n\n<p>Reference: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p></li>\n<li>\n\n<pre><code>Log.v(\"DEBUG\", key + \"[\" + type + \"]\");\n</code></pre>\n\n<p>A more detailed log could be more useful here. Furthermore, if the loop found an unknown data type would it be worth to continue the serialization? I don't think so. I'd consider throwing an exception here to stop the whole processing.</p></li>\n<li><p>Log calls from the <code>read</code> and <code>write</code> methods could be moved out to the <code>bundleToByteArray</code> method if you don't need to log the length.</p></li>\n<li><p>Maybe reflection could help to reduce the number of classes to a couple of classes: one for handling simple types, one for lists and one for arrays.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-04T19:45:14.567",
"Id": "13320",
"ParentId": "12305",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-05T20:37:58.990",
"Id": "12305",
"Score": "1",
"Tags": [
"java",
"android"
],
"Title": "I am trying to manually serialize an android.Bundle. Any thoughts on the implementation?"
}
|
12305
|
<p><strong>Problem Statement:</strong></p>
<blockquote>
<p><strong>First Case:</strong> Where inclusion and exclusion both are not empty so that means inclusion overrides anything in exclusion so for that algorithm is like this:</p>
<p>If key is either equal to 155 or 156 and if temp is there in inclusion
then go into that if loop and do whatever you want. But if temp is not
there in inclusion then don't do anything.</p>
<p><strong>Second Case:</strong> Where inclusion is null and exclusion is not null so that means now you need to exclude everything present in exclusion string, so the algorithm is like this:</p>
<p>If key is either equal to 155 or 156 and if temp is not there in exclusion then do whatever you want to do in that else loop otherwise don't do anything.</p>
<p><strong>Third Case:</strong> If key is not equal to 155 or 156 then do whatever you want to do in that loop.</p>
</blockquote>
<p>Is there any way we can improve this code in terms of performance, readability, accuracy? as when I see this it contains lot of if/else statements to make the above problem works</p>
<p>P.S: Things that I am doing in each if/else loop is same everytime.</p>
<p><strong>Cases1:</strong> Where input parameters can be-</p>
<pre><code>String inclusion = null; // It can be null also
String exclusion = "100;77";
String temp = "0"; // It can change anytime
</code></pre>
<p><strong>Cases2:</strong> Where input parameter can be-</p>
<pre><code>String inclusion = "0"; // It can be null also
String exclusion = null;
String temp = "0"; // It can change anytime
</code></pre>
<p>Below is the code in which above input parameters can be used:</p>
<pre><code>for(TesxAttrKey key: pdsxWriteRequest.getAttrKeys()){
if((key.equals("156") || key.equals("155"))) {
if(inclusion != null && !inclusion.trim().isEmpty()) {
if(inclusion.matches("(^|.*;)" + temp + "(;.*|$)")) {
//Check the DsxAttrValue has a Synthesizer
if(metadata!=null){
Synthesizer synthesizer = metadata.getSynthesizer();
if(synthesizer!=null){
//Synthesize the attribute
DsxAttrValue synthesizedVal =
synthesizer.synthesize(key, record);
val = synthesizedVal;
}
}
if(val!=null){
writeRecord.getAttrs().put(key, val);
}
}
} else {
if(!exclusion.matches("(^|.*;)" + temp + "(;.*|$)")) {
//Check the DsxAttrValue has a Synthesizer
if(metadata!=null){
Synthesizer synthesizer = metadata.getSynthesizer();
if(synthesizer!=null){
//Synthesize the attribute
DsxAttrValue synthesizedVal =
synthesizer.synthesize(key, record);
//if(synthesizedVal!=null){
val = synthesizedVal;
//}
}
}
if(val!=null){
writeRecord.getAttrs().put(key, val);
}
}
}
} else {
//Check the DsxAttrValue has a Synthesizer
if(metadata!=null){
Synthesizer synthesizer = metadata.getSynthesizer();
if(synthesizer!=null){
//Synthesize the attribute
DsxAttrValue synthesizedVal = synthesizer.synthesize(key, record);
//if(synthesizedVal!=null){
val = synthesizedVal;
//}
}
}
if(val!=null){
writeRecord.getAttrs().put(key, val);
}
}
</code></pre>
<p>Is there any way we can improve this code in terms of performance, as I have lot of if/else loops to solve the above problem?</p>
|
[] |
[
{
"body": "<p>Your logic seems good. The problem statement was a tough to understand, but I think I got it. </p>\n\n<p>Since <code>inclusion</code> and <code>exclusion</code> do not change, we should extract that checking from the loop and place it before the loop. </p>\n\n<p>Furthermore, to reduce programmer errors, I reduced the code duplicity. The <em>\"do whatever you want\"</em> is now only typed once, and the regex pattern is only typed once.</p>\n\n<pre><code>String tempPattern = \"(^|.*;)\" + temp + \"(;.*|$)\";\n\nboolean tempInInclusionOrNotInExclusion;\nif(inclusion != null && !inclusion.trim().isEmpty()){\n tempInInclusionOrNotInExclusion = inclusion.matches(tempPattern);\n} else if(exclusion != null) {\n tempInInclusionOrNotInExclusion = !exclusion.matches(tempPattern);\n} else {\n tempInInclusionOrNotInExclusion = true;\n}\n\nfor(PdsxAttrKey key: pdsxWriteRequest.getAttrKeys()){\n boolean shouldDoWhatIWantToDo;\n if(key.equals(\"156\") || key.equals(\"155\")) {\n shouldDoWhatIWantToDo = tempInInclusionOrNotInExclusion;\n } else {\n shouldDoWhatIWantToDo = true;\n }\n\n if(shouldDoWhatIWantToDo){\n //Check the PdsxAttrValue has a Synthesizer\n if(metadata!=null){\n Synthesizer synthesizer = metadata.getSynthesizer();\n if(synthesizer!=null){\n //Synthesize the attribute\n PdsxAttrValue synthesizedVal = synthesizer.synthesize(key, record);\n //if(synthesizedVal!=null){\n val = synthesizedVal;\n //}\n }\n }\n if(val!=null){\n writeRecord.getAttrs().put(key, val);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T20:44:04.657",
"Id": "19813",
"Score": "0",
"body": "It looks good, but in my case there can be situation where inclusion and exclusion both can be null. And if that is the case then `shouldDoWhatIWantToDo` should be `true` and that means it should go inside that if loop `if(shouldDoWhatIWantToDo){`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T22:40:33.317",
"Id": "19817",
"Score": "0",
"body": "In that case, I added an extra check to the `tempInInclusionOrNotInExclusion` for when `exclusion` is null. `temp` is not in `exclusion` when null, so I set it to true."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T05:05:35.957",
"Id": "12315",
"ParentId": "12307",
"Score": "1"
}
},
{
"body": "<p>Regarding the performance:</p>\n\n<p>Are you sure there are any actual performance problems in that code? My point is that it could actually make the code slower when you try to improve code that you \"think\" is slow.</p>\n\n<p>Here's an <a href=\"https://stackoverflow.com/a/10800412/1158895\">answer</a> I gave recently to a related question. Its for a different programming language and a different subject matter, but the concept is the same. If you make changes to the code, how will you know if it is faster?</p>\n\n<p>Something else to consider: What are the performance requirements? And remember a requirement that states \"As fast as possible...\" is <strong><em>not</em></strong> a valid requirement.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T18:29:31.517",
"Id": "19808",
"Score": "0",
"body": "I just wanted to make sure here is that, I am not repeating things here in my code. As sometimes it happened that you are repeating your code when you can do the same thing without repeating it. That's what I wanted to make sure. Hope it helps."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T07:24:16.857",
"Id": "19822",
"Score": "0",
"body": "@user1419563, ok sounds reasonable. Have you looked into using a profiler to see if the changes you make actually improve the performance?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T07:11:59.440",
"Id": "12320",
"ParentId": "12307",
"Score": "0"
}
},
{
"body": "<p>I would always recommend util classes for common checks like:</p>\n\n<pre><code>if(inclusion != null && !inclusion.trim().isEmpty()) {\n\n--> StringUtil.isNotBlank(inclusion)\n</code></pre>\n\n<p>This makes code more readable. If you don't have these kind of util classes from former projects just use public implementations (from Spring, for example).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T23:01:17.153",
"Id": "12673",
"ParentId": "12307",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12315",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-05T21:28:09.927",
"Id": "12307",
"Score": "1",
"Tags": [
"java",
"performance"
],
"Title": "Inclusion and exclusion"
}
|
12307
|
<p>This is my first attempt at BDD and RSpec. I'm more of a C# xUnit kind of guy. </p>
<p>I wrote this class while developing a 2D random tile map generator (just for fun). The project is still ongoing.</p>
<p>I would particularly like some review on:</p>
<ul>
<li>Test granularity/scope in relation to BDD</li>
<li>Use of RSpec</li>
<li>Are these too much like unit tests?</li>
<li>Adherence to Ruby and RSpec idioms, conventions, coding style</li>
</ul>
<p>I am also open to any other kind of comments and review.</p>
<pre><code>require './map_factory'
describe MapFactory, "map creation" do
before(:each) do
@map_factory = MapFactory.new
end
it "should return a new Map instance" do
map = @map_factory.make(20, 20)
map.should be_an_instance_of(Map)
end
it "should be a map of the specified size" do
map = @map_factory.make(20, 20)
map.width.should equal(20)
map.height.should equal(20)
map.tiles.length.should equal(400)
end
it "should be an island" do
map = @map_factory.make(20, 20)
# an island should have water all around it
for x in 0...map.width
map.tile_at(x, 0).type.should eq(:water)
map.tile_at(x, 19).type.should eq(:water)
end
for y in 0...map.height
map.tile_at(0, y).type.should eq(:water)
map.tile_at(19, y).type.should eq(:water)
end
end
it "should have more than half the tiles be landmass" do
map = @map_factory.make(40, 40)
number_of_water_tiles = 0
number_of_land_tiles = 0
map.tiles.each do |tile|
if tile.type == :water then
number_of_water_tiles += 1
else
number_of_land_tiles += 1
end
end
number_of_land_tiles.should be > number_of_water_tiles
end
end
</code></pre>
|
[] |
[
{
"body": "<p>A small hint: the count method could clean up one of your test case, more or less as such:</p>\n\n<pre><code>it \"should have more than half the tiles be landmass\" do \n map = @map_factory.make(40, 40)\n number_of_water_tiles = map.tiles.count{|tile| tile.type == :water}\n number_of_land_tiles = map.tiles.size - number_of_water_tiles\n number_of_land_tiles.should be > (map.tiles.size / 2)\n end\nend\n</code></pre>\n\n<p>Also your <code>map</code> could go in the <code>before</code> section too imho.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T19:41:56.150",
"Id": "12333",
"ParentId": "12309",
"Score": "1"
}
},
{
"body": "<p>I am no RSpec pro yet, but here are a few things I would have done differently (see the comments):</p>\n\n<pre><code>require './map_factory'\n\ndescribe MapFactory, \"map creation\" do\n before(:each) do\n @map_factory = MapFactory.new\n end \n\n # I would put those 3 tests in the same context to DRY up things\n context \"20 x 20 map\" do\n before(:each) do\n map_factory = MapFactory.new # EDIT: this was an instance variable, which is useless here\n @map = map_factory.make(20, 20) # all three following tests used that, so why not use an instance variable here?\n end\n\n it \"should return a new Map instance\" do\n @map.should be_an_instance_of(Map)\n end\n\n it \"should be a map of the specified size\" do\n @map.width.should equal(20)\n @map.height.should equal(20)\n @map.tiles.length.should equal(400)\n end\n\n # you had a comment here, maybe it could be in the test description?\n it \"should be an island and have water all around it\" do\n # Enforce the use of Ruby ranges and iterator\n (0...@map.width).each do |x| \n @map.tile_at(x, 0).type.should eq(:water)\n @map.tile_at(x, 19).type.should eq(:water)\n end\n\n (0...@map.height).each do |y|\n @map.tile_at(0, y).type.should eq(:water)\n @map.tile_at(19, y).type.should eq(:water)\n end\n end\n end\n\n it \"should have more than half the tiles be landmass\" do \n number_of_water_tiles = 0\n number_of_land_tiles = 0\n\n @map.tiles.each do |tile|\n if tile.type == :water # remove \"then\" here as it is not needed\n number_of_water_tiles += 1\n else\n number_of_land_tiles += 1\n end\n end\n\n number_of_land_tiles.should be > number_of_water_tiles\n end\nend\n</code></pre>\n\n<p>edit: see in code comments</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T21:05:47.130",
"Id": "20232",
"Score": "0",
"body": "I often see the advice to use each rather than a for loop. Is there any reason beyond stylistic reasons?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T00:48:11.283",
"Id": "12341",
"ParentId": "12309",
"Score": "1"
}
},
{
"body": "<p>Your tests are good. But they can be better)</p>\n\n<ul>\n<li><p>At first, use one <code>should</code> for one example( <code>it</code> ). Your test falls when first matcher in order return false. And conditions below won't be checked. It's good for finding bugs and refactoring. Green test is not the reason of thinking that your code haven't got any bugs :) Read <a href=\"http://blog.jayfields.com/2007/06/testing-one-assertion-per-test.html\" rel=\"nofollow\">this</a></p></li>\n<li><p>Don’t begin tests(examples) names with the word ‘should’ for readability. Results should be easy to read.</p></li>\n<li><p>Some developers very like custom matchers for readable and clean code. It's very cool, but it is not essential often</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T07:31:15.197",
"Id": "12481",
"ParentId": "12309",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12341",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-05T23:49:46.753",
"Id": "12309",
"Score": "4",
"Tags": [
"ruby",
"rspec",
"bdd"
],
"Title": "First BDD/RSpec tests, would like some review regarding idioms, conventions and style"
}
|
12309
|
<h2>Learning Scala</h2>
<p>I'm trying to learn Scala and I'm interested in criticism about how to make my code more idiomatic. I've programmed a simple Connect-four game. Can I get some feedback?</p>
<p><a href="https://github.com/jamiely/connect-four-scala">https://github.com/jamiely/connect-four-scala</a></p>
<p>The two most important classes are <a href="https://github.com/jamiely/connect-four-scala/blob/master/src/connect_four/Board.scala">Board.scala</a> and <a href="https://github.com/jamiely/connect-four-scala/blob/master/src/connect_four/Game.scala">Game.scala</a>. They are shown below for your convenience as well. </p>
<h2>Board.scala</h2>
<pre><code>package connect_four
import connect_four._
class Index(val row: Int, val col: Int) {
def tuple(): (Int, Int) = (row, col)
}
class Size(val width: Int = 7, val height: Int = 6)
class Board(val size: Size = new Size()) {
val length = size.width * size.height
val board = (for (_ <- 0 to length-1) yield Markers.Empty).toArray
// Return a list of index objects
def getPositionIndices() = {
for {
row <- 0 to size.height-1
col <- 0 to size.width-1
}
yield new Index(row, col)
}
def isEmpty = board.forall(x => x == Markers.Empty)
def isInBounds(index: Index) = {
val row = index.row
val col = index.col
row >= 0 && row < size.height && col >= 0 && col < size.width
}
def fromIndex(index: Index): Option[Int] = {
if(isInBounds(index)) {
Some(index.row * size.width + index.col)
}
else None
}
def move(marker: Markers.Marker, index: Index): Boolean = {
val pos: Option[Int] = for {
pos <- fromIndex(index)
_ <- Some(updatePosition(marker, pos))
} yield pos
!pos.isEmpty
}
// Updates the given position without performing a check.
// @returns Returns a pair of the marker that was put at the position and the position.
def updatePosition(marker: Markers.Marker, position: Int) = {
board(position) = marker
(marker, position)
}
def markerAt(index: Index): Option[Markers.Marker] = {
for {
pos <- fromIndex(index)
m <- Some(board(pos))
} yield m
}
def posIs(marker: Markers.Marker, index: Index) = {
val result: Option[Boolean] = for {
m <- markerAt(index)
// return the result of a check against the marker
result <- Some(m == marker)
} yield result
result.getOrElse(false)
}
def hasMovesLeft = board.exists(x => x == Markers.Empty)
}
</code></pre>
<h2>Game.scala</h2>
<pre><code>package connect_four
import connect_four._
class Game {
val board = new Board
var currentMarker = Markers.A
// directions are deltas used to check board locations in the cardinal directions
val directions = (for {
i <- -1 to 1
j <- -1 to 1
if !(i==0 && j==0)
} yield (i, j)).toList
def checkPosition(index:Index, marker:Markers.Marker, delta: (Int, Int), steps: Int): Boolean = {
if(steps == 0) {
true
}
else if (board.isInBounds(index) && board.posIs(marker, index)) {
val newIndex = new Index(index.row + delta._1, index.col + delta._2)
checkPosition(newIndex, marker, delta, steps-1)
}
else {
false
}
}
def isWin:Boolean =
board.getPositionIndices().exists(testWinAtIndex)
def testWinAtIndex(index:Index): Boolean = {
board.markerAt(index) match {
case None => false
case Some(Markers.Empty) => false
case Some(m) => directions.exists(delta => checkPosition(index, m, delta, 4))
}
}
def getFirstEmptyRowInColumn(c: Int): Option[Int] = {
def helper(row: Int): Int = {
if (row < 0) {
row
} else {
val marker = markerAt(new Index(row, c))
if (marker == Some(Markers.Empty)) row else helper(row - 1)
}
}
if(!board.isInBounds(new Index(0, c))) {
None
}
else {
val r = helper(board.size.height-1)
if(r < 0) None else Some(r)
}
}
def toggleMarker(): Markers.Marker = {
currentMarker = if(currentMarker == Markers.A) Markers.B else Markers.A
currentMarker
}
def updateBoard(index: Index): Markers.Marker = {
board.move(currentMarker, index)
toggleMarker()
}
def move(mv: Move): Option[Markers.Marker] = {
if(isWin) {
None
}
else {
for {
row <- getFirstEmptyRowInColumn(mv.col)
result <- if(row >= 0) Some(updateBoard(new Index(row, mv.col))) else None
} yield result
}
}
def markerAt(index:Index): Option[Markers.Marker] = board.markerAt(index)
def getCurrentMarker: Markers.Marker = currentMarker
}
</code></pre>
|
[] |
[
{
"body": "<p>Nice code! You did the most things correct only some hints:</p>\n\n<ul>\n<li>Use case classes. They bring you some nice methods (like copy or apply) and result in easier maintainable code. There is no need any more to instantiate objects directly with <code>new</code> - instead it is possible to use the apply-method (factory pattern). Later, when your application grows, maybe you detect that you have to much object creations - with case classes it is easy to cache object instantiation inside of the apply-method - without changing any call side code.</li>\n<li>If you need mutable state then centralize and encapsulate it in single places. The Game class does have some public <code>var</code> - refactor this. No one outside of this class should be able to change the state of this <code>var</code>.</li>\n<li>Make Game immutable. You should hold different game instances at the call side such as your UIConsole.</li>\n<li>In Scala algebraic data types are more powerful than enumerations. </li>\n<li>Instead of sharing libraries in your repository use build tools like sbt.</li>\n<li>Move test code outside of your main code - this makes it easier to publish your code as an standalone application.</li>\n</ul>\n\n<p>Syntax clues:</p>\n\n<ul>\n<li>You can leave curly braces when you have single expressions.</li>\n<li>For-expressions can be nested: <code>for(a <- ...; b <- ...; c <- ...)</code></li>\n<li>Methods with side effects should marked with parentheses: <code>def x { println } -> def x() { println }</code></li>\n<li>Type Application is deprecated, use App instead</li>\n<li>There is no need to move each class to its own file. In particular when you have a lot of small classes (like your Move, Markers) it can be more clear to put them together.</li>\n</ul>\n\n<p>Some months ago I have written the game Othello in Scala - <a href=\"https://gist.github.com/2472666\">here</a> is the result. Maybe it offers some concepts to you.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T12:44:59.727",
"Id": "12327",
"ParentId": "12312",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "12327",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T00:47:06.683",
"Id": "12312",
"Score": "5",
"Tags": [
"scala"
],
"Title": "Connect Four In Idiomatic Scala"
}
|
12312
|
<p>I need some advice\suggestions on how to create\handle database connections for a project I'm working on. I'm creating a simple work order system for my company using PHP 5.4.3, right now there isn't any type of authentication as I'm not ready for that complexity.</p>
<p>So far I'm planning on the following structure:</p>
<pre><code>class Db {
private static $dbh = null;
static function open_connection() {
self::$dbh = new PDO(... }
static function query($sql) {
$result = self::$dbh->... }
static function fetch_array($result){
...}
...
}
class Workorder extends Db {
protected static $table_name = ...
...
public $wonum;
...
function instantiate {
//return workorder objects
...}
fucntion findallwos {
//find all work orders...
...}
...}
</code></pre>
<p>I think this will work fine for pages that I need to display all of the work orders or put in new work orders. But I have a few pages that require very simple queries, for example one of the reporting pages will just have a drop down list of the 3 technicians we have working for us, if I was using a global <code>$dbh</code> variable I could just do:</p>
<pre><code>function create_dropdown () {
GLOBAL $dbh;
$sql = "select...";
$sth = $dbh->prepare($sql);
$sth->execute();
$arry = $sth->fetchAll(PDO::FETCH_ASSOC);
.....
</code></pre>
<p>But I'd rather stay away from global variables as eventually I would like to add future complexity to this site which might not work with globals. (Including multiple users with authentication etc).</p>
<p>My questions are:</p>
<ol>
<li>Should I not use the Db class as I have it designed, and instead use some sort of connection_factory class instead that passes out connections? (and not have my workorder class be an extension of anything)</li>
<li>Should I just use static calls to the Db class to pull in simple queries? <code>db::fetch_array...</code></li>
<li>Do you have any other suggestions? I've come across a lot of different ways to go about this, but ideally I'd like to design this so that I don't have to completely recode everything when I get to the point where I'm adding multiple users with different permissions etc.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T05:45:16.003",
"Id": "19792",
"Score": "0",
"body": "You can use opensource classes http://code.google.com/p/digg/wiki/PDB"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T03:47:46.603",
"Id": "12313",
"Score": "1",
"Tags": [
"object-oriented",
"php5",
"database"
],
"Title": "Using database connections in PHP classes"
}
|
12313
|
<p>I have an interface named <code>ICodeRunner</code>, defined like this:</p>
<pre class="lang-cs prettyprint-override"><code>public interface ICodeRunner
{
ExecutionResult Run(string code);
}
</code></pre>
<p>I have more classes that implement <code>ICodeRunner</code>, but regardless of which one is used, in some contexts only I have to impose a time limit on the execution of the <code>Run</code> method. This is a regular timeout: "if it's not done in x seconds, throw an exception."</p>
<p>To achieve this, I have created a class called <code>CodeRunnerTimeLimitDecorator</code> that can wrap any class implementing <code>ICodeRunner</code> and provide this functionality.</p>
<p>This is how the class is implemented:</p>
<pre class="lang-cs prettyprint-override"><code>public class CodeRunnerTimeLimitDecorator : ICodeRunner
{
private readonly ICodeRunner _wrapped;
private readonly int _timeoutInSeconds;
public CodeRunnerTimeLimitDecorator(ICodeRunner wrapped, int timeoutInSeconds)
{
_wrapped = wrapped;
_timeoutInSeconds = timeoutInSeconds;
}
public ExecutionResult Run(string code)
{
var executionResult = new ExecutionResult();
var t = new Thread(() => executionResult = _wrapped.Run(code));
t.Start();
var completed = t.Join(_timeoutInSeconds * 1000);
if (completed)
return executionResult;
throw new ApplicationException(
string.Format("Code took longer than {0} seconds to run, so it was aborted.", _timeoutInSeconds));
}
}
</code></pre>
<p>While I welcome any advice about how to make this code better, I'm particularly interested in comments/improvements regarding the time limit mechanism.</p>
<p><strong>Update:</strong></p>
<p>More specifically, the questions are:</p>
<ol>
<li><p>Is there an easier/cleaner way to do it? </p></li>
<li><p>Would it be OK if I called <code>t.Abort()</code> in case the timeout had elapsed*?</p></li>
</ol>
<p>*<em>I do not control the process that goes on inside <code>_wrapped.Run(code)</code>, so I cannot implement <a href="http://msdn.microsoft.com/en-us/library/dd997396.aspx" rel="nofollow">Task Cancellation</a> or similar techniques.</em></p>
|
[] |
[
{
"body": "<p>This is actually a stab in the dark but could you use the .NET 4 System.Threading.Task object for this. Something like:</p>\n\n<pre><code>var task = Task.Factory.StartNew(() => _wrapped.Run(code) });\n\n// Wait returns true if the task finished within the allocated timeframe\n// http://msdn.microsoft.com/en-us/library/dd270644.aspx\nif(task.Wait(_timeoutInSeconds * 1000))\n{\n return executionResult;\n}\nelse\n{\n throw new ApplicationException(string.Format(\"Code took longer than {0} seconds to run, so it was aborted.\", _timeoutInSeconds));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T11:12:40.600",
"Id": "19771",
"Score": "0",
"body": "This definitely gains in terms of conciseness and code clarity, so +1! I am also looking for a advice on aborting the thread, in case it has exceeded the timeout."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T12:30:20.470",
"Id": "19782",
"Score": "0",
"body": "@w0lf there is a CancellationToken that can be used with the TPL which has been shown above. http://msdn.microsoft.com/en-us/library/dd997396.aspx or see http://stackoverflow.com/questions/4783865/how-do-i-abort-cancel-tpl-tasks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T12:48:12.633",
"Id": "19783",
"Score": "0",
"body": "@TrevorPilley Thanks for this clarification; I just realized I did not properly formulate the question. Please see my edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T14:58:07.953",
"Id": "19799",
"Score": "0",
"body": "@w0lf I don't think you should really be either 'newing' up a Thread or calling Thread.Abort(), have a look into ThreadPool.QueueUserWorkItem instead"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T20:11:27.920",
"Id": "19809",
"Score": "0",
"body": "@W0lf ah, my bad. I'll be interested to see what others say!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T09:40:26.533",
"Id": "12323",
"ParentId": "12321",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "12323",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T08:46:57.737",
"Id": "12321",
"Score": "3",
"Tags": [
"c#",
"timeout"
],
"Title": "Time Limit decorator"
}
|
12321
|
<p>I am trying to get user's current location base on the accuracy and less battery consumption. </p>
<p>Please review my code to help determine if I am going in right direction.</p>
<pre><code>Location location = null;
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_
try {
String provider = locationManager.getBestProvider(criteria, false);
locationManager.requestLocationUpdates(provider, 2000, 5,locationListener);
location = locationManager.getLastKnownLocation(provider);
lati = Double.toString(location.getLatitude());
longi = Double.toString(location.getLongitude());
} catch (Exception ex) {
ex.printStackTrace();
}
</code></pre>
|
[] |
[
{
"body": "<p>The last know location could be null. So you need a further check for this, then ask for a quick update:</p>\n\n<pre><code> if(location == null){\n String provider = locationManager.getBestProvider(criteria, true);\n if (provider != null){\n locationManager.requestLocationUpdates(provider, 0, 0, singeUpdateListener, context.getMainLooper()); \n }else {\n Log.e(\"TAG\", No location set\"); \n }\n }\n</code></pre>\n\n<p>class variable:</p>\n\n<pre><code>protected LocationListener singeUpdateListener = new LocationListener() {\n public void onLocationChanged(Location location) {\n String lati = Double.toString(location.getLatitude());\n String longi = Double.toString(location.getLongitude());\n locationManager.removeUpdates(singeUpdateListener);\n }\n\n public void onStatusChanged(String provider, int status, Bundle extras) {}\n public void onProviderEnabled(String provider) {}\n public void onProviderDisabled(String provider) {}\n };\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-05T07:45:16.187",
"Id": "13335",
"ParentId": "12322",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "13335",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T09:05:30.280",
"Id": "12322",
"Score": "1",
"Tags": [
"java",
"android"
],
"Title": "Getting user's current location"
}
|
12322
|
<p>I have this function takes a long time to complete. Is there a way i can improve it to quicken the procedure</p>
<pre><code>function do_updatebonus() {
global $site_config;
$res200 = SQL_Query_exec("SELECT DISTINCT userid FROM peers WHERE seeder = 'yes'");
while ($row200 = mysql_fetch_assoc($res200)) {
$userid = $row200["userid"];
$res201 = SQL_Query_exec("SELECT COUNT(torrent) FROM peers WHERE seeder = 'yes' AND userid = $userid");
$c = mysql_result($res201, 0);
if ($c >= 5) {
SQL_Query_exec("UPDATE users SET seedbonus = seedbonus + '" . $site_config["bonuspertime"] . "' WHERE id = $userid");
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Yeah, you can optimize your query,</p>\n\n<pre><code> $res201 = SQL_Query_exec(\"SELECT COUNT(torrent) FROM peers WHERE seeder = 'yes' AND userid = $userid\");\n</code></pre>\n\n<p>As this query will first check for seeder which has 'yes' and then for userid. So you can first check for userid, then for seeder. This will improve performance</p>\n\n<pre><code>$res201 = SQL_Query_exec(\"SELECT COUNT(torrent) FROM peers WHERE userid = $userid\" AND seeder = 'yes' );\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-04T18:35:16.060",
"Id": "12325",
"ParentId": "12324",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12325",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-04T18:27:01.797",
"Id": "12324",
"Score": "1",
"Tags": [
"php"
],
"Title": "can this php function be written to perform better?"
}
|
12324
|
<p>I would like to execute a series of events at the time at which they occur.</p>
<p>The events are stored in a list and always sorted by time of execution.</p>
<pre><code>volatileEvents.Sort(SortScriptEventAscending.Comparer);
</code></pre>
<p>I would like to have my update method execute the following points.</p>
<ul>
<li>The list should be checked to see if it contains any events (if not then don't continue)</li>
<li>The events should be executed and remain in the list until the next event is executed</li>
<li>Once the current event is executed the previous event should be removed</li>
<li>Events should always be checked to see if they have either expired or are yet to occur</li>
</ul>
<p>I have the basic conditions implemented but the algorithm doesn't work as intended.</p>
<pre><code> float currentTime = game.ScriptTimer.CurrentTime;
int numEvents = volatileEvents.Count;
// Check for no events
if (numEvents == 0)
{
return;
}
// Check for expired events
while (volatileEvents[0].Time < currentTime)
{
volatileEvents.RemoveAt(0);
}
// Check if the current event has yet to occur
if (volatileEvents[0].Time > currentTime)
{
return;
}
// Protect against index range error
int next = numEvents == 1 ? 0 : 1;
ScriptEvent currentEvent = volatileEvents[0];
ScriptEvent nextEvent = volatileEvents[next];
// Update the current value based on the script and event parameters
float value = currentEvent.Interpolate ?
MathTools.Lerp2D(currentEvent.Value, nextEvent.Value, currentEvent.Time, currentTime, nextEvent.Time) :
currentEvent.Value;
</code></pre>
<p>I would like some help to achieve the four bullet points as the basic conditions are there but the method's order of execution is incorrect.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T13:48:02.907",
"Id": "19789",
"Score": "0",
"body": "Why does an event have to stay in the list while it's executing? And it really should stay there even after it's finished?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T13:56:49.800",
"Id": "19790",
"Score": "0",
"body": "Good question. It needs to stay there because of the interpolation code (Lerp2D needs the value). I could store the value only instead of course."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T13:58:38.393",
"Id": "19791",
"Score": "0",
"body": "In response to the second question. It is being removed so the current event is always at the same index of the list. No need for searching the list for the event."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T09:34:46.820",
"Id": "19828",
"Score": "0",
"body": "Worked this out with pen and paper last night. Problem can be considered closed or solved."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T09:44:59.220",
"Id": "19829",
"Score": "0",
"body": "Could you share your solution with us and post it as an answer? If you don't want to do that, you can delete this question."
}
] |
[
{
"body": "<p>My simplified answer (without interpolation or looping):</p>\n\n<pre><code> int numEvents = events.Count;\n\n // Check if there are any events to execute\n if (eventIndex == numEvents)\n {\n return;\n }\n\n // Check if the current event has yet to occur \n if (events[eventIndex].Time > currentTime)\n {\n return;\n }\n else\n {\n // Update the property based on the current event\n UpdateProperty(events[eventIndex].Value);\n\n // Current event has been executed so increase the event index\n eventIndex++;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T21:24:54.030",
"Id": "12406",
"ParentId": "12328",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12406",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T13:32:25.347",
"Id": "12328",
"Score": "2",
"Tags": [
"c#",
"algorithm",
"timer"
],
"Title": "Timed series of events. Logic for organizing events based on time?"
}
|
12328
|
<p>In view of the recent LinkedIn breach, would anyone care to review my data access routines relating to user access?</p>
<p>This is a standard node.js module, accessing a Postgres database.</p>
<pre><code>(function () {
'use strict';
var crypto = require('crypto'),
hash = function (pass, salt) {
var h = crypto.createHash('sha512');
h.update(pass);
h.update(salt);
return h.digest('base64');
};
module.exports.getUser = function (conn, email, password, callback) {
conn.query({
name: 'getUser',
text: 'SELECT "id", "passwordHash" FROM "user" WHERE "email" = $1 LIMIT 1',
values: [email]
}, function (err, result) {
if (err) {
throw err;
}
if (result.rows.length === 0) {
callback(null);
} else {
var newHash = hash(password, email),
row = result.rows[0];
if (row.passwordHash === newHash) {
callback({id: row.id, email: email});
} else {
callback(null);
}
}
});
};
module.exports.addUser = function (conn, email, password, callback) {
var newHash = hash(password, email);
conn.query({
name: 'addUser',
text: 'INSERT INTO "user" ("email", "passwordHash") VALUES ($1, $2) RETURNING "id"',
values: [email, newHash]
}, function (err, result) {
var id;
if (err) {
console.error(err);
callback(null);
} else {
id = result.rows[0].id;
callback({id: id, email: email});
}
});
};
}());
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T14:33:20.667",
"Id": "19794",
"Score": "1",
"body": "The code looks fine to me, but I wouldn't use the email as the hash salt because it doesn't provide enough entropy. I always use a GUID as a salt because it ensures that `bits(password+salt) > bits(hash())`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T15:07:39.747",
"Id": "19801",
"Score": "0",
"body": "OK, so perhaps where I do `h.update(pass); h.update(salt);`, I should also add `h.update(<secret-guid>);`"
}
] |
[
{
"body": "<p>I do not see anything immediately wrong with your <code>addUser()</code> and <code>getUser()</code> implementations.<br>\nYour <code>hash()</code> implementation could be improved in two areas though.</p>\n\n<ol>\n<li><p><strong>Salt</strong><br>\nAs already indicated by Bill Barry in the comments, your should use a better salt.<br>\nSome rules to keep in mind when handling salts,</p>\n\n<ul>\n<li><p><strong>Salts should be unique per password.</strong><br>\n Every password should have a unique salt. Sharing a salt reduces its effectiveness. </p></li>\n<li><p><strong>Salts should be unpredictable</strong><br>\nYou should generate a salt using a Cryptographically Secure Pseudo-Random Number Generator (<a href=\"http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator\">CSPRNG</a>). </p>\n\n<p>You may want to try using <a href=\"http://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback\">crypto.randomBytes(size, [callback])</a> if available.</p></li>\n<li><p><strong>Salts should be large</strong><br>\n <a href=\"http://www.rsa.com/rsalabs/node.asp?id=2127\">PKCS#5</a> recommends a salt be no smaller than 64-bits (8 bytes).<br>\nI like to start with 128-bit salts (16 bytes), favoring higher salt-lengths for more passwords and better security. </p></li>\n<li><p><strong>Salts are not secret</strong><br>\nAlthough purposefully disclosing the salt isn't a good idea, you can store them in cleartext. </p></li>\n</ul></li>\n<li><p><strong>Key stretching / Iterations</strong><br>\nWikipedia has a good description on <a href=\"http://en.wikipedia.org/wiki/Key_stretching\">Key Stretching</a>, </p>\n\n<blockquote>\n <p>key stretching refers to techniques used to make a possibly weak key, typically a password or passphrase, more secure against a brute force attack by increasing the time it takes to test each possible key. </p>\n</blockquote>\n\n<p>The <code>crypto</code> module does not appear to offer key stretching natively for sha512. </p>\n\n<p>You should look into using <a href=\"http://nodejs.org/api/crypto.html#crypto_crypto_pbkdf2_password_salt_iterations_keylen_callback\">crypto.pbkdf2(password, salt, iterations, keylen, callback)</a> which uses HMAC-SHA1. You shouldn't use SHA1 on its own, but <code>pbkdf2</code> using HMAC-SHA1 is still secure.<br>\nSee <a href=\"http://en.wikipedia.org/wiki/PBKDF2\">Password-Based Key Derivation Function 2</a> for more information.</p>\n\n<p>You will want to set the number of iterations as high as possible while still maintaining an acceptable responsiveness for your application. Though <a href=\"http://www.rsa.com/rsalabs/node.asp?id=2127\">PKCS#5</a> recommends a minimum of 1000 iterations, 10000+ iterations is fairly typical; computers are only getting faster.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-14T23:21:23.967",
"Id": "15635",
"ParentId": "12330",
"Score": "7"
}
},
{
"body": "<p>@Jared Paolin's answer is good.</p>\n\n<p>Expanding on it a little:</p>\n\n<ol>\n<li>The salt should be exactly the same length as the hash.</li>\n<li>When you verify, always use a constant-time algorithm so that attackers can't play hangman to guess passwords. If it takes longer to get a response for a mostly right password, attackers can use that data to progressively guess the password one letter at a time.</li>\n<li>For 2014, you need at least 128,000 iterations to be safe with PDKDF2 / HMAC-SHA1. Make sure to pass the work load in as a parameter to PDKDF2, so you can change it as processors get faster. Double the iterations every 2 years.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-06T20:39:40.487",
"Id": "32345",
"ParentId": "12330",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "15635",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T14:22:45.187",
"Id": "12330",
"Score": "11",
"Tags": [
"javascript",
"node.js",
"postgresql"
],
"Title": "Node.js password salting/hashing"
}
|
12330
|
<p>I am using this <a href="http://onsetsds.sourceforge.net/" rel="nofollow">onset source code</a> and <a href="http://courseware.ee.calpoly.edu/~jbreiten/C/" rel="nofollow">this fft file</a> to try to perform onset detection. Currently the code is working, but as my DSP and C skills are subpar I could use some advice on how to improve it. </p>
<p>My main points of insecurity are the FFT (maybe there is a more suitable method out there?) and the C code. All advice appreciated!</p>
<p>NB: This code will eventually being going into iPhone project.</p>
<pre><code>OnsetsDS *ods = malloc(sizeof *ods);
float* odsdata = (float*) malloc(onsetsds_memneeded(ODS_ODF_RCOMPLEX, 512, 11));
onsetsds_init(ods, odsdata, ODS_FFT_FFTW3_HC, ODS_ODF_RCOMPLEX, 512, 11, 44100);
int i;
int x;
double (*vocalData)[2] = malloc(2 * 512 * sizeof(double));
double (*doubleFFTData)[2] = malloc(2 * 512 * sizeof(double));
for (i = 0; i < vocalBuffer.numFrames; i=i+512){
bool onset;
for (x = 0; x < 512; x++){
*vocalData[x] = (double)vocalBuffer.buffer[i+x];
}
fft(512, vocalData, doubleFFTData);
float *floatFFTData = malloc(512 * sizeof(float));
int z;
for (z = 0; z < 512; z++){
floatFFTData[z] = (float)*doubleFFTData[z];
}
onset = onsetsds_process(ods, floatFFTData);
if (onset){
printf("onset --> %i\n", i);
}
}
free(ods->data); // Or free(odsdata), they point to the same thing in this case
return nil;
</code></pre>
|
[] |
[
{
"body": "<p>The link in the post to your fft file is broken, so I can't see the function\nprototype. This is a pity, because it is otherwise difficult to know what to\nmake of your arrays:</p>\n\n<pre><code>double (*vocalData)[2] = malloc(2 * 512 * sizeof(double));\n</code></pre>\n\n<p>This says <code>vocalData</code> is a pointer to an array of two doubles. You have\nallocated 1024 doubles at this address. So on a 64bit system you have:</p>\n\n<pre><code> 8 bytes\nvocalData[0] -> |--------|\n |--------|\nvocalData[1] -> |--------|\n |--------|\nvocalData[2] -> |--------|\n |--------|\n etc \n</code></pre>\n\n<p>You fill the array with</p>\n\n<pre><code>for (x = 0; x < 512; x++){\n *vocalData[x] = (double)vocalBuffer.buffer[i+x];\n}\n</code></pre>\n\n<p>This fills alternate doubles in your allocated space and leaves the others\nuninitialized.</p>\n\n<pre><code> 8 bytes\nvocalData[0] -> |xxxxxxxx|\n |--------|\nvocalData[1] -> |xxxxxxxx|\n |--------|\nvocalData[2] -> |xxxxxxxx|\n |--------|\n etc \n</code></pre>\n\n<p>I don't know for sure that this is not what you want, but...</p>\n\n<p>Also all that converting from float to double and then back to float is very\ninefficient. As <code>onsetsds_process</code> takes floats, I can see the need, but\nmaybe you should use an FFT function that also deals in floats.</p>\n\n<p>Finally it would be better to <code>#define FFT_SIZE 512</code> at the top and use\n<code>FFT_SIZE</code> throughout instead of the explicit <code>512</code>. This is better practice,\nfor example making it much easier to change the FFT length if it is necessary.</p>\n\n<p>Oh and don't forget to free any memory you have allocated once you have\nfinished with it. In this case, that means all of your allocations should be\nfreed on exit (although if your <code>return 0</code> is the end of the program that is\nacademic).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-02T00:11:21.153",
"Id": "59793",
"Score": "4",
"body": "Answers are normally a bit longer than a simple comment. This could have been posted as a comment to the question instead of an answer. If you could expand the answer a bit, then it is more worthy of being an answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-02T01:11:54.113",
"Id": "59797",
"Score": "1",
"body": "Assume that the OP doesn't know what you are talking about, please explain to him how to do this, maybe showing some example code. I totally agree with you but what you have is not a review, it's a one liner, and will not get any up votes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-09T17:02:12.813",
"Id": "60866",
"Score": "1",
"body": "Well done, this answer has been significantly improved!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-01T23:44:35.947",
"Id": "36475",
"ParentId": "12331",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T15:22:16.260",
"Id": "12331",
"Score": "4",
"Tags": [
"c",
"signal-processing"
],
"Title": "Onset detection using FFT"
}
|
12331
|
<blockquote>
<p>Consider an 8-bit complier, in which we have an integer of size, say
2-words i.e. 16-bits or 2 bytes. You need to store three integer
values which are supposed to be as:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Name Range Size Required
--------------------------------------------------
Integer 1 0-3 2bits (00-11 in binary)
Integer 2 0-5 3bits (000-101 in binary)
Inetger 3 0-7 3bits (000-111 in binary)
</code></pre>
</blockquote>
<p>In total, we need only 8 bits to store all of these three values.
Which means that a single variable of integer datatype has enough
memory to accommodate these values. The challenge is to store all of
these three variables into a single instance of integer datatype and
retrieve it whenever required.</p>
<p>In other words, you need to develop a program which can - at the
maximum - use only two instances of integer datatype, first one for
the purpose of scanning values from the standard input device say
keyboard and the second one to store the data entered by user in the
form of three integer variables as discussed above and print them by
retrieving it from the second instance in which the data was stored.</p>
</blockquote>
<p>This is my program with no input validation. Please review it.</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <assert.h>
#ifdef DEBUG
void test();
#endif
#define store(_out, _in, _pos) ((_out) |= ((_in) << (_pos)))
#define ret(_out, _pos, _mask) (((_out) >> (_pos)) & (_mask))
#define firstnum_pos 0
#define secondnum_pos 2
#define thirdnum_pos 5
#define firstnum_mask 0x3
#define secondnum_mask 0x7
#define thirdnum_mask 0x7
int main()
{
unsigned short input = 0, output = 0;
printf ("Enter first number:");
scanf ("%hu", &input);
store(output, input, firstnum_pos);
printf ("Enter second number:");
scanf ("%hu", &input);
store(output, input, secondnum_pos);
printf ("Enter third number:");
scanf ("%hu", &input);
store(output, input, thirdnum_pos);
printf ("first number: %d", ret(output, firstnum_pos, firstnum_mask));
printf ("second number: %d", ret(output, secondnum_pos, secondnum_mask));
printf ("third number: %d", ret(output, thirdnum_pos, thirdnum_mask));
#ifdef DEBUG
test();
#endif
return 0;
}
#ifdef DEBUG
void test()
{
int i,j,k;
short out;
for (i=0; i<=3; i++)
for (j=0; j<=5; j++)
for (k=0; k<7; k++)
{
out = 0;
store(out, i, firstnum_pos);
store(out, j, secondnum_pos);
store(out, k, thirdnum_pos);
assert (i == ret(out, firstnum_pos, firstnum_mask));
assert (j == ret(out, secondnum_pos, secondnum_mask));
assert (k == ret(out, thirdnum_pos, thirdnum_mask));
}
printf ("Test completed\n");
}
#endif
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T06:36:55.020",
"Id": "19821",
"Score": "0",
"body": "Checked this code in both little endian and big endian machines."
}
] |
[
{
"body": "<p>Some ideas:</p>\n\n<ol>\n<li><p>I'd try encapsulating the position and mask parameters to one parameter. Maybe a struct would be fine for this. It is easy to mix up the parameters of <code>ret</code>, for example, somebody could call it accidentally with </p>\n\n<pre><code>`ret(output, secondnum_pos, firstnum_mask)` \n</code></pre>\n\n<p>or with </p>\n\n<pre><code>`ret(output, firstnum_mask, firstnum_pos)`. \n</code></pre>\n\n<p>(Note the parameter order.)</p></li>\n<li><p>Consider writing tests which store the <code>i</code>, <code>j</code>, <code>k</code> values in different order. Currently they do not detect if storing at the <code>firstnum_pos</code> overrides the second or the third values.</p></li>\n<li><p>Consider making copies of <code>i</code>, <code>j</code> and <code>k</code> for the <code>assert</code> calls before you call the marcos. If a macro accidentally changes values of <code>i</code>, <code>j</code> or <code>k</code> the assert will not detect it.</p></li>\n<li><p>A unit testing framework would be better for the testing: <a href=\"https://stackoverflow.com/questions/65820/unit-testing-c-code\">Unit Testing C Code</a></p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T21:53:36.033",
"Id": "12422",
"ParentId": "12332",
"Score": "2"
}
},
{
"body": "<p>Your code only works if the bits are not set. If you set the value multiple times, it will not work correctly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T22:05:52.423",
"Id": "12423",
"ParentId": "12332",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12422",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T17:17:18.377",
"Id": "12332",
"Score": "4",
"Tags": [
"algorithm",
"c",
"unit-testing",
"homework",
"integer"
],
"Title": "Storing three integer values"
}
|
12332
|
<p>I have implemented a socket listener that runs on my Linux Ubuntu server accepting connections and then starting up a new thread to listen on those connections (classic socket listener approach). The socket listener is persistant and the way it is restarted is by restarting the server.</p>
<p>I have implemented a logging feature in the code so that information such as the data received, any events that have occurred etc are logged to a file. All threads log to this same file and the file is named by the day it's on. So I end up with log files such as <code>2012-May-01.txt</code>, <code>2012-May-02.txt</code> etc etc.</p>
<p>In order to provide this logging, I implemented a couple of classes to handle the logging.</p>
<ul>
<li><code>EventLog</code> - Just a wrapper to hide away my actual logger and what is used by the various threads etc for logging</li>
<li><code>Logstream</code> - The class that does the logging to file</li>
</ul>
<p>I'm a bit concerned about this class and ensuring I capture all log events. As it can be called by multiple threads I do not want to lose any information.</p>
<p>I'm pretty sure logging is such a common issue so I'm hoping someone can point out the issues in this code and provide a much more robust solution. I am potentially going to look into other existing logging solutions as suggested by sudmong, but for now this is the easiest for me to get my head around (assuming it's a valid solution).</p>
<p><strong>Important:</strong> I want to keep the facility to log items in a file naming convention that fits the day the item was logged. I don't want one log file that spans multiple days etc</p>
<p><strong>EDIT</strong>: Following from <strong>X-Zero's</strong> comments I've changed my logging mechanism to use a <code>BlockingQueue</code> approach. Does this seem like a scalable solution if I was to look at logging perhaps up to 100 lines per second? The main issue I can see is perhaps the opening and closing of my log file for every log write and whether I should catch the <code>FileWriter</code> handle and only re-create on each new day?</p>
<pre><code>// Class interface through which all logging occurs
public class EventLog {
private static Logstream _eventLog;
public static Logstream create(BlockingQueue<StringBuilder> queue, String rootPath, int port)
{
_eventLog = new Logstream(queue, rootPath, port);
return _eventLog;
}
public static Logstream create(String rootPath, int port)
{
return create(new LinkedBlockingQueue<StringBuilder>(), rootPath, port);
}
public static void write(Exception ex, String cls, String func)
{
write("Exception: " + ex.toString(), cls, func);
}
public static void write(String msg, String cls, String func)
{
_eventLog.write(msg, cls, func);
}
}
</code></pre>
<p>And the actual logging class:</p>
<pre><code>import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.text.SimpleDateFormat;
public class Logstream implements Runnable {
private final String _path; // The root path we will use for logging
private final int _port; // the port of the application using this logger
private final BlockingQueue<StringBuilder> _queue; // Used to queue up messages for logging
private final Thread _writeThread; // Thread to run this logstream on
private int _dayOfMonth = -1; // The current day of the month
private String _cachedPath = ""; // Our log path. Changes for each day of the month
protected Logstream(BlockingQueue<StringBuilder> queue, String rootPath, int port) {
_port = port;
_path = rootPath;
_queue = queue; // LinkedBlockingQueue<StringBuilder>();
_writeThread = new Thread(this);
_writeThread.start();
}
public void write(String msg, String cls, String func)
{
queue(msg, cls, func);
}
public void run()
{
// logging never stops unless we restart the entire server so just loop forever
while(true) {
try {
StringBuilder builder = _queue.take();
flush(builder);
} catch(InterruptedException ex) {
flush(ex.toString());
System.out.println("Exception: LogStream.run: " + ex.getMessage());
}
}
}
private void flush(StringBuilder builder) {
flush(builder.toString());
}
private void flush(String data) {
BufferedWriter writer = null;
try {
System.out.println(data);
writer = getOutputStream();
writer.write(data);
writer.newLine();
writer.flush();
}
catch(IOException ex) {
// what to do if we can't even log to our log file????
System.out.println("IOException: EventLog.flush: " + ex.getMessage());
}
finally {
closeOutputStream(writer);
}
}
private boolean dayOfMonthHasChanged(Calendar calendar) {
return calendar.get(Calendar.DAY_OF_MONTH) != _dayOfMonth;
}
private String getPath() {
Calendar calendar = Calendar.getInstance();
if(dayOfMonthHasChanged(calendar)) {
StringBuilder pathBuilder = new StringBuilder();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yy");
Date date = new Date(System.currentTimeMillis());
_dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
pathBuilder.append(_path);
pathBuilder.append(df.format(date)).append("_");
pathBuilder.append(_port);
pathBuilder.append(".txt");
_cachedPath = pathBuilder.toString();
}
return _cachedPath;
}
private BufferedWriter getOutputStream() throws IOException {
return new BufferedWriter(new FileWriter(getPath(), true));
}
private void closeOutputStream(BufferedWriter writer) {
try {
if(writer != null) {
writer.close();
}
}
catch(Exception ex) {
System.out.println("Exception: LogStream.closeOutputStream: " + ex.getMessage());
}
}
private StringBuilder queue(String msg, String cls, String func) {
Date date = new Date(System.currentTimeMillis());
// $time . ": " . $func . ": " . $msg ."\n"
StringBuilder msgBuilder = new StringBuilder();
msgBuilder.append(new SimpleDateFormat("H:mm:ss").format(date));
msgBuilder.append(": ");
msgBuilder.append(cls);
msgBuilder.append("->");
msgBuilder.append(func);
msgBuilder.append("()");
msgBuilder.append(" :: ");
msgBuilder.append(msg);
try {
_queue.put(msgBuilder);
}
catch (InterruptedException e) {
flush(new StringBuilder(e.toString()));
flush(msgBuilder);
}
return msgBuilder;
}
}
</code></pre>
<p>So I created a unit test to check if overloading the log writing with multiple writes at once will ensure all events get written. I toggled between using two blockingqueue approaches.</p>
<ul>
<li><code>ArrayBlockingQueue</code>, with capacity set to 1 </li>
<li><code>LinkedBlockingQueue</code></li>
</ul>
<p>When using these I noticed that <code>LinkedBlockingQueue</code> could not keep up, where as <code>ArrayBlockingQueue</code> seemed to work 100% of the time. The <code>LinkedBlockingQueue</code> would often get to about 100 and stop outputing lines to the console where as the <code>ArrayQueue</code> would go through the full 1000.</p>
<p>My unit test code was:</p>
<pre><code> @Test
public void testLogStreamArrayBlockingQueue() {
EventLog.create(new ArrayBlockingQueue<StringBuilder>(1), "", 1);
for(int i = 0; i < 1000; i++) {
EventLog.write("ArrayBlockingQueue: " + i, "EventLogUnitTest", "testLogStreamArrayBlockingQueue");
}
Assert.assertTrue(true);
}
@Test
public void testLogStreamLinkedBlockingQueue() {
EventLog.create(new LinkedBlockingQueue<StringBuilder>(), "", 1);
for(int i = 0; i < 1000; i++) {
EventLog.write("LinkedBlockingQueue: " + i, "EventLogUnitTest", "testLogStreamLinkedBlockingQueue");
}
Assert.assertTrue(true);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T21:06:11.787",
"Id": "20012",
"Score": "2",
"body": "For loggging, I suggest you to adopt an existing logging framework they take care of issues faced by you.have a look into log4j and slf4j."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T22:25:40.863",
"Id": "20014",
"Score": "0",
"body": "@sudmong cheers will do. Am still interested in ideas on the code though :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T23:49:12.663",
"Id": "20233",
"Score": "1",
"body": "The class to use instead of `Vector` is probably an implementation of [Blocking Queue](http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html), which is threadsafe. Just let it block on `take()` until something is returned, and you're golden on the consumer end."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T01:00:33.790",
"Id": "20234",
"Score": "0",
"body": "@X-Zero thanks for that. I'll look into and post what I've done for any comments"
}
] |
[
{
"body": "<p>Here are some ideas:</p>\n\n<ul>\n<li>For better granularity of logs, if you're looking at high performance, write on a minutely, or hourly basis. Use the idea of writing to logs as jobs, each dispatched to a thread. This makes searchability of log files inherently parallelizable.</li>\n<li>Use a shutdown hook to flush on shutdown.</li>\n<li>Keep an option to convert your log class into out-of-proc - like a TCP Daemon or web server + client library.... That will definitely help all the applications you write, including those which crash sporadically.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T21:05:29.040",
"Id": "20074",
"Score": "0",
"body": "thanks for the tips. Any thoughts on the actual code posted as far as improvements go?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T07:43:22.490",
"Id": "12435",
"ParentId": "12336",
"Score": "4"
}
},
{
"body": "<p>Just some random notes about the code and the comments:</p>\n\n<ol>\n<li><p>The cause of missing log messages in the <code>testLogStreamLinkedBlockingQueue</code> is that that JUnit (or JUnit in Eclipse, I haven't tested from command line) stops the threads of the tests when the test method ends. Because writing is done by another thread it may need some time to write out every message from the queue. If you put a <code>Thread.sleep(5000)</code> at the end of the test method both version writes out all the 1000 messages.</p></li>\n<li><p>It's good to know that logging system sometimes are best-effort fail-stop logging systems which means that you could loose messages without any exception if there is an IO error. (<a href=\"https://stackoverflow.com/a/7683755/843804\">Logback reliability</a>)</p></li>\n<li><p>Field names should not start with underscore. <code>Logstream</code> should be <code>LogStream</code>. See <em>Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions</em> and <a href=\"http://docs.oracle.com/javase/specs/\" rel=\"nofollow noreferrer\">The Java Language Specification, Java SE 7 Edition, 6.1 Declarations</a>:</p>\n\n<blockquote>\n <p>Class and Interface Type Names</p>\n \n <p>Names of class types should be descriptive nouns or noun phrases, not overly long, in mixed\n case with the first letter of each word capitalized.</p>\n \n <p>[...]</p>\n \n <p>Names of fields that are not final should be in mixed \n case with a lowercase first letter and the first letters of \n subsequent words capitalized.</p>\n</blockquote></li>\n<li><p>What is <code>cls</code>? A longer name would be easier to understand.</p></li>\n<li><p>Starting a thread from a constructor does not smell well. It's rather error-prone.\n<a href=\"http://www.ibm.com/developerworks/java/library/j-jtp0618/index.html\" rel=\"nofollow noreferrer\">Java theory and practice: Safe construction techniques</a></p></li>\n<li><p><code>new Date(System.currentTimeMillis());</code> is the same as <code>new Date()</code>.</p></li>\n<li><p>I'd store <code>String</code> objects in the queue. <code>String</code>s are immutable which is more concurrency-friendly (there is no risk that another thread modifies the object without synchronization). Furthermore, usage of <code>String</code>s would move the cost of <code>StringBuilder.toString()</code> to other threads. The writer thread could be a bottleneck, so it's better if it has to do as less work as possible.</p></li>\n<li><p><code>flush(new StringBuilder(e.toString()))</code> could be simply <code>flush(e.toString())</code>.</p></li>\n<li><p>I'd check <code>null</code>s in the constructors. <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Preconditions.html\" rel=\"nofollow noreferrer\">checkNotNull from Guava</a> is a great choice for that. (Also see: <em>Effective Java, 2nd edition, Item 38: Check parameters for validity</em>)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T22:21:51.670",
"Id": "22408",
"Score": "1",
"body": "Those are great comments. Thanks a-lot. I'll re-take a look at my code and read some of the articles and post an update."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T19:54:53.797",
"Id": "13885",
"ParentId": "12336",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "13885",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T20:27:00.897",
"Id": "12336",
"Score": "4",
"Tags": [
"java",
"multithreading",
"unit-testing",
"queue",
"logging"
],
"Title": "Robust logging solution to file on disk from multiple threads on serverside code"
}
|
12336
|
<p>I have a simple atomic access class designed to work with Windows threads:</p>
<pre><code>template <class aa_type>
class AtomicAccess{
private:
CRITICAL_SECTION lock;
aa_type value;
public:
AtomicAccess(){
InitializeCriticalSection(&lock);
}
~AtomicAccess(){
DeleteCriticalSection(&lock);
}
AtomicAccess &operator=(const aa_type &val){
EnterCriticalSection(&lock);
value = val;
LeaveCriticalSection(&lock);
return *this;
}
AtomicAccess &operator++(int){
EnterCriticalSection(&lock);
value++;
LeaveCriticalSection(&lock);
return *this;
}
AtomicAccess &operator--(int){
EnterCriticalSection(&lock);
value--;
LeaveCriticalSection(&lock);
return *this;
}
bool operator==(const aa_type &val){
aa_type current;
EnterCriticalSection(&lock);
current = value;
LeaveCriticalSection(&lock);
return current == val;
}
bool operator!=(const aa_type &val){
aa_type current;
EnterCriticalSection(&lock);
current = value;
LeaveCriticalSection(&lock);
return current != val;
}
};
typedef AtomicAccess<int> int_aa;
</code></pre>
<p>Right now I am using it to only atomic-access integers, and the only operators I need are <code>=</code> (for assignment), <code>++</code>, <code>--</code>, <code>==</code> and <code>!=</code>. If I decide I need more operators, I will add them.</p>
<p>Testing race conditions is very tricky, so I would like to ask here if my approach will work or if I am missing something.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T10:18:37.950",
"Id": "23116",
"Score": "0",
"body": "Doing this just for simple integer ops seems like overkill. You should look into CAS/intrinsic ops (InterlockedIncrement & associated functions)."
}
] |
[
{
"body": "<p>I'm pretty bad at concurrency, and by no means a C++ expert, but this question has gotten surprisingly little attention, so I'll take a stab at it. Note that I've focused mostly on coding style rather than thread safety. Once I've had some more time to think about the code, I'll edit and post more about that.</p>\n\n<hr>\n\n<p><strong>operator=(AtomicAccess)</strong></p>\n\n<p>The following will evoke undefined behavior:</p>\n\n<pre><code>int_aa x;\nint_aa y;\nx = y;\n</code></pre>\n\n<p>The reason why is that CRITICAL_SECTION is not movable or assignable. (It technically is, but not safely.) The default <code>operator=</code> will copy the CRITICAL_SECTION.</p>\n\n<hr>\n\n<p><strong>Constructors</strong></p>\n\n<pre><code>int_aa x = 5;\n</code></pre>\n\n<p>Interestingly, MSVC++ 2010 will not consider this valid. I would have expected it to default-construct <code>x</code> then use x.operator=(5). Apparently my C++ knowledge is worse than I thought though :).</p>\n\n<p>Anyway, I consider it bad design to have an object in an unknown state.</p>\n\n<pre><code>int_aa x;\n</code></pre>\n\n<p>Is in an unknown state as the value of the int inside of <code>x</code> is unknown. I would have the default constructor default construct <code>value</code>, and I would also provide a constructor to set the value:</p>\n\n<pre><code>AtomicAccess(aa_value& val = aa_value()) : value(val)\n{\n InitializeCriticalSection(&lock);\n}\n</code></pre>\n\n<p>This could arguably be written with a lock around the assignment, however, I do not think that a different thread should be touching the object while it's being constructed anyway.</p>\n\n<p>I might also provide a constructor to copy from a different AtomicAccess:</p>\n\n<pre><code>AtomicAccess(const AtomicAccess& aa)\n{\n InitializeCriticalSection(&lock);\n}\n</code></pre>\n\n<p>This one will definitely require locking.</p>\n\n<hr>\n\n<p><strong>Unnecessary copy in <code>operator==</code> and <code>operator!=</code></strong></p>\n\n<p>Instead of storing a temporary copy of <code>value</code>, you can store a temporary bool:</p>\n\n<pre><code>bool operator==(const aa_type &val){\n EnterCriticalSection(&lock);\n bool equals = (this->value == val);\n LeaveCriticalSection(&lock);\n return equals;\n}\n</code></pre>\n\n<hr>\n\n<p><strong>operator!= could be implemented as <code>!operator==</code></strong></p>\n\n<p>Unless there's some compelling reason to implement them separately (which there almost never is), I would implement operator!= as the opposite of operator==:</p>\n\n<pre><code>bool operator!=(const aa_type &val)\n{\n return !(operator==(val));\n}\n</code></pre>\n\n<p>This will of course always call <code>aa_type::operator==</code> instead of <code>aa_type::operator!=</code>, but this shouldn't matter.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T09:56:23.463",
"Id": "19894",
"Score": "0",
"body": "Assignment operator is *never* invoked in an initialisation. That explains why `int_aa x = 5;` doesn’t work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T15:44:29.433",
"Id": "19937",
"Score": "0",
"body": "The assignment operator works for me, if I declare it as a class field and assign a value in the constructor. And I also don't want to copy Critical sections. They are meant only as a necessary evil and if I do the assignment from one AtomicAcess to another, then the inner value should be copied only. This is a good remark, thanks, even though I have no such assignments in the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T15:48:54.980",
"Id": "19939",
"Score": "0",
"body": "And other remarks do not lack relevance as well. Thanks. Just one clarification: The way I intend to design it is only through typedefs. So if I typedef int_aa, then I want int_aa to behave in every way (or at least in ways I need) as a normal integer, but with synchronized access. The code using it should neved use the AtomicAccess class directly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T16:00:29.877",
"Id": "19943",
"Score": "0",
"body": "And I now realized I don't even have `operator=(AtomicAccess)`, I have `operator=(aa_type)`. (I am assigning value at initialisation and then only ++ing or --ing.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T22:46:38.267",
"Id": "19970",
"Score": "0",
"body": "@KonradRudolph That explains it then. I had always thought that converting `type x = ...;` to `type x (...)` was an *optional* optimization."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T22:51:52.860",
"Id": "19971",
"Score": "0",
"body": "@JakubZaverka \"The assignment operator works for me, if I declare it as a class field and assign a value in the constructor.\" It works for now. But when you clobber one of the CRITICAL_SECTIONs with a different CRITICAL_SEECTION all kinds of weird bugs can happen later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T11:09:36.747",
"Id": "20002",
"Score": "0",
"body": "@Corbin it is, but `type x = …` would invoke *copy construction*, never copy *assignment*. But it’s always optimised anyway so that no copy is made, ever. But note that the copy constructor needs to be available anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T11:19:02.010",
"Id": "20004",
"Score": "0",
"body": "@KonradRudolph Ah ok, thanks. I thought it would silently do: `type x; x.operator=(...);` Did not realize it would do `type x(...);`. Been a while since I've done anything more than a few lines of C++ :)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T01:49:36.800",
"Id": "12365",
"ParentId": "12340",
"Score": "2"
}
},
{
"body": "<p>In addition to Corbin’s remarks (in particular the <strong>bug</strong> relating to copying!), the one thing that immediately jumps at me when looking at the code is the <em>code duplication</em>:</p>\n\n<p>Basically, every function of the class has the pattern</p>\n\n<pre><code>EnterCriticalSection(&lock);\nsome_action\nLeaveCriticalSection(&lock);\n</code></pre>\n\n<p>This can be reduced by the clever use of RAII:</p>\n\n<pre><code>scoped_lock sl(lock);\nsome_action\n</code></pre>\n\n<p>… where <code>scoped_lock</code> is a simple scoped guard implementation that acquires the lock in its constructor and releases it in its destructor.</p>\n\n<p>The implementation is straightforward (but could be made even cleaner by using a <code>std::unique_ptr</code> in C++11):</p>\n\n<pre><code>class scoped_lock {\n CRITICAL_SECTION& lock;\n scoped_lock(scoped_lock const&); // = delete\n\npublic:\n\n explicit scoped_lock(CRITICAL_SECTION& lock) : lock(lock) {\n EnterCriticalSection(&lock);\n }\n\n ~scoped_lock() {\n LeaveCriticalSection(&lock);\n }\n};\n</code></pre>\n\n<p>And yes, taken together this is <em>still</em> more code than your version but it importantly removes code duplication and that is more important than raw line count.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T15:54:54.050",
"Id": "19941",
"Score": "0",
"body": "Thanks, this definitely looks interesting. I would stick with the original version, however. Maybe it is not as elegant and quite verbose and repetitive, but I like how the code is more readable - it is immediately apparent what the code acomplishes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T22:56:56.067",
"Id": "19974",
"Score": "0",
"body": "@Konrad What are your thoughts on completely abstracting away the critical section from the class? Before I posted my answer, I thought for a while on the critical section duplicated code and couldn't decide how I felt. I thought about suggesting a second template parameter that is the locking class, then using blah.lock() and blah.unlock() to 'hide' the critical section code (and make it interchangeable with a different locking mechanism). Ultimately I could not decide if this would be worth it though, and am curious what others think."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T11:15:18.923",
"Id": "20003",
"Score": "1",
"body": "@Jakub My code uses an idiomatic pattern of C++, you *must* familiarise yourself with it, it’s a core part of C++ code bases. In idiomatic C++, my code is *at least* as readable as yours, arguably more so, because it uses an established pattern to express the concept of scoped lifetime. (This is in addition to what 20c has said.)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T10:06:47.817",
"Id": "12381",
"ParentId": "12340",
"Score": "2"
}
},
{
"body": "<p>Konrad's answer has a big advantage: it is safe!\nIn your code sample, if an operator raise an exception before you leave the critical section, this one will never be released. In Konrad's answer, not matter what, the critical section will be unlocked when you exit the scope, even if you don't catch an exception.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T21:16:23.530",
"Id": "12404",
"ParentId": "12340",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-06T23:33:35.727",
"Id": "12340",
"Score": "4",
"Tags": [
"c++",
"multithreading",
"windows",
"atomic"
],
"Title": "Win7 atomic access class"
}
|
12340
|
<p>I am working through the exercises in the book Accelerated C++. I wanted to get some feedback on proper use of the Standard Library, correctness, overall style, portability, etc.</p>
<pre><code>/*******************************************************************************
Accelerated C++ Chapter 3
Write a program to count how many times each distinct word appears in its input
*******************************************************************************/
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::cout << "Enter a list of words followed by end-of-file: ";
typedef std::vector<std::string>::size_type vector_sz;
std::vector<std::string> words;
std::string word;
while (std::cin >> word)
{
words.push_back(word);
}
vector_sz size = words.size();
if(size == 0)
{
std::cout << "Please enter some words!";
return -1;
}
std::vector<int> frequency;
std::vector<std::string> unique_words;
int count = 0;
bool isUnique;
unique_words.push_back(words[0]);
for(unsigned i = 0; i < words.size(); ++i)
{
isUnique = true;
for(unsigned j = 0; j < unique_words.size(); ++j)
{
if(words[i] == unique_words[j])
{
isUnique = false;
}
}
if(isUnique)
{
unique_words.push_back(words[i]);
}
}
for(unsigned i = 0; i < unique_words.size(); ++i)
{
for(unsigned j = 0; j < words.size(); ++j)
{
if(unique_words[i] == words[j])
{
count += 1;
}
}
frequency.push_back(count);
count = 0;
}
for(unsigned i = 0; i < unique_words.size(); ++i)
{
std::cout << unique_words[i] << " " << frequency[i] << std::endl;
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>You could cut your code in half if you used a map:</p>\n\n<pre><code>typedef std::map<std::string, unsigned int> Map;\n\nMap tMap;\nwhile(std::cin >> word)\n{\n // When accessing a map with `[]` If the value does not exist\n // it is created and initialized to zero.\n //\n // The plus plus then increments the stored value\n tMap[word]++;\n}\n\n// Iterate through map and print frequency\n</code></pre>\n\n<p>Couple other notes from the code you have:</p>\n\n<ul>\n<li>After <code>unique_words.push_back(words[0]);</code> you can start the <code>i</code> loop at index 1 instead of 0.</li>\n<li>When checking for uniqueness in the first pair of loops, once you determine uniqueness to be false you can stop looping for that word: <code>while(j < unique_words.size() && isUnique) ...</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T04:26:38.233",
"Id": "19819",
"Score": "0",
"body": "On the correct line but you can simplify."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T11:38:40.917",
"Id": "19833",
"Score": "0",
"body": "At first glance, I don't quite understand how this works, but I will research how to use a map, thank you!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T16:09:49.893",
"Id": "19845",
"Score": "0",
"body": "Assuming a new compiler and no requirement to print the results in order, you might also consider `std::unordered_map` instead of `std::map`. Also, though it makes no difference here, absent a reason to do otherwise, you generally want to use pre-increment instead of post-increment (`++tMap[word];`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T21:44:11.067",
"Id": "19858",
"Score": "0",
"body": "@Jerry Coffin Yes I am using a new compiler, Thank you for your help!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T03:09:11.737",
"Id": "12343",
"ParentId": "12342",
"Score": "6"
}
},
{
"body": "<p>See @sfpiano about using a map directly to count each word.</p>\n\n<p>This is perfectly fine.</p>\n\n<pre><code> std::vector<std::string> words;\n std::string word;\n while (std::cin >> word)\n {\n words.push_back(word);\n }\n</code></pre>\n\n<p>But if you want to learn the STL then you can replace the above with a single line:</p>\n\n<pre><code> std::copy(std::istream_iterator<std::string>(std::cin),\n std::istream_iterator<std::string>(),\n std::back_inserter(words));\n</code></pre>\n\n<p>You don't need to store the value (especially since you don't re-use it) </p>\n\n<pre><code> vector_sz size = words.size();\n if(size == 0)\n</code></pre>\n\n<p>Do this in a single line:</p>\n\n<pre><code> if (words.size() == 0)\n</code></pre>\n\n<p>But this test is embodied in a single call. </p>\n\n<pre><code> if (words.empty())\n</code></pre>\n\n<p>Here you use two vectors.</p>\n\n<pre><code> std::vector<int> frequency;\n std::vector<std::string> unique_words;\n</code></pre>\n\n<p>This can be replaced by a std::map (see sfpiano) for details.</p>\n\n<p>Declare as close to the use point as possible.</p>\n\n<pre><code> bool isUnique;\n</code></pre>\n\n<p>This is not used outside the loop. So declare it inside the loop (and initialize at declaration.</p>\n\n<pre><code> // So it should look like this.\n for(unsigned i = 0; i < words.size(); ++i)\n {\n bool isUnique = true;\n</code></pre>\n\n<p>Also you should start using iterators rather than using the index.</p>\n\n<pre><code> for(auto loop = words.begin(); loop != words.end(); ++loop)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T11:39:42.710",
"Id": "19834",
"Score": "0",
"body": "I thought about using iterators, but that accesses elements at random right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T15:21:41.857",
"Id": "19842",
"Score": "0",
"body": "@newToProgramming: No. For vectors. begin() is index 0 and ++ moved through the vector in order. For Map/Set the order is the sorted order of the container."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T22:33:25.967",
"Id": "19862",
"Score": "0",
"body": "I am having trouble implementing std::copy from your code snippet, but I will figure it out, thank you for all of the corrections, I clearly have a lot to learn about using c++ correctly. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T22:51:06.397",
"Id": "19864",
"Score": "0",
"body": "ok, i figured it out, the second argument in std::copy is initialized with the istream_iterator default constructor which points to end-of-file, so it should be istream_iterator<std::string>() or just omit the paranthesis entirely. Is that correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T03:37:21.610",
"Id": "19871",
"Score": "0",
"body": "Fixed the `std::copy()` above. You need the braces in this context."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T08:40:38.643",
"Id": "20169",
"Score": "0",
"body": "What are the advantages of using an iterator instead of instead of an index in this case and in general?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T15:55:59.623",
"Id": "20197",
"Score": "0",
"body": "@FairDinkumThinkum: There are no advantages but also no disadvantages in this case. But it is a habit that will make the algorithms in the STL easier to use when you instinctively use iterators. Using the STL algorithms is the ultimate goal and the interface to the algorithms is via iterators."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T04:39:52.617",
"Id": "12344",
"ParentId": "12342",
"Score": "6"
}
},
{
"body": "<p>As long as you've typedef'ed <code>std::vector<std::string>::size_type</code> as <code>vector_sz</code>, use it in the code</p>\n\n<pre><code>for(vector_sz i = 0; i < words.size(); ++i)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T21:51:23.540",
"Id": "19860",
"Score": "0",
"body": "You are right of course, but I think I will switch to using an iterator."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T07:27:03.427",
"Id": "19878",
"Score": "1",
"body": "It's not about this case, it's about the general rule for loop coding."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-28T09:39:00.363",
"Id": "248956",
"Score": "0",
"body": "You can just use `auto`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T13:43:09.447",
"Id": "12351",
"ParentId": "12342",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "12343",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T01:14:23.700",
"Id": "12342",
"Score": "5",
"Tags": [
"c++"
],
"Title": "Exercise from Accelerated C++"
}
|
12342
|
<p>I have been tasked with creating financial reports. I am looking for any suggestions on improving performance, readability/formatting or best practices. </p>
<pre><code>/*setting dummy parameters */
SET DATEFORMAT dmy
DECLARE @startProduct NVARCHAR = ''
DECLARE @endProduct NVARCHAR = 'zzzzzzzzzzzzzzzzzzzzzz'
DECLARE @startGroup NVARCHAR = ''
DECLARE @endGroup NVARCHAR = 'zzzzzzzzzzzzzzzzzz'
DECLARE @startDepartment NVARCHAR = ''
DECLARE @endDepartment NVARCHAR = 'zzzzzzzzzzzzzzzzzzzzzzz'
DECLARE @startDate DATE = '01/05/2000'
DECLARE @endDate DATE = CAST('31/05/2012' AS DATE)
DECLARE @StartTime TIME = '08:00:00'
DECLARE @endTime TIME = '17:00:00'
DECLARE @grouping INT = 0
DECLARE @site INT = 21
/*
ProductCode = 0
ProductGroup = 1
Department = 2
Pump = 3
Date = 4
*/
SELECT
CASE @grouping
WHEN 0 THEN P.Code
WHEN 1 THEN P.[Group]
WHEN 2 THEN P.Department
WHEN 3 THEN P.[Description]
WHEN 4 THEN CONVERT(VARCHAR,RPS.SalesDateTime,103)
END AS GroupCode,
CASE @grouping
WHEN 0 THEN P.[Description]
WHEN 1 THEN PG.[Description]
WHEN 2 THEN PD.[Description]
WHEN 3 THEN 'PUMP: ' + CONVERT(VARCHAR,RPS.PumpId) +' HOSE: ' + CONVERT(VARCHAR,RPS.HoseId)
WHEN 4 THEN CONVERT(VARCHAR(MAX),CAST(FLOOR(CAST(RPS.SalesDateTime AS FLOAT)) AS DATETIME))
END AS [GroupDescription],
SUM(RPS.Quantity) AS Quantity,
SUM( CASE
WHEN P.GSTable = 1 THEN RPS.TotalAmount / 1.1
ELSE RPS.TotalAmount
END) AS AmountX,
SUM(CASE
WHEN P.GSTable = 1 THEN (rps.TotalAmount * .10)
ELSE 0 END
) AS GST,
SUM(RPS.UnitLastCost * RPS.Quantity) AS CostXgst,
SUM(RPS.TotalAmount) AS AmountInc,
FLOOR(ROUND(((1 -
(
SUM(RPS.UnitLastCost * RPS.Quantity)
/
NULLIF(SUM
(
CASE
WHEN P.GSTable = 1 THEN RPS.TotalAmount / 1.1
ELSE RPS.TotalAmount
END
),0))) * 100 ),0))
AS Margin
FROM
RetailPosSales RPS
JOIN Products P ON RPS.ProductCode = P.Code
LEFT OUTER JOIN ProductGroups PG ON P.[Group] = PG.Code /*need this if the grouping is 1*/
LEFT OUTER JOIN ProductDepartments PD ON P.Department = PD.Code /*need this if the grouping is 2 */
WHERE
((@grouping <> 3) OR (@grouping = 3 AND RPS.IsFuelSale = 1)) /*When grouping by pump, only allow fuel products */
AND P.Code BETWEEN @startProduct AND @endProduct
AND P.[Group] BETWEEN @startGroup AND @endGroup
AND P.Department BETWEEN @startDepartment AND @endDepartment
AND CAST(RPS.SalesDateTime AS DATE) BETWEEN @startDate AND @endDate
AND CAST(RPS.SalesDateTime AS TIME) BETWEEN @StartTime AND @endTime
AND RPS.SiteId = @site
GROUP BY
CASE @grouping
WHEN 0 THEN P.Code
WHEN 1 THEN P.[Group]
WHEN 2 THEN P.Department
WHEN 3 THEN P.[Description]
WHEN 4 THEN CONVERT(VARCHAR,RPS.SalesDateTime,103)
END,
CASE @grouping
WHEN 0 THEN P.[Description]
WHEN 1 THEN PG.[Description]
WHEN 2 THEN PD.[Description]
WHEN 3 THEN 'PUMP: ' + CONVERT(VARCHAR,RPS.PumpId) +' HOSE: ' + CONVERT(VARCHAR,RPS.HoseId)
WHEN 4 THEN CONVERT(VARCHAR(MAX),CAST(FLOOR(CAST(RPS.SalesDateTime AS FLOAT)) AS DATETIME))
END
ORDER BY
GroupCode,
GroupDescription
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T07:24:26.533",
"Id": "19877",
"Score": "0",
"body": "Which database (SQL Server, Oracle, other?) and version?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T09:15:52.420",
"Id": "19890",
"Score": "0",
"body": "Sorry. mssql2008+"
}
] |
[
{
"body": "<p>It appears that you're using the same expressions for the <code>GroupCode</code> and <code>GroupDescription</code> columns in the <code>GROUP BY</code> clause. That's asking for trouble later on if someone needs to modify either expression, especially given their size. Instead, use a subquery:</p>\n\n<pre><code>SELECT\n GroupCode,\n GroupDescription,\n -- etc\nFROM\n (\n SELECT\n CASE /* etc */ END AS GroupCode,\n CASE /* etc */ END AS GroupDescription,\n -- etc\n FROM\n -- etc\n WHERE\n -- etc\n ) AS dummy\nGROUP BY\n GroupCode,\n GroupDescription\nORDER BY\n GroupCode,\n GroupDescription\n</code></pre>\n\n<p><em>EDIT:</em></p>\n\n<p>There may be some other opportunities to use subqueries to reduce duplication of expressions. For example, the expression for the column <code>AmountX</code> is also used in the <code>Margin</code> calculation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T07:32:41.593",
"Id": "12375",
"ParentId": "12345",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "12375",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T06:14:44.557",
"Id": "12345",
"Score": "3",
"Tags": [
"performance",
"sql",
"finance"
],
"Title": "Financial report query"
}
|
12345
|
<p>I am a PHP newbie, gone through a couple starter tutorials which went ok, so I thought I'd try creating a more complex project to get some experience. It is a NetBeans PHP project where I try to replicate some of the functionality from Microsoft's CodeDOM technology and Zend_CodeGenerator. Basically it is a class library that helps generating PHP code. My goals with this are:</p>
<ul>
<li>Get accustomed to NetBeans</li>
<li>Get some routine in writing PHP code</li>
<li>Learn OOP</li>
<li>Learn about unit tests</li>
<li>Learn about versioning</li>
</ul>
<p>I uploaded the project to GitHub (<a href="https://github.com/Anonimista/PHPCodeModel" rel="nofollow">here</a>). I would be thankful for any comments.</p>
<p>The base class:</p>
<pre><code><?php
/**
* @package UC_PHPCodeModel
* @author Uros Calakovic
*/
/**
* The CodeObject class is the base class for most code model objects.
*
* @abstract
*/
abstract class CodeObject
{
public function __construct()
{
$this->Comments = new CommentStatementCollection();
}
/**
* __set() is used in CodeObject and inherited classes
* to make private / protected variables accessible from outside the class.
*
* __set() simply calls the appropriate field setter method.
* It is still possible to call field setter methods directly.
*
* @param string $name Name of the field to be accessed
* @param mixed $value The value the field should be set to, usually a collection.
*/
public function __set($name, $value)
{
if($name == 'Comments')
{
$this->set_Comments($value);
}
}
/**
* __get() is used in CodeObject and inherited classes
* to make private / protected variables accessible from outside the class.
*
* __get calls the appropriate field getter method.
* It is still possible to call field getter method directly.
*
* @param string $name Name of the field to be accessed
* @return mixed The field that $name specified, usually a collection
*/
public function __get($name)
{
if($name == 'Comments')
{
return $this->get_Comments();
}
}
/**
* The $UserData getter method
*
* @return mixed Returns any value stored in $UserData
*/
public function get_UserData()
{
return $this->UserData;
}
/**
* The $UserData setter method
*
* @param mixed $UserData An arbitrary value
*/
public function set_UserData($UserData)
{
$this->UserData = $UserData;
}
/**
* The $Comments getter method
*
* @return CommentStatementCollection
*/
public function get_Comments()
{
return $this->Comments;
}
/**
* The $Comments setter method
*
* @param CommentStatementCollection $Comments
*/
public function set_Comments(CommentStatementCollection $Comments)
{
$this->Comments = $Comments;
}
/**
* Stores the collection of comments for a code object.
*
* @var CommentStatementCollection
*/
protected $Comments;
/**
* Can contain arbitrary user-defined data related to a code object.
*
* @var mixed
*/
protected $UserData = null;
}
?>
</code></pre>
<p>The child class representing a PHP statement:</p>
<pre><code><?php
include_once 'CodeObject.php';
/**
* This is a parent class for other statement classes
* and should not be instantiated.
*
* @package UC_PHPCodeModel
* @author Uros Calakovic
*/
class Statement extends CodeObject
{
public function __construct()
{
parent::__construct();
}
public function __set($name, $value)
{
parent::__set($name, $value);
if($name == 'BlankLinesAfter')
{
$this->set_BlankLinesAfter($value);
}
}
public function __get($name)
{
$ret = parent::__get($name);
if($ret != null)
{
return $ret;
}
if($name == 'BlankLinesAfter')
{
return $this->get_BlankLinesAfter();
}
}
public function get_BlankLinesAfter()
{
return $this->BlankLinesAfter;
}
public function set_BlankLinesAfter($BlankLinesAfter)
{
if(is_int($BlankLinesAfter) )
{
if($BlankLinesAfter >= 0)
{
$this->BlankLinesAfter = $BlankLinesAfter;
}
else
{
throw new InvalidArgumentException(
'The value should be greater or equal to zero.');
}
}
else
{
throw new InvalidArgumentException(
'The value should be an integer value.');
}
}
private $BlankLinesAfter = 0;
}
?>
</code></pre>
<p>The child class representing an if..else statement:</p>
<pre><code><?php
include_once 'ConditionStatement.php';
include_once 'StatementCollection.php';
/**
* Represents an if...else statement
*
* elseif is not supported
*
* @package UC_PHPCodeModel
* @author Uros Calakovic
* @example ../Classes/IfElseStatementExample.php
*/
class IfElseStatement extends ConditionStatement
{
/**
* The IfElseStatement constructor
*
* Both $TrueStatements and $FalseStatements can be ommited by setting them to null
*
* @param Expression $Condition The boolean expression to be evalueted true or false
* @param StatementCollection $TrueStatements The statements in the if block
* @param StatementCollection $FalseStatements The statements in the else block
*/
public function __construct(Expression $Condition,
StatementCollection $TrueStatements = null,
StatementCollection $FalseStatements = null)
{
parent::__construct();
$this->set_Condition($Condition);
$TrueStatements == null ?
$this->TrueStatements = new StatementCollection() :
$this->set_TrueStatements($TrueStatements);
$FalseStatements == null ?
$this->FalseStatements = new StatementCollection() :
$this->set_FalseStatements($FalseStatements);
}
/**
* Used for making private / protected variables
* accessible from outside the class.
*
* @param string $name Name of the field to be accessed
* @param mixed $value The value the field should be set to, usually a collection.
* @see CodeObject::__set()
*/
public function __set($name, $value)
{
parent::__set($name, $value);
if($name == 'TrueStatements')
{
$this->set_TrueStatements($value);
}
if($name == 'FalseStatements')
{
$this->set_FalseStatements($value);
}
}
/**
* Used for making private / protected variables
* accessible from outside the class.
*
* @param string $name Name of the field to be accessed
* @return mixed The field that $name specified, usually a collection
* @see CodeObject::__get()
*/
public function __get($name)
{
$ret = parent::__get($name);
if($ret != null)
{
return $ret;
}
if($name == 'TrueStatements')
{
return $this->get_TrueStatements();
}
if($name == 'FalseStatements')
{
return $this->get_FalseStatements();
}
}
/**
* The $TrueStatements getter method
* @return StatementCollection
*/
public function get_TrueStatements()
{
return $this->TrueStatements;
}
/**
* The $TrueStatements setter method
* @param StatementCollection $TrueStatements
*
* @assert (123) throws PHPUnit_Framework_Error
* @assert ('name') throws PHPUnit_Framework_Error
* @assert (new stdClass()) throws PHPUnit_Framework_Error
*/
public function set_TrueStatements(StatementCollection $TrueStatements)
{
$this->TrueStatements = $TrueStatements;
}
/**
* The $FalseStatements getter method
* @return StatementCollection
*/
public function get_FalseStatements()
{
return $this->FalseStatements;
}
/**
* The $FalseStatements setter method
* @param StatementCollection $FalseStatements
*
* @assert (123) throws PHPUnit_Framework_Error
* @assert ('name') throws PHPUnit_Framework_Error
* @assert (new stdClass()) throws PHPUnit_Framework_Error
*/
public function set_FalseStatements(StatementCollection $FalseStatements)
{
$this->FalseStatements = $FalseStatements;
}
/**
* The statements in the if block
* @var StatementCollection
*/
private $TrueStatements;
/**
* The statements in the else block
* @var StatementCollection
*/
private $FalseStatements;
}
?>
</code></pre>
<p>The test unit class for the if..else class:</p>
<pre><code><?php
require_once dirname(__FILE__) . '/../../Classes/IfElseStatement.php';
/**
* Test class for IfElseStatement.
* Generated by PHPUnit on 2012-05-23 at 21:05:00.
*/
class IfElseStatementTest extends PHPUnit_Framework_TestCase
{
/**
* @var IfElseStatement
*/
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this->object = new IfElseStatement(
new BinaryOperatorExpression(
BinaryOperator::VALUE_EQUALITY,
new VariableReferenceExpression('a'),
new PrimitiveExpression(0)));
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
{
}
/**
* Generated from @assert (123) throws PHPUnit_Framework_Error.
*
* @covers IfElseStatement::set_TrueStatements
* @expectedException PHPUnit_Framework_Error
*/
public function testSet_TrueStatements()
{
$this->object->set_TrueStatements(123);
}
/**
* Generated from @assert ('name') throws PHPUnit_Framework_Error.
*
* @covers IfElseStatement::set_TrueStatements
* @expectedException PHPUnit_Framework_Error
*/
public function testSet_TrueStatements2()
{
$this->object->set_TrueStatements('name');
}
/**
* Generated from @assert (new stdClass()) throws PHPUnit_Framework_Error.
*
* @covers IfElseStatement::set_TrueStatements
* @expectedException PHPUnit_Framework_Error
*/
public function testSet_TrueStatements3()
{
$this->object->set_TrueStatements(new stdClass());
}
/**
* Generated from @assert (123) throws PHPUnit_Framework_Error.
*
* @covers IfElseStatement::set_FalseStatements
* @expectedException PHPUnit_Framework_Error
*/
public function testSet_FalseStatements()
{
$this->object->set_FalseStatements(123);
}
/**
* Generated from @assert ('name') throws PHPUnit_Framework_Error.
*
* @covers IfElseStatement::set_FalseStatements
* @expectedException PHPUnit_Framework_Error
*/
public function testSet_FalseStatements2()
{
$this->object->set_FalseStatements('name');
}
/**
* Generated from @assert (new stdClass()) throws PHPUnit_Framework_Error.
*
* @covers IfElseStatement::set_FalseStatements
* @expectedException PHPUnit_Framework_Error
*/
public function testSet_FalseStatements3()
{
$this->object->set_FalseStatements(new stdClass());
}
/**
* @covers IfElseStatement::__set
*/
public function test__set()
{
$trueStatements = new StatementCollection();
$trueStatements->add(new AssignStatement(
new VariableReferenceExpression('a'),
new PrimitiveExpression(0)));
$this->object->TrueStatements = $trueStatements;
$this->assertTrue(
$trueStatements === $this->object->get_TrueStatements());
}
/**
* @covers IfElseStatement::__set
*/
public function test__set2()
{
$falseStatements = new StatementCollection();
$falseStatements->add(new AssignStatement(
new VariableReferenceExpression('a'),
new PrimitiveExpression(0)));
$this->object->FalseStatements = $falseStatements;
$this->assertTrue(
$falseStatements === $this->object->get_FalseStatements());
}
/**
* @covers IfElseStatement::__get
*/
public function test__get()
{
$this->assertTrue(
$this->object->TrueStatements === $this->object->get_TrueStatements());
}
/**
* @covers IfElseStatement::__get
*/
public function test__get2()
{
$this->assertTrue(
$this->object->FalseStatements === $this->object->get_FalseStatements());
}
/**
* @covers IfElseStatement::get_TrueStatements
*/
public function testGet_TrueStatements()
{
$this->assertTrue(
$this->object->get_TrueStatements() instanceof StatementCollection ||
$this->object->get_TrueStatements() == null);
}
/**
* @covers IfElseStatement::get_FalseStatements
*/
public function testGet_FalseStatements()
{
$this->assertTrue(
$this->object->get_FalseStatements() instanceof StatementCollection ||
$this->object->get_FalseStatements() == null);
}
}
?>
</code></pre>
<p>The if..else class example usage:</p>
<pre><code><?php
include_once 'Classes/PHPCodeProvider.php';
/*
* Create an instance of the CodeGeneratorOptions class
* using the default options for code generation.
*/
$options = new CodeGeneratorOptions();
/*
* Create an instance of the IndentedTextWriter.
* After the generateCodeFromStatement call
* $writer will hold the generated code.
*/
$writer = new IndentedTextWriter();
/*
* Create an instance of the PHPCodeProvider class
*/
$provider = new PHPCodeProvider();
/*
* Variable and field references that will be used
* to generate if statements
*/
$thisReference = new ThisReferenceExpression();
$isWinning = new VariableReferenceExpression('isWinning');
$attemptNumber = new FieldReferenceExpression('attemptNumber', $thisReference);
$gameFinished = new FieldReferenceExpression('gameFinished', $thisReference);
/*
* A simple if statement
*/
$ifElseStatement1 = new IfElseStatement($isWinning);
$ifElseStatement1->TrueStatements->add(
new AssignStatement(
new FieldReferenceExpression('isWinning', $thisReference),
$isWinning));
/*
* Generate the code and output the result.
*/
$provider->generateCodeFromStatement($ifElseStatement1, $writer, $options);
echo
'<pre>' . str_replace(
'<br />', '', highlight_string($writer->get_String(), true)) .
'<pre/>';
$writer->clear();
/*
* An if statement with both the if and the else block
*/
$ifElseStatement2 = new IfElseStatement(
new BinaryOperatorExpression(
BinaryOperator::LESS_THAN,
$attemptNumber,
new PrimitiveExpression(8)));
$ifElseStatement2->TrueStatements->add(
new AssignStatement(
$attemptNumber,
new PrimitiveExpression(1),
CompoundAssignmentOperator::PLUS_ASSIGN));
$ifElseStatement2->FalseStatements->add(
new AssignStatement(
$gameFinished,
new PrimitiveExpression(true)));
/*
* Generate the code and output the result.
*/
$provider->generateCodeFromStatement($ifElseStatement2, $writer, $options);
echo
'<pre>' . str_replace(
'<br />', '', highlight_string($writer->get_String(), true)) .
'<pre/>';
/*
* The output should be:
*
* if($isWinning)
* {
* $this->isWinning = $isWinning;
* }
*
*
* if($this->attemptNumber < 8)
* {
* $this->attemptNumber += 1;
* }
* else
* {
* $this->gameFinished = true;
* }
*
*/
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T07:49:38.927",
"Id": "19823",
"Score": "0",
"body": "Please post your code here and specify what kind of feedback you're looking for: code correctness, best practices and design pattern usage, application UI, security issues, etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T07:56:38.813",
"Id": "19824",
"Score": "0",
"body": "Thanks for the comment. I have ~70 PHP classes, too much code long to post here. If providing only a link is not acceptable, I'm sorry, somebody close the topic. I would like feedback on unit tests, project OOP design (inheritance, etc) and my code in general as I am new to PHP."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T08:00:59.140",
"Id": "19825",
"Score": "0",
"body": "Maybe try to find a class or two that's representative of your coding style, and post it here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T08:01:27.513",
"Id": "19826",
"Score": "0",
"body": "OK I'll do that."
}
] |
[
{
"body": "<p>as i do not know the technologies you try to implement i will focus on general stuff. </p>\n\n<p>first:</p>\n\n<pre><code>public function __construct()\n{\n $this->Comments = new CommentStatementCollection();\n}\n</code></pre>\n\n<p>it would be better to inject \"CommentStatementCollection\" into the constructor</p>\n\n<pre><code>public function __construct(Collection $CommentCollection)\n{\n $this->Comments = $CommentCollection\n}\n</code></pre>\n\n<p>this has some benefits one of them is better unit testing as you are now able to mock the collection. CommentStatementCollection was only an example, this advice is true for every \"new\" statement within your classes.</p>\n\n<pre><code> public function __construct()\n {\n parent::__construct();\n }\n</code></pre>\n\n<p>if you do not extend the behavior of the parent constructor there is no point in overriding it to call it again. </p>\n\n<p><strong>+++ EDIT</strong></p>\n\n<blockquote>\n <p>As for calling parent constructor, I need it to initialize my $Comments property in the child class, I thought this would not happen if I didn't call the parent constructor explicitly? </p>\n</blockquote>\n\n<p>here some test code</p>\n\n<pre><code><?php\nabstract class test {\n public function __construct() {\n $this->test = 'test';\n }\n}\nclass child extends test {\n\n}\n\n$test = new child();\nvar_dump($test->test); // string(4) \"test\"\n</code></pre>\n\n<p><strong>--- EDIT</strong></p>\n\n<p>i would suggest not to use the magic methods __set and __get as they obfuscate the code and you use custom setter anyway (like set_UserData)</p>\n\n<pre><code>new PrimitiveExpression(8)));\n</code></pre>\n\n<p>there you have magic numbers</p>\n\n<p>you could use __toString instead of implementing \"get_string\", but there is nothin wrong if that. </p>\n\n<pre><code>testSet_TrueStatements2\n</code></pre>\n\n<p>this is very bad naming of tests. If they fail you will not know why they failed or what failed at first glance. Try to use names like \"testSet_TrueStatementsWithInvalidArgument\" or something like that, do not worry about long method names! \nAlso you could work with dataproviders to test the same functionality with different arguments. </p>\n\n<pre><code> $trueStatements = new StatementCollection();\n $trueStatements->add(new AssignStatement(\n new VariableReferenceExpression('a'),\n new PrimitiveExpression(0)));\n</code></pre>\n\n<p>This looks like you can use a Builder or Factory class to seperate the setup of your objects. </p>\n\n<p><strong>+++ EDIT2</strong></p>\n\n<pre><code>class StatementFactory {\n public static function getAssignStatement($var, $prim) {\n return new AssignStatement(new VariableReferenceExpression($var), new PrimitiveExpression($prim));\n }\n}\n//...\n $trueStatements = new StatementCollection();\n $trueStatements->add(StatementFactory::getAssignStatement('a', 0));\n</code></pre>\n\n<p>i would have to dive deeper into your code if this factory makes sense in the context of your implementation but maybe you get the idea. I dont think it is a good factory, just an example.</p>\n\n<p><strong>--- EDIT2</strong></p>\n\n<p>I think thats all on the first look ( - : hope it helps</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T12:50:45.423",
"Id": "19835",
"Score": "0",
"body": "Good points. Regarding the first issue, I've been thinking to refactor all the constructors so that the arguments have type hints and default value of null. This way I would need to initialize my variables only if nothing is passed to the constructor. As for calling parent constructor, I need it to initialize my $Comments property in the child class, I thought this would not happen if I didn't call the parent constructor explicitly? Your point about __get and __set is actually one of my biggest dilemmas, I only added that so I could access fields like $var->Comments instead of using getters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T13:03:37.233",
"Id": "19836",
"Score": "0",
"body": "I only did because I prefer to use $var->Comments instead of $var->getComments(), but I've read that __set() and __get() are slow, so I may remove them after all.The tests were generated by NetBeans, never thought of changing method names. If you mean $writer->get_String() this is just a getter for a private field that contains the generated code and I will need to change the name to something meaningful first thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T13:10:43.790",
"Id": "19837",
"Score": "0",
"body": "One thing I'm not clear though is your last comment. I realize that code looks messy but I don't know how to make it more easier to use. $trueStatements is an array of Statement objects. Each Statement object has its own constructor so I ended up with a new statement within a new statement.I'v read something about the Factory pattern but I'm not sure how to apply it here. Thanks again for the comments, you've nailed several things I've been thinking about."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T13:15:59.313",
"Id": "19838",
"Score": "0",
"body": "@Anonimista as for the constructor issue i extended my post by an example. As for the other questions i will have to answer them later this day"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T20:08:43.027",
"Id": "19853",
"Score": "0",
"body": "@Anonimista added a factory example (see edit2)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T11:31:32.680",
"Id": "12350",
"ParentId": "12346",
"Score": "3"
}
},
{
"body": "<p>Again braunbaer beat me to it. This is just an addition to what he already has. +1 braunbaer :)</p>\n\n<p><strong>NetBeans</strong></p>\n\n<p>Its a good IDE, but like most free things there are bugs with it. I'm using it currently, so don't think I'm trying to persuade you to choose another IDE. Just thought I'd point out a few issues I've been having so you don't spend hours trying to figure out why something isn't working right. Line wrapping doesn't always work (more noticeable with HTML, my PHP isn't that long). I've been noticing recently that PHPDoc comments once edited cannot be collapsed again until the page is reloaded. Its really slow at loading dirty XML (no indents), and can actually lag the entire program while they are up, clean XML seems to work fine. There are a few others, but I can't remember them all off the top of my head. Again, this is just a heads up not a warning against it. I've yet to find a better (free) IDE.</p>\n\n<p><strong>Learn OOP</strong></p>\n\n<p>I tell this to everyone who says they are new to PHP. Learn PHP first! You don't want to start learning OOP until you are good and familiar with the language, any language. Its like trying to read fine literature when you're still trying to sound out your words. Sure you can do it, but it will be slow and cumbersome. Save yourself a lot of headaches and learn the basics first. The only time I'd suggest jumping right into OOP is if you are coming from another language and feel comfortable in converting that knowledge into PHP knowledge. OOP is a completely different beast and should be tackled when you're not still struggling with the basics. Its good to push your self with difficult projects like this, but I think you bit off more than you could chew for your first project.</p>\n\n<p>That was before I actually started reading your code. From what I can see, you seem versed enough to start looking into it. The only reason I'm leaving the above is as a disclaimer :)</p>\n\n<p><strong>Setters/Getters</strong></p>\n\n<p>I agree with braunbaer, I don't think it a good idea to use the magic setter and getter methods. At least not in a \"public\" class. I think the only \"good\" reason to use them is in factory classes in which it is all done behind the scenes and on variables that have already been verified and sanitized. But I've not gotten into that yet so I can't tell you much about it. Also as braunbaer started to say but did not elaborate on. Your magic methods are not truly doing anything that another method does not already do (<code>set_Comments()</code>). A true magic setter would use variable variables (read: evil) or a \"master\" array to accomplish what you are trying and would do so for anything passed to it, or for a select few \"allowed\" variables. Maybe there are other ways, but I tend to steer clear of this kind of thing so I'm unfamiliar with them. Now, I, and I'm sure everyone else here, am going to hate myself for showing you this, but here's the \"proper\" way to do what you are attempting.</p>\n\n<pre><code>public function __set( $name, $value ) {\n $method = \"set_$name\";\n if( method_exists( $this, $method ) { $this->$method( $value ); }\n\n //Here are those other ways I was talking about...\n if( in_array( $name, $this->allowedVariables ) ) {\n $this->$name = $value;\n //OR\n $this->_data[ $name ] = $value;\n }\n}\n</code></pre>\n\n<p>However, you should just cut out the middle man (setter/getter) and just call the method you've already created for that purpose manually. Sure you can't do cool things like <code>$var->Comments = 'blah';</code> anymore, but it is more secure and easier to debug.</p>\n\n<p><strong>include_once</strong></p>\n\n<p>Try not to use (include/require)_once. They pretty much say, \"I'm not sure if I've already included this, so please make sure I don't do so again.\" You should be sure. And not that it will make much difference here, but if you ever find yourself including a bunch of files you will notice a drop in speed because of it.</p>\n\n<p><strong>So Many Classes</strong></p>\n\n<p>Unless you are planning on extending these later I don't see the point in having a class who's only purpose is to set and get a variable. I'd seriously consider a factory class to do this.</p>\n\n<p><strong>Ternary Operations</strong></p>\n\n<p>Ternary operations are meant to improve your code by shortening it. Many argue that they are bad form, but I am not one of those people (within limits). My only necessity for ternary expressions is that they be short and legible, and never extend more than one line. I don't think they should be used to replace if/else statements, so what you have in your ConditionStatement constructor looks off to me. I would rewrite it like so...</p>\n\n<pre><code>if( ! $TrueStatements ) { $TrueStatements = new StatementCollection(); }\n$this->set_TrueStatements( $TrueStatements );\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T17:44:59.870",
"Id": "19846",
"Score": "0",
"body": "Thank you for the comments. I've been only using NetBeans for a couple of months for this single project. The good thing is that it helped me to start with PHPDoc, PHPUnit and GIT. I've recently started using these from the command line (I'm on Windows) which is probably more difficult for a beginner but the IDE helped me with the basics."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T17:53:53.977",
"Id": "19847",
"Score": "0",
"body": "I know programming basics (control structures, data types etc) even some OOP concepts (I think I do). I've read through a couple of PHP basics tutorials. I started this as a learning experience so I don't mind that this project is too much for me (and it is). I feel a lot more comfortable with PHP than I did a month ago."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T18:01:57.883",
"Id": "19848",
"Score": "0",
"body": "You're right those __set() and __get() methods don't really add anything useful, I only added them because I like to use $var->Comments->add() instead of $var->_getComments()->add, but I think I can safely remove them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T18:05:09.140",
"Id": "19849",
"Score": "0",
"body": "I noticed that my include_once statements slow down things when using the debugger. PHP jumps to the file it is supposed to be including, says 'I know you already' and jumps back. That's one more thing to look into."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T18:11:34.327",
"Id": "19850",
"Score": "0",
"body": "You're right about too many classes. When I started this, I followed Microsoft's CodeDOM implementation - they have a separate class for almost every language construct that do nothing more than contain relevant variables. There is also one behemoth class (PHPCodeGenerator in my case) that does all the code generation. I have ~1300 lines of code in it right now, but I am thinking of getting rid of it and let each class generate it's own code (so that IfElseStatement contains the code that generate PHP if..else statements etc)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T18:12:56.580",
"Id": "19851",
"Score": "0",
"body": "Guilty as charged of using the ternary operator just because I found out it existed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T18:13:56.957",
"Id": "19852",
"Score": "0",
"body": "Again, thank you both for the great comments."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T20:10:29.220",
"Id": "19854",
"Score": "0",
"body": "@showerhead again your addition deserves a +1 (- ;"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T17:08:05.373",
"Id": "12355",
"ParentId": "12346",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "12350",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T06:17:47.487",
"Id": "12346",
"Score": "2",
"Tags": [
"php",
"object-oriented",
"unit-testing"
],
"Title": "PHP class library"
}
|
12346
|
<p>I have a particular if statement that could be written in different ways, and I'm curious as to whether there's any significant difference in readability that I should prefer one over the other:</p>
<p>The flow can be boiled down to</p>
<pre><code>if string does not begin with '_'
do stuff
else
throw error
</code></pre>
<p>Some different ways of writing the <code>if</code> condition:</p>
<pre><code>str[0] !== '_'
str.indexOf('_')
!/^_/.test(str)
/^[^_]/.test(str)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T15:54:24.343",
"Id": "19843",
"Score": "1",
"body": "@palacsint, The title is the question, please don't change my question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T17:53:37.650",
"Id": "19955",
"Score": "2",
"body": "You title is suboptimal. It should really relate to the actual piece of code, its to generic right now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T17:54:05.060",
"Id": "19956",
"Score": "1",
"body": "What if the string is empty?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T18:11:16.943",
"Id": "19957",
"Score": "0",
"body": "empty string is a valid condition, just not strings beginning with `_`."
}
] |
[
{
"body": "<p>The first one is the most clear, to me. You're only testing one character so the patterns in the 3rd and 4th are a little overkill. The second one is OK, but still not as clear as the first.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T15:18:36.447",
"Id": "12353",
"ParentId": "12352",
"Score": "2"
}
},
{
"body": "<p>I think the first is the simplest and the most readable one from the list but I'd prefer the <code>charAt</code> function:</p>\n\n<pre><code>x.charAt(0) !== '_'\n</code></pre>\n\n<p>Furthermore, I'd reverse the condition:</p>\n\n<pre><code>if string begins with '_' {\n throw error\n}\ndo stuff\n</code></pre>\n\n<p>Reference: </p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/3427132/how-to-get-first-character-of-string\">How to get first character of string?</a></li>\n<li><a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow noreferrer\">Flattening Arrow Code</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T09:58:19.990",
"Id": "19895",
"Score": "2",
"body": "I'm guessing this is why you said you prefer it, but you should mention that `charAt` has greater compatibility than `'string'[0]`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T11:21:37.423",
"Id": "19904",
"Score": "0",
"body": "@st-boost: Actually not, I haven't known that. It was just more readable for me. Thanks for pointing that out!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T15:43:59.047",
"Id": "12354",
"ParentId": "12352",
"Score": "12"
}
},
{
"body": "<p>Go with the option that makes the code clearest. Unless you're optimizing for performance (after you have profiled your code to ensure this is the bottleneck, of course), there is no need to consider performance for a trivial case like this.</p>\n\n<p>Of these options:</p>\n\n<pre><code>str[0] !== '_'\nstr.indexOf('_')\n!/^_/.test(str)\n/^[^_]/.test(str)\n</code></pre>\n\n<p>The latter two require you understand some regex, which is not at all simple, intuitive, readable, or natural for humans. The second one requires the reader to manually convert an integer to a boolean. The first one clearly identifies the purpose of the if-statement.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T09:54:27.937",
"Id": "19893",
"Score": "1",
"body": "Just because you're not familiar with regex doesn't mean nobody is. It's not the right solution for this problem, but there are plenty of problems for which the simplest, most intuitive, and most readable solution is a regex."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T13:11:18.487",
"Id": "19918",
"Score": "0",
"body": "@st-boost My point is merely that for such a simple problem a regex is complete overkill. I'm very familiar with regex, and when I am skimming through code I can't just glance at a simple regex and immediately comprehend. It takes a second to recognize it. I'll agree that regex are best for some problems, but often they are not. They are useful for keeping parsing separate from logic, but keep in mind: >> Some people, when confronted with a problem, think \"I know, I'll use regular expressions.\" Now they have two problems."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T18:19:09.930",
"Id": "19958",
"Score": "0",
"body": "Well I agree that it's overkill here, and that it's easy to use regular expressions when there is a better alternative. But I do think that, in some situations, I (and the average reader) can decipher a regex faster than we could process an equivalent body of code."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T20:02:12.787",
"Id": "12357",
"ParentId": "12352",
"Score": "2"
}
},
{
"body": "<p>If JavaScript provided a <code>startsWith</code> function I’d say that this would easily be the clearest since it expresses the intent <em>exactly</em>.</p>\n\n<p>Of course you could <em>add</em> this method to the string class but that’s probably just overkill.</p>\n\n<p>Of the methods you have shown, the one <em>expressing the intent</em> most directly is the third, namely using regular expressions and the start-of-string anchor: <code>!/^_/.test(str)</code>.</p>\n\n<p>Of course, this requires the reader to be passably fluent in regular expressions but this is a <em>reasonable assumption</em>. And not only that, it’s actually kind of a <em>requirement</em> when working on JavaScript code.</p>\n\n<p>That said, you’re only testing for a single character here, so just testing that character directly makes a lot of sense, never mind that it’s way more efficient than a full-blown regular expression.</p>\n\n<p>So <em>in this particular case</em> I’d compare the character directly; in the general case, the regular expression expresses the intent most clearly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T10:02:24.190",
"Id": "19896",
"Score": "0",
"body": "`this requires the reader to be passably fluent in regular expressions but this is a reasonable assumption.` I disagree."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T10:19:03.090",
"Id": "19899",
"Score": "1",
"body": "@ANeves Then you are wrong, sorry. It’s as simple as that. Regular expressions are a fundamental part of the JavaScript language (and many other modern languages) and if you can’t read it you are simply impaired in those languages. It’s like saying that you can’t read `for` statements, only `while`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T12:35:56.620",
"Id": "19915",
"Score": "0",
"body": "Agreed: reg.ex. are a fundamental part of JS and we are impaired if we can't read them. Disagreed: \"reasonable assumption\". One can make a living from JS without being \"passably fluent\" in regex, without knowing the difference between `===` and `==`, etc. I think it's risky to assume that these impaired developers do not exist."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T13:11:34.790",
"Id": "19919",
"Score": "2",
"body": "@ANeves Let me rephrase them: you *should not* write code aimed to ease understanding for such people. Because the direct consequence of this is that you restrict yourself unreasonably and consequently write worse code. **Write idiomatic code, not idiotic code.**"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T13:17:13.177",
"Id": "19920",
"Score": "1",
"body": "One can make a living from JS without understanding what `foo = foo || {}` means, doesn't mean I shouldn't use it. I wholeheartedly agree about assuming that other developers would understand regular expressions (or at least assume that they'd be smart enough to look up what it does). JS even has RegExp *literals* which IMHO changes them from being an advanced feature to a fundamental part of the language."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T09:54:36.320",
"Id": "12380",
"ParentId": "12352",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "12354",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T15:12:48.997",
"Id": "12352",
"Score": "4",
"Tags": [
"javascript"
],
"Title": "poh-tay-toh poh-tah-toh, does writing the same code a different way affect readability?"
}
|
12352
|
<p>I just started learning Haskell, and I must say it is unlike anything else. As my first not-entirely-trivial piece of code I tried to write a simple Bayes Classifier. It is in two parts, a classifier module and a cli.</p>
<p>What could be done to improve it? Is it entirely awful? Is it too imperative? Any and all feedback appreciated. Here are the two files:</p>
<p>The Main Classifier: </p>
<pre><code>module BayesClassifier where
-- Text Classifier Using Bayes Formula
import Data.List
import Data.Char
type Category = String
newtype Classifier = Classifier { training :: [(Category, [String])] } deriving (Eq, Show)
-- Get a new classifer with no training
classifier :: Classifier
classifier = Classifier []
-- classifier probabilities
probabilityOfWordInCategory :: Classifier -> String -> Category -> Double
probabilityOfCategory :: Classifier -> Category -> Double
-- Adding + 1 for Laplacian Correction
probabilityOfWordInCategory (Classifier training) word category = let allInCategory = filter (\(cat, _) -> cat == category) training
allInCategoryContainingWord = filter (\(_, text) -> word `elem` text) allInCategory
in (fromIntegral $ length allInCategoryContainingWord + 1) / (fromIntegral $ length allInCategory + 1)
probabilityOfCategory (Classifier training) category = let allInCategory = filter (\(cat, _) -> cat == category) training
in (fromIntegral $ length allInCategory) / (fromIntegral $ length training)
-- Train a classifier
train :: Classifier -> String -> Category -> Classifier
train (Classifier training ) text category = Classifier $ (category, cleanInput $ text):training
-- Categorize text with a classifier
classify :: Classifier -> String -> Category
classify classifier text = fst $ head $ sortBy (\(_, a) (_, b) -> b `compare` a) $ probabilities classifier text
-- Get Probability for each Category
probabilities :: Classifier -> String -> [(Category, Double)]
probabilities classifier@(Classifier training) text = map (\cat -> (cat, probabilityForCategory classifier text cat)) $ nub $ map (\(cat, _) -> cat) training
-- Get Probability for a passage in a certain category
probabilityForCategory :: Classifier -> String -> Category -> Double
probabilityForCategory classifier text category = (+) (log $ probabilityOfCategory classifier category) (sum $ map (\word -> log $ probabilityOfWordInCategory classifier word category) $ cleanInput text)
-- Lowercase, Remove Punctuation
cleanInput :: String -> [String]
cleanInput text = filter (\w -> not (w `elem` stopWords)) $ words $ filter (`elem` ' ':['a'..'z']) $ map toLower text
where stopWords = ["a","about"....(More Stop Words)...."yourself","yourselves"]
</code></pre>
<p>and the Interface: </p>
<pre><code>import System.IO
import BayesClassifier
interactionLoop myClassifier function = case function of
"start" ->
do
putStrLn "Enter an action [train|classify]"
action <- getLine
interactionLoop myClassifier action
"train" ->
do
putStr "Category: "
category <- getLine
putStr "Material: "
material <- getLine
interactionLoop (train myClassifier material category) "start"
"classify" ->
do
putStr "Material: "
material <- getLine
putStrLn $ classify myClassifier material
putStrLn . show $ probabilities myClassifier material
putStrLn "\n\n\n\n"
interactionLoop myClassifier "start"
_ ->
interactionLoop myClassifier "start"
main = do
hSetBuffering stdout NoBuffering
hSetBuffering stdin NoBuffering
interactionLoop classifier "start"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T02:18:46.217",
"Id": "19865",
"Score": "0",
"body": "what is (More Stop Words)? Is that a comment? I think it is, but your capitalization is throwing me off :)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T02:21:50.877",
"Id": "19866",
"Score": "0",
"body": "As a general note, Add quickcheck to your code if you can. That would help you in future, and would also help the reviewers to understand the code better. HUnit would also help as a way to document your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T12:35:15.530",
"Id": "19914",
"Score": "0",
"body": "@blufox Yes, the whole list is really long and posting it seemed unnecessary."
}
] |
[
{
"body": "<p>The most obvious problem to me is formatting. Cut down on line width by putting <code>let</code> and <code>case</code> expressions down:</p>\n\n<pre><code>probabilityOfWordInCategory (Classifier training) word category =\n let allInCategory = filter (\\(cat, _) -> cat == category) training\n allInCategoryContainingWord = filter (\\(_, text) -> word `elem` text) allInCategory\n in (fromIntegral $ length allInCategoryContainingWord + 1) / (fromIntegral $ length allInCategory + 1)\n</code></pre>\n\n<p>Also, when defining helper functions for an equation, see if using <code>where</code> instead of <code>let</code> looks nicer:</p>\n\n<pre><code>probabilityOfWordInCategory (Classifier training) word category =\n (fromIntegral $ length allInCategoryContainingWord + 1) / (fromIntegral $ length allInCategory + 1)\n where\n allInCategory = filter (\\(cat, _) -> cat == category) training\n allInCategoryContainingWord = filter (\\(_, text) -> word `elem` text) allInCategory\n</code></pre>\n\n<p>Also, you can use <a href=\"http://www.haskell.org/haskellwiki/Pointfree\" rel=\"nofollow\">point-free style</a> to make <code>classify</code> more concise. Here's the current form of <code>classify</code>:</p>\n\n<pre><code>classify a b = f1 $ f2 $ f3 $ f4 a b\n</code></pre>\n\n<p>We can eta-reduce by using the <code>(.)</code> operator:</p>\n\n<pre><code>classify a = f1 . f2 . f3 . f4 a\n</code></pre>\n\n<p>Now for the revised definition of <code>classify</code>:</p>\n\n<pre><code>classify classifier = fst . head . sortBy (\\(_, a) (_, b) -> b `compare` a)\n . probabilities classifier\n</code></pre>\n\n<p>If you don't like writing out the transformations \"backwards\" like this, you can use the <code>>>></code> operator <a href=\"http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Category.html#v%3a-62--62--62-\" rel=\"nofollow\">from Control.Category</a>:</p>\n\n<pre><code>classify classifier = probabilities classifier\n >>> sortBy (\\(_, a) (_, b) -> b `compare` a)\n >>> head\n >>> fst\n</code></pre>\n\n<p>Finally, the <code>sortBy</code> transformation can be made more concise using the handy <code>on</code> function <a href=\"http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Function.html#v%3aon\" rel=\"nofollow\">from Data.Function</a>:</p>\n\n<pre><code>sortBy (flip compare `on` snd)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T12:36:22.943",
"Id": "19916",
"Score": "0",
"body": "Thank's, those are all great suggestions! I will definitely take them in to account."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T02:41:00.073",
"Id": "12366",
"ParentId": "12359",
"Score": "3"
}
},
{
"body": "<p>Rather nice attempt :)</p>\n\n<p>A small advice first. Do not use Category as a type name. It may confuse haskell people who might mistake it for a completely different <a href=\"http://www.haskell.org/haskellwiki/Category_theory\" rel=\"nofollow\">thing</a>.</p>\n\n<pre><code>import Data.List\nimport Data.Char\nimport qualified Data.Set as Set\nimport qualified Control.Monad as Ctl\nimport Test.HUnit\n</code></pre>\n\n<p>I added the unit test import here, and the set.</p>\n\n<p>It is rather adviced in haskell to look out for opportunities to take out\ngeneral definitions when possible from a more complicated expression. The idea is to build the language to describe your problem and then use it to solve the problem by describing it. So lots of tiny general purpose functions are very good.</p>\n\n<pre><code>onlyLetters = filter (\\x -> isLetter x || isSpace x)\n</code></pre>\n\n<p>I prefer the below version because liftM2 follows naturally and is quite readable.</p>\n\n<pre><code>onlyLetters = filter (Ctl.liftM2 (||) isLetter isSpace)\n</code></pre>\n\n<p>stopWords is clearly a constant. So take its construction out. Also see that a set is used. It makes the member operation cheaper.</p>\n\n<pre><code>stopWords = Set.fromAscList $ sort [\"a\",\"about\",\"you\",\"yourself\",\"yourselves\"]\n</code></pre>\n\n<p>Where possible use function composition. From my experience, it makes it easier to understand the essence of the function. Also if there is a choice between composing functions and using parenthesis or $, go for (.), That would make refactoring easier later. Use currying in preference to explicit lambdas.</p>\n\n<pre><code>cleanInput :: String -> [String]\ncleanInput = filter (flip Set.notMember stopWords) . words . clean\n where clean = onlyLetters . (map toLower)\n</code></pre>\n\n<p>Run tt to execute the test.</p>\n\n<pre><code>tests = TestList [TestLabel \"clean\" testClean]\ntt = runTestTT tests \n\ntInput = \"I and you and elephant\"\ntestClean = TestCase $ assertEqual\n \"cleanInput\"\n [\"i\",\"and\",\"and\",\"elephant\"] (cleanInput tInput)\n</code></pre>\n\n<p>Try to restrict your line width. First, it makes it easier to read your code, and second, it makes you on the lookout for refactoring opportunities. </p>\n\n<pre><code>-- Get Probability for a passage in a certain category\nprobabilityForCategory :: Classifier -> String -> Category -> Double\nprobabilityForCategory classifier text cat = sum $ pfst cat : plst cat (cleanInput text)\n where plst cat = map (log . probabilityOfWordInCategory classifier cat)\n pfst = log . probabilityOfCategory classifier\n</code></pre>\n\n<p>Note that the way you declared your data structure for Classifier, you get the function 'training' defined. So there is no point in extracting it using @ as you did. </p>\n\n<pre><code>-- Get Probability for each Category\nprobabilities :: Classifier -> String -> [(Category, Double)]\nprobabilities classifier text = map (wrap text) $ nub $ map fst (training classifier)\n where wrap = wrapfn . probabilityForCategory classifier\n</code></pre>\n\n<p>Thus we take out the wrapfn because it is nice and generic.</p>\n\n<pre><code>wrapfn fn cat = (cat, fn cat)\n</code></pre>\n\n<p>We can do the same with classify</p>\n\n<pre><code>-- Categorize text with a classifier\nclassify :: Classifier -> String -> Category\nclassify = ((fst . extMax snd) .) . probabilities\n</code></pre>\n\n<p>And our extract max is now nice and clean.</p>\n\n<pre><code>extMax :: Ord b => (x -> b) -> [x] -> x\nextMax fn = maximumBy (compare `F.on` fn)\n</code></pre>\n\n<p>The training function is clean, but remove the extra $, and make use of your\ntraining accessing function from classify.</p>\n\n<pre><code>-- How to train a dragon\ntrain :: Classifier -> String -> Category -> Classifier\ntrain c text category = Classifier $ (category, cleanInput text) : training c\n</code></pre>\n\n<p>The changes here should be self evident now.</p>\n\n<pre><code>filterElem :: Eq a1 => (a -> [a1]) -> a1 -> [a] -> [a]\nfilterElem fn word = filter ((elem word) . fn)\nfilterEq :: Eq b => (a -> b) -> b -> [a] -> [a]\nfilterEq fn x = filter ((x ==) . fn)\n\nallInCategory :: Eq a => a -> [(a, b)] -> [(a, b)]\nallInCategory = filterEq fst\n\n\nfl = fromIntegral . length\n\n-- Adding + 1 for Laplacian Correction\nprobabilityOfWordInCategory :: Classifier -> String -> Category -> Double\nprobabilityOfWordInCategory (Classifier training) word category = succ a / succ b\n where a = fl $ (filterElem snd) word y\n b = fl y\n y = allInCategory category training\n\n\nprobabilityOfCategory :: Classifier -> Category -> Double\nprobabilityOfCategory (Classifier training) category = a / b\n where a = fl (allInCategory category training)\n b = fl training\n</code></pre>\n\n<p>Also, make use of precedence of operators and avoid extra parenthesis. They are ugly :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T12:41:17.510",
"Id": "19917",
"Score": "0",
"body": "Wow, thanks for the great, in depth review. I feel like the main think I could do would be to break it into more functions to make it more readable. I'll add these suggestions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T14:47:46.387",
"Id": "19931",
"Score": "0",
"body": "@blufox: When you say `curry`, don't you mean \"function composition\" (i.e. the `(.)` operator) ? curry means take a function `(a, b) -> c` and turn it into `a -> (b -> c)` so the `a` can be partially applied."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T03:25:49.153",
"Id": "12371",
"ParentId": "12359",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "12371",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T20:16:42.613",
"Id": "12359",
"Score": "10",
"Tags": [
"optimization",
"haskell",
"functional-programming"
],
"Title": "Naive Bayes classifier"
}
|
12359
|
<p>I have two string variables <code>site_inclusion</code> and <code>site_exclusion</code>. If <code>site_inclusion</code> has some values, then I don't care what values <code>site_exclusion</code> contains. This means <code>site_inclusion</code> overrides <code>site_exclusion</code> if <code>site_inclusion</code> has some values. But if <code>site_inclusion</code> is null and <code>site_exclusion</code> has some values, then go into the <code>site_exclusion</code> loop.</p>
<p>Requirements:</p>
<ol>
<li>If site_inclusion and site_exclusion both are null then set <code>useTheSynthesizer</code> as true;</li>
<li>If site_inclusion is not null and it matches with the <code>regexPattern</code> then set <code>useTheSynthesizer</code> as true. And I don't care what values are there in site_exclusion.</li>
<li>If <code>site_inclusion</code> is null and <code>site_exclusion</code> is not null and <code>site_exclusion</code> does not match the regexPattern, then set <code>useTheSynthesizer</code> to true.</li>
</ol>
<p>I wrote the below code but somehow I think I am repeating some stuff here in the if/else loop. Any code improvements that fulfill my conditions will be appreciated.</p>
<pre><code>String site_inclusion = metadata.getSiteInclusion();
String site_exclusion = metadata.getSiteExclusion();
// fix for redundant data per site issue
if(site_inclusion != null && site_inclusion.matches(regexPattern)) {
useTheSynthesizer = true;
} else if(site_exclusion != null && !(site_exclusion.matches(regexPattern))) {
useTheSynthesizer = true;
} else if(site_inclusion == null && site_exclusion == null ) {
useTheSynthesizer = true;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T22:10:48.913",
"Id": "19861",
"Score": "0",
"body": "Your [question on SO](http://stackoverflow.com/questions/10940360/remove-repeated-code) should probably be merged into this one."
}
] |
[
{
"body": "<p>Please spinning it to a separate function. Here is what I think is a little more simpler implementation.</p>\n\n<pre><code>public boolean checkInclusion(String site_i, String site_e, Regex re) {\n if (site_i != null)\n return site_e.matches(re);\n else if(site_e != null)\n return !site_e.matches(re)))\n else\n return true;\n}\n</code></pre>\n\n<p>In your implementation, what happens when the site inclusion has values but does not match, and site_exclusion is null? It seems to not match any of the conditions, which is not in sync with the requirements from my reading.</p>\n\n<p>Also what happens when the site inclusion has values but does not match, and site_exclusion has values that does not match? In your implementation, it seems like site exclusion takes precedence. But that does not seem to be the requirement.</p>\n\n<p>Perhaps I am reading either requirement wrongly or your implementation conditions wrongly?</p>\n\n<p>A rather terse implementation that is same as above is,</p>\n\n<pre><code>public boolean checkInclusion(String site_i, String site_e, Regex re) {\n if (site_i != null) return site_i.matches(re);\n return site_e == null || !site_e.matches(re)\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T21:54:22.990",
"Id": "20076",
"Score": "0",
"body": "Could you explain how OR works on return statement ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T02:38:08.173",
"Id": "20077",
"Score": "0",
"body": "It is just a return of a boolean value. So first site_e == null is evaluated. If it is true, then true is returned. If not, site_e.matches(re) is evaluated and its negation is returned."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T02:38:41.543",
"Id": "20078",
"Score": "0",
"body": "The statement is same as [ bool x = site_e == null || !site_e.matches(re); return x; ]"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T01:35:42.260",
"Id": "12364",
"ParentId": "12361",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "12364",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T21:45:12.860",
"Id": "12361",
"Score": "2",
"Tags": [
"java"
],
"Title": "Check site inclusion and exclusion"
}
|
12361
|
<p>The program finds the first non repeating character in a character array, array contains only small case letters. </p>
<pre><code>#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char a2z[26]={0};//Hash
char input[100] = "abcbbbcdegh";//sample input, only small case english alphabets
int n = strlen(input);
for(int i=0; i<n; ++i)
{
if( a2z[ input[i]-97 ]<0 )
{
//do nothing, this character has already repeated
}
else if( a2z[ input[i]-97 ]==0 )
{
a2z[ input[i]-97 ] = i+1; //character encoutered first time
}
else
{
a2z[ input[i]-97 ] = -(i+1); //repeating character
}
}
int minAt=n+1;
for(int i=0; i<26; ++i) //finding first non-negative character in the Hash
{
if( (a2z[i]>0) && (a2z[i]<minAt) )
{
minAt=a2z[i];
}
}
if( minAt == n+1 )
cout<<"\n\n no unique character";
else
cout<<"\n\nFirst unique character is "<<input[minAt-1]<<" at position "<<minAt-1<<endl;
}
</code></pre>
<p>output :: </p>
<pre><code>First unique character is a at position 0
</code></pre>
<p>here, i have taken an character array (i.e. a2z) of 26 characters initialized with zero, using it as Hash.<br>
if a2z[i] is zero means ith character (of English alphabet) has not encountered till now, postive value of a2z[i] denotes ith character has been encountered only once at position a2z[i]-1, and negative values shows it has repeated.<br>
pls review this code.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T06:13:05.623",
"Id": "19875",
"Score": "0",
"body": "Add the output of the program too. It makes it easier for people without access to a compiler right now to look at your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T06:16:13.107",
"Id": "19876",
"Score": "0",
"body": "@blufox added the output."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T07:31:14.860",
"Id": "19879",
"Score": "0",
"body": "Are you looking for coding style tips, or trying to optimize for speed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T07:33:03.917",
"Id": "19880",
"Score": "0",
"body": "@Corbin mainly coding style tips,but getting speed optimizations tips too would be great."
}
] |
[
{
"body": "<p>The same program with a few changes. first, try to refactor your functions so that they are small, second, Often, using a case statement is more clearer to using cascading ifs. third, 'using namespace std' is a bad habit. It is probably ok to use in a small one off program like this, but avoid polluting your global namespace in larger projects. And avoid magic numbers when possible</p>\n\n<pre><code>#include<iostream>\n\nchar a2z[26]={0};\n\nint process(char* input, int len) {\n for (int i=0; i<len; i++) {\n int c = input[i] - 'a';\n switch(a2z[c]) {\n case -1:\n continue;\n case 0:\n a2z[c] = i+1;\n break;\n default:\n a2z[c] = -1;\n }\n }\n}\n\nint findfirst(int min) {\n for(int i=0; i< sizeof(a2z); ++i) {\n if( a2z[i]>0 && a2z[i]<min ) min = a2z[i];\n }\n return min;\n}\n\nint main() {\n char input[] = \"aabbbcbbbcddegghh\";\n int n = sizeof(input);\n process(input, n);\n int minAt = findfirst(n+1);\n\n if( minAt > n )\n std::cout<<\"no unique character\"<<std::endl;\n else\n std::cout<<\"First unique character is \"\n <<input[minAt-1]\n <<\" at position \"<<minAt-1<<std::endl; \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T08:07:43.880",
"Id": "19882",
"Score": "0",
"body": "Globals are almost always bad."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T08:12:31.387",
"Id": "19883",
"Score": "0",
"body": "Almost always :), here though, it may be an overkill to carry the hash around."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T08:14:09.410",
"Id": "19884",
"Score": "0",
"body": "It would be 26 extra bytes, or an extra parameter. Seems worth it for thread safety and better encapsulation. (I'm likely being a bit overly picky, but it's a code review site.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T08:16:48.107",
"Id": "19885",
"Score": "0",
"body": "agreed. I will update my answer accordingly."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T08:04:26.530",
"Id": "12376",
"ParentId": "12372",
"Score": "1"
}
},
{
"body": "<p>As far as this program goes, there's not very many non-opinion improvements possible.</p>\n\n<p>There are, however, a few correctness/(micro) optimization points:</p>\n\n<hr>\n\n<p><strong><code>char a2z[26]</code></strong></p>\n\n<p>A char is likely not big enough.</p>\n\n<pre><code>a2z[ input[i]-97 ] = i+1;\na2z[ input[i]-97 ] = -(i+1);\n</code></pre>\n\n<p><code>i = 0 ... strlen(input)-1</code> therefore <code>min(i) = 0</code> and <code>max(i) = strlen(input)</code>.</p>\n\n<p>A signed char, c, can be: -128 <= c <= 127, therefore, your implementation is limited to <code>strlen(input) <= 127</code>.</p>\n\n<p><strong>Implicit Double Looping</strong></p>\n\n<p>Typically <code>strlen()</code> is implemented vaguely like:</p>\n\n<pre><code>size_t strlen(const char* str)\n{\n size_t len = 0;\n while (str[len] != 0) {\n ++len;\n }\n return len;\n}\n</code></pre>\n\n<p>Thus your program is looping over the string twice.</p>\n\n<p>You could change your loop to basically embed the strlen in your code:</p>\n\n<pre><code>for(int i=0, const char* c = input; c != 0; ++i, ++c) {\n</code></pre>\n\n<p>That could be written a bit more cleanly, but hopefully it gets the point across.</p>\n\n<p>(It also is probably not a very meaningful optimization. It likely would have equal, or depending on exactly how the loop is done, potentially worse performance. Just something to consider if you're trying to micro-optimize.)</p>\n\n<hr>\n\n<p><strong>Style oddities <em>(blatant opinion with no backing)</em></strong></p>\n\n<p>These are a few items that are completely arbitrary in terms of correctness (basically all personal preferences):</p>\n\n<ul>\n<li>It's valid, but for the sake of explicitness, I prefer to use the<br>\nlong form of main() and always include a <code>return</code>.</li>\n<li>I also prefer to always use braces around the expressions for if and else statements. It's entirely a personal preference, but I've found that it tends to produces clearer, less error prone code</li>\n<li><code>#include<iostream></code> I don't actually know if it's valid to not have a space between include and the file. Either way, I very rarely see it written like that, and it looks a bit odd.</li>\n<li><code>a2z[ input[i]-97 ]</code> looks a bit odd to me.</li>\n<li><code>char input[100] = \"abcbbbcdegh\";</code> could be <code>const char input[] = \"abcbbbcdegh\";</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T10:08:34.913",
"Id": "19897",
"Score": "0",
"body": "You complexity is wrong. Its O(n) as the loops are not nested."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T22:35:19.293",
"Id": "19969",
"Score": "0",
"body": "Oh you're right! Would be 2n which is still O(n). Thanks. Will edit it once I'm on a computer and not my phone."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T08:04:36.020",
"Id": "12377",
"ParentId": "12372",
"Score": "2"
}
},
{
"body": "<p>This is a bad habbit stop doing it.</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>Once your programs are more than 10 lines long it starts adding complexity including the whole namespace. SO best not to do it. Get into the habit of not using now otherwise breaking the habit is hard latter.</p>\n\n<p>Don't put bad comments in you code (in fact try not to put comments). A comment should explain what you are trying to achieve (or potentially why) (NOT HOW). The code explains how so don't duplicate the code in comments. The worst thing to find in code is comments that don't match the code.</p>\n\n<pre><code>char a2z[26]={0};//Hash\n</code></pre>\n\n<p>This is not a hash. A hash has a very specific meaning and this is not what you are doing.</p>\n\n<p>Prefer to use [] when declaring the array. This means the compiler will try and establish the length of the array for you.</p>\n\n<pre><code>char input[100] = \"abcbbbcdegh\";//sample input, only small case english alphabets\n</code></pre>\n\n<p>While we are here. Stop using C stuff in C++. Learn to use C++ constructs and don't mix the languages up. Another bad habbit you should fall into.</p>\n\n<pre><code>int n = strlen(input);\n</code></pre>\n\n<p>C++ has its own string class.</p>\n\n<pre><code>std::string input(\"abcbbbddddd\");\n// size is input.size()\n</code></pre>\n\n<p>Learn how to use iterators.</p>\n\n<pre><code>for(int i=0; i<n; ++i)\n</code></pre>\n\n<p>It will allow you to be more versatile with your code. Potentially allowing your code to work with multiple container types (not just string). But more importantly it is the first step to using the standard algorithms.</p>\n\n<p>You are making the assumption that your input only contains lower case letters. You should always code defensively. You MUST validate your input.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T16:03:33.407",
"Id": "19944",
"Score": "1",
"body": "\"habit\" not \"habbit\" :P Couldn't resist."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T23:28:04.657",
"Id": "19979",
"Score": "1",
"body": "@Casey: The normal way to say that is `s/habbit/habit/` We are comp sci people here and understand how to write things succinctly without ambiguity."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T10:34:27.673",
"Id": "12382",
"ParentId": "12372",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "12377",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T03:41:57.090",
"Id": "12372",
"Score": "0",
"Tags": [
"c++",
"array"
],
"Title": "Searching first non repeating character"
}
|
12372
|
<p>I am having a popup which is styled to match the page and am using that single popup to display messages to the user. My popup contains one h1 element and an ASP.NET Label.</p>
<p>The h1 element and Label contents and color change according to the operation: if the information was successfully inserted the h1 text becomes <code>Success</code> and Label's text becomes "Your information was saved".</p>
<p>On incorrect input it changes accordingly, and on some unexpected error it changes the same way.</p>
<p>Currently I am calling three different JavaScript functions on appropriate events from my code behind using <code>RegisterClientScriptBlock</code>.</p>
<p><strong>HTML:</strong></p>
<pre><code><div id="NewCustomerSubmitStatusPopUp">
<a href="#" class="NewCustomerSubmitPopUpClose"><img class="NewCustomerSubmitPopUpImg" src="Images/cancel1.png"/></a>
<h1></h1>
<asp:Label ID="NewCustomerlblSubmitStatusMsg" runat="server" Text=""></asp:Label><br /><br />
<input class="NewCustomercmdSubmitPopUp" type="button" value="Close" />
</div>
</code></pre>
<p><strong>CSS:</strong></p>
<pre><code>#NewCustomerSubmitStatusPopUp
{
display:none;
position: fixed;
width:500px;
height: 150px;
top: 50%;
left: 50%;
margin-left:-255px;
margin-top:-110px;
/*background-color:#F7DFDE; */
padding:10px;
z-index:102;
font-family:Verdana;
font-size:10pt;
border-radius:10px;
-webkit-border-radius:20px;
-moz-border-radius:20px;
font-weight:bold;
}
#NewCustomerSubmitStatusPopUp h1
{
/*color:#BD494A;*/
padding:20px 0;
text-align:center;
}
.NewCustomercmdSubmitPopUp
{
height:30px;
width:50px;
margin-left:220px;
}
.NewCustomerSubmitPopUpImg
{
float:right;
margin-top:-30px;
margin-right:-25px;
}
</code></pre>
<p>javascript:</p>
<pre><code>function ShowSubmitSuccessPopUp()
{
$('#NewCustomerMask').show("slow");
$('#NewCustomerSubmitStatusPopUp').show("slow");
$('#NewCustomerSubmitStatusPopUp').show("slow");
$('#NewCustomerSubmitStatusPopUp').css({ background: 'white' });
$('#NewCustomerSubmitStatusPopUp').css({ border: '10px solid #9cc3f7'});
$('#NewCustomerSubmitStatusPopUp h1').html("Success");
$('#NewCustomerSubmitStatusPopUp h1').css({ color: '#9cc3f7' });
$('#ctl00_ContentPlaceHolder1_NewCustomerlblSubmitStatusMsg').css({ color: '#9cc3f7' });
}
function ShowSubmitErrorPopUp()
{
$('#NewCustomerMask').show("slow");
$('#NewCustomerSubmitStatusPopUp').show("slow");
$('#NewCustomerSubmitStatusPopUp').css({ background: '#F7DFDE' });
$('#NewCustomerSubmitStatusPopUp').css({ border:'10px solid #BD494A'});
$('#NewCustomerSubmitStatusPopUp h1').html("Error");
$('#NewCustomerSubmitStatusPopUp h1').css({ color: '#BD494A' });
$('#ctl00_ContentPlaceHolder1_NewCustomerlblSubmitStatusMsg').html("There are some errors in the page.Please rectify the errors by visiting the Errors tab.");
$('#ctl00_ContentPlaceHolder1_NewCustomerlblSubmitStatusMsg').css({ color: '#BD494A' });
}
function ShowSubmitUnexpectedErrorPopUp()
{
$('#NewCustomerMask').show("slow");
$('#NewCustomerSubmitStatusPopUp').show("slow");
$('#NewCustomerSubmitStatusPopUp').css({ background: '#F7DFDE' });
$('#NewCustomerSubmitStatusPopUp').css({ border: '10px solid #BD494A' });
$('#NewCustomerSubmitStatusPopUp h1').html("Something Went Wrong");
$('#NewCustomerSubmitStatusPopUp h1').css({ color: '#BD494A' });
$('#ctl00_ContentPlaceHolder1_NewCustomerlblSubmitStatusMsg').html("There was some error while submitting your information.Please re-enter the values and try again.");
$('#ctl00_ContentPlaceHolder1_NewCustomerlblSubmitStatusMsg').css({ color: '#BD494A' });
}
</code></pre>
<p>As you can see, for every event, I change text text of the h1 and the label element and change the style too.</p>
<p>Can anybody tell me if I am doing it in a good manner or if there is something wrong?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T08:38:24.183",
"Id": "19886",
"Score": "1",
"body": "Next time, care about your grammar/spelling. It's ok not to speak english perfectly, but at least give some air to your text."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T09:00:06.730",
"Id": "19887",
"Score": "0",
"body": "@FlorianMargaine can you just point me what was not ok."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T09:05:08.050",
"Id": "19888",
"Score": "0",
"body": "Just look at the edit: http://codereview.stackexchange.com/posts/12378/revisions"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T09:07:30.717",
"Id": "19889",
"Score": "0",
"body": "@FlorianMargaineya I checked that , I agreee it needs to be proper next time , I will take care of it."
}
] |
[
{
"body": "<p>A few ideas:</p>\n\n<ul>\n<li>Your three javascript functions could easily be combined into one with some simple arguments, like headerText, statusMessage, statusType.</li>\n<li>In your description you list some success text, but this isn't in the javascript, so I guess this is set in the code-behind. I consolidate how the text is set. If you choose to use javascript, you could simplify things by changing the asp:Label to a span.</li>\n<li>It might be nicer to put the style information in the CSS file and then in the javascript just toggle which classes apply.</li>\n</ul>\n\n<p>Here's an example of how it might look:</p>\n\n<p>CSS</p>\n\n<pre><code>#NewCustomerSubmitStatusPopup.successPopup\n{\n background-color: white;\n border-color: #9cc3f7; /* width, pattern added to main CSS block */\n}\n\n#NewCustomerSubmitStatusPopup.successPopup h1, #NewCustomerSubmitStatusPopup.successPopup span\n{\n color: #9cc3f7;\n}\n\n#NewCustomerSubmitStatusPopup.errorPopup\n{\n background-color: #F7DFDE;\n border-color: #BD494A;\n}\n\n#NewCustomerSubmitStatusPopup.errorPopup h1, #NewCustomerSubmitStatusPopup.errorPopup span\n{\n color: #BD494A;\n}\n</code></pre>\n\n<p>javascript</p>\n\n<pre><code>function ShowSubmitPopUp(headingText, statusMessage, statusType)\n{\n $('#NewCustomerMask').show(\"slow\");\n $('#NewCustomerSubmitStatusPopUp').show(\"slow\");\n\n var popupClass = (statusType == 'error' ? 'errorPopup' : 'successPopup');\n $('#NewCustomerSubmitStatusPopUp').attr('class', popupClass);\n $('#NewCustomerSubmitStatusPopUp h1').html(headingText);\n $('#NewCustomerSubmitStatusPopUp span').html(statusMessage);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T17:21:57.960",
"Id": "12395",
"ParentId": "12378",
"Score": "1"
}
},
{
"body": "<p>Additionally to @CodeMonkey1 answer you can cache your jQuery objects for ex. \n<code>$('#NewCustomerSubmitStatusPopUp')</code> to a variable like this: \n<code>var myObj = $('#NewCustomerSubmitStatusPopUp');</code></p>\n\n<p>Then you can rewrite this code:</p>\n\n<pre><code>$('#NewCustomerSubmitStatusPopUp').show(\"slow\");\n$('#NewCustomerSubmitStatusPopUp').css({ background: '#F7DFDE' });\n$('#NewCustomerSubmitStatusPopUp').css({ border: '10px solid #BD494A' });\n$('#NewCustomerSubmitStatusPopUp h1').html(\"Something Went Wrong\");\n$('#NewCustomerSubmitStatusPopUp h1').css({ color: '#BD494A' });\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>myObj.show(\"slow\");\nmyObj.css({ background: '#F7DFDE' });\nmyObj.css({ border: '10px solid #BD494A' });\nmyObj.find(\"h1\").html(\"Something Went Wrong\");\nmyObj.find(\"h1\").css({ color: '#BD494A' });\n</code></pre>\n\n<p>This has the benefit that you dont have to query the DOM five times for the same thing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T05:17:46.750",
"Id": "19991",
"Score": "0",
"body": "thanks a lot for correcting my mistake , really helpful.Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T06:25:52.827",
"Id": "19995",
"Score": "1",
"body": "You made no mistake - you're just learning and that is very good."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T06:27:31.480",
"Id": "19996",
"Score": "0",
"body": "You are right,getting feedbacks from better people is a blessing.Thanks mate."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T21:21:20.030",
"Id": "12405",
"ParentId": "12378",
"Score": "1"
}
},
{
"body": "<p>It's pretty much commented in the code:</p>\n\n<p><strong>JavaScript:</strong></p>\n\n<pre><code>$(function() {\n //cache repeatedly used elements to avoid re-querying them \n var customermask = $('#NewCustomerMask'),\n popup = $('#NewCustomerSubmitStatusPopUp'),\n //use context to get descendants of a target context. it's similar to a .find()\n popupHeader = $('h1', popup),\n placeholder = $('#ctl00_ContentPlaceHolder1_NewCustomerlblSubmitStatusMsg'),\n //move out your text as variables. don't mingle them with the code\n errorMsg = 'There are some errors in the page.Please rectify the errors by visiting the Errors tab.',\n unexpectedErrorMsg = 'There was some error while submitting your information.Please re-enter the values and try again.';\n\n //condense the function to one\n function ShowSubmitPopUp(status) {\n\n //and do common tasks\n customermask.show('slow');\n //use classes to determine the state and style of the pop-up \n popup.show('slow').addClass(status);\n placeholder.addClass(status);\n\n //use the status to determine specific tasks\n switch (status) {\n case 'success':\n //use .text() when setting only text\n popupHeader.text('Success');\n break;\n case 'error':\n placeholder.text(errorMsg);\n popupHeader.text('Error');\n break;\n case 'uerror':\n placeholder.text(unexpectedErrorMsg);\n popupHeader.text('Something went awfully wrong!');\n break;\n }\n }\n});\n</code></pre>\n\n<p><strong>CSS:</strong></p>\n\n<pre><code>/*since styles are common, you can stack them to avoid repeating*/\n\n/*success styles*/\n#NewCustomerSubmitStatusPopUp.success{\n background: #FFF;\n border: 10px solid #9cc3f7;\n}\n\n#NewCustomerSubmitStatusPopUp.success h1,\n#ctl00_ContentPlaceHolder1_NewCustomerlblSubmitStatusMsg.success{\n color: #9cc3f7;\n}\n\n/*error and uerror styles*/\n#NewCustomerSubmitStatusPopUp.error,\n#NewCustomerSubmitStatusPopUp.uerror{\n background: #F7DFDE;\n border: 10px solid #BD494A;\n}\n\n#NewCustomerSubmitStatusPopUp.error h1,\n#NewCustomerSubmitStatusPopUp.uerror h1,\n#ctl00_ContentPlaceHolder1_NewCustomerlblSubmitStatusMsg.error,\n#ctl00_ContentPlaceHolder1_NewCustomerlblSubmitStatusMsg.uerror{\n color: #BD494A;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T05:14:54.167",
"Id": "19990",
"Score": "0",
"body": "I will give it a try and then come back to you , if I have any doubts.Thanks for the help.Really appreciate your effort."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T05:22:12.967",
"Id": "19993",
"Score": "0",
"body": "Another question ,I need to call ShowSubmitPopUp() function and pass appropriate class name as arguments right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T05:40:09.617",
"Id": "19994",
"Score": "0",
"body": "Thanks a lot , it worked and the code is clean and less as well.Thanks."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T00:03:29.667",
"Id": "12411",
"ParentId": "12378",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12411",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T08:22:29.217",
"Id": "12378",
"Score": "0",
"Tags": [
"javascript",
"jquery"
],
"Title": "Using a popup to display messages to the user"
}
|
12378
|
<p>I just answered the question on project euler about finding <a href="http://projecteuler.net/problem=35" rel="nofollow">circular primes below 1 million</a> using python. My solution is below. I was able to reduce the running time of the solution from 9 seconds to about 3 seconds. I would like to see what else can be done to the code to reduce its running time further. This is strictly for educational purposes and for fun.</p>
<pre><code>import math
import time
def getPrimes(n):
"""returns set of all primes below n"""
non_primes = [j for j in range(4, n, 2)] # 2 covers all even numbers
for i in range(3, n, 2):
non_primes.extend([j for j in range(i*2, n, i)])
return set([i for i in range(2, n)]) - set(non_primes)
def getCircularPrimes(n):
primes = getPrimes(n)
is_circ = []
for prime in primes:
prime_str = str(prime)
iter_count = len(prime_str) - 1
rotated_num = []
while iter_count > 0:
prime_str = prime_str[1:] + prime_str[:1]
rotated_num.append(int(prime_str))
iter_count -= 1
if primes >= set(rotated_num):
is_circ.append(prime)
return len(is_circ)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T10:21:37.733",
"Id": "19907",
"Score": "0",
"body": "do you have any idea which region takes the most time? the getPrimes method looks like it's going to be expensive, as you're building two very large sets then subtracting one from the other."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T10:23:45.203",
"Id": "19908",
"Score": "0",
"body": "getPrimes takes the most time (about 1.9s according to the python profiler)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T10:25:23.873",
"Id": "19909",
"Score": "0",
"body": "and I'm fairly sure you'll be having duplicates in the `non_primes` list."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T10:27:00.253",
"Id": "19910",
"Score": "0",
"body": "if `getPrimes` takes 1.9s, the rest of the function is taking 7.1. if you're using a profiler it's running in debug I assume? how does it perform in release?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T10:30:20.280",
"Id": "19911",
"Score": "0",
"body": "and I just don't think your method of determining circular primes is efficient. can't even work out it it's correct, tbh."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T10:31:54.303",
"Id": "19912",
"Score": "0",
"body": "it is correct..you could see that if you test it and it takes approximately 3 seconds to run now not 9 seconds."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T11:12:41.193",
"Id": "19913",
"Score": "0",
"body": "sorry, misread the timing bit in your question. I think you'd get a big perfomance boost if you shifted your way of getting a list of prime numbers. You currently have something of the order of 10^12 iterations going on in generating the list of none-prime numbers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T13:33:41.487",
"Id": "19923",
"Score": "0",
"body": "What happens if you replace list comprehensions with generator comprehensions (`[j for j in…]` with `(j for j in…)`)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T14:37:59.720",
"Id": "19928",
"Score": "0",
"body": "You might look at this question to speed things up: http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T04:52:13.253",
"Id": "19989",
"Score": "0",
"body": "http://stackoverflow.com/questions/2211990/how-to-implement-an-efficient-infinite-generator-of-prime-numbers-in-python"
}
] |
[
{
"body": "<p>Python 2.7: <strong>100 ms</strong>, pypy 1.8.0: <strong>60 ms</strong> (Intel Core i7-3770K, 4x 3.50GHz):</p>\n\n<pre><code>import time\n\ndef rwh_primes2(n):\n # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188\n \"\"\" Input n>=6, Returns a list of primes, 2 <= p < n \"\"\"\n correction = (n%6>1)\n n = {0:n,1:n-1,2:n+4,3:n+3,4:n+2,5:n+1}[n%6]\n sieve = [True] * (n/3)\n sieve[0] = False\n for i in xrange(int(n**0.5)/3+1):\n if sieve[i]:\n k=3*i+1|1\n sieve[ ((k*k)/3) ::2*k]=[False]*((n/6-(k*k)/6-1)/k+1)\n sieve[(k*k+4*k-2*k*(i&1))/3::2*k]=[False]*((n/6-(k*k+4*k-2*k*(i&1))/6-1)/k+1)\n return [2,3] + [3*i+1|1 for i in xrange(1,n/3-correction) if sieve[i]]\n\ndef main():\n start = time.time()\n primes = set(rwh_primes2(1000000))\n circular_primes = set()\n for prime in primes:\n include = True \n s = str(prime)\n for n in xrange(len(s)-1): \n s = s[1:] + s[:1]\n if int(s) not in primes: \n include = False\n break \n if include: \n circular_primes.add(prime)\n print(len(circular_primes))\n print(\"Time (s) : \" + str(time.time()-start))\n\nmain()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T22:55:17.613",
"Id": "19973",
"Score": "1",
"body": "a bit of comments would help."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T15:00:06.137",
"Id": "12389",
"ParentId": "12383",
"Score": "1"
}
},
{
"body": "<p>After a bit of fiddling coupled with some insight from SO on the topic which happens to be one with a lot of previous questions and answers, I was able to modify and get the running time of the getPrimes function down to 0.95s from 1.9s for an n value of 1000000. The code is given below and this was acheived by eliminating redundant instructions. Any more fiddling around is welcome.</p>\n\n<pre><code>def getPrimes(n):\n \"\"\"returns set of all primes below n\"\"\"\n primes = [1] * n\n for i in range(3, n, 2):\n for j in range(i*3, n, 2*i):\n primes[j] = 0\n return len([1] + [primes[j] for j in range(3, n, 2) if primes[j]])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T23:58:42.013",
"Id": "12410",
"ParentId": "12383",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "12389",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T10:12:17.230",
"Id": "12383",
"Score": "4",
"Tags": [
"python",
"optimization",
"project-euler",
"primes"
],
"Title": "Improving runtime of prime generation"
}
|
12383
|
<p>I needed a singleton in JavaScript in order to make a DataManager which is called multiple times, but I just want it to load its data only the first time it is called, then give pieces of the data out view public methods, never loading the initial data again.</p>
<p>I found a number of approaches to building singletons in JavaScript but this one seems to have everything I need.</p>
<p>Does anyone see any kind of problem this singleton is going to have for the uses I need it for?</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>test singleton</title>
<script type="text/javascript">
var DatapodManager = (function() {
var instantiated;
that = this;
//DEFINE INTERNAL VARIABLES HERE:
var message = '';
function init() {
//LOAD DATA ONCE HERE:
that.message = 'singleton message defined at: ' + getMilliseconds();
//ALLOW PUBLIC ACCESS TO SINGLETON DATA HERE:
return {
getMessage : function() {
return that.message;
},
id : '1234'
}
}
return {
getInstance : function() {
if(!instantiated) {
instantiated = init();
}
return instantiated;
}
}
})()
function dowait() {
for( x = 1; x <= 10000000; x++) {
var y = 1000;
var z = 2000;
var b = y * z;
}
}
function getMilliseconds() {
var d = new Date();
return d.getMilliseconds();
}
window.onload = function() {
console.log('getting first singleton message at: '+getMilliseconds());
console.log(DatapodManager.getInstance().getMessage());
dowait();
console.log('getting second singleton message at: '+getMilliseconds());
console.log(DatapodManager.getInstance().getMessage());
console.log('the static id is '+DatapodManager.getInstance().id);
};
</script>
</head>
<body></body>
</code></pre>
<h2> </h2>
<h3>Output:</h3>
<p><img src="https://i.stack.imgur.com/0La13.png" alt="enter image description here"></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T14:57:33.613",
"Id": "19932",
"Score": "0",
"body": "Is that java factory?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T16:16:51.847",
"Id": "19946",
"Score": "0",
"body": "Is there a reason why you don't use an object literal?"
}
] |
[
{
"body": "<ul>\n<li><p>Once you start to chain properties or function calls, you incur performance penalty due to scope differences. It's best you keep the property/function depth to a minimum. This ain't Java or AS3 that needs deep namespacing.</p></li>\n<li><p>What's the idea of <code>getInstance()</code>? Can't the singleton module itself be the instance?</p></li>\n<li><p>Regarding the output image, it is correct. You get the first message at 440ms, then the singleton created the message at 442ms during <code>init()</code>. The next call you made is at 482ms. Since the instance was already created, the same message (the one created at 442ms) was used.</p></li>\n</ul>\n\n<p>Here's <a href=\"http://jsfiddle.net/qCFPH/\" rel=\"nofollow\">a very short version</a> of it. Basically, I just removed <code>getInstance()</code> and made <code>DatapodManager</code> the instance. No visible speed difference but you have shorter code. I also preserved the idea of it being a closure in case you ever needed private properties:</p>\n\n<pre><code>var DatapodManager = (function () {\n return {\n message: 'singleton message defined at: ' + getMilliseconds(),\n getMessage: function () {\n return this.message\n },\n id: '1234'\n }\n}());\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T23:13:37.450",
"Id": "12409",
"ParentId": "12388",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "12409",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T14:53:43.763",
"Id": "12388",
"Score": "1",
"Tags": [
"javascript",
"singleton"
],
"Title": "Can this JavaScript singleton be improved?"
}
|
12388
|
<p>I'm a beginner programmer and I'm hoping someone would be willing to take a look at my code and tell me how to improve my coding style and development approach. Sorry about not commenting, I will try to get into the habit of commenting.</p>
<p><strong>board.h</strong></p>
<pre><code>#include <iostream>
#include <vector>
using namespace std;
class board{
int values[5][5], blankX, blankY, parent, index, manhattan;
public:
board(int _values[5][5], int _blankX, int _blankY, int _index, int _parent);
void printBoard();
bool checkUp();
bool checkDown();
bool checkLeft();
bool checkRight();
void createChild(vector<board> &_children, int &_index, int &_count);
void exchangeUp();
void exchangeDown();
void exchangeLeft();
void exchangeRight();
int nextLevel(vector<board> &_children, int &_index, board _goal, int &parentCount);
void findSolution(vector<board> &_vector, int &_index, board _goal);
bool compare(board _goal);
int getParent(){return parent;};
void moveUp(){blankX--;};
void moveDown(){blankX++;};
void moveLeft(){blankY--;};
void moveRight(){blankY++;};
int getBlankX(){return blankX;};
int getBlankY(){return blankY;};
void setManhattan(board _goal);
int getManhattan(){return manhattan;};
};
</code></pre>
<p><strong>board.cpp</strong></p>
<pre><code>#include "board.h"
#include <vector>
board::board(int _values[5][5], int _blankX, int _blankY, int _index, int _parent){
for (int i=0; i<5; i++) {
for (int j=0; j<5; j++) {
values[i][j]=_values[i][j];
}
}
blankX = _blankX;
blankY = _blankY;
index = _index;
parent = _parent;
}
void board::printBoard(){
for (int i=1; i<4; i++) {
for (int j=1; j<4; j++) {
cout << values[i][j]<<' ';
}
cout << '\n';
}
}
bool board::checkUp(){
if (values[blankX-1][blankY]==-1) {
return false;
}else {
return true;
}
}
bool board::checkDown(){
if (values[blankX+1][blankY]==-1) {
return false;
}else {
return true;
}
}
bool board::checkLeft(){
if (values[blankX][blankY-1]==-1) {
return false;
}else {
return true;
}
}
bool board::checkRight(){
if (values[blankX][blankY+1]==-1) {
return false;
}else {
return true;
}
}
void board::createChild(vector<board>& _children, int& _index, int & _count){
_children.push_back(board(values, blankX, blankY, index, _index));
_count++;
}
void board::exchangeUp(){
values[blankX][blankY]=values[blankX-1][blankY];
values[blankX-1][blankY]=0;
}
void board::exchangeDown(){
values[blankX][blankY]=values[blankX+1][blankY];
values[blankX+1][blankY]=0;
}
void board::exchangeLeft(){
values[blankX][blankY]=values[blankX][blankY-1];
values[blankX][blankY-1]=0;
}
void board::exchangeRight(){
values[blankX][blankY]=values[blankX][blankY+1];
values[blankX][blankY+1]=0;
}
int board::nextLevel(vector<board> &_vector, int &_index, board _goal, int &parentCount){
if(_vector[parentCount].checkUp()){
createChild(_vector, parentCount, _index);
_vector[_index].exchangeUp();
_vector[_index].moveUp();
_vector[_index].setManhattan(_goal);
board temp = _vector[_index];
board parent = _vector[getParent()];
if (temp.compare(_vector[parent.getParent()])) {
_vector.pop_back();
_index--;
}else if (temp.getManhattan()>parent.getManhattan()) {
_vector.pop_back();
_index--;
}
}
if(_vector[parentCount].checkDown()){
createChild(_vector, parentCount, _index);
_vector[_index].exchangeDown();
_vector[_index].moveDown();
_vector[_index].setManhattan(_goal);
board temp = _vector[_index];
board parent = _vector[getParent()];
if (temp.compare(_vector[parent.getParent()])) {
_vector.pop_back();
_index--;
}else if (temp.getManhattan()>parent.getManhattan()) {
_vector.pop_back();
_index--;
}
}
if(_vector[parentCount].checkLeft()){
createChild(_vector, parentCount, _index);
_vector[_index].exchangeLeft();
_vector[_index].moveLeft();
_vector[_index].setManhattan(_goal);
board temp = _vector[_index];
board parent = _vector[getParent()];
if (temp.compare(_vector[parent.getParent()])) {
_vector.pop_back();
_index--;
}else if (temp.getManhattan()>parent.getManhattan()) {
_vector.pop_back();
_index--;
}
}
if(_vector[parentCount].checkRight()){
createChild(_vector, parentCount, _index);
_vector[_index].exchangeRight();
_vector[_index].moveRight();
_vector[_index].setManhattan(_goal);
board temp = _vector[_index];
board parent = _vector[getParent()];
if (temp.compare(_vector[parent.getParent()])) {
_vector.pop_back();
_index--;
}else if (temp.getManhattan()>parent.getManhattan()) {
_vector.pop_back();
_index--;
}
}
return _index;
}
bool board::compare(board _goal){
for (int i=0; i<5; i++) {
for (int j=0; j<5; j++) {
if(values[i][j]!=_goal.values[i][j]){
return false;
}
}
}
return true;
}
void board::setManhattan(board _goal){
int manhatCounter = 0;
for (int i=1; i<4; i++) {
for (int j=1; j<4; j++) {
if(values[i][j]!=_goal.values[i][j]){
manhatCounter++;
}
}
}
manhattan = manhatCounter;
manhatCounter = 0;
}
</code></pre>
<p><strong>main.cpp</strong></p>
<pre><code>#include <iostream>
#include <sstream>
#include <vector>
#include "board.h"
using namespace std;
int main (int argc, char * const argv[]) {
stringstream ss;
string initialState, goalState, test;
int tempStore, blankXstate, blankYstate;
vector<int> initialList;
vector<int> goalList;
int count = 0;
int count2 = 0;
int parentIndexCounter=0;
vector<board> tree;
int indexCount = 0;
int counter = 0;
vector<int> final;
cout << "Please enter the initial state with a number followed by a comma (0,1,2,3,4,5,6,7,8), no spaces.\n";
getline(cin, initialState);
ss << initialState;
while (ss >> tempStore) {
initialList.push_back(tempStore);
if(ss.peek() == ','){
ss.ignore();
}
}
ss.str("");
ss.clear();
cout << "Please enter the goal state with a number followed by a comma (0,1,2,3,4,5,6,7,8), no spaces.\n";
getline(cin, goalState);
ss << goalState;
while (ss >> tempStore) {
goalList.push_back(tempStore);
if(ss.peek() == ','){
ss.ignore();
}
}
int initialBoard[5][5];
int goalBoard[5][5];
for (int i=0; i<5; i++) {
if (i==0 || i==4) {
for (int j=0; j<5; j++) {
initialBoard[i][j] = -1;
}
}else {
initialBoard[i][0] = -1;
initialBoard[i][4] = -1;
}
}
for (int i=1; i<4; i++) {
for (int j=1; j<4; j++) {
initialBoard[i][j]=initialList[count];
if (initialBoard[i][j]==0) {
blankXstate = i;
blankYstate = j;
}
count++;
}
}
for (int i=0; i<5; i++) {
if (i==0 || i==4) {
for (int j=0; j<5; j++) {
goalBoard[i][j] = -1;
}
}else {
goalBoard[i][0] = -1;
goalBoard[i][4] = -1;
}
}
for (int i=1; i<4; i++) {
for (int j=1; j<4; j++) {
goalBoard[i][j]=goalList[count2];
count2++;
}
}
board firstCreatedBoard(initialBoard, blankXstate, blankYstate, 0, NULL);
board goalCreateBoard(goalBoard, NULL, NULL, NULL, NULL);
tree.push_back(firstCreatedBoard);
tree[0].setManhattan(goalCreateBoard);
vector <int> nodes;
for (int i=0; !(tree[i].compare(goalCreateBoard)); i++) {
tree[i].nextLevel(tree, indexCount, goalCreateBoard, parentIndexCounter);
parentIndexCounter++;
cout << "Generated " << parentIndexCounter - 1 << " states." << '\n';
counter = i + 1;
}
while (counter != -1) {
final.push_back(counter);
counter = tree[counter].getParent();
if (counter == 0) {
counter = -1;
}
}
final.push_back(0);
reverse(final.begin(),final.end());
for (int i = 0; i < final.size(); i++) {
cout << "Step " << i << '\n';
tree[final[i]].printBoard();
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T16:43:50.423",
"Id": "19948",
"Score": "0",
"body": "I am curious. Why do you use _parameter names? I have usually seen Object._member convention, (The given reason is that object members are from a non-local scope, and hence need to stand out)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T18:33:36.977",
"Id": "19960",
"Score": "0",
"body": "Best not to use a leading underscore in identifier names: http://stackoverflow.com/a/228797/14065"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T17:42:32.960",
"Id": "20063",
"Score": "0",
"body": "so should variables of board been declared with an _?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T17:59:11.130",
"Id": "20068",
"Score": "0",
"body": "Would yall of went a different way about designing this program, I have a very weak concept of pointers, so instead of using them, I had every possible move pushed into a vector with their current index value and their parent index value. This made things a lot more complex as I had to depend on keeping very careful track of this index. As far as i know about pointers, you can find address location of a variable, but what good does knowing where it is in the memory do. Can someone give some examples of how to use pointers and cool pointers tricks? Thanks again everyone who answered"
}
] |
[
{
"body": "<p>Just a few things I noticed which may be of use in the future. All these items come from the amazing book by Scott Meyers' <a href=\"http://www.amazon.co.uk/Effective-Specific-Addison-Wesley-Professional-Computing/dp/0321334876/ref=sr_1_1?s=books&ie=UTF8&qid=1339173771&sr=1-1\" rel=\"nofollow\">Effective C++</a> which I recommend you get if you want to improve your coding standards!</p>\n\n<h1>Use const whenever possible</h1>\n\n<p>This not only allows you a semantic constraint (item within this cannot be modified), but allows you to communicate to both to compiler and any other programmer who may use your code!</p>\n\n<p>So for example, a lot of your methods could use the following:</p>\n\n<pre><code>void PrintBoard() const;\n</code></pre>\n\n<p>This particular example doesn't really effect anything, but will generally help the compiler. You can see a better example when looking at inspectors or mutators (get/sets):</p>\n\n<pre><code>void Mutator(const int val) { _memberVal = val; }\nint Inspector() const { return _memberVal; }\n</code></pre>\n\n<p>Mutator: Not only does it tell the programmer that the inputted value does not change within the method, but with the lack of const at the end of the method it tells us that there will a change of data within the class</p>\n\n<p>Inspector: With the const at the end of the method, it tells not only the programmer but also the compiler that there will be no change to the data within the class.</p>\n\n<h1>Make sure that objects are initialized before they're used</h1>\n\n<p>It's good to see that inside your constructor that you have initialized all the items, including the array, but there is another, more efficient, way of doing this with the use of <em>initialization lists</em>. For example:</p>\n\n<pre><code>board::board(int _values[5][5], int _blankX, int _blankY, int _index, int _parent)\n : blankX(_blankX), blankY(_blankY), parent(_parent), index(_index)\n{\n // Initialize the array here\n}\n</code></pre>\n\n<p>The reason this is more efficient is mainly due to how the different types of constructors work with assignments. </p>\n\n<p>If anything else pops into mind I will post again!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T18:34:57.070",
"Id": "19961",
"Score": "0",
"body": "+1. But had to fixe your usage of const. Note there is no point in const when returning by value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T18:36:51.497",
"Id": "19962",
"Score": "0",
"body": "Avoid get/set (ers) they tightly couple your code to a particular implementation. In OO you ask the object to mutate its own state by asking it to perform an action (ie your methods should be verbs). You should not be providing state for sombody else to act on you that is very close to breaking encapsulation (but is tightly coupling)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T19:31:42.477",
"Id": "19963",
"Score": "0",
"body": "There is no point from what can see but does help the compiler. Also, it stops silly errors like... (a*b) = c, or even better example... if(a*b = c) when doing comparison"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T19:50:48.207",
"Id": "19964",
"Score": "0",
"body": "@D Hansen: You are misreading \"Scott's Book\". Your comments are correct if the result was returned by reference. But in this case they are not (they are returned by value). Thus the result of the method call is not an `r-value` and thus not susceptible to the assignment problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T20:14:02.890",
"Id": "19965",
"Score": "0",
"body": "@LokiAstari My mistake haha, Not having a good thinking day today :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T20:18:49.857",
"Id": "19966",
"Score": "0",
"body": "That's OK. I have been doing this longer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T17:55:02.290",
"Id": "20067",
"Score": "0",
"body": "So does declaring a const save time? As opposed to not using const. I see the how the second initialization is a lot easier to read/write. Thanks for your input"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T13:00:32.340",
"Id": "20089",
"Score": "0",
"body": "@user1444974 Not really but it does give more control over the class you have created. For instance, if you declair a const reference as an input to the method, it will let the person using that class that you are taking it in to the method, but not changing it. It also works the same when putting this at the end of the method. That states that there will be no change to any member variables within the class (hence why always use them if having an inspector). It basically helps you to not make silly mistakes as well as anyone else using the class"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T17:02:49.930",
"Id": "12393",
"ParentId": "12391",
"Score": "2"
}
},
{
"body": "<h3>Style:</h3>\n<p>Why to many get/set (ers).<br />\nYour methods should be actions that perform actions on your object and mutate state. You should not expose your state (even through getters) as this binds your implementation (tightly couples) your implementation to that interface.</p>\n<h3>Code:</h3>\n<p>This:</p>\n<pre><code>bool board::checkUp(){\n if (values[blankX-1][blankY]==-1) {\n return false;\n }else {\n return true;\n }\n}\n</code></pre>\n<p>Is easier to write (and read) as:</p>\n<pre><code>bool board::checkUp() { return values[blankX-1][blankY] != -1;}\n</code></pre>\n<p>And this:</p>\n<pre><code>void board::exchangeUp(){\n values[blankX][blankY]=values[blankX-1][blankY];\n values[blankX-1][blankY]=0; \n}\n</code></pre>\n<p>Is easier to read.write as:</p>\n<pre><code>void board::exchangeUp()\n{\n std::swap(values[blankX][blankY], values[blankX-1][blankY]); \n --blankX;\n}\n</code></pre>\n<p>But why are you allowing an external entity to blindly change your state. You need to validate that the move is good. You should never trust the code using you to blindly always be correct. Validate the move.</p>\n<h3>Exposing State</h3>\n<pre><code>void board::createChild(vector<board>& _children, int& _index, int & _count){\n _children.push_back(board(values, blankX, blankY, index, _index));\n _count++;\n}\n</code></pre>\n<p>To me the <code>vector<board></code> should be a private member (or method member) of the board used for solving the problem. You should not be passing this in from the outside. Also the <code>count</code> variable seems redundant. The count will be equivalent to <code>size()</code> of the vector.</p>\n<h3>Printing</h3>\n<p>It's ok to have a print method. But you should pass it the stream you want to print too.</p>\n<pre><code>void board::printBoard(std::ostream& out) const\n</code></pre>\n<p>I would also add your own custom operator<< to make sure your object can be printed like other objects. It also helps with standard algorithms where you can use the operator<< in a standard way for printing serialization etc.</p>\n<pre><code>std::ostream& operator<<(std::ostream& stream, board const& data)\n{\n data.printBaord(stream);\n return stream;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T17:50:34.853",
"Id": "20066",
"Score": "0",
"body": "So is it bad in coding to have unnecessary public functions/objects? This is not something that I've actively tried to hide, but I will from now on. Also the rewriting of the code makes sense. The exchange of the state is only called later on when the checkUp is true I.E. checkUP -> true then exchange up. So I've broken up some steps that could have been combined. Would it of been best to rewrote it to where check and exchange are the same functions? Lastly, I've heard of overloading? operators but have never really fully understood how to use them. Thank you for taking the time and helping"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T18:17:01.447",
"Id": "20069",
"Score": "0",
"body": "Yes. Minimize your exposed public interface (public interface are all the methods in public/protected). Never put member variables anywhere but private. Always validate untrusted data. operator overloading is when you write your owne version of +/-/*/ etc. It is not recommended. Unless you are writing a new class that represents a number. function overloading may be what you mean. This is where you have multiple functions with the same name (buf different parameters)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T18:50:28.983",
"Id": "12400",
"ParentId": "12391",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T16:19:36.883",
"Id": "12391",
"Score": "4",
"Tags": [
"c++",
"beginner",
"pathfinding",
"sliding-tile-puzzle"
],
"Title": "Sliding block puzzle, A*"
}
|
12391
|
<p>I'm beginning to learn HTML and CSS, and since our lead developer is busy finishing up our project, I was asked to code the landing page.</p>
<p>I read up on some tutorials and beginning books, so I have a general grasp of things. But I'm curious as to how I use HTML and CSS to layout images efficiently. </p>
<p>When I first made the site, I used relative and absolute positioning to layout all the images. That was not good.</p>
<p>This time I decided to use margins/padding to organize it, but I still feel like there is a much better to lay all this out.</p>
<p>Basically I just want to be able to code the website, where if I add an image or move around images, the original pieces of the website don't end up going all over the place.</p>
<p>This is a rough image of what our landing page is supposed to look like:</p>
<p><img src="https://i.stack.imgur.com/meEQ8.png" alt="enter image description here"></p>
<p><strong>HTML</strong></p>
<pre class="lang-html prettyprint-override"><code><div id="container">
<img src="images/iphone.png" alt="iPhone" id="iphone" />
<div id="imagesBlock">
<img src="images/DashLogo.png" alt="Dash Logo" id="DashLogo" />
<!--<div id="snappyText">
<p>Ever think, "Where are the most mediocre places</p>
<p>to eat around here? I want me some of that."</p>
</div> -->
<img src="images/textQuestion.png" alt="textQuestion" id="textQuestion">
<img src="images/videoThumbnail.png" alt="Video Screenshot" id="videoThumbnail" />
<!--<div id="response">
<p>Yeah, neither do we.</p>
</div>-->
<img src="images/textResponse.png" alt="textResponse" id="textResponse"/>
<a href="http://itunes.apple.com/app/memix-pro/id300136119?mt=8" title="App Store" target="_blank" ><img src="images/appStoreOrange.png" alt="App Store" id="appStoreOrange" /></a>
<a href="http://twitter.com/#!/thedashapp" class="twitter" title="twitter link" target="_blank" ></a>
<a href="http://www.facebook.com/" class="facebook" title="facebook link"target="_blank" ></a>
</div>
</code></pre>
<p><strong>CSS</strong></p>
<pre class="lang-css prettyprint-override"><code>body{
background:url(images/whiteBackground.png);
}
.container{
width:1200px;
margin:0 auto;
position:relative;
}
#iphone{
margin-left: 166px;
margin-top: 88px;
}
/* images Block */
#imagesBlock{
position:relative;
left: 550px;
bottom:592px;
width: 515px;
}
#DashLogo{
}
#textQuestion{
margin-top:35px;
}
#videoThumbnail{
margin-top:20px;
}
#textQuestion{
}
#textResponse{
margin-bottom: 50px;
margin-left: 30px;
}
#appStoreOrange{
margin-top: 20px;
}
.twitter{
width:117px;
height:112px;
display: block;
background: url(images/twitter.png);
margin-left: 280px;
margin-top:-105px;
}
/*.twitter:hover{
background-image: url(images/twitterBlue.png);
}*/
.facebook{
width:117px;
height:112px;
display:block;
background: url(images/facebook.png);
margin-left:400px;
margin-top:-112px;
}
/*.facebook:hover{
background-image:url(images/facebookBlue.png);
}*/
</code></pre>
|
[] |
[
{
"body": "<p>A good tip is to layout in columns and not rows, similar to a newspaper. That is, divide the page into columns and stack the contents as rows, similar to <a href=\"http://pinterest.com/\" rel=\"nofollow noreferrer\">Pinterest</a>. So, in your site, that makes the iPhone 1 column, and the rest in another column. Now this simplifies things.</p>\n\n<p>Stacking the rest as rows controls their bounds and acts as groupings. That way, if one of these rows were to expand like if the slogan has more text, it does not affect the layout of the next row since the next row clears below it cleanly.</p>\n\n<p><img src=\"https://i.stack.imgur.com/oN96B.png\" alt=\"enter image description here\"></p>\n\n<p>As for pseudocode, it looks something like (Sorry, I really hate typing the <code><></code> and <code>{}</code>):</p>\n\n<p>HTML:</p>\n\n<pre><code>div id=\"wrapper\"\n\n div class=\"left\"\n img src=\"iphone.png\"\n\n div class=\"right\"\n\n img class=\"row\" src=\"logo.png\" \n\n p class=\"row\"\n Picking good food fast\n\n p class=\"row\"\n Ever think...\n\n div class=\"row\"\n img src=\"thumb\"\n span\n Yeah...\n\n ul class=\"row\"\n li\n a\n img src=\"appstore.png\"\n li\n a\n img src=\"twitter.png\"\n li\n a\n img src=\"facebook.png\"\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>#wrapper\n overflow:hidden //just a clearfix\n zoom:1 \n\n.row \n display:block //this makes the element a box\n clear:both //nothing is at the left and right, and must be above and below\n\n.left\n float:left\n width: something\n\n.right\n overflow:hidden //ensures that the right column does not wrap around left\n</code></pre>\n\n<hr>\n\n<p>Off-topic:</p>\n\n<p>Substituting text for images is not good for several reasons:</p>\n\n<ul>\n<li>It's a whole lot heavier than text</li>\n<li>SEO (if ever it isn't a myth) isn't that good as they say compared to a text site. So if this is a landing page, better pack it with good description text to summarize the site.</li>\n<li>Without properly titled images, screen readers suffer</li>\n<li>Resizing the browser either squishes the images or if they scale, the text also shrinks making them unreadable.</li>\n<li>Like you mentioned, they are hard to move around</li>\n</ul>\n\n<p>However, a little mix of text and images won't hurt. A general tip is to turn into text whatever can be turned into text. That would be:</p>\n\n<ul>\n<li>Your logo text \"dash\"</li>\n<li>The slogan</li>\n<li>Your catch phrases</li>\n</ul>\n\n<p>And don't forget to mind the semantics. Use the proper tags for the job.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T15:17:53.200",
"Id": "12417",
"ParentId": "12402",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T19:47:13.360",
"Id": "12402",
"Score": "3",
"Tags": [
"html",
"css"
],
"Title": "Laying out images for a landing page"
}
|
12402
|
<p>In order to do its work, a DataProcessor needs Data and otherData.</p>
<p>One instance of Data will be shared over a set of DataProcessor,
but each DataProcessor has its own otherData.</p>
<p>For sharing Data instances, fields of Data could not be defined inside DataProcessor,
thus, there are two hierarchies: Data and DataProcessor.</p>
<p>Each subClass of DataProcessor relates a subClass of Data.</p>
<p>And I have tried three design to fit the requirement, which way is the best? why?</p>
<p>Is my design bad? Why?</p>
<p>Is there any other solution?</p>
<p>Is there any existing design pattern to solve this kind of problem?</p>
<p>It is said that this is a "parallel inheritance hierarchy". Should I avoid this? How? Or is it a good design for my requirement, and do I not need to avoid?</p>
<p>Data hierarchies</p>
<pre><code>abstract class Data {
int field1;
}
abstract class AData extends Data {
int field2;
}
class AAData extends AData {
int field3;
}
class BData extends Data {
int field4;
}
</code></pre>
<p>DataProcessor hierarchies way 1, each super class instance keeps a private reference to Data</p>
<pre><code>abstract class DataProcessor {
private Data data;
protected Object otherData;
DataProcessor(Data data){
this.data = data;
}
void doSomethingUsingDataAndOtherData(){}
}
abstract class ADataProcessor extends DataProcessor {
private AData data;
ADataProcessor(AData data) {
super(data);
this.data = data;
}
void doSomethingUsingADataAndOtherData(){}
}
class AADataProcessor extends ADataProcessor {
private AAData data;
AADataProcessor(AAData data) {
super(data);
this.data = data;
}
void doSomethingUsingAADataAndOtherData(){}
}
class BDataProcessor extends DataProcessor {
private BData data;
BDataProcessor(BData data) {
super(data);
this.data = data;
}
void doSomethingUsingBDataAndOtherData(){}
}
</code></pre>
<p>DataProcessor hierarchies way 2, only top superclass instance keeps a protected reference to Data, when subclass needs to use the data, it has to cast the data to its expected Data subclass. And I don't want to define DataProcessor as DataProcessor, because once introducing generic types, I have to use generic types everywhere, and sometimes using generic types is not so simple (i.e. we can not create a generic array in java).</p>
<pre><code>abstract class DataProcessor {
protected Data data;
protected Object otherData;
DataProcessor(Data data) {
this.data = data;
}
void doSomethingUsingDataAndOtherData(){}
}
abstract class ADataProcessor extends DataProcessor {
ADataProcessor(AData data) {
super(data);
}
void doSomethingUsingADataAndOtherData(){}
}
class AADataProcessor extends ADataProcessor {
AADataProcessor(AAData data) {
super(data);
}
void doSomethingUsingAADataAndOtherData(){}
}
class BDataProcessor extends DataProcessor {
BDataProcessor(BData data) {
super(data);
}
void doSomethingUsingBDataAndOtherData(){}
}
</code></pre>
<p>DataProcessor hierarchies way3, only bottom sub class instance keep a priavte reference to Data, super class use a abstract method getData() to retrieve the Data</p>
<pre><code>abstract class DataProcessor {
protected Object otherData;
protected abstract Data getData();
void doSomethingUsingDataAndOtherData(){}
}
abstract class ADataProcessor extends DataProcessor {
protected abstract AData getData();
void doSomethingUsingADataAndOtherData(){}
}
class AADataProcessor extends ADataProcessor {
private AAData data;
protected AAData getData() {
return data;
}
AADataProcessor(AAData data) {
this.data = data;
}
void doSomethingUsingAADataAndOtherData(){}
}
class BDataProcessor extends DataProcessor {
private BData data;
protected BData getData() {
return data;
}
BDataProcessor(BData data) {
this.data = data;
}
void doSomethingUsingBDataAndOtherData(){}
}
</code></pre>
|
[] |
[
{
"body": "<p>Well, given the examples, i'd avoid inheritance and implement an interface for the DataProcessor.</p>\n\n<pre><code>package net.icodeapps.examples.ooad;\n\npublic interface DataProcessor<T, OtherData> {\n\n T processData();\n}\n</code></pre>\n\n<p>This could be implement by any class like</p>\n\n<pre><code>package net.icodeapps.examples.ooad;\n\npublic class ADataProcessor implements DataProcessor<AData, OtherData> {\n\n private AData aData;\n\n private OtherData otherData;\n\n public ADataProcessor(AData aData, OtherData otherData) {\n this.aData = aData;\n this.otherData = otherData;\n }\n\n @Override\n public AData processData() {\n return aData;\n }\n}\n</code></pre>\n\n<p>Having a second class implementing the interface</p>\n\n<pre><code>package net.icodeapps.examples.ooad;\n\npublic class BDataProcessor implements DataProcessor<BData> {\n\n private BData aData;\n\n private OtherData otherData;\n\n public BDataProcessor(BData aData, OtherData otherData) {\n this.aData = aData;\n this.otherData = otherData;\n }\n\n @Override\n public BData processData() {\n return aData;\n }\n}\n</code></pre>\n\n<p>With more information, still would skip the abstract class. The reason you use it is providing a contract and avoid code replication. But since the code you try to avoid replicating is the problem itself, i'd skip that and just provide private fields to store references. That way you have the right type in processData.</p>\n\n<p>Keeping the processors stateless and just store the data in a queue could be a better approach though. Depending on the data, you would create a processor on demand. The could be implemented via the command processor pattern. Using that pattern, more complexity would be introduced though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T19:15:39.243",
"Id": "20010",
"Score": "0",
"body": "DataProcessor need not only Data but also otherData. in fact the DataProcessor is a Task, and need to be queued, and later to be executed one by one by a thread, so i must put Data inside DataProcessor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T08:36:25.680",
"Id": "20044",
"Score": "0",
"body": "I changed the code because know i have more insight."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T12:06:43.177",
"Id": "20051",
"Score": "0",
"body": "it looks like way3 - only bottom sub class instance keep a priavte reference to Data. and there is another point need to be consider: in the top super class - DataProcessor, i would implement some common logic, so i use abstract class instead of interface. if not for the common logic, i event would not introduce a abstract base class(or base interface). ADataProcessor also has a sub class AADataProcessor. but that is not the key point, the key point is the way of handling Data instance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T12:30:29.040",
"Id": "20053",
"Score": "0",
"body": "You could introduce a stateless abstract super class, which contains the common logic. But you can avoid the accessors and fields, since they don't make any sense in the super class. You want to use covariant fields anyway. Extracting that common logic in a strategy would even make it testable and you could avoid the inheritance chain in the processors."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T09:57:10.490",
"Id": "12413",
"ParentId": "12412",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T05:15:45.097",
"Id": "12412",
"Score": "1",
"Tags": [
"java",
"design-patterns"
],
"Title": "Two related hierarchies of classes"
}
|
12412
|
<p>I'm trying to create a generic function that takes a data structure as input and then sends each non-empty item—e.g.: str, int—individually:</p>
<pre><code>def print_this(v, delim1="", delim2=""):
print v, delim1, delim2
def pass_many(vals, some_funct, args=None):
if vals:
if type(vals) == list or type(vals) == tuple:
for v in vals:
if v:
pass_many(v, some_funct, args)
else:
if args:
some_funct(vals, *args)
else:
some_funct(vals)
>>> pass_many([['foo'],['',(5,3)]], print_this, ["newline","notnewline"])
foo newline notnewline
5 newline notnewline
3 newline notnewline
</code></pre>
<p>My current implementation works reasonably well, but feels hacky...</p>
<p>How could I generalise it to unroll all data-structures (except strings), and make it less hacky?</p>
|
[] |
[
{
"body": "<p>I'd make a few changes: </p>\n\n<p>1) Take the <code>if v</code> check out of the inner loop into the function body (<code>if not vals: return</code>) - seems more consistent that way, unless you want <code>pass_many(0,print)</code> to print something but <code>pass_may([0], print)</code> not to?</p>\n\n<p>2) I'm not sure there's any reason to use <code>args=None</code> and then check for it being <code>None</code>, rather than just doing <code>args=()</code> to start with, and the implementation's shorter that way.</p>\n\n<p>3) There are definitely better ways to check whether something is a tuple/list/set/etc than using type. Unfortunately none of them are perfect... I really wish there was a good clean way of distinguishing these things from strings and dictionaries.<br>\nProbably he most general thing I can come up with, using <a href=\"http://www.python.org/dev/peps/pep-3119/\" rel=\"nofollow\">Abstract Base Classes</a> from <a href=\"http://docs.python.org/library/collections.html#collections-abstract-base-classes\" rel=\"nofollow\">the collections module</a> - it goes over all elements of iterable objects <em>except</em> for mappings (dictionaries etc - unless you want to include those?) and strings (I think the basic string type/s may be different in python3? Not sure.)</p>\n\n<pre><code>from collections import Iterable, Mapping\n\ndef pass_many(vals, some_funct, args=()):\n if not vals:\n return\n if isinstance(vals, Iterable) and not isinstance(vals, (basestring, Mapping)):\n for v in vals:\n pass_many(v, some_funct, args)\n else:\n some_funct(vals, *args)\n</code></pre>\n\n<p>Still, the ABCs aren't perfect - maybe using <code>hasattr</code> checks for whether something is an iterable or a mapping would be better. Not sure. Probably every possible way will have some downsides. </p>\n\n<p>If you want to be more stringent and just accept plain lists and tuples and no other iterables, <code>isinstance(vals, (list, tuple))</code> will be fine. It just won't work on things like iterators - whether that matters depends on the intended use. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T23:19:03.660",
"Id": "20020",
"Score": "0",
"body": "Use `basestring` instead of `str` and `unicode`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T23:23:53.317",
"Id": "20021",
"Score": "0",
"body": "@WinstonEwert - yes, I had just remembered that a few minutes ago. Edited, thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T02:03:16.157",
"Id": "20033",
"Score": "0",
"body": "I've never used the default arg of `()` before, which is why I didn't use it :). Your version seems to work quite nicely, thanks :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T02:19:12.423",
"Id": "20034",
"Score": "0",
"body": "@AT - glad it works! I still wish there was a better solution to the \"all data-structures (except strings)\" problem in python (and the \"all iterables except mappings\" one too), but this should work for all standard python types and hopefully most custom ones."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T21:52:36.440",
"Id": "12421",
"ParentId": "12414",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12421",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T11:34:48.273",
"Id": "12414",
"Score": "2",
"Tags": [
"python",
"generics"
],
"Title": "Generic pass_many(vals, pass_one) to unroll and call pass_one(val)"
}
|
12414
|
<p>I know this may be very time consuming for you as the answerer of this question, but I have recently been looking into C# and I decided that I would try to develop a pinging application, so that I did. I have all the functionality. I just have a question regarding readability and how to set up the individual documents. As for now I only have one document and one class and several methods, but I was wondering whether I should have multiple? I am only using one global variable (<code>path</code>). Also I would like you to comment on the code, if you see somewhere where I could do something differently, optimizing my code.</p>
<p>Here's the code: </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.Threading;
using System.Net.NetworkInformation;
using System.Media;
using System.IO;
using System.Text.RegularExpressions;
namespace PingComplete
{
public partial class Form1 : Form
{
public string pingFilePath = Application.StartupPath + "/ping.dll"; //the file where all the ip addresses are located
public Form1()
{
InitializeComponent();
}
private void Ping(string hostname) //ping function
{
using (Ping ping = new Ping())
{
try
{
PingReply reply = ping.Send(hostname, 100);
if (reply.Status == IPStatus.Success)
{
txtConsole.AppendText("Pinged " + hostname + " at " + reply.Address + " Successfully. \t Time: " + reply.RoundtripTime + " ms \r\n");
}
else if (reply.Status == IPStatus.TimedOut) //Problem with the pings to be too frequently timed out, so a "fix" or "hack" around this.
{
txtConsole.AppendText("Connection time out. Connection retried for " + hostname + "\r\n");
PingReply reply2 = ping.Send(hostname, 100);
txtConsole.AppendText("Pinged " + hostname + " at " + reply2.Address + " Successfully. \t Time: " + reply2.RoundtripTime + " ms \r\n");
}
else
{
txtConsole.AppendText("Couldn't ping " + hostname + "; Error: " + reply.Status + ".\r\n");
playAlertSound();
Console.WriteLine(reply.Status);
}
}
catch
{
txtConsole.AppendText("Error in hostname.\r\n");
}
}
}
public void updateListWithAddresses() //Reloads the list in the sidebar with newest addresses
{
if (File.Exists(pingFilePath))
{
listAddresses.Items.Clear();
string[] fileContents = File.ReadAllLines(pingFilePath);
listAddresses.Items.AddRange(fileContents);
}
}
public void playAlertSound() //Alert sound when there's an error, horrible sound - should be revised
{ //Alert sound
SoundPlayer alertSound = new SoundPlayer(@"c:\Windows\Media\chimes.wav");
alertSound.Play();
}
private void saveConsoleData() //logs the console to the file
{
if (txtConsole.Text != "")
{
string pathtohistory = Application.StartupPath + "/history-from-y-" + DateTime.Now.Year + "-m-" + DateTime.Now.Month + "-d-" + DateTime.Now.Day + "-h-" + DateTime.Now.TimeOfDay.Hours + "-m-" + DateTime.Now.TimeOfDay.Minutes + "-s-" + DateTime.Now.TimeOfDay.Seconds + "-ms-" + DateTime.Now.TimeOfDay.Milliseconds + ".txt";
//create file
StreamWriter MyStream = null;
MyStream = File.CreateText(pathtohistory);
MyStream.Close();
using (System.IO.StreamWriter file = new System.IO.StreamWriter(pathtohistory, true))
{
file.WriteLine(txtConsole.Text);
file.Close();
}
}
}
private void newAddress() //adding new address
{
if (File.Exists(pingFilePath))
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(pingFilePath, true))
{
if (txtNewAddress.Text != "")
{
file.WriteLine(txtNewAddress.Text);
txtConsole.AppendText(txtNewAddress.Text + " was added, now go ping it!\r\n");
file.Close();
updateListWithAddresses();
txtNewAddress.Text = "";
}
else
{
txtConsole.AppendText("You have to write something in the address field. Try again.\r\n");
}
}
}
else
{
//create file
StreamWriter MyStream = null;
MyStream = File.CreateText(pingFilePath);
MyStream.Close();
using (System.IO.StreamWriter file = new System.IO.StreamWriter(pingFilePath, true))
{
file.WriteLine(txtNewAddress.Text);
txtConsole.AppendText(txtNewAddress.Text + " was added, now go ping it!\r\n");
file.Close();
updateListWithAddresses();
}
}
}
private void btnPing_Click(object sender, EventArgs e) //When ping button is clicked
{
for (int i = 0; i < listAddresses.Items.Count; i++)
{
listAddresses.SetSelected(i, true);
Ping(listAddresses.Text);
listAddresses.SetSelected(i, false);
}
txtConsole.AppendText("Query completed.\n");
}
private void btnNewAddress_Click(object sender, EventArgs e) //add new address
{
newAddress();
}
private void Form1_Load(object sender, EventArgs e)
{
llAbout.Links.Add(0, 24, "http://mikkeljuhl.com");
updateListWithAddresses();
}
private void btnDelete_Click(object sender, EventArgs e) //deletes an address from the file and sidebar
{
if (listAddresses.SelectedIndex >= 0)
{
listAddresses.Items.RemoveAt(listAddresses.SelectedIndex);
string[] contentOfFile = new string[listAddresses.Items.Count];
listAddresses.Items.CopyTo(contentOfFile, 0);
File.WriteAllLines(pingFilePath, contentOfFile);
txtConsole.AppendText(listAddresses.Text + " was succcessfully removed!\r\n");
}
}
private void btnClearConsole_Click(object sender, EventArgs e) //clears console
{
txtConsole.Clear();
}
private void llAbout_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string target = e.Link.LinkData as string;
System.Diagnostics.Process.Start(target);
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
saveConsoleData();
}
private void txtNewAddress_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
newAddress();
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T15:41:44.260",
"Id": "20009",
"Score": "3",
"body": "Run StyleCop on it, learn about `StringBuilder`, String.Format, about `static`, `readonly` modifiers. http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html. Run StyleCop on it. If you have ReSharper, use that too ;) but it does cost money. `Path.Combine` is useful too. Some things are better off marked as static and initialized at the top of the class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T22:49:00.327",
"Id": "20016",
"Score": "0",
"body": "Please include the design level information like Class Diagram, Use cases, etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T04:57:19.460",
"Id": "20103",
"Score": "0",
"body": "There is a reason why you are not getting replies ..."
}
] |
[
{
"body": "<p>You have a 338 character line, find a way to split up your long lines.</p>\n\n<hr>\n\n<p>You don't need to fully qualify things that you have a using statement for: <code>System.IO.StreamWriter</code> could be <code>StreamWriter</code> because you have a <code>using System.IO;</code> at the start of the file.</p>\n\n<hr>\n\n<p>These using statements aren't needed:</p>\n\n<pre><code>using System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Text.RegularExpressions;\n</code></pre>\n\n<hr>\n\n<p>Default value of a variable is null, usually no need to set it explicity. In fact why not just combine these two lines.</p>\n\n<pre><code>StreamWriter MyStream = null;\nMyStream = File.CreateText(pathtohistory);\n</code></pre>\n\n<hr>\n\n<p><code>succcessfully</code> is spelled wrong.</p>\n\n<hr>\n\n<p>I didn't look at your logic, cleanup your code, including some of the things mentioned in the comments and someone might be able to look at it in more detail.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T21:13:07.270",
"Id": "12596",
"ParentId": "12415",
"Score": "4"
}
},
{
"body": "<p>I don't code C#, so just two general notes:</p>\n\n<ol>\n<li><p>If I'm right you are storing configuration in a <code>dll</code> file (<code>ping.dll</code>). DLL extension is usually used for executable code, not for config files.</p></li>\n<li><p>I guess there are better ways to format a datetime than concatenating strings: (<a href=\"http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx\" rel=\"nofollow\">Custom Date and Time Format Strings</a>)</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T12:49:27.697",
"Id": "14369",
"ParentId": "12415",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T12:49:49.527",
"Id": "12415",
"Score": "2",
"Tags": [
"c#",
".net"
],
"Title": "Pinging application"
}
|
12415
|
<p>I'm trying declare a string in ANSI C and am not sure of the best way to do it.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
char *InitStr(char *ReturnStr){
ReturnStr = NULL;
ReturnStr = realloc( ReturnStr, strlen("") +1 );
strcpy( ReturnStr , "");
return ReturnStr;
}
char *AddStr(char *StrObj1,char *StrObj2){
StrObj1 = realloc(StrObj1,(strlen(StrObj1) + strlen(StrObj2)+1));
strcat(StrObj1, StrObj2);
return StrObj1 ;
}
char *JoinStr(const char *fmt, ...) {
char *p = NULL;
size_t size = 30;
int n = 0;
va_list ap;
if((p = malloc(size)) == NULL)
return NULL;
while(1) {
va_start(ap, fmt);
n = vsnprintf(p, size, fmt, ap);
va_end(ap);
if(n > -1 && n < size)
return p;
// failed: have to try again, alloc more mem.
if(n > -1) // glibc 2.1
size = n + 1;
else //* glibc 2.0
size *= 2; // twice the old size
if((p = realloc (p, size)) == NULL)
return NULL;
}
}
main(){
printf("\n");
char *MyLocalString = InitStr(MyLocalString);
printf("InitStr: %s\n",MyLocalString);
printf("---------------------------------------------------\n");
AddStr(MyLocalString ,"Hello String!");
printf("1. AddStr: %s\n",MyLocalString);
printf("---------------------------------------------------\n");
AddStr(MyLocalString ,"\n\tAdd more string 1");
printf("2. AddStr: %s\n",MyLocalString);
printf("---------------------------------------------------\n");
AddStr(MyLocalString ,"\n\tAdd more string 2");
printf("3. AddStr: %s\n",MyLocalString);
printf("---------------------------------------------------\n");
//MyLocalString = AddStr(MyLocalString ,"\n Add more string");
MyLocalString = AddStr(MyLocalString ,JoinStr("%s%s%s", "\n\tString3", "\n\tString2", "\n\tString3"));
printf("4. JoinStr: %s\n",MyLocalString);
printf("---------------------------------------------------\n");
printf("\n");
}
</code></pre>
<p>In this code I have 3 functions to handle the string:</p>
<ol>
<li><code>InitStr</code> - to initial string </li>
<li><code>AddStr</code> - to add string</li>
<li><code>JoinStr</code> -to Join string</li>
</ol>
<p>The code works fine, however, I am not sure if this is a decent way of handling a string since I am using pointers.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T23:25:14.247",
"Id": "20023",
"Score": "3",
"body": "for a beginner, this is reasonable source code. the `char *InitStr(char *ReturnStr){\n ReturnStr = NULL; ...} however, makes no sense. Why give an argument to a function, knowing that the first thing the function does is setting it to NULL ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T23:26:38.380",
"Id": "20024",
"Score": "0",
"body": "Hopefully useful: http://www.gratisoft.us/todd/papers/strlcpy.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T23:34:44.257",
"Id": "20025",
"Score": "0",
"body": "InitStr will work but consider `char* EmptyStr(void){ return strdup(\"\"); }`"
}
] |
[
{
"body": "<p>This question might be more appropriate for programmers or codereview, but, this is what a code review of mine, probably with at least one controversial statement inside somewhere, would go like. Hopefully you will find some advice in here that answers your questions.</p>\n\n<p>1) Make sure you want to be using C and not C++ (or Java, Perl...) for whatever you're doing. If you can avoid doing strings in C in real life code, always. Use C++ strings instead. And if you want a sturdy C library to do this in, consider glib (or writing C++ wrappers).</p>\n\n<p>2) If you want to write a full ADT (abstract data type) for strings, follow the usual C paradigm: You should have functions <code>mystring_init</code>, <code>mystring_{whateveroperations}</code>, and <code>mystring_cleanup</code>. The init will typically have a <code>malloc</code> and if so cleanup will definitely have <code>free</code>. The <code>realloc</code>s I think (not sure) are only safe provided <code>malloc</code> happens first and <code>free</code> last, which without an <code>init</code> that <code>malloc</code>s would be bad. </p>\n\n<p>3) But in real life I think an ADT for strings, which experienced C developers can program in pretty fluently, will make the code less readable, not more.</p>\n\n<p>4) Always work on the stack when possible. <code>char str[STR_MAX_SIZE]</code> is preferable to dynamic strings when possible, and it's possible more than most developers think. A few wasted bytes from safely overestimating is worth avoiding a crash or leak from dynamic memory usage. And your function <code>JoinStr</code> from its signature looks like it will accept a stack variable as its first argument, then bam! realloc. If you're going to do something sneaky like this, it pretty much has to be with an ADT you wrote via a pattern similar to (2).</p>\n\n<p>5) Along those lines, the usual way to pass a string to a function is <code>myoperation(char* str, size_t size);</code> so the caller is responsible for memory management - and in particular gets to choose whether it's stack or heap - and the inside of the function just respects those parameters passed. If you braek this I strongly recommend the ADT pattern in (2).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T23:40:53.313",
"Id": "12429",
"ParentId": "12428",
"Score": "1"
}
},
{
"body": "<p>I have a few suggestions.</p>\n\n<p>First you are not verifying that realloc() properly allocated memory. When using realloc() you should use two pointers so you can properly check for a successful allocation:</p>\n\n<pre><code>char * increaseBuffer(char * buff, size_t newBuffSize)\n{\n void * ptr;\n\n // adjust buffer size\n ptr = realloc(buff, newBuffSize);\n\n // verify allocation was successful\n if (ptr == NULL)\n {\n perror(\"realloc()\"); // prints error message to Stderr\n return(buff);\n };\n\n // adjust buff to refer to new memory allocation\n buff = ptr;\n\n /* use buffer for something */\n\n return(buff);\n};\n</code></pre>\n\n<p>Since your InitStr() function is only providing an initial allocation, you can simplify it to:</p>\n\n<pre><code>char *InitStr(){\n char * ReturnStr;\n\n // allocate new buffer\n ReturnStr = malloc(1);\n\n // verify allocation was successful before using buffer\n if (ReturnStr != NULL)\n ReturnStr[0] = '\\0';\n\n // return buffer\n return(ReturnStr);\n}\n</code></pre>\n\n<p>This could also be condensed a little more:</p>\n\n<pre><code>char *InitStr(){\n char * ReturnStr;\n\n if ((ReturnStr = malloc(1)) != NULL)\n ReturnStr[0] = '\\0';\n\n return(ReturnStr);\n}\n</code></pre>\n\n<p>Here is another example of checking your allocation using your AddStr() function:</p>\n\n<pre><code>char *AddStr(char *StrObj1,char *StrObj2){\n void * ptr;\n ptr = realloc(StrObj1,(strlen(StrObj1) + strlen(StrObj2) + 1));\n if (ptr == NULL)\n return(StrObj1);\n StrObj1 = ptr;\n strcat(StrObj1, StrObj2);\n return(StrObj1);\n}\n</code></pre>\n\n<p>You can slightly improve the runtime efficiency of this function be reducing the number of times you need to find the terminating NULL character in your strings:</p>\n\n<pre><code>char *AddStr(char *StrObj1,char *StrObj2){\n void * ptr;\n size_t len1;\n size_t len2;\n\n // determine length of strings\n len1 = strlen(StrObj1);\n len2 = strlen(StrObj2);\n\n // increase size of buffer\n if ((ptr = realloc(StrObj1, (len1 + len2 + 1))) == NULL)\n return(StrObj1);\n StrObj1 = ptr;\n\n // this passes a pointer which references the terminating '\\0' of\n // StrObj1. This makes the string appear to be empty to strcat() which\n // in turn means that it does not compare each character of the string\n // trying to find the end. This is a minor performance increase, however if\n // running lots of string operations in a high iteration program, the combined\n // affect could be substantial. \n strcat(&StrObj1[len1], StrObj2);\n\n return(StrObj1);\n}\n</code></pre>\n\n<p>You can complete your last function without the while loop:</p>\n\n<pre><code>char *JoinStr(const char *fmt, ...)\n{\n\n int len;\n char * str;\n void * ptr;\n va_list ap;\n\n // start with a small allocation to pass to vsnprintf()\n if ((str = malloc(2)) == NULL)\n return(NULL);\n str[0] = '\\0';\n\n // run vsnprintf to determine required length of string\n va_start(ap, fmt);\n len = vsnprintf(str, 2, fmt, ap);\n va_end(ap);\n\n if (len < 2)\n return(str);\n\n // allocate enound space for entire formatted string\n len++;\n if ((ptr = realloc(str, ((size_t)len))) == NULL)\n {\n free(str);\n return(NULL);\n };\n\n // format string\n va_start(ap, fmt);\n vsnprintf(str, len, fmt, ap);\n va_end(ap);\n\n return(str);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T00:49:39.210",
"Id": "20029",
"Score": "0",
"body": "thank you for reviewing my code. your suggestions are greatly appreciated. However, I have 2 more thing to ask. 1. where/why use `char * increaseBuffer()` since i have `char *AddStr(char *StrObj1,char *StrObj2)`? 2. should i use `free(MyString)` before exit the program?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T01:55:54.247",
"Id": "20032",
"Score": "0",
"body": "@FlanAlflani 1. `increaseBuffer()` is just a hypothetical example and is not used within your program. 2. Yes, you are correct. Any memory you allocate, must also free before you exit the program or re-use the pointer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T05:46:36.437",
"Id": "20038",
"Score": "0",
"body": "Just as a nitpick the correct prototype would be `char *InitStr(void)`. With empty `()` at the call side this is only \"known\" as a function that receives any kind of argument, so some error checking would be off."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T13:02:33.887",
"Id": "20057",
"Score": "0",
"body": "@David I keep getting `*** glibc detected *** ./myprogram: munmap_chunk(): invalid pointer: 0x0000000002588ca0 ***` when try to use JoinStr"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T00:13:15.627",
"Id": "12430",
"ParentId": "12428",
"Score": "3"
}
},
{
"body": "<pre><code>char *InitStr(char *ReturnStr){\n ReturnStr = NULL; \n</code></pre>\n\n<p>This line throws away whatever the user passed in as the parameter</p>\n\n<pre><code> ReturnStr = realloc( ReturnStr, strlen(\"\") +1 );\n</code></pre>\n\n<p>This throws away what the previous line does. It should also be pretty obvious the strlen(\"\") is, so why calculate it?</p>\n\n<pre><code> strcpy( ReturnStr , \"\");\n</code></pre>\n\n<p>This line only ends up doing the same as <code>ReturnStr[0] = '\\0'</code></p>\n\n<pre><code> return ReturnStr;\n}\n</code></pre>\n\n<p>The whole function should be written as <code>strdup(\"\")</code>.</p>\n\n<p>You assume that a negative return value means not enough memory was provided. However, its possible that any of a number of things could have gone wrong. If something else wrong, bad format string for example, this function will sit there exhausting your memory trying to fill out the string.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T00:17:47.500",
"Id": "12431",
"ParentId": "12428",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12430",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-09T23:19:00.373",
"Id": "12428",
"Score": "3",
"Tags": [
"c",
"strings"
],
"Title": "String in ANSI C?"
}
|
12428
|
<p>As a learning process I created 'reverse' function in a few different ways. Tinkering with 'reverse' made currying, folds and other stuff easier to understand. Almost natural!</p>
<p>I know these are trivial things for someone who had years of Haskell practice. Try to look at if from the perspective of real beginner. <a href="http://www.imdb.com/title/tt0441773/quotes?qt0511936" rel="nofollow">Level zero</a> </p>
<p><strong>Edit: New version is added in the new post.</strong> </p>
<p>Questions:</p>
<ul>
<li>I don't know names of each recursions. Regular recursion, tail, head, flat...?</li>
<li>=== should be the same but...</li>
<li>??? are things I don't know.</li>
<li>I think my comments are correct, but I'm not 100% sure.</li>
<li>did I get grouping ok?</li>
<li>anything you want to add to this list, change,</li>
<li>any suggestion how to improve this will be most welcome</li>
</ul>
<blockquote>
<p>How to read the code:</p>
<ul>
<li><p>revA, revB, revC... are grouping of similar versions of reverse.</p></li>
<li><p>numbers are sub-versions in a group:</p></li>
<li>1 original</li>
<li>2 where</li>
<li>3 let</li>
<li>4 case of </li>
<li>' currying, argument free</li>
</ul>
</blockquote>
<p>.<br>
.<br>
.
Recursions, <a href="http://www.imdb.com/title/tt0441773/quotes?qt0545403" rel="nofollow">level zero</a></p>
<pre><code>
{- can't be argument free because we need (x:xs) to decompile arg
This is pattern match, pattern can not be curried!
recursion name ??? -}
revA1 [] = [] -- next one is faster, but fails on [] - dave4420
-- revA1 (x:[]) = [x] -- === revA1 [x] = [x]
revA1 (x:xs) = revA1 xs ++ [x]
{- If we wrap pattern match in function, currying becomes possible: revA2'
help === revA1
recursion name ??? -}
revA2 xs = help xs -- revA2' = help -- curried help
where
help [] = []
help (b:bs) = help bs ++ [b]
revA3 xs = let
help [] = []
help (b:bs) = help bs ++ [b]
in help xs
revA3' = let
help [] = []
help (b:bs) = help bs ++ [b]
in help
revA4 y = case y of -- blufox
[] -> []
(x:xs) -> revA4 xs ++ [x]
--
revB1 xs = foldl (flip (:)) [] xs
revB1' = foldl (flip (:)) [] -- foldl takes 3 args. supplying only two args rev2 becomes curried f waiting for third arg
revB2 xs = foldl step [] xs -- === revB2' = foldl step []
where step acc x = x:acc -- === flip (:)
revB3 xs = let
step acc x = x:acc
in foldl step [] xs
revB3' = let
step acc x = x:acc
in foldl step []
--
--revC1 = foldl (flip (++)) [] -- doesn't work: [] ++ Char
revC1 xs = foldl (\acc x -> [x] ++ acc) [] xs
revC1' = foldl (\acc x -> [x] ++ acc) []
revC2 xs = foldl step [] xs -- revC2' = foldl step []
where step acc x = [x] ++ acc -- === (\acc x -> [x] ++ acc)
revC3 xs = let
step acc x = [x] ++ acc
in foldl step [] xs
revC3' = let
step acc x = [x] ++ acc
in foldl step []
--
revD1 xs = foldr step [] xs -- revD1' = foldr step []
where step x acc = acc ++ [x] -- === (\x acc -> acc ++ [x])
revD2 xs = foldr (\x acc -> acc ++ [x]) [] xs
revD2' = foldr (\x acc -> acc ++ [x]) []
--
-- don't know how to do it with only (:)
--revE1 xs = foldr step [] xs
-- where step x acc = ??? : ???
revF1 xs = help xs [] -- must have xs param!
where
help [] acc = acc -- brake recursion
help (b:bs) acc = help bs (b:acc)
-- but if we use flip
revF1' = flip help []
where
help [] acc = acc -- brake recursion
help (b:bs) acc = help bs (b:acc)
-- or flip params manualy
revF2 xs = help [] xs -- === revF2' = help []
where
help acc [] = acc
help acc (b:bs) = help (b:acc) bs
revG1 xs = help [] xs -- revG1' = help []
where
help acc [] = acc
help acc (b:bs) = help ([b]++acc) bs
</code></pre>
<p>.<br>
.<br>
.</p>
<h2>Test Functions:</h2>
<pre><code>
functions =
[revA1, revA2, revA3, revA3',
revB1, revB1', revB2, revB3, revB3',
revC1, revC1', revC2, revC3, revC3',
revD1, revD2, revD2',
revF1, revF2,
revG1
]
-- return [] of reversed param
tf1 [] param = []
tf1 (x:xs) param = (x param) : tf1 xs param
-- True if all functions return result equal as reverse param
tf2 xs param = foldl step True xs
where
p = reverse param
step acc x = (x param == p) && acc
--tfs :: [t -> t1] -> t -> IO [Double] -- ???
--tfs xs param = foldl' step [] xs
-- where step acc x = time2 (x param) : acc
tf1 functions "some string"
tf2 functions "some string"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T04:08:18.387",
"Id": "20036",
"Score": "0",
"body": "Let's try [codereview.se] since you appear to have functional code already."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T08:21:55.790",
"Id": "20043",
"Score": "0",
"body": "Because your A functions use `[x]` as the base case instead of `[]`, they result in a pattern match failure when given `[]` as input. You are worrying about speed, but do not forget about correctness."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T10:10:07.047",
"Id": "20045",
"Score": "0",
"body": "@dave4420: Ha, you are absolutely right :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T10:24:56.127",
"Id": "20046",
"Score": "0",
"body": "@All: Should I edit original post to update what I've just learned or create new one? First solution is compact, second will preserve each change."
}
] |
[
{
"body": "<p>I do not know much about performance of each versions because GHC has various optimizations built in, and I have not kept up to date with them. The best option for checking that is to benchmark the code in question.</p>\n\n<p>Here are my updates,</p>\n\n<pre><code>import Test.HUnit\n\n-- revA1 [] = [] \n-- is next one faster? - don't know but it is unlikely to be very much different.\nrevA1 [x] = [x] -- I prefer this notation\nrevA1 (x:xs) = revA1 xs ++ [x] -- I didn't understand your comment here.\n</code></pre>\n\n<p>You can also write it as</p>\n\n<pre><code>revA1' y = case y of\n [] -> []\n (x:xs) -> revA1' xs ++ [x]\n</code></pre>\n\n<p>this is equivalent to the [x] in your example, but using :</p>\n\n<pre><code>revD1 xs = foldr step [] xs\n where step x acc = acc ++ ((:) x [])\n</code></pre>\n\n<p>can use flip here to eliminate xs param</p>\n\n<pre><code>revF1= flip help []\n where\n help [] acc = acc -- brake recursion\n help (b:bs) acc = help bs (b:acc)\n</code></pre>\n\n<p>Use HUnit to write unit tests and run them</p>\n\n<pre><code>tests = TestList [\n TestLabel \"tA1\" testA1,\n TestLabel \"tD1\" testD1,\n TestLabel \"tF1\" testF1\n ]\n\ntestA1 = TestCase $ assertEqual \"aA1\" \"olleH\" (revA1 \"Hello\")\ntestD1 = TestCase $ assertEqual \"aD1\" \"olleH\" (revD1 \"Hello\")\ntestF1 = TestCase $ assertEqual \"aF1\" \"olleH\" (revF1 \"Hello\")\n\n-- execute tt to run all tests.\ntt = runTestTT tests \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T10:38:59.090",
"Id": "20047",
"Score": "0",
"body": "I thought `revA1 (x:xs) = revA1 xs ++ [x]` can not be written as curried f because you need (x:xs) to decompile argument in `revA1 (x:xs) = ...` The truth is you can not curry pattern match. You need to wrap it in another f. I thought revA2 was just useless wrapper :D It turned out it was an eye opener :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T07:11:56.427",
"Id": "12434",
"ParentId": "12432",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12434",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T02:14:48.300",
"Id": "12432",
"Score": "3",
"Tags": [
"haskell",
"recursion"
],
"Title": "Haskell recursions, level zero"
}
|
12432
|
<p>I need to write a service to return objects in pages of size 20. The caching of these objects is done in pages of size 60.</p>
<p>To abstract the logic of streaming differently-sized pages, I wrote this <code>PagingAdapter</code> class:</p>
<pre><code>public abstract class PagingAdapter<T> implements Iterable<List<T>> {
private final int callerPageSize;
private final int sourcePageSize;
private final LoadingCache<Integer, List<T>> localCache =
CacheBuilder.newBuilder().build(new CacheLoader<Integer, List<T>>() {
@Override
public List<T> load(Integer sourcePageNumber) throws Exception {
return fetchPageFromSource(sourcePageNumber);
}
});
public PagingAdapter(int callerPageSize, int sourcePageSize) {
Preconditions.checkArgument(callerPageSize > 0, "callerPageSize must be greater than 0.");
Preconditions.checkArgument(sourcePageSize > 0, "sourcePageSize must be greater than 0.");
this.callerPageSize = callerPageSize;
this.sourcePageSize = sourcePageSize;
}
/**
* Returns a List of objects from the source for the specified page.
*
* <p>If the returned List is smaller in size than the source page size, that
* means there are no further source pages.
*
* @param sourcePageNumber The requested page.
* @return The List of objects.
* @throws Exception
*/
protected abstract List<T> fetchPageFromSource(int sourcePageNumber) throws Exception;
/**
* Returns a List of objects for the specified page, as defined by the caller
* page size.
*
* <p>If the returned List is smaller in size than the caller page size, that
* means there are no further pages available.
*
* @param callerPageNumber The requested page.
* @return The List of objects.
*/
public List<T> getPage(int callerPageNumber) {
Preconditions.checkArgument(callerPageNumber > 0, "callerPageNumber must be greater than 0.");
List<T> callerPage = Lists.newArrayListWithCapacity(callerPageSize);
int numLeftToFetch;
while ((numLeftToFetch = callerPageSize - callerPage.size()) > 0) {
int fetchFromAbsoluteIndex = (callerPageNumber * callerPageSize) - numLeftToFetch;
int sourcePageNumber = IntMath.divide(fetchFromAbsoluteIndex + 1, sourcePageSize, RoundingMode.CEILING);
List<T> sourcePage;
try {
sourcePage = localCache.get(sourcePageNumber);
}
catch (ExecutionException exception) {
throw Throwables.propagate(exception.getCause());
}
int sourcePageStartAbsoluteIndex = (sourcePageNumber - 1) * sourcePageSize;
int addFromIndex = fetchFromAbsoluteIndex - sourcePageStartAbsoluteIndex;
int addToIndex = Math.min(addFromIndex + numLeftToFetch, sourcePage.size());
if (addFromIndex >= addToIndex) {
break;
}
callerPage.addAll(sourcePage.subList(addFromIndex, addToIndex));
if (sourcePageSize - sourcePage.size() > 0) {
break; //this optimization assumes a partial page is the last one
}
}
return callerPage;
}
@Override
public Iterator<List<T>> iterator() {
return new Itr();
}
private class Itr implements Iterator<List<T>> {
private int currentPageNumber = 0;
private List<T> currentPage = null;
@Override
public boolean hasNext() {
initIfNeeded();
return !currentPage.isEmpty();
}
@Override
public List<T> next() {
initIfNeeded();
List<T> temp = currentPage;
currentPage =
(currentPage.size() < callerPageSize)
? Collections.<T>emptyList() //this optimization assumes a partial page is the last one
: getPage(++currentPageNumber);
return temp;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
private void initIfNeeded() {
if (currentPage == null) {
currentPage = getPage(++currentPageNumber);
}
}
}
/*** TESTING ***/
public static void main(String[] args) {
testHelper(10);
testHelper(5);
testHelper(3);
testHelper(13);
testHelper(58);
}
private static void testHelper(int callerPageSize) {
final TestSource ts = TestSource.INSTANCE;
PagingAdapter<String> pg = new PagingAdapter<String>(callerPageSize, ts.getPageSize()) {
@Override
protected List<String> fetchPageFromSource(int sourcePageNumber) {
return ts.get(sourcePageNumber);
}
};
System.out.println("caller page size = " + callerPageSize);
int pageNum = 0;
for (List<String> lst : pg) {
System.out.println("page " + ++pageNum + " (" + lst.size() + "): " + lst);
}
System.out.println();
}
private static class TestSource {
public static final TestSource INSTANCE = new TestSource();
private final String[][] store = {
{ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"},
{"11", "12", "13", "14", "15", "16", "17", "18", "19", "20"},
{"21", "22", "23", "24", "25", "26", "27", "28", "29", "30"},
{"31", "32", "33", "34", "35", "36", "37", "38", "39", "40"},
{"41", "42", "43", "44", "45", "46", "47", },
};
private TestSource() { }
public List<String> get(int page) {
try {
return Arrays.asList(store[page - 1]);
}
catch (ArrayIndexOutOfBoundsException aioobe) {
return Collections.emptyList();
}
}
public int getPageSize() {
return store[0].length;
}
public int getNumPages() {
return store.length;
}
}
}
</code></pre>
<p>I mainly want to make sure the <code>getPage</code> method is correct and optimal. The <code>Iterator</code> is less important. I included the "testing" section at the bottom for your convenience and as a usage example.</p>
<p>Note that the code is using <a href="http://code.google.com/p/guava-libraries/wiki/Release12">Guava 12</a>.</p>
<p><strong>Edit:</strong> I added memoization of pages fetched from source using Guava's <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/cache/LoadingCache.html"><code>LoadingCache</code></a>. I also declared <code>fetchPageFromSource</code> as throwing <code>Exception</code> so implementations can just let all exceptions propagate - <code>getPage</code> will unwrap these from <code>ExecutionException</code> and rethrow them using <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Throwables.html#propagate%28java.lang.Throwable%29"><code>Throwables.propagate</code></a> (or I might consider wrapping them in my own checked <code>PagingException</code>). </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T06:48:07.207",
"Id": "20040",
"Score": "0",
"body": "This is my first time posting on code review - let me know if/how I can improve the question at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-30T12:14:02.517",
"Id": "24664",
"Score": "0",
"body": "I guess you should specify what you'd like to know in an answer. You tagged it with \"optimization\" - what do you want opimized? Readability, speed, memory consumtion? What don't you like about your own code in that regard? Right now, I have a hard time to find the right angle for an answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T14:20:30.133",
"Id": "29974",
"Score": "1",
"body": "If you have unit tests (with assertions), could you include them, please?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T02:53:43.853",
"Id": "30781",
"Score": "0",
"body": "@palacsint Unfortunately I don't - just the cobbled psuedo-testing toward the bottom. I'll try to write unit tests when I get the chance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T02:58:37.807",
"Id": "30782",
"Score": "1",
"body": "@Arne Sorry for the late reply. I was mainly concerned with identifying any clever optimizations that could be done within `getPage` that I may have missed. I'm satisfied with the readability and memory consumption is a lesser concern."
}
] |
[
{
"body": "<p>I like your usage of Guava, and overall your code seems really good. I might actually use it myself somewhere.</p>\n<p>The code could use some more Javadoc though, especially on the class itself and the constructor. Explaining those <code>callerPageSize</code> and <code>sourcePageSize</code> parameters is very important.</p>\n<h3>Possible extension</h3>\n<p>Currently, you leave some work for the user of your code to divide it into some fixed page size. What if that programmer is very lazy and don't want to do that? An optional constructor could be helpful to indicate that technically, you support that feature.</p>\n<pre><code>public PagingAdapter(int callerPageSize) {\n this(callerPageSize, 1);\n</code></pre>\n<p>However, if you add that optional constructor; the users will have to send your code a List of size one. That's not optimal. Perhaps a class to create pagination without some previously already existing pagination would be useful? (This is actually what I expected from your code when I first saw the class name of it)</p>\n<h3>A possible bug</h3>\n<p>Your variable <code>sourcePageSize</code> confused me a bit at first, even though it sounds like it should be equal to <code>sourcePage.size()</code> there is absolutely nothing that forces it to be so.</p>\n<p>What if <code>fetchPageFromSource</code> returns a list that <strong>does not</strong> correspond to the <code>sourcePageSize</code> that the class got? I can tell you what happens:</p>\n<p>Adding one extra string to the second page of your example causes it to be completely ignored for some <code>callerPageSize</code>s, and for other values of callerPageSize the first absolute index directly after is ignored.</p>\n<p>Also, if <code>fetchPageFromSource</code> accidentally returns a list of size <em>less</em> that <code>sourcePageSize</code> <strong>before</strong> it actually is over, then that effectively cuts the list so that the last items does not get seen. By removing the item <code>"20"</code> in your example, the list always stopped at 19 for values of <code>callerPageSize</code>.</p>\n<p>Possible Solution: Throw an exception if the <code>fetchPageFromSource</code> method returns a list of a bigger size than what was expected. Solving the problem of an incorrect smaller list is more difficult because of your optimization of smaller lists == no more items.</p>\n<p>Even though this might be by design, it is very important to document this behavior.</p>\n<p>Another possible problems might encounter when using your class is that if <code>fetchPageFromSource</code> returns null; this causes <code>InvalidCacheLoadException</code> (caused by Guava). This should either be fixed or documented. Returning null might be a way for a programmer to try and tell your code: "This page does not exist".</p>\n<p>Remember that when writing code for other people to use, they might not use it in the way that is intended.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T01:31:10.010",
"Id": "67627",
"Score": "0",
"body": "Thanks for the good points. A variation of the code I posted is being used in production and has been successful - I'll make sure to review it to see if what you suggest can be applied."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T19:27:57.987",
"Id": "37617",
"ParentId": "12433",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37617",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T06:47:07.410",
"Id": "12433",
"Score": "8",
"Tags": [
"java",
"optimization",
"pagination"
],
"Title": "Streaming pages of a different size than a cache's pages"
}
|
12433
|
<p>This is my first VBScript I have ever written and I would like to know if there is any obvious blunders in the code. All the code should do is check if file exists then change the Yahoo URL to the Google URL in the XML file. Note: The code seems to function properly.</p>
<pre><code>Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
If (objFSO.FileExists("C:\urlsinfo.xml")) Then
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Dim textToReplace
Dim textReplacement
textToReplace = "http://www.yahoo.com"
textReplacement = "http://www.google.com"
Set objFile = objFSO.OpenTextFile("C:\urlsinfo.xml", ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, textToReplace, textReplacement)
Set objFile = objFSO.OpenTextFile("C:\urlsinfo.xml", ForWriting)
objFile.WriteLine strNewText
objFile.Close
WScript.Quit()
Else
Dim errorFileSys, errorLogTxt
Set errorFileSys = CreateObject("Scripting.FileSystemObject")
Set errorLogTxt = errorFileSys.OpenTextFile("C:\urlsinfoError.log", ForAppending, True)
errorLogTxt.WriteLine(Now &" urlsinfo.xml file did not exist in directory C:\. ")
errorLogTxt.Close
WScript.Quit()
End If
'Exit Script
WScript.Quit()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T12:51:15.477",
"Id": "20055",
"Score": "5",
"body": "This isn’t an answer but I *strongly* suggest you drop VBScript, which is old, unmaintained and a horrible, hacky mess, and use a modern scripting language (such as Python) instead. Even at the height of its usage VBS was *never* very good and since there are now tools to replace it, there’s simply no use-case where it’s ever appropriate. The last version of VBS was released over 10 years ago, before .NET came out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T15:52:33.053",
"Id": "62376",
"Score": "1",
"body": "`C:\\urlsinfo.xml` should be a named constant. It occurs multiple times in the code."
}
] |
[
{
"body": "<p>I reworked your VBScript a bit with comments, see below. In response to the comment from Konrad, I can agree with him for 90% of the cases. VBScript stays interesting for system management, logon scripts, etc., but I myself am replacing it with Ruby which isn't a big step up from VBScript, and on the other hand it has almost all the goodies from python. If you want to compare, take a look at e.g. <a href=\"http://yagni.com/rosetta-stone/#0\" rel=\"nofollow\">http://yagni.com/rosetta-stone/#0</a> (what happened to <a href=\"https://rosettacode.org/\" rel=\"nofollow\">https://rosettacode.org/</a> ?). You'll see that the Ruby code is most of the time the smallest and the most comprehensible.</p>\n\n<p>The adapted VBScript version:</p>\n\n<pre><code>Option explicit 'always use this\n'declarations first, be concise\nConst ForReading = 1, ForWriting = 2, ForAppending = 8, CreateIfNeeded = true\nDim objFSO, objFile, textToReplace, textReplacement, strNewText, strText\nDim errorFileSys, errorLogTxt, urlsinfo\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\nIf objFSO.FileExists(urlsinfo) Then 'indent\n textToReplace = \"http://www.yahoo.com\"\n textReplacement = \"http://www.google.com\"\n urlsinfo = \"C:\\urlsinfo.xml\"\n Set objFile = objFSO.OpenTextFile(urlsinfo, ForReading)\n strText = objFile.ReadAll\n objFile.Close\n strNewText = Replace(strText, textToReplace, textReplacement)\n Set objFile = objFSO.OpenTextFile(urlsinfo, ForWriting)\n objFile.WriteLine strNewText\n objFile.Close\nElse\n Set errorFileSys = CreateObject(\"Scripting.FileSystemObject\")\n Set errorLogTxt = errorFileSys.OpenTextFile(\"C:\\urlsinfoError.log\", ForWriting, CreateIfNeeded) \n errorLogTxt.WriteLine(Now &\" urlsinfo.xml file did not exist in directory C:\\. \")\n errorLogTxt.Close\n Wscript.Quit 1 'you could use quit here to give an errorlevel back to the OS\nEnd If\n\n'Exit Script 'no need for obvious comments\n'WScript.Quit() 'no need for this at the end of the script\n'also quit is a sub, no need for the ()\n</code></pre>\n\n<p>And the same script in Ruby:</p>\n\n<pre><code>urlsinfo, urlsinfoError = \"C:/urlsinfo.xml\", \"c:/urlsinfoError.log\"\ntextToReplace, textReplacement = \"http://www.yahoo.com\", \"http://www.google.com\"\n\nbegin\n File.write(urlsinfo, File.read(urlsinfo).gsub(textToReplace, textReplacement))\nrescue\n File.write(urlsinfoError, \"#{Time.now} urlsinfo.xml file did not exist in directory C:\\. \")\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T15:12:01.897",
"Id": "20059",
"Score": "0",
"body": "Thank you both for your replies. Peter thanks for the rework. It definitely helps me understand how to approach the code in a much better way.Wow look at Ruby! 7 lines and done!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T14:30:34.910",
"Id": "62476",
"Score": "0",
"body": "Hey are you still around? we have a need for VBScript Programmers here on Code Review, I hope that you come back to CR. even if it is to tell me my code looks like crap"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T15:44:06.020",
"Id": "62899",
"Score": "0",
"body": "I know you said that you are writing in Ruby, we have several Ruby Questions, I will eventually learn Ruby ( my cousin teaches it ) but I can only help with the logic as is right now."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T14:29:25.167",
"Id": "12441",
"ParentId": "12439",
"Score": "6"
}
},
{
"body": "<h2>Possible Error?</h2>\n\n<p>Another thing that I noticed is that you have not Declared <code>objFile</code> in your code??\nI am not sure if you meant to do this or not, I haven't tested this code, but I left <code>objFile</code> alone because you do set it twice, for some reason I want to say that you should <code>Dim</code> and then <code>ReDim</code> that variable/object or <strong>probably a better idea</strong> create one for reading and another for writing.</p>\n\n<hr>\n\n<ol>\n<li><p>you can't get away with not Indenting in Python or Ruby, and not indenting in any flavor of VB is really bad coding practice, it would be much different if the language used semi-colons or line terminators, but it doesn't so indentation helps everyone know where they are.</p></li>\n<li><p>don't Declare variables inside of <code>If</code>'s, <code>For</code>'s or other blocks unless they are only going to be used inside that block and not carried to other parts of the code.</p>\n\n<ul>\n<li>that means <code>Const ForAppending = 8</code> needs to be moved outside of the <code>If</code> Statement</li>\n<li>all of those variables should be declared outside of that <code>If</code> Statement, especially the first 3 <code>ForReading</code> , <code>ForWriting</code>, and <code>ForAppending</code></li>\n</ul></li>\n<li><p>Joined Declaration and Assignment - you can assign these like this</p>\n\n<ul>\n<li><code>Dim objFSO : Set objFSO = CreateObject(\"Scripting.FileSystemObject\")</code></li>\n<li><code>Dim textToReplace : Set textToReplace = \"http://www.yahoo.com\"</code></li>\n<li><code>Dim textReplacement : Set textReplacement = \"http://www.google.com</code></li>\n<li><code>Dim errorFileSys : Set errFileSys = CreateObject(\"Scripting.FileSystemObject\")</code></li>\n<li><code>Dim errorLogTxt : Set errorLogTxt = errorFileSys.OpenTextFile(\"C:\\urlinforError.log\",ForAppending, True)</code></li>\n</ul></li>\n<li><p>I am sure that you could use a <code>Try Catch</code> type of statement in there somewhere too. </p></li>\n<li>it also looks like you could use a <code>Using</code> statement there for writing to your Error log, but I am not sure that VBScript can do that? </li>\n<li>the last statement will never be reached, you don't need it. \n<ul>\n<li><code>WScript.Quit()</code></li>\n</ul></li>\n<li>what palacsint said about the <code>C:\\urlsinfo.xml</code> and that it should be a constant variable.</li>\n</ol>\n\n<p>here is what it would look like after all but Items 4 & 5</p>\n\n<hr>\n\n<pre><code>Dim objFSO : Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\nConst ForReading = 1\nConst ForWriting = 2\nConst ForAppending = 8\nConst xmlInput = \"C:\\urlsinfo.xml\"\n\nDim textToReplace : Set textToReplace = \"http://www.yahoo.com\"\nDim textReplacement : Set textReplacement = \"http://www.google.com\"\n\n\nIf (objFSO.FileExists(xmlInput)) Then\n\n Set objFile = objFSO.OpenTextFile(xmlInput, ForReading)\n strText = objFile.ReadAll\n objFile.Close\n strNewText = Replace(strText, textToReplace, textReplacement)\n\n Set objFile = objFSO.OpenTextFile(xmlInput, ForWriting)\n objFile.WriteLine strNewText\n objFile.Close\n WScript.Quit()\n\nElse\n Dim errorFileSys : Set errorFileSys = CreateObject(\"Scripting.FileSystemObject\")\n Dim errorLogTxt : Set errorLogTxt = errorFileSys.OpenTextFile(\"C:\\urlsinfoError.log\", ForAppending, True) \n errorLogTxt.WriteLine(Now &\" urlsinfo.xml file did not exist in directory C:\\. \")\n errorLogTxt.Close\n WScript.Quit()\nEnd If\n</code></pre>\n\n<hr>\n\n<p>This is a little bit cleaner, I think that some Exception Handling could be added in there to make it a little nicer, maybe a <code>Try Catch</code> or the VBScript equivalent. I would also look into using the <code>Using</code> statement style code in VBScript, I know you can do it in VB but not sure about VBScript.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T13:22:14.970",
"Id": "62879",
"Score": "0",
"body": "I only do maintenance with vbscript, new programs are in Ruby, if you see the example i posted you see why. No, vbscript has no using keyword or functionality and the error catching is poor, no try catch, you can set error skipping on with \"on error resume next\" but if you want to check if an error did occor you have to check every time with \"if err.number <>0 then wscript.echo err.description\", so it is not very usable"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T15:40:26.473",
"Id": "62898",
"Score": "0",
"body": "@peter, I hear what you are saying, I use VBScript for Writing tokens inside a 3rd party application, and it's a pain, right now I have a token that works in stage but not in production, can't figure it out, yet."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T22:50:27.260",
"Id": "37638",
"ParentId": "12439",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T12:31:25.137",
"Id": "12439",
"Score": "7",
"Tags": [
"vbscript"
],
"Title": "Check if an XML file exists then change URLs in it"
}
|
12439
|
<p>I have to list a integers from a text file separated by newlines into a python list. I ended up with the code above which works (for my case) but certainly is far form optimal.</p>
<pre><code>def readIntegers(pathToFile):
f = open(pathToFile)
contents = f.read()
f.close()
tmpStr = ""
integers = []
for char in contents:
if char == '\r':
integers.append(int(tmpStr))
tmpStr = ""
continue
if char == '\n':
continue
tmpStr += char
return integers
</code></pre>
<hr>
<p>Now I have much less code, but I'm not sure for which cases split() works correctly.</p>
<pre><code>def readIntegers(pathToFile):
with open(pathToFile) as f:
a = [int(x) for x in f.read().split()]
return a
</code></pre>
|
[] |
[
{
"body": "<p>No need for <code>split</code> (you can use <a href=\"http://docs.python.org/library/stdtypes.html#file.readlines\"><code>readlines</code></a>). But no need for <code>readlines</code>, for that matter:</p>\n\n<pre><code>def read_integers(filename):\n with open(filename) as f:\n return map(int, f)\n</code></pre>\n\n<p>or, if that’s more to your fancy:</p>\n\n<pre><code>def read_integers(filename):\n with open(filename) as f:\n return [int(x) for x in f]\n</code></pre>\n\n<p>A <code>file</code> object is simply iterable in Python, and iterates over its lines.</p>\n\n<p>Note that, contrary to what I said earlier, wrapping the file object in a <code>with</code> block is highly recommended. <a href=\"http://docs.python.org/reference/datamodel.html\">Python doesn’t actually guarantee (although it recommends it) that objects are disposed of automatically at the end of the scope.</a> Worse, it’s not guaranteed that a <code>file</code> object that is collected actually closes the underlying stream.</p>\n\n<p>(Note that I’ve adapted the method name to Python conventions.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T06:02:14.347",
"Id": "20084",
"Score": "0",
"body": "Thx for your answer :) I didn't think of using map here."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T20:16:41.270",
"Id": "12449",
"ParentId": "12443",
"Score": "16"
}
}
] |
{
"AcceptedAnswerId": "12449",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T16:17:53.333",
"Id": "12443",
"Score": "8",
"Tags": [
"python"
],
"Title": "Reading ints line from a file in Python"
}
|
12443
|
<p>Every shim I have seen for this function has used the IE-only CSS <code>expression</code> trick. While there's no denying it's effective, it's made useless if the browser is not IE and doesn't support <code>querySelectorAll</code> either.</p>
<p>jQuery is out of the question, since I don't want to get a whole framework just to shim one tiny little function. So I went and wrote my own. I'd like to submit it for review, which may include optimisations.</p>
<p>Please note that this is not a complete shim, only enough for what is frequently used:</p>
<ul>
<li>tag name</li>
<li>id</li>
<li>class name</li>
<li>attribute, presence and exact value match</li>
<li>descendant combinator</li>
<li>child combinator</li>
</ul>
<p>The code:</p>
<pre><code>if( typeof document.querySelector == "undefined") {
document.querySelectorAll = function(sel) {
var sels = sel.split(","),
run = function(node,selector) {
var sel = selector.split(/[ >]+/), com = selector.match(/[ >]+/g) || [], s, c, ret = [node], nodes, l, i, subs, m, j, check, x, w, ok,
as;
com.unshift(" ");
while(s = sel.shift()) {
c = com.shift();
if( c) c = c.replace(/^ +| +$/g,"");
nodes = ret.slice(0);
ret = [];
l = nodes.length;
subs = s.match(/[#.[]?[a-z_-]+(?:='[^']+'|="[^"]+")?]?/gi);
m = subs.length;
for( i=0; i<l; i++) {
if( subs[0].charAt(0) == "#") ret = [document.getElementById(subs[0].substr(1))];
else {
check = c == ">" ? nodes[i].children : nodes[i].getElementsByTagName("*");
if( !check) continue;
w = check.length;
for( x=0; x<w; x++) {
ok = true;
for( j=0; j<m; j++) {
switch(subs[j].charAt(0)) {
case ".":
if( !check[x].className.match(new RegExp("\\b"+subs[j].substr(1)+"\\b"))) ok = false;
break;
case "[":
as = subs[j].substr(1,subs[j].length-2).split("=");
if( !check[x].getAttribute(as[0])) ok = false;
else if( as[1]) {
as[1] = as[1].replace(/^['"]|['"]$/g,"");
if( check[x].getAttribute(as[0]) != as[1]) ok = false;
}
break;
default:
if( check[x].tagName.toLowerCase() != subs[j].toLowerCase()) ok = false;
break;
}
if( !ok) break;
}
if( ok) ret.push(check[x]);
}
}
}
}
return ret;
}, l = sels.length, i, ret = [], tmp, m, j;
for( i=0; i<l; i++) {
tmp = run(this,sels[i]);
m = tmp.length;
for( j=0; j<m; j++) {
ret.push(tmp[j]);
}
}
return ret;
};
document.querySelector = function(sel) {
var ret = this.querySelectorAll(sel);
if( ret.length > 0) return ret[0];
else return null;
};
if( typeof HTMLElement != "undefined") {
HTMLElement.prototype.querySelector = document.querySelector;
HTMLElement.prototype.querySelectorAll = document.querySelectorAll;
}
else {
dommods_extend.push(function() {
var a = document.getElementsByTagName("*"), l = a.length, i;
for( i=0; i<l; i++) {
a[i].querySelector = document.querySelector;
a[i].querySelectorAll = document.querySelectorAll;
}
});
// dommods_extend is an array of functions that are run whenever the DOM is updated,
// to apply changes such as auto-resizing textareas, default value for <select> and so on.
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T17:02:38.810",
"Id": "20060",
"Score": "1",
"body": "Just a quick note: is it really necessary to `querySelectorAll` when you just want to `querySelector`? It seems highly inefficient."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T17:09:05.527",
"Id": "20061",
"Score": "0",
"body": "Maybe you should have `querySelectorAll` and `querySelector` call a single function taking a last argument (a flag saying whether to take more than one result or not)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T17:09:59.673",
"Id": "20062",
"Score": "1",
"body": "And the last suggestion: what about separating your code into multiple functions? It'd allow you to have less nesting than you currently have (so, more readability)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T21:51:52.493",
"Id": "20075",
"Score": "7",
"body": "You could take a look at [Sizzle's source](https://github.com/jquery/sizzle/blob/master/sizzle.js). It's the DOM selector engine used in jQuery (Not the entire jQuery library)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T05:14:56.213",
"Id": "22138",
"Score": "0",
"body": "For something as complex as this, it is probably a good idea to write some tests."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T20:42:05.377",
"Id": "23230",
"Score": "0",
"body": "Are you taking into account that commas may be present besides separating multiple selectors? E.g. `a[href=\"/foo?bar=1,2,4\"]`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T23:54:03.103",
"Id": "23238",
"Score": "0",
"body": "@Lèsemajesté No, I'm not, since I know they won't be anywhere I use them. Good point, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T00:27:30.447",
"Id": "23239",
"Score": "0",
"body": "@Kolink: Do you have this up on Github or somewhere, or would you mind if I forked it? Because I think it's a worthwhile concept, and it might be useful on a future project I might work on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T00:38:39.280",
"Id": "23240",
"Score": "0",
"body": "@Lèsemajesté Please feel free to copy, paste, edit, whatever you like with this code. I won't provide support for it though, so make sure you understand its limitations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T00:40:50.477",
"Id": "23241",
"Score": "0",
"body": "@Kolink: Excellent. I'll post here if I make any changes to it."
}
] |
[
{
"body": "<h2>Overal</h2>\n\n<p>I am not sure which non IE-browser doesn't support querySelectorAll. Regardless, the code seems very performant, if a little Golfic ( reminds me of code golf ).</p>\n\n<h2>Nitpickings</h2>\n\n<p>If you wish this source to be maintained / debugged /reviewed by others, there are some things you can change to make that easier:</p>\n\n<ul>\n<li><p>Declare unassigned variables last. It is easier on the eyes to know when to stop reading that long var line.</p></li>\n<li><p>I am all for Spartan coding, but w,m,c (which is not a character!), l etc. just make for unmaintainable code.</p></li>\n<li><p>Make your regex's constants with a meaningful name, it will make your code easier to understand.</p></li>\n<li><p>Use new lines after the <code>if</code> condition</p></li>\n<li><p>if/else branches should either both have curly braces, or both not have curly braces, dont mix</p></li>\n<li><p>You could use <code>Array.concat</code> here:</p></li>\n</ul>\n\n<blockquote>\n<pre><code>//As is\nfor( i=0; i<l; i++) {\n tmp = run(this,sels[i]);\n m = tmp.length;\n for( j=0; j<m; j++) {\n ret.push(tmp[j]);\n }\n}\n//Replacement proposal\nfor( i=0; i<l; i++)\n ret.push( run(this,sels[i]) );\n</code></pre>\n</blockquote>\n\n<ul>\n<li>You could use a trinary here :</li>\n</ul>\n\n<blockquote>\n<pre><code>//As is \nif( ret.length > 0) return ret[0];\nelse return null\n//Replacement proposal\nreturn ret.length?ret[0]:null;\n</code></pre>\n</blockquote>\n\n<h2>Finally</h2>\n\n<p>It is considered bad practice to shim in incomplete implementations, if you want to add to the HTMLElement prototype, use your own names to remove any confusion. <code>HTMLElement.prototype.darkQuerySelector</code> sounds so much better anyway ;)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T15:18:55.177",
"Id": "62895",
"Score": "0",
"body": "If nothing else, +1 for `darkQuerySelector` XD I've stopped supporting IE7 in new projects anyways, but thanks for your input!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T14:55:18.143",
"Id": "37805",
"ParentId": "12444",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37805",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T16:24:14.723",
"Id": "12444",
"Score": "11",
"Tags": [
"javascript",
"cross-browser"
],
"Title": "querySelectorAll shim for non-IE browsers"
}
|
12444
|
<p>I am not sure the square brackets are correct (although it has not yet failed some simple tests). I would also like to reduce and simplify this code to one line if practical. I think the code is self explanatory.</p>
<pre><code> str = str.replace(/[\n]/g,'<br>')
str = str.replace(/[\t]/g,'&nbsp;&nbsp;&nbsp;&nbsp;')
</code></pre>
|
[] |
[
{
"body": "<p>The square brackets are technically correct, but unneeded:</p>\n\n<pre><code>str = str.replace(/\\n/g, \"<br>\");\n</code></pre>\n\n<p>Also, since a new string is returned, you can chain the methods:</p>\n\n<pre><code>str = str.replace(/\\n/g, \"<br>\").replace(/\\t/g, \"&nbsp;&nbsp;&nbsp;&nbsp;\");\n</code></pre>\n\n<p>For more information, you can read the MDN pages on <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace\" rel=\"nofollow\">replace</a> and <a href=\"https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions\" rel=\"nofollow\">regular expressions</a>.</p>\n\n<hr>\n\n<p>Though the above is one line, if wanted to combine it into one replace, you could, but in my opinion this is uglier and less clear:</p>\n\n<pre><code>str.replace(/(\\n|\\t)/g, function (s) { return (s === \"\\n\" ? \"<br>\" : \"&nbsp;&nbsp;&nbsp;&nbsp;\"); });\n</code></pre>\n\n<p>This could be useful though if you had a large set of simple replacements:</p>\n\n<pre><code>var map = {\"\\n\": \"<br>\", \"\\t\": \"&nbsp;&nbsp;&nbsp;&nbsp;\"};\nstr.replace(/(\\n|\\t)/g, function (s) { return map[s]; });\n</code></pre>\n\n<p>The idea could be extended farther to automatically generate the regex instead of relying on changing it every time <code>map</code> is updated.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T03:20:06.533",
"Id": "20079",
"Score": "0",
"body": "I agree. I like the chained example. Thanks for clarifying the square brackets. I like the last example too, I think I have seen something similar."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T12:55:23.600",
"Id": "20088",
"Score": "0",
"body": "Since you don't actually need regular expressions here, I would do it this way: `str = str.split('\\n').join('<br>').split('\\t').join(' ')`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T03:13:10.080",
"Id": "12457",
"ParentId": "12454",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "12457",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T02:30:36.303",
"Id": "12454",
"Score": "4",
"Tags": [
"javascript",
"regex"
],
"Title": "JavaScript replace"
}
|
12454
|
<p>I have been programming a simple number guessing game and I am wondering if there is any way of making my code more efficient and cleaner. I have spent some time on it implementing error checking to make it as safe as I know how. I feel as if the way's that I have done this may be 'long winded' so if you know of a shorter way to do so then this would be much appreciated.</p>
<p>I do have comments, and I hope they make the program readable!</p>
<p>I am using Visual Studio 2010 - not sure if this changes much.</p>
<pre><code>#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <string>
#include <sstream>
// Include the standard namespace for easy use of cout/cin
using namespace std;
// Function Declarations.
string convertIntToString(int input);
bool isValidInput_Int(string input);
void cls();
void pause();
void printError(int ErrorNumber, bool ClearWindow);
void game(int difficulty);
// Main Function
int _tmain(int argc, _TCHAR* argv[])
{
// Variables
string input;
int inputVal;
bool gameIsRunning = true;
// We want rand() to be as random as possible.
srand( time(NULL) );
// Run until the user wishes to quit.
while(gameIsRunning)
{
cout << "Welcome to the number guessing game V1.0\n\nPlease select an option:\n";
cout << "1- Easy\n2- Medium\n3- Hard\n4- Expert\n5- Exit\n>>";
cin >> input;
// Check if the data is valid according to our wishes.
if(isValidInput_Int(input))
{
// Act correctly according to the input.
// Store the integer we want.
inputVal = atoi(input.c_str());
// Make sure the input is a correct selection
if(inputVal < 5 && inputVal > 0)
{
// Run the game.
game(inputVal);
}
else if(inputVal == 5)
{
// Quit the application.
exit(0);
}
else
{
printError(2, true);
}
}
else
{
printError(1, true);
}
}
// Leave the Application.
return 0;
}
///--------------------------------------
/// Resource:
/// http://www.cplusplus.com/forum/beginner/7777/
/// Converts an integer to a string.
///--------------------------------------
string convertIntToString(int input)
{
stringstream ss; //create a stringstream
ss << input; //add number to the stream
return ss.str(); //return a string with the contents of the stream
}
///--------------------------------------
/// Checks if the input is of size 1 and
/// The values inside this are of type
/// Integer and nothing else.
///--------------------------------------
bool isValidInput_Int(string input)
{
bool retVal = 0;
try
{
if(atoi(input.c_str()))
retVal = 1;
}
catch(exception)
{
retVal = 0;
}
return retVal;
}
///--------------------------------------
/// Clears the console window of text.
///--------------------------------------
void cls()
{
system("cls");
return;
}
///--------------------------------------
/// Pauses the console window.
///--------------------------------------
void pause()
{
system("pause");
return;
}
///--------------------------------------
/// Shows an error based on the input to
/// The function. If your error is not
/// Listed then put '0' in as a default
/// value. This returns a some-what
/// Generic message to the use.
///--------------------------------------
void printError(int ErrorNumber, bool ClearWindow)
{
// Clear the console window
if(ClearWindow)
cls();
switch(ErrorNumber)
{
case 1:
cout << "---Error: Invalid Input---\n\n";
break;
case 2:
cout << "---Error: Please enter a correct option---\n\n";
break;
default:
cout << "---Error: Something went wrong---\n\n";
break;
}
return;
}
///--------------------------------------
/// This is where the 'game' code is kept
///--------------------------------------
void game(int difficulty)
{
// Variables
string input;
string message;
int inputVal;
// Generate our random number!
int numberToGuess = rand() % ((difficulty * 2) * 10) + 1;
cout << "Welcome!\n";
cout << "You have 10 lives.\nThe number is between 1 and " << (difficulty * 2) * 10 << "\n";
cout << "Start guessing!\n\n";
// Loop until they are dead or they guess the number.
for(int lives = 10;lives > 0; lives--)
{
cout << ">>";
cin >> input;
// Check if the data is valid according to our wishes.
if(isValidInput_Int(input))
{
// Store the integer we want.
inputVal = atoi(input.c_str());
// Check if the guess was correct or not
// If it isnt, give them some 'guidance'.
if(inputVal == numberToGuess)
{
message = "Congratulations!\nYou Win!\n";
lives -= 10;
}
if(lives != 1)
{
if(inputVal > numberToGuess)
{
message = "Incorrect, try guessing lower!\n";
}
if(inputVal < numberToGuess)
{
message = "Incorrect, try guessing higher!\n";
}
}
else
{
message = "Incorrect, the number was: [" + convertIntToString(numberToGuess) + "]\n";
}
cout << message;
}
else
{
// Let them know that there input was invalid.
printError(1, false);
// We could 'punish' however, we will be nice.
lives++;
}
}
// Pause.
pause();
// Clear the screen before showing the menu again.
cls();
return;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T19:23:56.030",
"Id": "20092",
"Score": "0",
"body": "May I suggest that you modify the question title to include more information about your specific issue (because \"help me make my code better\" is *everyone's* goal here :) )."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T01:10:36.060",
"Id": "20098",
"Score": "1",
"body": "I am new to c++ and I want to make sure that when I code I am doing everything correctly. I know that 'in general' everyone is trying ot improve there code, however, since I am somewhat new, I dont know as much as you do. I'll think of a more specific title though if I can. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T01:11:56.420",
"Id": "20099",
"Score": "0",
"body": "Flyphe, I just meant something like \"How can I make a simple number guessing game more efficient\" :)"
}
] |
[
{
"body": "<p>Here some of my language-focused remarks, not touching the actual program design.</p>\n\n<h2>usings</h2>\n\n<pre><code>// Include the standard namespace for easy use of cout/cin\nusing namespace std;\n</code></pre>\n\n<p>Very nice to list what you need by adding the comment. But instead of pulling all names you could make it more explicit</p>\n\n<pre><code>using std::cin;\nusing std::cout\n</code></pre>\n\n<p>In big files you may want to \"sectionize\" the using by from which <code>#include</code> they came from. (Edit, thanks to comment below) Best do not introduce <code>using</code> before other <code>#includes</code> though, you can group the using afterwards. E.g.:</p>\n\n<pre><code>#include <iostream>\n#include <string>\n#include <map>\n#include <vector>\n// for shorten code\nusing std::string;\nusing std::map;\nusing std::vector;\n// from iostreeam\nusing std::cin;\nusing std::cout;\n</code></pre>\n\n<p>I do <strong>not</strong> do this for <strong>all names</strong>, only for the most frequent ones when it really saves space -- and most people do know anyway. Most <code>std::</code>-items I write <em>with</em> their namespace when I use them.</p>\n\n<p><code>string</code> I often apply a <code>using</code> to (lots of strings in function arguments), but <code>map</code> and <code>vector</code> I typically do not (better being explicit at the few location they are used). When I have to use lots of <code>std::vector<thingy>::const_iterator</code> somewhere I shorten the code with a local <code>typedef</code> or <code>using</code>.</p>\n\n<pre><code>void drawData(std::vector<thingy> &data) {\n typedef std::vector<thingy>::const_iterator tit;\n const tit end = data.end();\n for(tit it=data.begin(); it!=end; ++it) {\n *it.drawYourself();\n }\n}\n</code></pre>\n\n<p>And with C++11 you do not even need that, you have <code>auto</code> and ranged-<code>for</code> to beautify your.</p>\n\n<h2>variable initialization</h2>\n\n<pre><code>// Variables\nstring input;\nint inputVal;\nbool gameIsRunning = true;\n</code></pre>\n\n<p>It is ok <strong>not to initialize</strong> <code>string</code>, because it is a class/object.</p>\n\n<p>But you <strong>should initialize</strong> <code>int</code> variables.</p>\n\n<h2>latest possible declaration</h2>\n\n<pre><code>// Variables\nstring input;\n\n...\nwhile(...)\n ...\n cin >> input;\n</code></pre>\n\n<p>Your rule-of-thumb should be to declare a variable <strong>as late as possible</strong> which would mean</p>\n\n<pre><code>...\nwhile(...)\n ...\n string input;\n cin >> input;\n</code></pre>\n\n<p>The exception are \"tight loops\" when the frequent initialization and destruction would cost to much. But actually, <code>string</code> is quite cheap and this is not a \"tight loop\", so I would recommend it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T11:47:26.073",
"Id": "12461",
"ParentId": "12460",
"Score": "8"
}
},
{
"body": "<h1>On Comments</h1>\n\n<blockquote>\n <p>I do have comments, I hope they make the program readable!</p>\n</blockquote>\n\n<p>Unfortunately, no. Your comments don’t help readability and only take up unnecessary space (which makes the program <em>less</em> readable).</p>\n\n<p>The problem is that your comments convey useless information. For instance,</p>\n\n<pre><code>// Pause.\npause();\n</code></pre>\n\n<p>How is this comment helping?</p>\n\n<p>There’s a commonly-quoted adage,</p>\n\n<blockquote>\n <p>Code explains the <em>how</em>, comments explain the <em>why</em></p>\n</blockquote>\n\n<p>which actually covers most cases: use <em>code</em> to explain <em>how</em> a solution is implemented. Only use comments when necessary to explain <em>why</em> you do something.</p>\n\n<p>In practice, this means that most code doesn’t need comments at all, good code should ideally be self-explanatory; if it isn’t, take that as a hint to rewrite it.</p>\n\n<p>Here’s a positive example, however:</p>\n\n<pre><code>// We could 'punish' however, we will be nice.\nlives++;\n</code></pre>\n\n<p>Now <em>this</em> comment is more helpful. But it could still be a bit clearer.</p>\n\n<p>There’s one exception to this no-comments rule:</p>\n\n<p><em>Do</em> provide documentation for all functions via comments. But again, use the documentation to explain stuff that is not explained by the function name and signature.</p>\n\n<p>For instance,</p>\n\n<pre><code>///--------------------------------------\n/// Pauses the console window.\n///--------------------------------------\nvoid pause();\n</code></pre>\n\n<p>… not particularly helpful. What does “pauses the console window” actually mean? A more helpful description would be, “Halts execution until the user hits any hey”.</p>\n\n<p>Your other function documentations are much better in this regard. But take care to explicitly describe all <em>parameters</em>, the <em>return value</em>, and all <em>side effects</em>.</p>\n\n<h1>Implementation</h1>\n\n<p>(In addition to what @towi already wrote.)</p>\n\n<h2>Input</h2>\n\n<p>Your input routine does three times the work:</p>\n\n<ol>\n<li>It inputs a string</li>\n<li>It tests whether this is a valid number, via <code>isValidInput_Int</code>.</li>\n<li>It converts it to a number via <code>atoi</code>.</li>\n</ol>\n\n<p><code>isValidInput_int</code> is actually a lot of boilerplate code doing the same thing as just calling <code>atoi</code>. In fact, <code>isValidInput_int</code> doesn’t work at all because <code>atoi</code> <em>cannot</em> be used reliably to test whether a valid number was entered. It doesn’t throw an exception, it just silently returns <code>0</code>. You have no way of knowing whether the user entered <code>0</code> or an invalid number.</p>\n\n<p>Furthermore, <code>isValidInput_int</code> uses the <code>bool</code> type but you never actually use the <code>bool</code> constants <code>true</code> and <code>false</code>, instead you use <code>1</code> and <code>0</code>. Do <em>not</em> do this. Unfortunately, C++ allows this but it’s a weakness of the type system (thanks to C).</p>\n\n<p>Furthermore, <code>atoi</code> is redundant here anyway, just input the number directly. That is, instead of reading a string, do this:</p>\n\n<pre><code>int difficulty;\nif (cin >> difficulty) {\n // Input was succesful, proceed.\n}\nelse {\n printError(1, true);\n}\n</code></pre>\n\n<h2>Use meaningful variable names</h2>\n\n<p><code>(difficulty * 2) * 10</code> crops up several times. What does it mean? Put it into a meaningful variable to increase readability (<code>range</code> would be a meaningful name).</p>\n\n<p><code>inputVal</code> describes where the value comes from, but not what it signifies. How about <code>nextGuess</code> instead?</p>\n\n<p>Also, you should settle on a single convention for names. At the moment you mix between camelCase and under_score, sometimes_WithCapital_Letters. Modern C++ code generally uses lowercase_words_separated_by_underscore but you’re free to use your own convention – the important thing is <em>consistency</em>.</p>\n\n<h2>Other stuff</h2>\n\n<p>You seem to always finish your functions with <code>return;</code> – that’s redundant. You only need <code>return</code> if you want to return a value, or if you want to exit the function <em>prematurely</em>. At the end of a function, you don’t need it.</p>\n\n<p>Furthermore, <code>main</code> is a special case, <code>return 0;</code> is implied at the end of it, so this is also redundant (but all other functions that return values need explicit <code>return</code>s).</p>\n\n<p>Finally, the logic flow in <code>game</code> isn’t entirely obvious. This could be cleared up. In particular, when do lives go up and down? It might help to simplify the input reading routine (see above) and to extract the guess into a separate function. In general, try to limit the level of nesting drastically. Four levels of nesting (here, a <code>for</code> and three <code>ifs</code>) should really be the exception. Your logic here could really be simplified, for instance by reversing the condition <code>if (lives != 1)</code>, and exiting the loop early:</p>\n\n<pre><code>if(lives == 1)\n{\n cout << \"Incorrect, the number was: [\" + convertIntToString(numberToGuess) + \"]\\n\";\n break;\n}\n\nif(inputVal > numberToGuess)\n{\n message = \"Incorrect, try guessing lower!\\n\";\n}\n\nif(inputVal < numberToGuess)\n{\n message = \"Incorrect, try guessing higher!\\n\";\n}\n</code></pre>\n\n<p>In my opinion, this still isn’t as readable as it could be because it takes up a lot of unnecessary <em>vertical space</em>. I find the following <em>much</em> more readable but be aware that this opinion isn’t shared by all.</p>\n\n<pre><code>if(lives == 1) {\n cout << \"Incorrect, the number was: [\" + convertIntToString(numberToGuess) + \"]\\n\";\n break;\n}\n\nif(inputVal > numberToGuess)\n message = \"Incorrect, try guessing lower!\\n\";\n\nif(inputVal < numberToGuess)\n message = \"Incorrect, try guessing higher!\\n\";\n</code></pre>\n\n<p>Some people will hate me for giving this advice but they probably wear their pants on their head. ;-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T01:07:59.730",
"Id": "20097",
"Score": "0",
"body": "Thank you very much for your help! I agree with everything you wrote, appart from the last section :P. I like to have the brackets there and on the same line as then it makes it easier to add additional code later on plus, in my opinion it is easier so see where a function/loop starts and ends. I agree however with the layout that you used as it is better, so thanks. I shall try to make my comments more usefull and helpful. Again, I would upvote you if I could!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T01:26:55.917",
"Id": "20101",
"Score": "0",
"body": "Also, the reason for adding the 'return;' at the end of void functions is because I was told that it is good practice. Thanks for telling me otherwise, I didn't think it was of any use anyway :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T16:50:17.317",
"Id": "12468",
"ParentId": "12460",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "12461",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T11:23:12.563",
"Id": "12460",
"Score": "4",
"Tags": [
"c++",
"optimization",
"game"
],
"Title": "How can I make a simple number guessing game more efficient?"
}
|
12460
|
<p>I have a small social networking site built in CodeIgniter. Any registered user can send messages to others by visiting their profile.</p>
<p>Today I noticed that one user sent bulk messages to 200 users. How he was able to do that?</p>
<p>Suggestions to make the code secure are welcome.</p>
<p>I have a textarea and a send button on the profile page.</p>
<p><strong>jQuery code on profile page (View)</strong></p>
<pre><code>$("#send").click(function(event){
var msg=$("#quick_message").val();
var uid=$(this).attr('uid');
if(msg.length > 0) {
$("#msg_status").html('<span id="loading_content"></span>');
$.post("<?=base_url()?>message/send_message", {"ids":uid,"msg":msg}, function(data){
$("#msg_status").html('<span class="errorsuc">Message sent.</span>');
$("#quick_message").val('');
});
} else {
$("#msg_status").html('<span class="errormsg">Write something to send message.</span>');
}
});
</code></pre>
<p><strong>Here is my controller</strong></p>
<pre><code> // send message
function send_message()
{
if (!$this->users->is_logged_in()) {
redirect('signin');
}
$user_id=$this->session->userdata('user_id');
$ids=trim($this->input->post('ids'));
$msg=trim($this->input->post('msg'));
$msg=htmlspecialchars($msg);
$msg=$this->replaceTolink($msg);
$msg=$this->replaceTowinks($msg);
$pieces=explode(",", $ids);
foreach ($pieces as &$user_id2) {
$this->db->insert('messages', array('user_id1' => $user_id,'user_id2' => $user_id2,'message' => $msg));
}
return true;
}
</code></pre>
<p>What I need to improve in my code and how to protect the code to send bulk messages?</p>
|
[] |
[
{
"body": "<p>First of all you should use site_url() in your jquery code instead of base_url() as it provides url flexibility. For more info visit <a href=\"http://codeigniter.com/user_guide/helpers/url_helper.html\" rel=\"nofollow\">http://codeigniter.com/user_guide/helpers/url_helper.html</a></p>\n\n<p>And in your controller code i suggest you to use bulk insert instead of loop insert. So you may use this piece of code:</p>\n\n<pre><code>foreach( $pieces as $user_id2)\n{\n $insert_arr[] = array('user_id1'=> $user_id, 'user_id2'=> $user_id2, 'message'=>$msg);\n}\n\n$this->db->insert_batch('messages', $insert_arr);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T06:56:34.817",
"Id": "12463",
"ParentId": "12462",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>Today I noticed that one of user sent bulk messages to 200 users. How he was able to do that? Suggestions to make code secure are welcome.</p>\n</blockquote>\n\n<pre><code> $pieces=explode(\",\", $ids);\n foreach ($pieces as &$user_id2) {\n $this->db->insert('messages', array('user_id1' => $user_id,'user_id2' => $user_id2,'message' => $msg)); \n }\n</code></pre>\n\n<p>You controller is splitting the recipients user_id by comma. It doesn't have any limit on how many user_ids can be entered and processed by the controller. You can impose that limit to be just one recipient user by using <code>$pieces[0]</code> instead of using <code>foreach</code> loop. </p>\n\n<pre><code>$pieces=explode(\",\", $ids); \n $this->db->insert('messages', array('user_id1' => $user_id,'user_id2' => $pieces[0],'message' => $msg)); \n</code></pre>\n\n<p>You can use <code>count</code> and <code>for</code> loop to limit the number of recipients. Like here it is 10.</p>\n\n<pre><code>$pieces=explode(\",\", $ids); \n$recipients = count($pieces);\n\nif ($recipients <= 10) {\n for ($i = 0; $i <= $recipients; $i++) {\n$this->db->insert('messages', array('user_id1' => $user_id,'user_id2' => $pieces[i],'message' => $msg)); \n}\n } else {\n\n for ($i = 0; $i <= 10; $i++) {\n$this->db->insert('messages', array('user_id1' => $user_id,'user_id2' => $pieces[i],'message' => $msg)); \n}\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T22:58:37.363",
"Id": "20095",
"Score": "0",
"body": "Bad idea. This doesn't stop the CSRF; it only makes it slightly more annoying for an attacker. It also doesn't reduce your network load like the answer provided by @ShayanHusaini"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T04:07:19.327",
"Id": "20102",
"Score": "0",
"body": "@BillBarry - That's right, this a basic rate limit functionality. I didn't consider CSRF token without knowing if he had that ability or no. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T03:24:01.053",
"Id": "20165",
"Score": "0",
"body": "@FirstnameLastname, CSRF in codeigniter is built in, which can be used easily. So there is no point of ability here."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T10:35:01.277",
"Id": "12464",
"ParentId": "12462",
"Score": "2"
}
},
{
"body": "<p>The <code>send_message</code> controller is vulnerable to automation.</p>\n\n<p>If I can discover a list of user ids I could create the following html page:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <title>Bulk Sender</title>\n</head>\n<body>\n <form action=\"yoursite/send_message\" method=\"POST\">\n <input type=\"text\" id=\"ids\" name=\"ids\" value=\"1,2,3,4,5,6,7,8,9,...\"><br>\n <textarea id=\"msg\" name=\"msg\"></textarea>\n <input type=\"submit\" value=\"Send\">\n </form>\n</body>\n</html>\n</code></pre>\n\n<p>To use that, a user would simply need to sign in to your site and then load up this page. <strong>Worse</strong>, an attacker who has discovered potential victims on your site may be able to fool one victim into opening a session and then loading a page similar to this that automatically sends a hidden form on behalf of the victim. This is commonly known as a <strong>Cross Site Request Forgery</strong>.</p>\n\n<p>Dealing with CSRFs is not entirely trivial. The easiest way to deal with it is to protect the vulnerable areas with a form of expiring validation that is unique to the form. I like to use a timestamp and hash, like this:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>//in jquery method:\n<?php\n $ts = generate_timestamp()\n?>\n$.post(\"<?=base_url()?>message/send_message\", {\"ids\":uid,\n \"msg\":msg,\"ts\": \"<?=$ts?>\",\n \"csrfhash\": \"<?=csrf_hash($ts)?>},\n</code></pre>\n\n<pre class=\"lang-php prettyprint-override\"><code>//elsewhere\nfunction csrf_hash($ts) {\n return hash('sha256', $ts . //timestamp limits potential csrf window\n $this->session->userdata('session_id') . //session id provides decent base\n //entropy, but is available in the \n //user's cookie so potentially XSS\n $this->users->get_user_salt()); //the user's password salt will stop XSS attempts\n}\n\n//in send_message\n$ts = $this->input->post('ts');\nif(csrf_hash($ts) != $this->input->post('csrfhash') && date($ts) > now()->add_minutes(-5)) {\n return error('Please refresh the page and try sending the message again. ' .\n 'It was caught by the spam filter due to taking more than 5 minutes to write. ' .\n 'You may select the text and copy it before refreshing the page if you wish.');\n}\n</code></pre>\n\n<p>(after substituting or writing the code that I didn't provide; you can probably do better than the error message I added as well)</p>\n\n<p><a href=\"http://codeigniter.com/user_guide/libraries/security.html\" rel=\"nofollow\">CodeIgnitor does have built in CSRF protection</a> (scroll to bottom), but I don't know how to use it (I've never written any significant php before and have never used this project) and the documentation is lacking (as evident by the comment in the source of that page).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T22:51:47.653",
"Id": "12473",
"ParentId": "12462",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12473",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T05:45:03.077",
"Id": "12462",
"Score": "3",
"Tags": [
"php",
"jquery",
"mysql",
"security",
"codeigniter"
],
"Title": "CodeIgniter AJAX messages submission security issue"
}
|
12462
|
<p>I just got back from my interview where I had to solve the following problem:</p>
<blockquote>
<p>Write a C++ program that prints the following pattern using nested <code>for</code> loops.</p>
</blockquote>
<pre><code>*
***
*****
***
*
</code></pre>
<p>Here is my solution:</p>
<pre><code>int inc = 2;
for (int i = 1; i >= 1; i += inc){
for (int j = 0; j < i; j++ )
std::cout<<'*';
std::cout<<endl;
if ( i == 5 )
inc = -2;
}
</code></pre>
<p>I'm just curious to know if there are better solutions (any criteria for better) or just different approaches.</p>
|
[] |
[
{
"body": "<p><strong>Edit</strong> Oh well, not using nested for... Sorry about that</p>\n\n<pre><code>int inc = 2;\nfor (int i = 1; i >= 1; i += inc){\n std::cout<<std::string(i,'*')<<endl;\n if ( i == 5 )\n inc = -2;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T16:25:57.910",
"Id": "12466",
"ParentId": "12465",
"Score": "8"
}
},
{
"body": "<p>This answer is simpler and shorter:</p>\n\n<pre><code>for(;0;)\n for(;0;)\n ;\nstd::cout << \"*\\n***\\n*****\\n***\\n*\\n\";\n</code></pre>\n\n<p>Perhaps you'd do better to consider how you could <em>generalise</em> your answer by <em>parametrising</em> it e.g. by the depth and the angle of the tree it outputs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T07:10:09.733",
"Id": "20105",
"Score": "8",
"body": "If this is an interview question and you came to me with this answer I would **not** give you the position -- because you are obviously too clever for your own good. And therefore for our team."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T07:40:24.937",
"Id": "20106",
"Score": "3",
"body": "Why? It's important to recognise when a simple, hard-coded solution is sufficient and not waste resources parametrising code in dimensions that are never used (YAGNI). Instead, one should explore the problem space with the customer to determine where parametrisation is required."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T08:03:06.337",
"Id": "20107",
"Score": "0",
"body": "I see that this would start a long discussion.. *smile*. Well, the customer said he wanted a nested-loop. This is of course nothing a real customer in a real project would say, but here it is a requirement. Often one has to interpret a vague specification and come up with the solution the customer *really* wanted, despite of what he *said*. And I'd say he asked for *useful* loops, even when he did not say that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T12:03:04.627",
"Id": "20115",
"Score": "4",
"body": "What’s “too clever for your own good” actually supposed to mean? It’s just an empty adage that’s begging the question, and not applicable in this context. Yes, the answer is clever. Too clever? No – why? And in particular, it answers the crucial question: *which parts of this answer are supposed to be the movable parts?* If we don’t have this information, we can’t design a good, general-purpose answer without over-engineering."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T12:30:15.697",
"Id": "76455",
"Score": "1",
"body": "@KonradRudolph, Ecatmur's solution follows the letter of the requirement, but only barely. The question is a thought puzzle, intended to test the candidate's problem-solving abilities. ecatmur's answer is a \"smart-a**\" answer that refuses to play by the rules of the problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T12:36:13.233",
"Id": "76457",
"Score": "0",
"body": "@Duncan that's nonsense. Like I said, the question is completely under-specified. In a real scenario I'd obviously ask die clarification. But given the exact requirements, this is the least complex and most obviously bug free solution, and hence superior. It plays completely by the rules. That's the whole point."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T16:34:54.583",
"Id": "12467",
"ParentId": "12465",
"Score": "8"
}
},
{
"body": "<p>I'm not sure about better, but this qualifies as a \"different\" solution.</p>\n\n<pre><code>int count;\nfor (int i = -2; i <= 2; i++){\n count = 1 + 2 * (2 - abs(i));\n for (int j = 0; j < count; j++ )\n std::cout<<'*';\n std::cout<<std::endl;\n}\nstd::cin >> count;\nreturn 0;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T18:12:16.233",
"Id": "12469",
"ParentId": "12465",
"Score": "3"
}
},
{
"body": "<p>This allows for reusability - any number of lines, whatever increment, to get the sideways triangle format:</p>\n\n<pre><code>int NUMBER_LINES = 5;\nint INC = 2;\nint stars = 1;\nfor( int i = 1; i <= NUMBER_LINES; i++ )\n{\n for( int j = 0; j < stars; j++ )\n std::cout<<'*';\n std::cout<<std::endl;\n if( i < (NUMBER_LINES / 2 + NUMBER_LINES % 2) )\n stars += INC;\n else if( NUMBER_LINES % 2 == 0 && i == NUMBER_LINES / 2 )\n ;\n else\n stars -= INC;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T08:58:02.290",
"Id": "20697",
"Score": "0",
"body": "Even better if you change `NUMBER_LINES` and `INC` to `const int`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T21:32:02.380",
"Id": "12472",
"ParentId": "12465",
"Score": "5"
}
},
{
"body": "<p>A friend of mine missed the part about the for loops and came up with the following recursive version:</p>\n\n<pre><code>const int MAX_STARS = 5;\nconst int INC = 2; \nconst int STARTING_STARS = 1;\n\nvoid printRowOfStars(int length){\n while( length-- > 0){\n std::cout<<'*'; \n }\n std::cout<<'\\n';\n }\n\nvoid printTriangle(int i = STARTING_STARS){\n assert (MAX_STARS - STARTING_STARS) % INC == 0;\n printRowOfStars(i);\n if (i == MAX_STARS)\n return;\n printTriangle(i+INC);\n printRowOfStars(i);\n }\n\nint main()\n{\n printTriangle();\n system(\"pause\");\n return 0;\n}\n</code></pre>\n\n<p>I liked it so I thought why not post it</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T03:30:10.583",
"Id": "12478",
"ParentId": "12465",
"Score": "3"
}
},
{
"body": "<p>@ecatmur hit the nail on the head: unless we know which are the moving parts, the hard-coded answer is the best. Otherwise, we can only guess what’s supposed to be variable:</p>\n\n<ol>\n<li>Does the number of lines change?</li>\n<li>Does the step increment change?</li>\n<li>Does the printed symbol change? E.g. <code>+</code> instead of <code>*</code>, or maybe even <code>[]</code>, necessitating a new data type (string instead of char).</li>\n<li>…</li>\n</ol>\n\n<p>Every solution will necessarily make some assumptions about these questions so it’s good to clear them up beforehand, or at least to be aware of them. As an interviewer, this is what I’d expect as the answer to this question.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T12:18:48.807",
"Id": "12486",
"ParentId": "12465",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "12467",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T16:20:40.257",
"Id": "12465",
"Score": "10",
"Tags": [
"c++",
"algorithm",
"interview-questions"
],
"Title": "Printing stars using nested loops"
}
|
12465
|
<p>Question is short. Assuming that I don't need reference itself, would this cast</p>
<pre><code>((TextView) findViewById(R.id.someTextView)).setText("lala");
</code></pre>
<p>be better (or at least not worse) than:</p>
<pre><code>TextView tv=(TextView) findViewById(R.id.someTextView);
tv.setText("lala");
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T00:33:09.820",
"Id": "20096",
"Score": "1",
"body": "I would say not worse from what's actually occurring point of view but defo second option IMHO for readability"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-26T14:35:17.567",
"Id": "79171",
"Score": "0",
"body": "This question appears to be off-topic because it is not asking for a code review."
}
] |
[
{
"body": "<p>The latter would be my preferred method. It enhances readability, and allows you to use that object more than once without casting it every time (more efficient). </p>\n\n<p>Though, if you are only casting to use one function inside the object, then there's no point in doing the latter (you would just be creating needless variables to only set one value in it once).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T10:34:49.460",
"Id": "20110",
"Score": "0",
"body": "As I said - the only purpose of casting is calling method."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T01:22:08.527",
"Id": "12477",
"ParentId": "12471",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T20:54:12.997",
"Id": "12471",
"Score": "2",
"Tags": [
"java",
"android",
"casting"
],
"Title": "Nice way to using cast on TextView"
}
|
12471
|
<pre><code>/********************************************************************************************
* ToDo - Make CIO and IServer basic functions....complete break down to functions.
*******************************************************************************************/
/********************************************************************************************
* foo.js - Module / File / Element Tracker
********************************************************************************************
* Model
| mSession
* View
| vTPane
| vBPane
| vFlipP
* Control
| cServer
| cIO
| cTryIt | tryit_button
| cBlocks | bottom_left_link, bottom_right_link
| cSignIn | signin_email_input, signin_email_label,signin_pass_input, signin_pass_label,
| signin_button
| cSignUp | signup_name_input, signup_name_label, signup_email_input, signup_email_label,
| signup_pass_input, signup_pass_label
* Independents
| iSerialize
| iFont
| iStyle
********************************************************************************************
*******************************************************************************************/
( function ( window, document )
{
"use strict";
/********************************************************************************************
********************************************************************************************
*Modle
********************************************************************************************
*******************************************************************************************/
function mUserTry()
{
cServer( 'model=user_try',function( response_text )
{
var array = JSON.parse( response_text.substring(3) );
mSession( 1, 'Test Account', 0, 0, 'Main' );
vStateElements( 'Test Account', '0' );
vBPane( array[1] );
vTPane( array[2] );
vFlipP( 'page_main' );
} );
}
function mUserNew()
{
cServer( 'model=user_new',function( response_text )
{
var array = JSON.parse( response_text.substring(3) );
mSession( array[0], 'Test Account', 0, 0, 'Main' );
vBPane( array[1] );
vTPane( array[2] );
vFlipP( 'page_main' );
} );
}
..
....
......
</code></pre>
|
[] |
[
{
"body": "<p>The singleton pattern <code>(function(x){...})(bar)</code> is useful for performing some complex set of actions once, without putting a bunch of members in the global namespace (or some other scope), and/or allowing the argument <code>bar</code> to be aliased as <code>x</code> within the outer function (including any inner functions), as with <code>jQuery</code> and <code>$</code> in a typical jQuery plugin.</p>\n\n<p>The singleton pattern <code>var FOO = (function(){ ...; return {...}; })()</code> forms a namespace <code>FOO</code>, with the ability to have private and privileged members.</p>\n\n<p>The pattern <code>Arc = ( function(window){...} )(window)</code> is a hybrid of these. <code>Arc</code> is <code>undefined</code> because the self-executing outer function doesn't return anything. The pattern's utility is therefore equivalent to the first pattern above but with the extra feature of creating the member <code>Arc</code>, which consumes a few bytes in the symbol table but is not useful.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T21:33:51.080",
"Id": "20440",
"Score": "0",
"body": "function my_function(){}...does this put my_function in the global namespace...?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T22:04:17.770",
"Id": "20443",
"Score": "0",
"body": "Not necessarily. It depends on where the statement sits. If it is not localized to an object, array or another function then it will be global. `function my_function(){}` can also be written `var my_function = function(){}`. From this you can see that the rules for function scope are the same as those for variable scope."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T23:52:56.877",
"Id": "12475",
"ParentId": "12474",
"Score": "0"
}
},
{
"body": "<p><code>Arc</code> in your code is undefined. The whole Immediately Invoked Function Expression (IFFE) returns nothing to <code>Arc</code>.</p>\n\n<p>Assuming that your code does nothing at all via the <code>Arc</code> reference and it's just being used as an initializer, we can simplify the code:</p>\n\n<pre><code>//the Arc reference was useless since the IFFE returned nothing\n//in the end, this whole IFFE basically just prevents global pollution\n//as well as executing the code immediately\n\n(function (window, document, undefined) {\n \"use strict\";\n\n //move these references outside the constructor\n //these elements are static. calling the functions call document.getElementById\n //to reference them again and again is an overhead when in fact, they don't change\n var tryit_button = document.getElementById('tryit_button'),\n bottom_left_link = document.getElementById('bottom_left_link'),\n bottom_right_link = document.getElementById('bottom_right_link'),\n signin_button = document.getElementById('signin_button'),\n signup_button = document.getElementById('signup_button'),\n signup_pass_input = document.getElementById('signup_pass_input');\n\n //use a function declaration (normal function) rather than a function expression (function in variable)\n //this gives you the advantage of \"hoisting\" - functions are moved up and exist before\n //operations even when they are declared after operations in the code\n function Cin() {\n function cTryIt() {\n tryit_button.addEventListener(\"click\", function () {}, false);\n }\n\n function cBlocks() {\n bottom_left_link.addEventListener(\"click\", function () {}, false);\n bottom_right_link.addEventListener(\"click\", function () {}, false);\n }\n\n function cSignIn() {\n vStyleTwitter([\"signin_email_input\", \"signin_email_label\", \"signin_pass_input\", \"signin_pass_label\"]);\n signin_pass_input.addEventListener(\"keypress\", function (event) {}, false);\n signin_button.addEventListener(\"click\", function () {}, false);\n }\n\n function cSignUp() {\n vStyleTwitter([\"signup_name_input\", \"signup_name_label\", \"signup_pass_input\", \"signup_pass_label\", \"signup_email_input\", \"signup_email_label\"]);\n signup_pass_input.addEventListener(\"keypress\", function (event) {}, false);\n signup_button.addEventListener(\"click\", function () {}, false);\n }\n\n this.initPage = function (page) {\n if (page === 'splash') {\n cTryIt();\n cBlocks();\n cSignIn();\n cSignUp();\n }\n };\n };\n\n //operations:\n console.log('ArcJ.js is Active');\n new Cin().initPage('splash')\n}(this, document));\n//use \"this\" instead of window. some developers say it's safer than using window\n//pass in document as well\n//Doug crockford recommends the parameter list be in the expression parenthesis\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T19:08:45.707",
"Id": "20137",
"Score": "0",
"body": "@stack.user.0 no, they don't persist through page changes. but in your original code, every call to functions like `cTryIt` and the rest calls `document.getElementById` which is an overhead. you can reference the element once in an outer scope."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T00:35:55.760",
"Id": "12476",
"ParentId": "12474",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12476",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-11T22:56:47.803",
"Id": "12474",
"Score": "-1",
"Tags": [
"javascript"
],
"Title": "Foo - No Globals | Remove identifier if no return"
}
|
12474
|
<p>I need a singleton that can safely operate in a multi-thread environment. Threading and concurrency is new to me, so I'm not sure if this implementation holds. Take a look:</p>
<pre><code>public class ObserverSingleton {
private static ObserverSingleton _instance;
private ArrayList<OnRequestFinishedListener> _listeners;
private ObserverSingleton() {
_listeners = new ArrayList<OnRequestFinishedListener>();
}
public static synchronized ObserverSingleton getInstance() {
if(_instance == null) {
_instance = new ObserverSingleton();
}
return _instance;
}
public synchronized void addOnRequestFinishedListener(OnRequestFinishedListener listener) {
// Check if listener already exists in list, skip if it does
for (OnRequestFinishedListener listListener : _listeners) {
if(listListener.equals(listener)) {
return;
}
}
_listeners.add(listener);
}
public synchronized void removeOnRequestFinishedListener(OnRequestFinishedListener listener) {
// Check if listener exists in list, remove if it does
for (OnRequestFinishedListener listListener : _listeners) {
if(listListener.equals(listener)) {
_listeners.remove(listListener);
}
}
}
private void notifyListeners() {
for (OnRequestFinishedListener listener : _listeners) {
listener.onRequestFinished();
}
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
public interface OnRequestFinishedListener {
public void onRequestFinished();
}
}
</code></pre>
<p>Any feedback?</p>
|
[] |
[
{
"body": "<p>The <code>notifyListeners()</code> method is private, and is never called anywhere. It should be synchronized on the same lock than the other methods using the list of listeners.</p>\n\n<p>Unless lazy instantiation is really needed, I wouldn't use it. Just use the following code:</p>\n\n<pre><code>private static final ObserverSingleton INSTANCE = new ObserverSingleton();\n\npublic static ObserverSingleton getInstance() {\n return INSTANCE;\n}\n</code></pre>\n\n<p>Also, I would use a <code>Set<OnRequestFinishedListener></code> rather than a list, since your add method makes sure there is only one copy of a listener inside the list, and Set is precisely used for that. If order of insertion matters, use a <code>LinkedHashSet<OnRequestFinishedListener></code>. </p>\n\n<p>Declaring the List as <code>ArrayList</code> is bad practice. You should declare it as <code>List</code>, since the concrete type doesn't matter.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T11:31:20.507",
"Id": "20112",
"Score": "0",
"body": "The code isn't complete, so notifyListeners() will get called later on. Thanks for the tips on instantiation and a Set implementation, really appreciated!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T11:32:39.803",
"Id": "20113",
"Score": "1",
"body": "That's what I thought, and this is why I didn't told you to remove it. But it's very important to synchronize it, else you might iterate on the list while another thread adds or removes a listener."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T11:27:51.447",
"Id": "12485",
"ParentId": "12484",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "12485",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T11:22:28.333",
"Id": "12484",
"Score": "4",
"Tags": [
"java",
"multithreading",
"singleton"
],
"Title": "Is this a good implementation of a thread-safe singleton using the observer pattern?"
}
|
12484
|
<p>I've just written this function for a test, but now I want to rewrite it for production.</p>
<p>I would like to know the best way to do this, or if this is "best practice" I think it's too long for the minimal stuff it does.</p>
<p>The whole idea is something like this: I have a one page with three sections floated left and a couple of subpages under each section.</p>
<p>X marks current page</p>
<pre>
-------------
| X | | |
-------------
| | | |
-------------
</pre>
<p>Then I have an indicator that looks like my little map above -
where X indicates which page is active etc...</p>
<pre><code> function pageIndicator() {
var projectCount = $('.current > .project').size();
var subcounter = $('.current > .page').size();
console.log(settings.subcount);
console.log(subcounter);
$('.activated').removeClass('activated');
$('.inactive').removeClass('inactive');
// SECTION ONE
if(settings.subcount == 1 && settings.count == 1) {
$('.pagination ul li:nth-child(1)').addClass('activated');
$('.pagination ul li:nth-child(3n+2), .pagination ul li:nth-child(3n+3)').addClass('inactive');
$('.pagination ul li:nth-child(2), .pagination ul li:nth-child(3)').removeClass('inactive');
}
if(settings.subcount != 1 && settings.subcount < (projectCount + 2) && settings.count == 1) {
$('.pagination ul li:nth-child(4)').addClass('activated');
$('.pagination ul li:nth-child(3n+2), .pagination ul li:nth-child(3n+3)').addClass('inactive');
$('.pagination ul li:nth-child(2), .pagination ul li:nth-child(3)').removeClass('inactive');
}
if(settings.subcount == (subcounter - 3) && settings.count == 1) {
$('.pagination ul li:nth-child(7)').addClass('activated');
$('.pagination ul li:nth-child(3n+2), .pagination ul li:nth-child(3n+3)').addClass('inactive');
$('.pagination ul li:nth-child(2), .pagination ul li:nth-child(3)').removeClass('inactive');
}
if(settings.subcount == (subcounter - 2) && settings.count == 1) {
$('.pagination ul li:nth-child(10)').addClass('activated');
$('.pagination ul li:nth-child(3n+2), .pagination ul li:nth-child(3n+3)').addClass('inactive');
$('.pagination ul li:nth-child(2), .pagination ul li:nth-child(3)').removeClass('inactive');
}
if(settings.subcount == (subcounter - 1) && settings.count == 1) {
$('.pagination ul li:nth-child(13)').addClass('activated');
$('.pagination ul li:nth-child(3n+2), .pagination ul li:nth-child(3n+3)').addClass('inactive');
$('.pagination ul li:nth-child(2), .pagination ul li:nth-child(3)').removeClass('inactive');
}
if(settings.subcount == subcounter && settings.count == 1) {
$('.pagination ul li:nth-child(16)').addClass('activated');
$('.pagination ul li:nth-child(3n+2), .pagination ul li:nth-child(3n+3)').addClass('inactive');
$('.pagination ul li:nth-child(2), .pagination ul li:nth-child(3)').removeClass('inactive');
}
// SECTION TWO
if(settings.subcount == 1 && settings.count == 2) {
$('.pagination ul li:nth-child(2)').addClass('activated');
$('.pagination ul li:nth-child(3n+1), .pagination ul li:nth-child(3n+3)').addClass('inactive');
$('.pagination ul li:nth-child(1), .pagination ul li:nth-child(3)').removeClass('inactive');
}
if(settings.subcount != 1 && settings.subcount < (projectCount + 2) && settings.count == 2) {
$('.pagination ul li:nth-child(5)').addClass('activated');
$('.pagination ul li:nth-child(3n+1), .pagination ul li:nth-child(3n+3)').addClass('inactive');
$('.pagination ul li:nth-child(1), .pagination ul li:nth-child(3)').removeClass('inactive');
}
if(settings.subcount == (subcounter - 3) && settings.count == 2) {
$('.pagination ul li:nth-child(8)').addClass('activated');
$('.pagination ul li:nth-child(3n+1), .pagination ul li:nth-child(3n+3)').addClass('inactive');
$('.pagination ul li:nth-child(1), .pagination ul li:nth-child(3)').removeClass('inactive');
}
if(settings.subcount == (subcounter - 2) && settings.count == 2) {
$('.pagination ul li:nth-child(11)').addClass('activated');
$('.pagination ul li:nth-child(3n+1), .pagination ul li:nth-child(3n+3)').addClass('inactive');
$('.pagination ul li:nth-child(1), .pagination ul li:nth-child(3)').removeClass('inactive');
}
if(settings.subcount == (subcounter - 1) && settings.count == 2) {
$('.pagination ul li:nth-child(14)').addClass('activated');
$('.pagination ul li:nth-child(3n+1), .pagination ul li:nth-child(3n+3)').addClass('inactive');
$('.pagination ul li:nth-child(1), .pagination ul li:nth-child(3)').removeClass('inactive');
}
if(settings.subcount == subcounter && settings.count == 2) {
$('.pagination ul li:nth-child(17)').addClass('activated');
$('.pagination ul li:nth-child(3n+1), .pagination ul li:nth-child(3n+3)').addClass('inactive');
$('.pagination ul li:nth-child(1), .pagination ul li:nth-child(3)').removeClass('inactive');
}
// SECTION THREE
if(settings.subcount == 1 && settings.count == 3) {
$('.pagination ul li:nth-child(3)').addClass('activated');
$('.pagination ul li:nth-child(3n+1), .pagination ul li:nth-child(3n+2)').addClass('inactive');
$('.pagination ul li:nth-child(1), .pagination ul li:nth-child(2)').removeClass('inactive');
}
if(settings.subcount != 1 && settings.subcount < (projectCount + 2) && settings.count == 3) {
$('.pagination ul li:nth-child(6)').addClass('activated');
$('.pagination ul li:nth-child(3n+1), .pagination ul li:nth-child(3n+2)').addClass('inactive');
$('.pagination ul li:nth-child(1), .pagination ul li:nth-child(2)').removeClass('inactive');
}
if(settings.subcount == (subcounter - 3) && settings.count == 3) {
$('.pagination ul li:nth-child(9)').addClass('activated');
$('.pagination ul li:nth-child(3n+1), .pagination ul li:nth-child(3n+2)').addClass('inactive');
$('.pagination ul li:nth-child(1), .pagination ul li:nth-child(2)').removeClass('inactive');
}
if(settings.subcount == (subcounter - 2) && settings.count == 3) {
$('.pagination ul li:nth-child(12)').addClass('activated');
$('.pagination ul li:nth-child(3n+1), .pagination ul li:nth-child(3n+2)').addClass('inactive');
$('.pagination ul li:nth-child(1), .pagination ul li:nth-child(2)').removeClass('inactive');
}
if(settings.subcount == (subcounter - 1) && settings.count == 3) {
$('.pagination ul li:nth-child(15)').addClass('activated');
$('.pagination ul li:nth-child(3n+1), .pagination ul li:nth-child(3n+2)').addClass('inactive');
$('.pagination ul li:nth-child(1), .pagination ul li:nth-child(2)').removeClass('inactive');
}
if(settings.subcount == subcounter && settings.count == 3) {
$('.pagination ul li:nth-child(18)').addClass('activated');
$('.pagination ul li:nth-child(3n+1), .pagination ul li:nth-child(3n+2)').addClass('inactive');
$('.pagination ul li:nth-child(1), .pagination ul li:nth-child(2)').removeClass('inactive');
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T15:12:22.317",
"Id": "20122",
"Score": "3",
"body": "Could you maybe post an example on jsfiddle and link it here or post your html? I think having your page markup will help significantly."
}
] |
[
{
"body": "<p>Well, there's a few basic best practice tips I can give to start without really looking at the logic.</p>\n\n<p>First, you can declare multiple variables in one statement, like so:</p>\n\n<pre><code>var projectCount = $('.current > .project').size(),\n subcounter = $('.current > .page').size();\n</code></pre>\n\n<p>Next, you access the same properties of an object multiple times, so you can avoid this and assign the value to a variable first.</p>\n\n<pre><code>var count = settings.count,\n subcount = settings.subcount;\n</code></pre>\n\n<p>Then </p>\n\n<pre><code>if(settings.subcount == (subcounter - 3) && settings.count == 1) {\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>if(subcount == (subcounter - 3) && count == 1) {\n</code></pre>\n\n<p>You can do the same thing with the class names that are used throughout:</p>\n\n<pre><code>var activated = 'activated',\n inactive = 'inactive';\n</code></pre>\n\n<p>This last step might seem pointless, but you can then run your script though a minifier such as <a href=\"http://dean.edwards.name/packer/\" rel=\"nofollow\">http://dean.edwards.name/packer/</a> which can reduce your long variable names into something much shorter for production.</p>\n\n<p>Looking at the logic it seems like you're repeating things an awful lot. For starters you should change your <code>if</code> statements to <code>else...if</code> as (I think) only one of these statements will be true, and if so there's no point in evaluating them all.</p>\n\n<p>There's probably a more concise way to achieve the same logical result but I'll leave that to you!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T15:10:09.133",
"Id": "12493",
"ParentId": "12492",
"Score": "2"
}
},
{
"body": "<p>Some suggestions: introduce a function for manipulating the classes, also you can check for the sections pretty easy and just once ... and actually, i'd stuff the bulks for the different sections in different methods. Determine the sections first, then pass the selected elements ... </p>\n\n<pre><code>function activate(el) {\n el.addClass('activated')\n}\n\nfunction toggle(el1, el2) {\n if (el1) el1.addClass('inactive');\n if (el2) el2.removeClass('inactive');\n}\n\nfunction pageIndicator() {\n\n $('.activated').removeClass('activated');\n $('.inactive').removeClass('inactive');\n\n var projectCount = $('.current > .project').size()\n , subcounter = $('.current > .page').size()\n , inSectionOne = settings.count == 1\n\n // SECTION ONE\n if (inSectionOne) {\n setUpSectionOne($('.pagination ul li:nth-child(3n+2), .pagination ul li:nth-child(3n+3)')\n , $('.pagination ul li:nth-child(2), .pagination ul li:nth-child(3)'))\n }\n}\n\nfunction setUpSectionOne(el1, el2) {\n var toggle = true;\n\n if (settings.subcount == 1) {\n activate($('.pagination ul li:nth-child(1)'));\n } else if (settings.subcount != 1 && settings.subcount < (projectCount + 2)) {\n activate($('.pagination ul li:nth-child(4)'));\n } else if (settings.subcount == (subcounter - 3)) {\n activate($('.pagination ul li:nth-child(7)'));\n } else if (settings.subcount == (subcounter - 2)) {\n activate($('.pagination ul li:nth-child(10)'));\n } else if (settings.subcount == (subcounter - 1)) {\n activate($('.pagination ul li:nth-child(13)'));\n } else if (settings.subcount == subcounter) {\n activate($('.pagination ul li:nth-child(16)'));\n } else {\n toogle = false;\n }\n\n if (toggle) {\n toggle(el1, el2);\n }\n}\n</code></pre>\n\n<p>This is just for the first section, but it should be easy to apply it for the others as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T07:25:01.907",
"Id": "20167",
"Score": "0",
"body": "I get a boolean error on the last if query"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T08:39:14.887",
"Id": "20168",
"Score": "0",
"body": "Solved it. Did trash the toggle function and added the classes directly instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T09:22:27.810",
"Id": "20172",
"Score": "0",
"body": "I added a null in the toggle function, that might have been solved it as well."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T20:51:51.933",
"Id": "12505",
"ParentId": "12492",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "12505",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T14:41:54.533",
"Id": "12492",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Page indicator - can it be smaller?"
}
|
12492
|
<p>This is my first real Cocoa app that I am writing. The first version of this app was just one long applescript. So in my app <a href="http://code.gogle.com/auto-git" rel="nofollow">auto git,</a> I have an NSTask instead of Tell terminal. My code looks like this:</p>
<pre><code>-(void) runScript:(NSString *) path:(NSString* )cmd1:(NSString *) cmd2:(NSString *) cmd3{
NSTask *aTask = [[NSTask alloc] init];
NSPipe *pipe;
pipe = [NSPipe pipe];
[aTask setStandardOutput: pipe];
NSFileHandle *file;
file = [pipe fileHandleForReading];
NSArray* args = [NSArray arrayWithObjects:cmd1,cmd2,cmd3, nil];
[aTask setArguments:args];
[aTask setCurrentDirectoryPath:path];
[aTask setLaunchPath:@"/usr/local/git/bin/git"];
[aTask setArguments:args];
[aTask launch];
[finished setStringValue:@"finished"];
}
</code></pre>
<p>Example usage: </p>
<pre><code>[self runScript:dirPath:@"add" :@"*" :nil];
[self runScript:dirPath:@"commit" :@"-m" :commitText];
[self runScript:dirPath:@"push" :@"origin" :@"HEAD"];
</code></pre>
<p>Is there a better way to do this? And what about errors? How to I let the user take care of custom errors? </p>
<p>All help appreciated. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T14:03:17.377",
"Id": "73401",
"Score": "0",
"body": "In regards to your question about errors, what kind of errors could happen? I see nothing relating to error handling in here. Also, your link doesn't work"
}
] |
[
{
"body": "<p>First of all, I don't care for this style of method naming in the slightest. This is Objective-C. Our method names should be verbose and descriptive. If the method name is too long, code completion will help us out. But if it's too short, and we have other methods that perform similar tasks, we may easily get confused. This is particularly true when the person who is implementing this code or maintaining code that uses your code ends up being someone other than yourself.</p>\n\n<pre><code>- (void)runScript:(NSString*)path \n command1:(NSString*)command1\n command2:(NSString*)command2\n command3:(NSString*)command3;\n</code></pre>\n\n<p>Already this method name is better, but it still needs work because the argument following \"runScript\" is labeled as (and internally used as) a path. This isn't the Objective-C way. </p>\n\n<p>And if I'm honest, the <code>command1</code>, <code>command2</code>, <code>command3</code> is a little confusing. The values sent here are arguments, not values. You know this, because as soon as you dealt with them, you moved them into an array called <code>args</code>, and then put them into the task using <code>setArguments:</code>.</p>\n\n<p>Here's how I'd change method signature:</p>\n\n<pre><code>- (void)runScript:(NSArray*)arguments inDirectoryPath:(NSString*)path;\n</code></pre>\n\n<p>Now instead of taking multiple arguments, we take the arguments in an array.</p>\n\n<p>But this alone probably isn't good enough. We do need to verify that they're actually sending us arguments, as <code>NSTask</code> will raise an exception if the arguments are nil.</p>\n\n<p>So, let's modify the method call one more time:</p>\n\n<pre><code>- (void)runScript:(NSArray*)arguments \n inDirectoryPath:(NSString*)path\n error:(NSError**)error;\n</code></pre>\n\n<p>This is the way Apple handles errors with many of the built-in Objective-C classes.</p>\n\n<p>The user can pass <code>nil</code> for the <code>error</code> argument if they don't care about it, but if they do, we can give them some useful information about the error back using it.</p>\n\n<p>Now let's verify the array will be okay to pass as the arguments array:</p>\n\n<pre><code>@autoreleasepool {\n NSString *errorString;\n NSInteger *errorCode;\n BOOL errorExists = NO;\n if ([arguments count] < 2) {\n errorString = @\"Invalid Arguments: too few arguments\";\n errorCode = 100;\n errorExists = YES;\n } else {\n for (NSObject *arg in arguments) {\n if (![arg isKindOfClass:[NSString class]]) {\n errorString = @\"Invalid Arguments: arguments must be strings\";\n errorCode = 101;\n errorExists = YES;\n } else if (!arg) {\n errorString = @\"Invalid Arguments: arguments cannot be nil\";\n errorCode = 102;\n errorExists = YES;\n }\n if (errorExists) {\n break;\n }\n }\n }\n if (errorExists) {\n if(error) {\n *error = [NSError errorWithDomain:errorString\n code:errorCode\n userInfo:nil];\n } \n return;\n }\n}\n</code></pre>\n\n<p>Now, before <code>NSTask</code> has an opportunity to raise an exception, we've stopped executing our method and given some feedback.</p>\n\n<p>This can be even more helpful if you change the return type from <code>void</code> to <code>BOOL</code>. Then in the above snippet, we'd change <code>return;</code> to <code>return NO;</code>.</p>\n\n<p>And then your code could be used as such:</p>\n\n<pre><code>if(![self runScript:aScript inDirectoryPath:aPath error:&error]) {\n // some code to make user aware of the error\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T14:43:03.960",
"Id": "73405",
"Score": "1",
"body": "passing in a space-separated string is a horrible idea (think of quoting, e.g. in `git commit -m \"some message\"`) – wouldn't it be better to pass in the array directly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T15:02:53.333",
"Id": "73407",
"Score": "0",
"body": "Sure. That could easily be done as well. I'm not exactly super familiar with what the git commands would be. I'll edit the answer to reflect this."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T14:36:24.727",
"Id": "42596",
"ParentId": "12494",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T15:21:34.497",
"Id": "12494",
"Score": "4",
"Tags": [
"objective-c",
"git",
"child-process"
],
"Title": "NSTask with Git"
}
|
12494
|
<p>I have a switch statement that checks whether or not one string matched another that was stored in an array. However, there are multiple cases in which the same result is returned for multiple matches. I originally had a large amount of if/else checks, but tried to shorten that down with the switch statement. I was wondering, is there anyway to shorten down this switch statement?</p>
<pre><code>
function checkLoc(xstreets) {
var address;
if(xstreets[2] == undefined) {
address = xstreets[0]+" & "+xstreets[1]+" Chicago IL";
}
else {
switch(xstreets[2]) {
case "aon":
address = "Aon Center Chicago IL";
break;
case "trump":
address = "401 North Wabash Avenue, Chicago, IL";
break;
case "pritzker":
address = "Pritzker Park Chicago IL";
break;
case "hyde":
case "hydepark":
case "uofc":
case "uchicago":
address = "5801 South Ellis Avenue, Chicago, IL";
break;
case "reg":
address = "1100 E 57th St, Chicago, IL 60637";
break;
case "willis":
case "wttw":
address = "233 South Wacker Drive, Chicago, IL";
break;
case "600":
address = "600 West Chicago Avenue, Chicago, IL";
break;
default:
address = xstreets[0]+" & "+xstreets[1]+" Chicago IL";
break;
}
}
return address;
}
</code></pre>
|
[] |
[
{
"body": "<p>You can convert it to two array. The first will normalize multiple \"aliases\" of the same key into one and second will have your address values.</p>\n\n<pre><code>var aliases = {\n \"hyde\" : \"hydepark\",\n \"uofc\" : \"hydepark\",\n \"uchicago\" : \"hydepark\",\n \"wttw\" : \"willis\"\n};\n\nvar addresses = {\n \"hydepark\" : \"5801 South Ellis Avenue, Chicago, IL\",\n ...\n};\n\nvar alias = aliases[xstreets[2]];\nif(alias == undefined) {\n alias = xstreets[2]\n}\nvar address = addresses[alias];\nif(address == undefined) {\n return xstreets[0]+\" & \"+xstreets[1]+\" Chicago IL\";\n}\nreturn address;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T16:39:23.673",
"Id": "12498",
"ParentId": "12495",
"Score": "4"
}
},
{
"body": "<p>Taking a step further, the function... <a href=\"http://jsfiddle.net/dCTjR/1/\" rel=\"nofollow\">I just turned into a one liner</a>:</p>\n\n<pre><code> //array indices are shorter than using aliases\n //we index streets to your addresses\nvar streets = {\n 'aon': 0,\n 'trump': 1,\n 'pritzker': 2,\n 'hyde': 3,\n 'hydepark': 3,\n 'uofc': 3,\n 'uchicago': 3,\n 'reg': 4,\n 'willis': 5,\n 'wttw': 5,\n '600': 6\n },\n addresses = [\n 'Aon Center Chicago IL', \n '401 North Wabash Avenue, Chicago, IL', \n 'Pritzker Park Chicago IL', \n '5801 South Ellis Avenue, Chicago, IL', \n '1100 E 57th St, Chicago, IL 60637',\n '233 South Wacker Drive, Chicago, IL',\n '600 West Chicago Avenue, Chicago, IL'\n ];\n\nfunction checkLoc(xstreets) {\n\n //an undefined index/key returns undefined\n //we can use \"||\" which acts like loose comparison\n //if the value before \"||\" is falsy, it evaluates the value\n //after \"||\". If the value after \"||\" is not followed by another \n //operator, it's considered the \"default value\"\n return addresses[streets[xstreets[2]]] || xstreets[0] + \" & \" + xstreets[1] + \" Chicago IL\";\n}\n\n//single check\nconsole.log(checkLoc(['foo','bar','aon']));\n\n//multi check\nconsole.log(checkLoc(['foo','bar','uofc']));\nconsole.log(checkLoc(['foo','bar','uchicago']));\n\n//nonexistent street\nconsole.log(checkLoc(['foo','bar','baz']));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T18:36:24.517",
"Id": "12501",
"ParentId": "12495",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "12498",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T15:26:58.747",
"Id": "12495",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "jQuery Shorten Switch Statement"
}
|
12495
|
<p>The <code>.htaccess</code> file redirects all requests to this file and the <code>$_REQUEST['path']</code> variable contains the url after the base url.</p>
<pre><code>$url = '';
$urlSegments = [];
$resource = '';
$action = '';
$parameters = [];
if(isset($_REQUEST['path'])){
$url = $_REQUEST['path'];
$urlSegments = explode('/', $url);
if(!empty($urlSegments[0])){
$resource = $urlSegments[0];
array_shift($urlSegments);
if(!empty($urlSegments[0])){
$action = $urlSegments[0];
array_shift($urlSegments);
$parameters = $urlSegments;
}
}
}
$method = $_SERVER['REQUEST_METHOD'];
</code></pre>
<p>I was wondering if there is an better way (with regex maybe?) to parse the url, loop through it and extract the MVC data from the url. <code>array_shift</code> looks ugly and it feels that there must be a better way.</p>
|
[] |
[
{
"body": "<p>This example:</p>\n\n<pre><code>$uri = '/users/create';\n$regex = '~^/(?P<resource>.*?)/(?P<action>.*?)/?$~';\n\nif (preg_match($regex, $uri, $matches)) {\n print_r($matches);\n}\n</code></pre>\n\n<p>Will produce following result:</p>\n\n<pre><code>Array\n(\n [0] => /users/create\n [resource] => users\n [1] => users\n [action] => create\n [2] => create\n)\n</code></pre>\n\n<p>Hope this helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T17:37:49.877",
"Id": "20128",
"Score": "0",
"body": "If that array could some how be cleaned up so it only had the associative keys in it, then you could use extract to get those variables out of it. However, what does this do in the instance that there are some parameters as well? I'm horrible with regex, so just curious..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T17:42:09.280",
"Id": "20130",
"Score": "0",
"body": "When match attempt is successful, everything is stored inside resulting array(i.e. $matches). Which includes a) full match; b) named group in first parens; c) just group without name(i.e. resource); d) second named group; and e) same group without name."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T16:24:18.187",
"Id": "12497",
"ParentId": "12496",
"Score": "4"
}
},
{
"body": "<p><strong>Disclaimer:</strong> I do eventually answer your question, there are just some other things I wished to point out.</p>\n\n<p><strong>GET vs REQUEST</strong></p>\n\n<p>First of all, I would consider using <code>$_GET</code> instead of <code>$_REQUEST</code>. I'm assuming its get your using judging by the data you are passing. It is generally a better idea to use the specific array you need if you know it rather than one that could potentially contain data from another source. For example, should you ever create a form with a path input, it will supersede any get path. But this isn't even necessary, the remote user can change that value should they wish. However, if you were to call them separately <code>$_GET[ 'path' ]</code> and <code>$_POST[ 'path' ]</code> you will be able to use them both together without losing any information and they are less likely to be hijacked (minus get, its pretty easy to hijack that).</p>\n\n<p><strong>Filter Input</strong></p>\n\n<p>Take a look at PHP's <code>filter_input()</code>. It will mean you only have to type that <code>$url</code> variable once and has the added benefit of sanitizing your input.</p>\n\n<pre><code>$url = filter_input( INPUT_GET, 'path', FILTER_SANITIZE_STRING );\n//returns false if not set so\nif( $url ) {\n //etc...\n}\n</code></pre>\n\n<p><strong>Array Shift</strong></p>\n\n<p>PHP's <code>array_shift()</code> returns the value shifted, so there is no reason to specifically call that value, simply set the variable as you shift it.</p>\n\n<pre><code>$resource = array_shift( $urlSegments );\n</code></pre>\n\n<p><strong>Order of Logic</strong></p>\n\n<p>Instead of checking if the value of <code>$urlSegments</code> is empty, I would set it first then check it. A couple of reasons for this. What if \"path\" starts with a forward slash \"/\"? I believe explode will produce an empty element at the very beginning. Unless this is the desired result, it could cause errors. Also, it removes the need for those magic numbers, i.e.(<code>$urlSegments[0]</code>) Yes its obvious where it came from and why you are using it, but it is a bad habit and is not extendable.</p>\n\n<pre><code>$resource = array_shift( $urlSegments );\nif( ! empty( $urlSegments ) ) {\n if( ! empty( $resource ) ) {\n $action = array_shift( $urlSegments );\n if( ! empty( $action ) ) { $parameters = $urlSegments; }\n } else {\n //handle $url starting with a forward slash\n //this is where having this set up in functions would help\n }\n}\n</code></pre>\n\n<p><strong>Here's the Better Solution: Only one parameter</strong></p>\n\n<p>However, the cleanest way of all is to guarantee the length of <code>$urlSegments</code>, then use PHP's <code>list()</code>. So, you can use <code>array_pad()</code> to fill out the rest of <code>$urlSegments</code> should it be too short, otherwise <code>list()</code> will produce errors. If it is already of the proper size it will not do anything so you don't need to test it first. Now, to ensure that it doesn't already contain empty elements, that it didn't start with a forward slash, or have any double slashes, you should run it through <code>array_filter()</code>. <strong>Note:</strong> This will remove any element that could be considered \"false\" (0, '', null, -1, etc) so be careful here. This also means that if you were using empty or false parameters before, then it may not work the same way. <strong>Edit:</strong> This is if you use <code>array_filter()</code> without a callback, you could always make your own callback function to ignore certain values.</p>\n\n<pre><code>$urlSegments = array_filter( $urlSegments );\n$urlSegments = array_pad( $urlSegments, 3, '' );\nlist( $resource, $action, $parameters ) = $urlSegments;\n</code></pre>\n\n<p><strong>Here's the Better Solution: Multiple parameters</strong></p>\n\n<p>I just realized that <code>$urlSegments</code> could very likely be longer than 3 elements. In this case, I would filter and pad it like I did above, shift the first two elements into their respective variables then set <code>$parameters</code> to whatever remains of <code>$urlSegments</code>. Padding it first ensures that each variable has a default value of an empty string.</p>\n\n<pre><code>$urlSegments = array_filter( $urlSegments );\n$urlSegments = array_pad( $urlSegments, 3, '' );\n$resource = array_shift( $urlSegments );//default = '';\n$action = array_shift( $urlSegments );//default = '';\n$parameters = $urlSegments;//default = array( '' );\n</code></pre>\n\n<p><strong>Shorthand</strong></p>\n\n<p>Finally, it is rarely a good idea to use shorthand in PHP. If I did not know what you were trying to accomplish, or had a slightly older version of PHP, I would think that <code>$urlSegments = [];</code> was syntactically wrong. Yes it works, but you could run across problems in the future. Not to mention its just easier to read <code>$urlSegments = array();</code></p>\n\n<p><strong>Regex</strong></p>\n\n<p>That should clean up your code considerably. I would hesitate to suggest any regex, mainly because I find it extremely difficult to read.</p>\n\n<p><strong>Edits</strong></p>\n\n<p>Edited a few times to clean up post and add the second \"Better Solution\".</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T19:01:09.510",
"Id": "20133",
"Score": "2",
"body": "@msanford: It's always good when you walk away from teaching someone something having learned something yourself. A lot of that explanation is me walking myself through it :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T11:04:26.083",
"Id": "20174",
"Score": "0",
"body": "@showerhead I really appreciate all the effort, but it was a little bit of an over kill, you tell me about santization, but that is not really needed at this point, since we'r just parsing the URL, we are not posting to the database. Also about the shorthand thing, [] instead of array(), go read php 5.4 release log ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T11:57:07.597",
"Id": "20176",
"Score": "0",
"body": "@onlineracoon I have read the 5.4 release log, at least enough to know about that method. As I said, I know what you are trying to do. But shorthand is not always the best way if you want to have readable code. Not only that but, not everyone is going to know about it, or be able to support it should you ever need to move it to another server. Sanitizing is still important, especially with URL parsing because of PHP injection. I don't know exactly how they do it, think it has more to do with eval users, but its always better to ensure it isn't possible. Especially if its only one extra line."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T17:15:22.590",
"Id": "12500",
"ParentId": "12496",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "12497",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T16:04:48.323",
"Id": "12496",
"Score": "4",
"Tags": [
"php",
"parsing"
],
"Title": "Parsing URL segments"
}
|
12496
|
<p>The "vectorizing" of fancy indexing by Python's NumPy library sometimes gives unexpected results.</p>
<p>For example:</p>
<pre><code>import numpy
a = numpy.zeros((1000,4), dtype='uint32')
b = numpy.zeros((1000,4), dtype='uint32')
i = numpy.random.random_integers(0,999,1000)
j = numpy.random.random_integers(0,3,1000)
a[i,j] += 1
for k in xrange(1000):
b[i[k],j[k]] += 1
</code></pre>
<p>It gives different results in the arrays '<code>a</code>' and '<code>b</code>' (i.e. the appearance of tuple (i,j) appears as 1 in '<code>a</code>' regardless of repeats, whereas repeats are counted in '<code>b</code>').</p>
<p>This is easily verified as follows:</p>
<pre><code>numpy.sum(a)
883
numpy.sum(b)
1000
</code></pre>
<p>It is also notable that the fancy indexing version is almost two orders of magnitude faster than the <code>for</code> loop.</p>
<p>Is there an efficient way for NumPy to compute the repeat counts as implemented using the for loop in the provided example?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T16:39:59.470",
"Id": "20140",
"Score": "0",
"body": "I'm not quite sure I understand the question. Wouldn't that always be the length of i and j? Is there a case where it isn't?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T17:06:15.043",
"Id": "20141",
"Score": "0",
"body": "Nope. In the fancy indexing case, a[i,j] += 1, any repeated (i,j) combinations will only increment a[i,j] once. It is as if the right-hand side is evaluated all at once, a[:] + 1, where all values in 'a' are 0, and the result is saved back at once setting some values in 'a' to 1. In the for-loop case, b[i[k],j[k]] += 1, repeated (i,j) pairs each increment their count by 1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T18:10:20.700",
"Id": "20142",
"Score": "0",
"body": "I see that the two indexing methods yield different results, but wouldn't the for-loop indexing always result in `numpy.sum(b) == j.size`? Because for each element in `i, j` some element of `b` is incremented once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T18:42:24.977",
"Id": "20143",
"Score": "0",
"body": "Yes. The for-loop version of `b` always adds up to `j.size`. However, the result I need is the final counts in `b`. Is there a fast way to compute `b`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T18:45:25.990",
"Id": "20144",
"Score": "0",
"body": "Ah, now I understand. You're not interested in `sum(b)`, but in `b` itself. Me blockhead today."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T18:55:53.613",
"Id": "20145",
"Score": "0",
"body": "Some folks have suggested using `bincount()` with various reshapings. I should have mentioned that I made my example much smaller than the actual dataset I am working with. In my case `b` is a `memmap()` with > (2*10**9,4) entries, and the `i,j` combinations are only a few million with frequent repeats. My point being that the 'bincount()' output will be very sparse, and expensive in terms of memory."
}
] |
[
{
"body": "<p>This is what I came up with (see the <code>flat</code> function at the bottom):</p>\n\n<pre><code>from timeit import timeit\nimport numpy\n\n# Dimensions\nROWS = 1000\nCOLS = 4\n\n# Number of times to run timeit\nTEST_COUNT = 100 \n\n# Matrices\na = numpy.zeros((ROWS, COLS), dtype='uint32')\nb = numpy.zeros((ROWS, COLS), dtype='uint32')\nc = numpy.zeros((ROWS, COLS), dtype='uint32')\n\n# Indices\ni = numpy.random.random_integers(0, ROWS - 1, ROWS)\nj = numpy.random.random_integers(0, COLS - 1, ROWS)\n\n# Fancy\ndef fancy():\n a[i,j] += 1\nprint \"Fancy:\", timeit(\"fancy()\", setup=\"from __main__ import fancy\", number=TEST_COUNT)\n\n# Loop\ndef loop():\n for k in xrange(1000):\n b[i[k],j[k]] += 1\nprint \"Loop:\", timeit(\"loop()\", setup=\"from __main__ import loop\", number=TEST_COUNT)\n\n# Flat\ndef flat():\n flatIndices = i*COLS + j\n sums = numpy.bincount(flatIndices)\n c.flat[:len(sums)] += sums\n\nprint \"Flat:\", timeit(\"flat()\", setup=\"from __main__ import flat\", number=TEST_COUNT)\n\n# Check that for_loop and custom are equivalent\nprint \"Equivalent:\", (c == b).all()\n</code></pre>\n\n<p>On my machine, that prints:</p>\n\n<pre><code>Fancy: 0.0117284889374\nLoop: 0.937140445391\nFlat: 0.0165873246295\nEquivalent: True\n</code></pre>\n\n<p>So the <code>flat</code> version is about 50% slower than <code>fancy</code>, but much faster than <code>loop</code>. It does take up some memory for the <code>flatIndices</code> and <code>sums</code>, though. Note that <code>c.flat</code> does not create a copy of <code>c</code>, it only provides a linear interface to the array.</p>\n\n<p><strong>Edit:</strong> Out of curiousity, I ran another test with <code>COLS = 1e6</code> with the following results:</p>\n\n<pre><code>Fancy: 24.6063425241\nLoop: N/A\nFlat: 22.4316268267\n</code></pre>\n\n<p>Memory usage according to the Windows task manager (not the most accurate measuring tool, I know) was at about 80 MB base-line, spiking up to 130 MB during <code>flat()</code>.</p>\n\n<p><strong>Edit Nr 2:</strong> Another attempt with your benchmark:</p>\n\n<pre><code>def flat():\n flatIndices = i*COLS + j\n uniqueIndices = numpy.unique(flatIndices)\n bins = numpy.append(uniqueIndices, uniqueIndices.max() + 1)\n histo = numpy.histogram(flatIndices, bins)\n c.flat[uniqueIndices] += histo[0]\n</code></pre>\n\n<p>This gives me </p>\n\n<pre><code>Fancy: 0.143004997089\nLoop: 9.48711325557\nFlat: 0.474580977267\nEquivalent: True\n</code></pre>\n\n<p>This looks much better. Unfortunately, I couldn't find a way to avoid the <code>bins</code> array since <code>numpy.histogram</code> treats the last bin as a closed interval. So if you only pass <code>uniqueIndices</code> as bins, histogram will put both the last and second to last index in the same bin, which is usually wrong.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T19:24:39.937",
"Id": "12504",
"ParentId": "12503",
"Score": "0"
}
},
{
"body": "<p>Ben,</p>\n\n<p>The following modification to your code is a more accurate reflection of my larger problem:</p>\n\n<pre><code>\n\n from timeit import timeit\n import numpy\n\n # Dimensions\n ROWS = 10000000\n SAMPLES = 10000\n COLS = 4\n\n # Number of times to run timeit\n TEST_COUNT = 100 \n\n # Matrices\n a = numpy.zeros((ROWS, COLS), dtype='uint32')\n b = numpy.zeros((ROWS, COLS), dtype='uint32')\n c = numpy.zeros((ROWS, COLS), dtype='uint32')\n\n # Indices\n i = numpy.random.random_integers(0, ROWS - 1, SAMPLES)\n j = numpy.random.random_integers(0, COLS - 1, SAMPLES)\n\n # Fancy\n def fancy():\n a[i,j] += 1\n print \"Fancy:\", timeit(\"fancy()\", setup=\"from __main__ import fancy\", number=TEST_COUNT)\n\n # Loop\n def loop():\n for k in xrange(SAMPLES):\n b[i[k],j[k]] += 1\n print \"Loop:\", timeit(\"loop()\", setup=\"from __main__ import loop\", number=TEST_COUNT)\n\n # Flat\n def flat():\n flatIndices = i*COLS + j\n sums = numpy.bincount(flatIndices)\n c.flat[:len(sums)] += sums\n\n print \"Flat:\", timeit(\"flat()\", setup=\"from __main__ import flat\", number=TEST_COUNT)\n\n # Check that for_loop and custom are equivalent\n print \"Equivalent:\", (c == b).all()\n\n</code></pre>\n\n<p>With the exception that there are probably few samples that are actually repeated in this version. Let's ignore that difference for now. On my machine, your code gave the following timings:</p>\n\n<pre><code>\n\n Fancy: 0.109203100204\n Loop: 7.37937998772\n Flat: 126.571173906\n Equivalent: True\n\n</code></pre>\n\n<p>This slowdown is largely attributable to the large sparse array output by bincount().</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T21:50:10.363",
"Id": "20155",
"Score": "0",
"body": "See the second edit in my post. I'm off to bed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T21:02:34.803",
"Id": "12507",
"ParentId": "12503",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-06-12T16:34:47.097",
"Id": "12503",
"Score": "2",
"Tags": [
"python",
"numpy"
],
"Title": "Compound assignment operators in Python's NumPy library"
}
|
12503
|
<p>I have been setting multiple variables like this </p>
<pre><code>function doSomething() {
var FirstName = $FirstName.data("ov");
var LastName = $LastName.data("ov");
var Company = $Company.data("ov");
var Website = $Website.data("ov");
}
</code></pre>
<p>I just read some reviewed code and both reviewers advised setting the variables in a single statement, like this:</p>
<pre><code>function doSomething() {
var FirstName = $FirstName.data("ov"),
LastName = $LastName.data("ov"),
Company = $Company.data("ov"),
Website = $Website.data("ov");
}
</code></pre>
<p>What would be the advantage of doing it the second way? Is there a performance benefit? Is it that there is less code? </p>
|
[] |
[
{
"body": "<p>There should be no noticeable difference in performance (even if there was, it would most likely be negligible) and they mean the same.</p>\n\n<p>It's just a matter of picking the one that's most readable. Frankly, I don't find the second example more readable than the first, but this is subjective.</p>\n\n<p>EDIT: One possible difference is that smaller code (assuming those are charaters replacing \"var\" are tabs and not spaces) might reduce traffic, making the page faster. However, in practice, I think the best JS minifiers should handle that sort of thing for you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T21:05:34.817",
"Id": "20150",
"Score": "0",
"body": "I think you meant \"there should be NO noticeable...\" Is that correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T21:06:48.463",
"Id": "20151",
"Score": "0",
"body": "@EvikJames Indeed. Sorry for the mistake."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T21:04:23.410",
"Id": "12508",
"ParentId": "12506",
"Score": "1"
}
},
{
"body": "<p>From a very good book called <a href=\"http://rads.stackoverflow.com/amzn/click/0596806752\" rel=\"nofollow\">JavaScript Patterns</a>:</p>\n\n<blockquote>\n <p>Using a single <strong>var</strong> statement at the top of your functions is a useful pattern to adopt. It has the following benefits:</p>\n \n <ul>\n <li>Provides a single place to look for all the local variables needed by the function</li>\n <li>Prevents logical errors when a variable is used before it's defined</li>\n <li>Helps you remember to declare variables and therefore minimize globals</li>\n <li>Is less code (to type and to transfer over the wire)</li>\n </ul>\n</blockquote>\n\n<p>The author also recommends initializing the variables when you declare them when possible.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T21:10:08.633",
"Id": "20152",
"Score": "0",
"body": "Those are some compelling reasons, the least of which is a performance boost."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T21:13:39.657",
"Id": "20153",
"Score": "0",
"body": "@Evik - mucking up the global namespace, by forgetting the var keyword can have huge performance impacts. So, I assume you are referring to the \"is less code\" bullet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T21:24:01.767",
"Id": "20154",
"Score": "0",
"body": "I tend to not mistakes like that, forgetting to var it. I made that mistake early on and killed my browser memory doing a bunch of Ajax stuff. Assuming I code it correctly, it will have little performance advantage. The real advantage will be in creating the necessary local variables right away at the top of the function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T22:42:54.070",
"Id": "20161",
"Score": "0",
"body": "I'd argue that at least #1 and #3 do not matter in this case. The first code example does provide a \"single place to look for\" and minimizes globals just as much as the second example. In fact, the only example of those 4 that seems to make a difference in this case is #4 and, even then, not by much(in this particular case - assuming spaces are used - there are exactly as many bytes being sent)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T21:07:41.957",
"Id": "12509",
"ParentId": "12506",
"Score": "3"
}
},
{
"body": "<p>In terms of performance, <a href=\"http://jsperf.com/single-var-vs-multiple-var\" rel=\"nofollow\">there is little difference</a> across both methods. <a href=\"http://jsperf.com/var-type-comparison\" rel=\"nofollow\">Another test found here</a> which has greater browser coverage.</p>\n\n<p>In terms of readability, I'd go for the multiple variables using a single <code>var</code> since it is less messy.</p>\n\n<p>All in all, it depends on you.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T21:07:55.293",
"Id": "12510",
"ParentId": "12506",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12509",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T20:53:11.807",
"Id": "12506",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "How to set multiple variables at once in JavaScript?"
}
|
12506
|
<p>I have many pages with functions that appear only once, which I am sure is really typical. I read that it's the best idea to use the local scope for functions when possible because the local scope is searched first, thereby making the function found sooner.</p>
<p>If I have no intention of reusing a function, is this the best way to create and use this function?</p>
<pre><code>var doCancel = function doCancel() {
// DO SOME CANCELLING TYPE STUFF
}
</code></pre>
<p>Or is this a better way?</p>
<pre><code>function doCancel() {
// DO SOME CANCELLING TYPE STUFF
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T22:58:18.277",
"Id": "20162",
"Score": "0",
"body": "Your examples are likely identical in scope (though there will be some differences: http://stackoverflow.com/questions/1013385/what-is-the-difference-between-a-function-expression-vs-declaration-in-javascrip)"
}
] |
[
{
"body": "<p>Global versus local scope:</p>\n\n<p>It depends on what you are working with. If you are in a framework or the javascript you are using could possibly collide with another javascript then you should localize it. Other than that, if it is a single page site, then there is no need to worry. I try to put most of my javascript in closures, but only because I work inside a framework where the possibility of collisions can be higher.</p>\n\n<p>As for the two ways laid out, it is really preference in how you want to call it. They are both still global in that a call to <code>doCancel</code> or <code>doCancel()</code> can be accessed anywhere that shares scope with the script.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T21:39:08.113",
"Id": "12513",
"ParentId": "12511",
"Score": "3"
}
},
{
"body": "<p>I always wrap my code in an IIFE:</p>\n\n<pre><code>(function () {\n 'use strict';\n\n //code here\n}());\n</code></pre>\n\n<p>I also pass in all global variables I am going to use in this code block:</p>\n\n<pre><code>(function (window, document, $) {\n 'use strict';\n\n //code here\n}(window, document, jQuery)); //...\n</code></pre>\n\n<p>If I am going to expose any global variables I explicitly add them to the global scope at the end of this function (but I avoid this if it is at all possible):</p>\n\n<pre><code>(function (window, document, $) {\n 'use strict';\n\n //code here\n\n window.XXX = somelocalreference;\n}(window, document, jQuery)); //...\n</code></pre>\n\n<p>This way I never unexpectedly leak globals and I can know that my code is not going to give me problems with future changes that my coworkers or myself make.</p>\n\n<p>See also: <a href=\"https://codereview.stackexchange.com/questions/11233/optimizing-and-consolidating-a-big-jquery-function/11235#11235\">Responsive/adaptive website code</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T01:32:34.563",
"Id": "12516",
"ParentId": "12511",
"Score": "14"
}
}
] |
{
"AcceptedAnswerId": "12516",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-12T21:30:46.597",
"Id": "12511",
"Score": "6",
"Tags": [
"javascript"
],
"Title": "Should I put a JavaScript function in a local or global scope?"
}
|
12511
|
<p>Inspired by Don Stewart's article on <a href="https://donsbot.wordpress.com/2010/08/17/practical-haskell/" rel="nofollow">Scripting with Haskell</a> I tried a rewrite of a shell-script I did the other day. I was really astonished how easily it worked but as a whole it is about double the size of my shell script and some things feel a bit "clumsy".</p>
<ul>
<li><code>myReadTile</code> and <code>getCurlIP</code> have <code>IO</code>-return type, which seems a bit "unhaskellish"</li>
<li><code>extractIp</code> and <code>extractFromFile</code> seem a bit unelegant especially the maybe parts and the trivial case "" to prevent last from throwing an error.</li>
</ul>
<p>To run my code the packages <code>curl</code> <code>network-info</code> had to be installed - the rest was already there (Debian haskell-platform 2012.2.0.0, ghc-7.4.1)</p>
<p>What my code does:<br>
I want to log the IP-address my provider gives me - and when it changes; as I have a dynamic IP. With this information I can ssh from other devices to my home PC, and I know how long the periods are in which my IP doesn't change.</p>
<h2>Code</h2>
<pre><code>import System.IO (readFile, appendFile)
import System.Exit (exitSuccess)
import System.Directory (doesFileExist, getHomeDirectory)
import Data.Maybe (listToMaybe, fromMaybe)
import Data.Time (getZonedTime)
import Network.BSD (getHostName)
import Network.Curl (curlGetString, URLString, CurlOption(CurlTimeout))
import Network.Curl.Code (CurlCode(CurlOK))
import Network.Info (getNetworkInterfaces, NetworkInterface, name, ipv4)
localFilePath :: FilePath
localFilePath = "/Dropbox/iplog.log"
dyndns :: URLString
dyndns = "http://checkip.dyndns.org"
main :: IO ()
main = do
home <- getHomeDirectory
let iplogFilePath = home ++ localFilePath
iplogS <- myReadFile iplogFilePath
curlS <- getCurlIP dyndns
let oldIP = extractFromFile iplogS
currentIP = extractIp curlS
if oldIP /= currentIP
then do
date <- fmap show getZonedTime
host <- getHostName
localIP <- fmap getLocalIP getNetworkInterfaces
let content = unwords [currentIP, date, host, localIP, "\n"]
appendFile iplogFilePath content
else
exitSuccess
extractFromFile :: String -> String
extractFromFile "" = ""
extractFromFile s = (fromMaybe [] . listToMaybe . words . last . lines) s
extractIp :: String -> String
extractIp "" = ""
extractIp s = (takeWhile (/='<') . last . words) s
myReadFile :: FilePath -> IO String
myReadFile fp = do
iplogExists <- doesFileExist fp
if iplogExists
then
readFile fp
else do
print "File does not exist - and will be created"
print ("at: ~" ++ localFilePath)
return ""
getCurlIP :: URLString -> IO String
getCurlIP url = do
(curlState, curlString) <- curlGetString url [CurlTimeout 60]
if curlState == CurlOK
then
return curlString
else do
print "No external IP found"
return "0.0.0.0"
getLocalIP :: [NetworkInterface] -> String
getLocalIP = show . ipv4 . head . filter (\x -> name x == "eth0")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T03:23:47.480",
"Id": "20164",
"Score": "1",
"body": "Please do consider adding a unit test suite (HUnit or Quickcheck) for your script, it is a tremendous help when refactoring."
}
] |
[
{
"body": "<p>You have produced rather nice code, so my review is restricted to just the peripherals.</p>\n\n<pre><code>import System.IO (readFile, appendFile)\nimport System.Exit (exitSuccess)\nimport System.Directory (doesFileExist, getHomeDirectory)\nimport Data.Time (getZonedTime)\nimport Data.Char (isDigit, isSpace)\nimport Network.BSD (getHostName)\nimport Network.Curl (curlGetString, URLString, CurlOption(CurlTimeout))\nimport Network.Curl.Code (CurlCode(CurlOK))\nimport Network.Info (getNetworkInterfaces, NetworkInterface, name, ipv4)\nimport Control.Applicative (<$>, <*>)\n\nlocalFilePath :: FilePath\nlocalFilePath = \"/myhaskell/iplog.log\"\n\ndyndns :: URLString\ndyndns = \"http://checkip.dyndns.org\"\n\nmyEth = \"eth0\"\n</code></pre>\n\n<p>It is nicer to separate out self contained functions even if they are of type IO a (You already have some, but take out as much as you can.)</p>\n\n<pre><code>getLogPath :: IO String\ngetLogPath = flip (++) localFilePath <$> getHomeDirectory \n</code></pre>\n\n<p>The warning that there are no external ips should really be elsewhere.</p>\n\n<pre><code>getCurlIP :: URLString -> IO String\ngetCurlIP url = extract <$> curlGetString url [CurlTimeout 60]\n where extract (CurlOK, str) = str\n extract _ = \"0.0.0.0\"\n\ngetLocalIP :: [NetworkInterface] -> String\ngetLocalIP = show . ipv4 . head . filter (flip (==) myEth . name)\n</code></pre>\n\n<p>Your ip extraction can be simplified further.</p>\n\n<pre><code>firstWord :: String -> String\nfirstWord = takeWhile (not . isSpace)\n\ngetFileIP = firstWord\n</code></pre>\n\n<p>I modified your implementation a bit to make it clear what is happening. We take letters while they are not numbers, and drop the suffix that start with '<'\nIf your parsing goes beyond this, then go for parsec. </p>\n\n<pre><code>-- \"<html><head><title>Current IP Check</title></head>\n-- <body>Current IP Address: 24.20.128.212</body></html>\\r\\n\"\nextractIp :: String -> String\nextractIp = takeWhile (/= '<') . dropWhile (not . isDigit)\n</code></pre>\n\n<p>Readfile shouldn't really say that a file if it does not exist will be created. It should just read the given file and return the value. The check and warning should be done elsewhere.</p>\n\n<pre><code>catFile :: FilePath -> IO String\ncatFile fp = doesFileExist fp >>= checkExist\n where checkExist True = readFile fp\n checkExist False = return []\n\ncheckS s [] = do \n print (\"File does not exist - and will be created\\n\" ++ \"at: ~\" ++ s)\n return []\ncheckS s str = return str\n</code></pre>\n\n<p>Using auxiliary definitions can make your code read much better. Prefer sequence to do notation when values are not used in intermediate computations.\nTry to move out of the imperative mindset when using do notation. (the do notation makes it easy to write 'c' in haskell :) ), using auxiliary functions can help you there. (I used case instead of if/then because that is what I prefer, there is no particular reason for that except that it makes it easy to use destructuring easier if I need to.)</p>\n\n<pre><code>main :: IO ()\nmain = do\n currentIP <- getCurrentIP\n iplogFilePath <- getLogPath\n oldIP <- getSavedIP iplogFilePath\n checkS iplogFilePath oldIP\n case oldIP /= currentIP of\n True -> getContent currentIP >>= appendFile iplogFilePath\n _ -> exitSuccess \n where getContent ip = unwords <$> sequence [return ip, show <$> getZonedTime, getHostName,\n getLocalIP <$> getNetworkInterfaces]\n getSavedIP path = getFileIP <$> catFile path\n getCurrentIP = extractIp <$> getCurlIP dyndns\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T14:03:44.460",
"Id": "20188",
"Score": "0",
"body": "Thank you very much for your answer - that was exactly what I was looking for. Now I have to read through it and write more haskell ;-)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T04:12:48.930",
"Id": "12518",
"ParentId": "12515",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "12518",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T00:14:12.783",
"Id": "12515",
"Score": "4",
"Tags": [
"haskell",
"networking",
"logging",
"curl",
"ip-address"
],
"Title": "Dynamic IP-address logging"
}
|
12515
|
<pre><code>#!/bin/bash
# Change the environment in which you are currently working.
# Actually, it calls the relevant 'lettus.sh' script
if [ "${BASH_SOURCE[0]}" == "$0" ]; then
echo "Try running this as \". chenv $1\""
exit 0
fi
usage(){
echo "Usage: . ${PROG} -- Shows a list of user-selectable environments."
echo " . ${PROG} [env] -- Select environment."
echo " . ${PROG} -h -- Shows this usage screen."
return
}
showEnv(){
# check if index0 exists, assume we have at least the first (zeroth) element
#if [ -z "${envList}" ]; then
if [ -z "${envList[0]}" ]; then
echo "array \$envList is empty! " >&2
return 1
fi
# Show all elements in array (0 -> n-1)
for i in $(seq 0 $((${#envList[@]} - 1))); do
echo ${envList[$i]}
done
return
}
setEnv(){
if [ -z "$1" ]; then
usage; return
fi
case $1 in
cold) FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_cold.sh;;
coles) FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_coles.sh;;
fc) FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_fc.sh;;
fcrm) FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_fcrm.sh;;
stable) FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_stable.sh;;
tip) FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_tip.sh;;
uat) FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_uat.sh;;
wellmdc) FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_wellmdc.sh;;
*) usage; return;;
esac
if $IS_SOURCED; then
echo "Environment \"$1\" selected."
echo "Now sourcing file \"$FILE_TO_SOURCE\"..."
. ${FILE_TO_SOURCE}
return
else
return 1
fi
}
main(){
if [ -z "$1" ]; then
showEnv; return
fi
case $1 in
-h) usage;;
*) setEnv $1;;
esac
return
}
PROG="chenv"
# create array of user-selectable environments
envList=( cold coles fc fcrm stable tip uat wellmdc )
main "$@"
return
</code></pre>
<p>If I could, I'd like to get some feedback on a better way to accomplish any of the following:</p>
<ol>
<li>run through the case statement</li>
<li>make script trivally simple to maintain/upgrade/update</li>
</ol>
|
[] |
[
{
"body": "<p>In <code>showEnv</code>, why do you need to check that <code>envList</code> is empty when you define it right in the program?</p>\n\n<p>I'd write the array elements one-per-line with:</p>\n\n<pre><code># Show all elements in array\nfor elem in \"${envList[@]}\"; do \n echo \"$elem\"\ndone\n</code></pre>\n\n<p>or, more succinctly</p>\n\n<pre><code>printf \"%s\\n\" \"${envList[@]}\"\n</code></pre>\n\n<p>In <code>setEnv</code>:</p>\n\n<pre><code>case $1 in\n cold|coles|fc|fcrm|stable|tip|uat|wellmdc)\n FILE_TO_SOURCE=\"/u2/tip/conf/ctrl/lettus_$1.sh\" ;;\n *) usage; return;;\nesac\n</code></pre>\n\n<p>or, without duplicating the contents of <code>envList</code>:</p>\n\n<pre><code>FILE_TO_SOURCE=\"\"\nfor elem in \"${envList[@]}\"; do\n if [ \"$elem\" = \"$1\" ]; then\n FILE_TO_SOURCE=\"/u2/tip/conf/ctrl/lettus_$1.sh\"\n break\n fi\ndone\nif [ -z \"$FILE_TO_SOURCE\" ];then \n usage\n return\nfi\n</code></pre>\n\n<p>You might want to check that the relevant file exists</p>\n\n<pre><code>if [ ! -f \"$FILE_TO_SOURCE\" ]; then\n echo \"missing config file '$FILE_TO_SOURCE'!\"\n echo \"contact $maintainer for assistance\"\n return 1\nfi\n</code></pre>\n\n<p>What is <code>$IS_SOURCED</code>? You might want to document how that environment variable is defined.</p>\n\n<p>You don't need the <code>return</code> at the end of <code>main</code> or at the end of the program.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T05:56:28.443",
"Id": "12521",
"ParentId": "12520",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "12521",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T04:27:12.330",
"Id": "12520",
"Score": "3",
"Tags": [
"bash"
],
"Title": "Bash arrays and case statements - review my script"
}
|
12520
|
<p>The goal with this function is to find one DNA sequence within another sequence, with a specified amount of mismatch tolerance. For example:</p>
<ul>
<li><code>dnasearch('acc','ccc',0)</code> shouldn't find a match, while</li>
<li><code>dnasearch('acc','ccc',1)</code> should find one.</li>
</ul>
<p><strong>EDIT:</strong> Function should also be able to find pat sequence in a sequence larger than the pat sequence; furthermore it should be able to find multiple matches within that sequence if they exist. For example, <code>dnasearch('acc','acaaatc',1)</code> would find two matches: 'aca' and 'act'. Thanks to @weronika for pointing this out.</p>
<p>Here's my working draft:</p>
<pre><code>def dnasearch(pat,seq,mismatch_allowed=0):
patset1=set([pat])
patset2=set([pat])
for number in range(mismatch_allowed):
for version in patset1:
for a in range(len(version)):
for letter in 'actg':
newpat=version[:a]+letter+version[a+1:]
patset2.add(newpat)
patset1|=patset2
for n in patset1:
if seq.find(n) != -1: print 'At position', seq.find(n),\
'found',n
</code></pre>
<p>I was wondering how to write this function:</p>
<ol>
<li>With fewer for-loops.</li>
<li>Without the second <code>patset</code>. Originally I tried just adding new patterns to <code>patset1</code>, but I got the error: <code>RuntimeError: Set changed size during iteration.</code></li>
<li>Simpler in any other way.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T08:42:02.887",
"Id": "20170",
"Score": "1",
"body": "Do you mean http://en.wikipedia.org/wiki/Levenshtein_distance (insertion, deletion, or substitution of a single character)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T19:01:15.993",
"Id": "20219",
"Score": "0",
"body": "You need to add a few more examples to clarify the problem, I think. It's unclear from the current examples what should happen when the two input sequences are different lengths."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T10:20:41.573",
"Id": "20245",
"Score": "0",
"body": "Look like InterviewStreet puzzle [\"Save Humanity\"](https://www.interviewstreet.com/challenges/dashboard/#problem/4f304a3d84b5e) :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T19:34:21.383",
"Id": "20285",
"Score": "0",
"body": "2012: where the words \"simple\" and \"DNS sequence finder\" appear in the same sentence."
}
] |
[
{
"body": "<p>This is a solved problem in bioinformatics and there are specific algorithms depending on your specific use-case:</p>\n\n<ul>\n<li>Do you allow gaps?</li>\n<li>How many mismatches do gaps incur?</li>\n<li>… etc.</li>\n</ul>\n\n<p>In the general case, this is a <a href=\"http://en.wikipedia.org/wiki/Sequence_alignment#Global_and_local_alignments\" rel=\"nofollow\">global pairwise alignment</a> which is computed by the <a href=\"http://en.wikipedia.org/wiki/Needleman%E2%80%93Wunsch_algorithm\" rel=\"nofollow\">Needleman–Wunsch algorithm</a>. If you are just interested in the score of the alignment, rather than the complete alignment, this can be simplified by not performing the backtracking.</p>\n\n<p>Now, if you have a threshold and are only interested in finding matches below said threshold, then a more efficient variant employs the Ukkonen trick – unfortunately, references for this are hard to find online, and the print literature is quite expensive. But what it does is essentially break the recurrence in the above-mentioned algorithm once the score exceeds the threshold chosen before (using the insight that the error score can only <em>increase</em>, never <em>decrease</em> in a given column).</p>\n\n<p><strong>But</strong> all this is unnecessary if you don’t allow gaps. In that case, the algorithm is as straightforward as walking over both strings at once and looking whether the current positions match.</p>\n\n<p>And this can be expressed in a single line:</p>\n\n<pre><code>def distance(a, b):\n return sum(map(lambda (x, y): 0 if x == y else 1, zip(a, b)))\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>def distance_less_than(k, a, b):\n return distance(a, b) < k\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T19:24:10.143",
"Id": "20220",
"Score": "0",
"body": "Thanks for the answer Konrad--I love the distance function in your answer. I did forget an important detail in my question though, pointed out by weronika, which is that the function should also be able to find the pattern sequence in a sequence larger than itself. And yes, I'm not worrying about gaps for the time being."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-07T12:30:52.063",
"Id": "155283",
"Score": "0",
"body": "The distance function can be written more simply\n\n `def distance(a, b):\n return sum(x == y for x, y in zip(a, b)))`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-07T14:08:14.423",
"Id": "155295",
"Score": "0",
"body": "@Caridorc That’s indeed correct. However, I prefer not muddling boolean and numeric types. In fact, I wish Python *wouldn’t* allow your solution, because it relies on weak typing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-07T15:14:53.453",
"Id": "155317",
"Score": "0",
"body": "That is impossibile because Python is strongly typed, bool is a subset of int."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-07T15:28:33.007",
"Id": "155320",
"Score": "1",
"body": "@Caridorc “strongly typed” is a relative, not an absolute statement. Python is indeed relatively strongly typed (compared to other languages), which is why I have zero tolerance for this “a bool is an integer” nonsense. Logically, a boolean is a quite distinct concept from a nominally unbounded integer number, and it rarely makes sense to treat one as a subtype of the other (in fact, it leads to a ton of nonsense; case in point: if we treat booleans as numbers then they are obviously a ring modulo 2 and `True+True` should either be `False` or `True`, not 2, because of modular arithmetic rules)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T14:53:48.733",
"Id": "12542",
"ParentId": "12522",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T08:19:34.183",
"Id": "12522",
"Score": "12",
"Tags": [
"python",
"bioinformatics"
],
"Title": "Simple DNA sequence finder w/ mismatch tolerance"
}
|
12522
|
<p>This is my code for sending mail in HTML format:</p>
<pre><code>import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
public void sendMail(String m_from,String m_to,String m_subject,String m_body){
try {
Session m_Session;
Message m_simpleMessage;
InternetAddress m_fromAddress;
InternetAddress m_toAddress;
Properties m_properties;
m_properties = new Properties();
m_properties.put("mail.smtp.host", "smtp.gmail.com");
m_properties.put("mail.smtp.socketFactory.port", "465");
m_properties.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
m_properties.put("mail.smtp.auth", "true");
m_properties.put("mail.smtp.port", "465");
m_Session=Session.getDefaultInstance(m_properties,new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxxxx","yyyyy"); // username and the password
}
});
m_simpleMessage = new MimeMessage(m_Session);
m_fromAddress = new InternetAddress(m_from);
m_toAddress = new InternetAddress(m_to);
m_simpleMessage.setFrom(m_fromAddress);
m_simpleMessage.setRecipient(RecipientType.TO, m_toAddress);
m_simpleMessage.setSubject(m_subject);
m_simpleMessage.setContent(m_body, "text/html");
//m_simpleMessage.setContent(m_body,"text/plain");
Transport.send(m_simpleMessage);
} catch (MessagingException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
SendMail send_mail = new SendMail();
String empName = "Antony Raj S";
String title ="<b>Hi !"+empName+"</b>";
send_mail.sendMail("anto@gmail.com", "anthony@slingmedia.com", "Please apply for leave for the following dates", title+"<br>by<br><b>HR<b>");
}
}
</code></pre>
<p>This works fine, but is there any other better way to do the same or how can I make the same code still better one? I get all the values like from address, SMTP host, port from the <code>contex.xml</code> file which is there in <code>conf</code> folder of Tomcat, so please do suggest anything better.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T11:46:52.847",
"Id": "20178",
"Score": "0",
"body": "here is a similar question: http://stackoverflow.com/questions/322298/how-to-send-html-email-to-outlook-from-java"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T11:47:37.297",
"Id": "20179",
"Score": "0",
"body": "if you change the host to smtp.bizmail.yahoo.com it will be better like the mail will be sent to any mail like ss@tcs.com"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T19:41:22.540",
"Id": "115599",
"Score": "0",
"body": "[This JavaMail FAQ entry](http://www.oracle.com/technetwork/java/javamail/faq/index.html#commonmistakes) will help you improve your code."
}
] |
[
{
"body": "<ol>\n<li><p>Try to minimize the scope of local variables. It's not necessary to declare them at the beginning of the method, declare them where they are first used.</p>\n<p>See <em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>. (Google for "minimize the scope of local variables", it's on Google Books too.))</p>\n</li>\n<li><p>The <code>m_</code> prefix is unnecessary and uncommon in the Java world. See <em>Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions</em></p>\n</li>\n<li><p>The <code>sendMail</code> method should validate its input parameters. Does it make sense if the <code>form</code>, <code>to</code> etc. is <code>null</code> or empty string? If not, check it and throw a <code>NullPointerException</code> or an <code>IllegalArgumentException</code>. (<em>Effective Java, Second Edition, Item 38: Check parameters for validity</em>)</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-29T16:58:34.833",
"Id": "13199",
"ParentId": "12529",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T11:43:47.680",
"Id": "12529",
"Score": "7",
"Tags": [
"java",
"email"
],
"Title": "Sending HTML-formatted mail in Java"
}
|
12529
|
<p>I have scoring system where I want to change icon color by changing CSS classes.</p>
<p>How can I optimize this jQuery? After testing, I found this the only alternative, but I trust there is a more simplified method.</p>
<pre><code>// Count scores
$('#bodyScore').text((90 / myarray.length) * bodyScore + '/90');
// Change icon color
var bodyPercent = bodyScore / myarray.length;
var successRatio = 0.9;
var warningRatio = 0.5;
if (bodyPercent >= successRatio) {
$(".bkf").removeClass("label-success");
$(".bkf").removeClass("label-warning");
$(".bkf").removeClass("label-important");
$(".bkf").addClass("label-success");
}
else if (bodyPercent >= warningRatio) {
$(".bkf").removeClass("label-success");
$(".bkf").removeClass("label-warning");
$(".bkf").removeClass("label-important");
$(".bkf").addClass("label-warning");
}
else {
$(".bkf").removeClass("label-success");
$(".bkf").removeClass("label-warning");
$(".bkf").removeClass("label-important");
$(".bkf").addClass("label-important");
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T13:38:38.330",
"Id": "20182",
"Score": "0",
"body": "Remove all classes first, then just add the one class in each statement."
}
] |
[
{
"body": "<p>Both the <a href=\"http://api.jquery.com/removeClass/\"><code>removeClass</code></a> and <a href=\"http://api.jquery.com/addClass/\"><code>addClass</code></a> methods will accept a space-separated list of class names to add/remove, and both can be chained.</p>\n\n<p>You can cache the selector so you don't have to repeatedly search the DOM.</p>\n\n<p>And since you remove the same three classes in each branch of execution, you can move that outside of the <code>if/else if/else</code>:</p>\n\n<pre><code>var bkf = $(\".bkf\").removeClass(\"label-success label-warning label-important\");\nif (bodyPercent >= successRatio) {\n bkf.addClass(\"label-success\");\n}\nelse if (bodyPercent >= warningRatio) {\n bkf.addClass(\"label-warning\");\n}\nelse {\n bkf.addClass(\"label-important\");\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T13:38:36.877",
"Id": "12532",
"ParentId": "12530",
"Score": "8"
}
},
{
"body": "<p>You can change it to</p>\n\n<pre><code> if (bodyPercent >= successRatio) {\n $(\".bkf\").removeClass(\"label-success label-warning label-important\")\n .addClass('label-success');\n\n }\n</code></pre>\n\n<p>Do the same thing for others too. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T13:38:53.890",
"Id": "12534",
"ParentId": "12530",
"Score": "0"
}
},
{
"body": "<p>You can specify all classes together and do chaining to call the add class like this</p>\n\n<pre><code> if (bodyPercent >= successRatio) {\n $(\".bkf\").removeClass(\"label-success label-warning label-important\") \n .addClass(\"label-success\");\n }\n\n else if (bodyPercent >= warningRatio) {\n $(\".bkf\").removeClass(\"label-success label-warning label-important\")\n .addClass(\"label-warning\");\n }\n\n else {\n $(\".bkf\").removeClass(\"label-success label-warning label-important\")\n .addClass(\"label-important\");\n }\n</code></pre>\n\n<p>The <a href=\"http://api.jquery.com/removeClass/\" rel=\"nofollow\">removeClass</a> method parameter (classname) takes one or more space-separated classes to be removed from the class attribute of each matched element.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T13:39:35.293",
"Id": "12536",
"ParentId": "12530",
"Score": "0"
}
},
{
"body": "<p>You don't have to repeat your removeClass code 3 times, and you can combine the remove's into one statement:</p>\n\n<pre><code>$(\".bkf\").removeClass(\"label-success label-warning label-important\");\n\nif (bodyPercent >= successRatio) {\n $(\".bkf\").addClass(\"label-success\");\n}\n\nelse if (bodyPercent >= warningRatio) {\n $(\".bkf\").addClass(\"label-warning\");\n}\n\nelse {\n $(\".bkf\").addClass(\"label-important\");\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T13:40:08.843",
"Id": "12537",
"ParentId": "12530",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "12532",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T13:35:52.147",
"Id": "12530",
"Score": "4",
"Tags": [
"javascript",
"jquery"
],
"Title": "removeClass and addClass optimization in a scoring system"
}
|
12530
|
<p>I feel like I should not be duplicating the code to gather the credit card number, but I am not sure how best to do it. Any suggestions?</p>
<pre><code>$('input[name="payment\[cc_number\]"]').keyup(function() {
var ccNum = $(this).val();
ccNum = ccNum.replace(/[^\d]/g, '');
setSelectValue(ccNum);
});
$('input[name="payment\[cc_number\]"]').blur(function(ccNum) {
var ccNum = $(this).val();
ccNum = ccNum.replace(/[^\d]/g, '');
if (!luhnCheck(ccNum)) {
alert('Please enter a valid credit card number.');
}
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T13:36:13.677",
"Id": "20184",
"Score": "1",
"body": "There is a [nice jQuery plugin](https://github.com/PawelDecowski/jQuery-CreditCardValidator) to handle credit card validation which might be easier than writing your own."
}
] |
[
{
"body": "<pre><code>$(function() {\n // Always select a context and use it as the second parameter \n // it will make everything far faster and less prone to errors\n var form = $('form'); \n var stripCcNum = function(el) {\n return $(this).val().replace(/[^\\d]/g, '');\n }\n\n $('input[name=\"payment\\[cc_number\\]\"]', form).keyup(function() {\n\n setSelectValue(stripCcNum(this));\n\n }).blur(function(ccNum) {\n\n if (!luhnCheck( stripCcNum(this) )) {\n alert('Please enter a valid credit card number.');\n }\n\n });\n\n});\n</code></pre>\n\n<p>Or for the totally and absolute 1337 (meaning you shouldn't do it for something this simple but it demonstrates some useful techniques)</p>\n\n<pre><code>$(function() {\n var form = $('form'),\n handleCcNum = function(doThis) {\n return function() { \n doThis.call(this, $(this).val().replace(/[^\\d]/g, ''));\n }\n }\n\n $('input[name=\"payment\\[cc_number\\]\"]', form)\n .keyup( handleCcNum(function(num) { setSelectValue(num); } )\n .blur( handleCcNum(function(num) { \n !luhnCheck(num) && alert('Please enter a valid credit card number.');\n }));\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T17:20:04.917",
"Id": "20205",
"Score": "2",
"body": "I would use [jQuery 1.7's .on](http://api.jquery.com/on/): `$(\"foo\").on({keyup: handleCcNum(...), blur: handleCcCum(...)};`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T18:57:39.013",
"Id": "20217",
"Score": "0",
"body": "Nice @ANeves - didn't know about that syntax"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T14:52:56.987",
"Id": "12541",
"ParentId": "12538",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-06-13T13:32:30.477",
"Id": "12538",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"validation",
"form"
],
"Title": "Calling a Luhn check function when a credit card field changes"
}
|
12538
|
<p>I have written this basic <a href="http://en.wikipedia.org/wiki/Heroes_of_Might_and_Magic_III">Heroes of Might and Magic 3</a> Battle Simulator. I am decent at procedural, C-style code and I am trying to get better at Object Oriented Programming. (I know procedural code be better suited for this problem, but I am comfortable with this material.)
Any and All critiques are appreciated (Speed Optimization, style, readability, maintainability, etc.). I am especially interested in comments on how i could improve the object oriented design and implement the Standard Library (or another library) better.</p>
<p>For those unfamiliar with the game, a quick example is given <a href="http://heroes.thelazy.net/wiki/Defense_Skill#Example">here</a>. (although ignore the "If the Attack skill is lower, then damage is reduced by 2% per point of difference" bit because i believe the correct number is 2.5%).</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <string>
#include <ctime>
#include <algorithm>
using std::cout;
using std::string;
using std::max;
using std::min;
//Global Variables
const double ATTACK_ADV_MULT = 0.05; //View Ecoris's 2nd comment
const double DEFENSE_ADV_MULT = 0.0025; //http://heroescommunity.com/viewthread.php3?TID=11801&pagenumber=2
const double MAX_DMG_MULT = 4.0;
const double MIN_DMG_MULT = 0.3;
const int NUM_FIGHTS = 1000;
class unitStack
{
public:
unitStack( string name, int speed, int attackSkill, int defenseSkill, int minDamage,
int maxDamage, int maxHealth, int curHealth, int numberOfUnits, int numberWins/*=0*/, double dmgMultiplier/*=0*/);
string getName() const;
int getSpeed() const;
int getMaxHealth() const;
int getCurHealth() const;
int getNumberOfUnits() const;
int getNumberWins() const;
int getDefenseSkill() const;
long int attack(unitStack);
void takeDamage(long int);
void addWin();
void resetHealth();
void resetNumUnits(int );
void setDmgMultiplier(int);
private:
string m_name;
int getAttackSkill() const;
int getMinDamage() const;
int getMaxDamage() const;
double getDmgMultiplier() const;
void setHealth(int );
void loseUnits(int);
int m_speed; //never changes
int m_attackSkill; //never changes
int m_defenseSkill; //never changes
int m_minDamage; //never changes
int m_maxDamage; //never changes
int m_maxHealth; //never changes
int m_curHealth; //fluctuates in combat, must be altered after damage/unit lost from stack
int m_numberOfUnits; //fluctuates during one fight, must be reset after each of the NUM_FIGHTS fights
int m_numberWins; // Starts at zero, can be increased up to NUM_FIGHTS
double m_dmgMultiplier; //Set Once
} ;
unitStack::unitStack( string name,
int speed,
int attackSkill,
int defenseSkill,
int minDamage,
int maxDamage,
int maxHealth,
int curHealth,
int numberOfUnits,
int numberWins=0,
double dmgMultiplier=0):
m_name(name),
m_speed(speed),
m_attackSkill(attackSkill),
m_defenseSkill(defenseSkill),
m_minDamage(minDamage),
m_maxDamage(maxDamage),
m_maxHealth(maxHealth),
m_curHealth(curHealth),
m_numberOfUnits(numberOfUnits),
m_numberWins(numberWins),
m_dmgMultiplier(dmgMultiplier)
{
}
string unitStack::getName() const
{return m_name;}
int unitStack::getSpeed() const
{return m_speed;}
int unitStack::getAttackSkill() const
{return m_attackSkill;}
int unitStack::getDefenseSkill() const
{return m_defenseSkill;}
int unitStack::getMinDamage() const
{return m_minDamage;}
int unitStack::getMaxDamage() const
{return m_maxDamage;}
int unitStack::getMaxHealth() const
{return m_maxHealth;}
int unitStack::getCurHealth() const
{return m_curHealth;}
int unitStack::getNumberOfUnits() const
{return m_numberOfUnits;}
int unitStack::getNumberWins() const
{return m_numberWins;}
double unitStack::getDmgMultiplier() const
{return m_dmgMultiplier;}
long int unitStack::attack(unitStack Enemy)
{
long int rawDamage = 0;
long int damage = 0;
for (int n=0; n <= this->getNumberOfUnits(); n++)
{
rawDamage += (rand() % (this->getMaxDamage() - this->getMinDamage() + 1)) + this->getMinDamage();
}
return damage = int(rawDamage * this->getDmgMultiplier());
}
void unitStack::takeDamage(long int dmg)
{
if (dmg < this->getCurHealth())
{
this->setHealth(this->getCurHealth() - dmg);
}
else
{
//There must be a better way to do this
dmg = dmg - this->getCurHealth(); //One unit gone from stack, top unit is at max health is at MaxHealth (reflected in next two lines)
this->loseUnits( 1 + (dmg/this->getMaxHealth())); // Lose top stack unit, and then floor of dmg/MaxHealth more
this->setHealth(this->getMaxHealth() - (dmg % this->getMaxHealth())); //Start at max (since top stackUnit is removed).
}
}
void unitStack::loseUnits(int unitsLost)
{
m_numberOfUnits -= unitsLost;
}
void unitStack::setHealth(int health)
{
m_curHealth = health;
}
void unitStack::setDmgMultiplier(int enemyDefenseSkill)
{
if (this->getAttackSkill() >= enemyDefenseSkill)
{
double dmgMultiplier = ((this->getAttackSkill() - enemyDefenseSkill) * ATTACK_ADV_MULT ) + 1;
m_dmgMultiplier = min(dmgMultiplier, MAX_DMG_MULT);
}
else
{
double dmgMultiplier = 1 - ((enemyDefenseSkill - this->getAttackSkill()) * DEFENSE_ADV_MULT );
m_dmgMultiplier = max(dmgMultiplier, MIN_DMG_MULT);
}
}
void unitStack::addWin()
{
m_numberWins += 1;
}
void unitStack::resetHealth()
{
m_curHealth = m_maxHealth;
}
void unitStack::resetNumUnits(int units)
{
m_numberOfUnits = units;
}
// Non-Class Prototypes
void greeting ();
void oneTurn (unitStack *, unitStack *);
void ReportResults (unitStack *, unitStack *);
int isUnit1Faster (int, int);
bool oneFight (unitStack *, unitStack *);
void CombatSim (unitStack *, unitStack *);
int main()
{
greeting();
srand(static_cast<unsigned int>(time(0)));
//To-Do; add functionality so user can choose creature,numberOfUnits
unitStack stack1("hobgoblin",7,5,3,1,2,5,5,219,0);
unitStack stack2("centaur captain",8,6,3,2,3,10,10,100,0);
unitStack * p_stack1 = &stack1;
unitStack * p_stack2 = &stack2;
cout << "\n\nSo, the matchup is " << stack1.getNumberOfUnits() << " " << stack1.getName() << "s versus "
<< stack2.getNumberOfUnits() << " " << stack2.getName() << "s\n\n";
CombatSim (p_stack1, p_stack2);
ReportResults (p_stack1, p_stack2);
return 0;
}
void greeting()
{
cout << "Welcome to the Heroes of Might and Magic III battle simulator!\n\n";
}
void ReportResults (unitStack * p_stack1, unitStack * p_stack2)
{
cout << "The " << p_stack1->getNumberOfUnits() << " " << p_stack1->getName() << "s win "
<< p_stack1->getNumberWins() << " times out of " << NUM_FIGHTS << "\n";
cout << "The " << p_stack2->getNumberOfUnits() << " " << p_stack2->getName() << "s win "
<< p_stack2->getNumberWins() << " times out of " << NUM_FIGHTS << "\n";
system("PAUSE");
}
//Faster unit Attacks. If slower unit is still alive, CounterAttack.
void oneTurn (unitStack * p_stack1, unitStack * p_stack2)
{
if (isUnit1Faster(p_stack1->getSpeed(), p_stack2->getSpeed() ))
{
p_stack2->takeDamage(p_stack1->attack(*p_stack2));
if (p_stack2->getNumberOfUnits() > 0)
{
p_stack1->takeDamage(p_stack2->attack( *p_stack1));
}
}
else
{
p_stack1->takeDamage(p_stack2->attack(*p_stack1));
if (p_stack1->getNumberOfUnits() > 0)
{
p_stack2->takeDamage(p_stack1->attack( *p_stack2));
}
}
}
int isUnit1Faster (int speed1, int speed2)
{
if (speed1 > speed2)
{
return 1;
}
else if (speed2 > speed1)
{
return 0;
}
else
{
int coinFlip = rand() % 2;
return coinFlip;
}
}
bool oneFight (unitStack * p_stack1, unitStack * p_stack2)
{
while (p_stack1->getNumberOfUnits() > 0 && p_stack2->getNumberOfUnits() > 0)
{
oneTurn (p_stack1, p_stack2);
}
if (p_stack1->getNumberOfUnits() > 0)
{
return 1;
}
else
{
return 0;
}
}
void CombatSim (unitStack * p_stack1, unitStack * p_stack2)
{
int maxNumUnits1 = p_stack1->getNumberOfUnits();
int maxNumUnits2 = p_stack2->getNumberOfUnits();
p_stack1->setDmgMultiplier(p_stack2->getDefenseSkill());
p_stack2->setDmgMultiplier(p_stack1->getDefenseSkill());
for (int i=0; i < NUM_FIGHTS; i++)
{
if (oneFight (p_stack1, p_stack2))
{
p_stack1->addWin();
}
else
{
p_stack2->addWin();
}
p_stack1->resetHealth();
p_stack2->resetHealth();
p_stack1->resetNumUnits(maxNumUnits1);
p_stack2->resetNumUnits(maxNumUnits2);
//To-Do, Add vector of ints to "unitStack", find mean, median, other stats for remaining units after win.
//e.g. Centaur Captains won 996 out of 1000 matches. On average, they had 55.56 units left.
//(*p_stack1).numUnitsLeft[i] = tempStack1.numberOfUnits;
//(*p_stack2).numUnitsLeft[i] = tempStack2.numberOfUnits;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Must say I completely disagree with:</p>\n\n<blockquote>\n <p>I know procedural code be better suited for this problem</p>\n</blockquote>\n\n<p>Global mutable state is bad so I cringe when I see</p>\n\n<pre><code>//Global Variables\n</code></pre>\n\n<p>Fortunately all your global members are const so its not a real problem. </p>\n\n<p>Don't passs by value (unless it is a small POD object). Pass by const reference to achieve the same result. If you need to mutate internally then you can make a copy at that point. SO</p>\n\n<pre><code>unitStack( string name,\n\n// Prefer\n\nunitStack(std::string const& name\n</code></pre>\n\n<p>Anything that never changes should be mareked as const:</p>\n\n<pre><code>int const m_speed; //never changes\n// ^^^^^\n</code></pre>\n\n<p>Same with methods and their parameters.</p>\n\n<p>If you are exposing your state via geters:</p>\n\n<pre><code>int unitStack::getSpeed() const\n{return m_speed;}\n\nint unitStack::getAttackSkill() const\n{return m_attackSkill;}\n</code></pre>\n\n<p>You are tightly coupling your code to where it is being used. This may or may not be a problem but it seems to be excessive here. Leave all your members private and don't expose them via getters. Provide methods that modify your objects state without exposing it.</p>\n\n<p>Here again you are passing by value:</p>\n\n<pre><code>long int unitStack::attack(unitStack Enemy)\n</code></pre>\n\n<p>In this case it is probably not what you want. You are making a copy of Enemy that you are using. What you probably want is to pass a reference to the enemy. This way of you damage him you damage the real enemy not a copy.</p>\n\n<pre><code>long int unitStack::attack(unitStack& Enemy)\n // ^^^\n</code></pre>\n\n<p>Here is an example of a bad interface:</p>\n\n<pre><code>void unitStack::setDmgMultiplier(int enemyDefenseSkill)\n</code></pre>\n\n<p>To use this you need to know <code>enemyDefenseSkill</code> to get that you need to extract (or get) state from the enemy. Which exposes your code to being abused. Better to pass a reference to the enemy and let you and the enemy talk directly.</p>\n\n<pre><code>void unitStack::setDmgMultiplier(UnitStack const& enemy)\n{\n // Becuase your a unitStack object you can accesses other unitStack objects.\n // so the this is valid here:\n\n if (m_defenseSkill < enemy.m_defenseSkill)\n {\n // STUFF\n }\n</code></pre>\n\n<p>Prefer to pass by reference than pointer:</p>\n\n<pre><code>void oneTurn (unitStack *, unitStack *);\n</code></pre>\n\n<p>Here you need to validate that the object exists before you can use them. If you pass by reference you know they exist.</p>\n\n<pre><code>void oneTurn (unitStack& , unitStack& );\n</code></pre>\n\n<p>Note: int C++ the <code>*</code> and the <code>&</code> are usually placed by the type rather than the identifier. Not a big thing and their are people that still do it your way.</p>\n\n<p>Passing pointers around in C++ is practically never done. This is because you don't know who owns the pointer and <strong>ownership is a big thing</strong>. It is the responsibility of the owner to delete the object. So it is very rare (and only deep in the bowels of a class to see a RAW pointer). Normally references work otherwise you should look into smart pointers.</p>\n\n<p>Now you don't need to do this:</p>\n\n<pre><code>unitStack stack1(\"hobgoblin\",7,5,3,1,2,5,5,219,0);\nunitStack stack2(\"centaur captain\",8,6,3,2,3,10,10,100,0);\nunitStack * p_stack1 = &stack1;\nunitStack * p_stack2 = &stack2;\n\nCombatSim (p_stack1, p_stack2);\n\n// You could have simplified that a lot with:\nunitStack stack1(\"hobgoblin\",7,5,3,1,2,5,5,219,0);\nunitStack stack2(\"centaur captain\",8,6,3,2,3,10,10,100,0);\n\nCombatSim (&stack1, &stack2);\n\n// But now that you know about references it can be:\n\nCombatSim (stack1, stack2);\n</code></pre>\n\n<p>Looking at all these free functions:</p>\n\n<pre><code>void oneTurn (unitStack *, unitStack *);\nvoid ReportResults (unitStack *, unitStack *);\nbool oneFight (unitStack *, unitStack *);\nvoid CombatSim (unitStack *, unitStack *);\n</code></pre>\n\n<p>I would encapsulate them in a Tournament manager class. The tournament takes two combatents as parameters in the constructor (passed by reference). Then You have one method called commense() the others are private (and you don't need to pass the anything around (as they are members of the Tournament).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T20:35:43.410",
"Id": "20801",
"Score": "0",
"body": "Thank you so much, this is great! I definitely will change the pointers to references, stop passing by value and make a Tournament class. One Question, are global consts poor practice? would it be better to put `0.05` directly into the code rather than using `ATTACK_ADV_MULT`? or would it only be ill advised if they were mutable? (i.e. not const)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T21:19:24.637",
"Id": "20805",
"Score": "0",
"body": "If a constant is only used in one place (as an argument) then I see little point in making it a const variable just use it in that one place."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T16:33:27.423",
"Id": "12544",
"ParentId": "12543",
"Score": "4"
}
},
{
"body": "<p>A few thoughts:</p>\n\n<p>1) I dislike using declarations, even if you're specific (as here) unless you're using them <em>very</em> often - the minor clutter the namespace produces is worth it IMHO.</p>\n\n<p>2) Don't use this->. It's implied and usually produces too much clutter (<em>e.g.</em> takeDamage).</p>\n\n<p>3) For the constant parts of unitStack, separate them out into a unitType structure - it groups them together into something that's standalone.</p>\n\n<p>4) For any function, if you're passing classes, then pass a reference instead - it avoids an unnecessary copy. And for that matter, if you're passing pointers then consider references instead as well, unless NULL is a perfectly valid value.</p>\n\n<p>5) The number of \"get...\" functions you have is a problem, I think. Bring their use into a suitable class function. So you might have</p>\n\n<pre><code>unitType::rawDamage() //if you do 3) above\n{\n return (rand() % (m_maxDamage - m_minDamage+ 1)) + m_minDamage;\n}\n...\n</code></pre>\n\n<p>And so in unitStack::attack, the appropriate line becomes</p>\n\n<pre><code>rawDamage += m_unitType.rawDamage();\n</code></pre>\n\n<p>and remove getMinDamage() & getMaxDamage() (and where does Enemy get used in this function?).</p>\n\n<p>6) Be consistent in your naming convention. Don't have some variables beginning with capitals and some with small letters (<em>e.g.</em>, dmg & Enemy) (I suspect it's a mistake, but still!).</p>\n\n<p>7) If a function returns a bool, return true and false, not 1 and 0.</p>\n\n<p>8) If function uses both stack1 and stack2, consider introducing a \"combatRound\" class with the combatants as members. Then have it as a friend of the unitStack class</p>\n\n<pre><code>class combatRound;\nclass unitStack\n{ ....\n friend class combatRound;\n}\n</code></pre>\n\n<p>This will enable you to do things like:</p>\n\n<pre><code>unitStack& combatRound::fasterUnit()\n{\n if ( m_s1.m_unitType.isFaster( m_s2.m_unitType ) )\n {\n return m_s1;\n....\n</code></pre>\n\n<p>and then can simplify some functions:</p>\n\n<pre><code>combatRound::oneTurn() // although you need a better name!\n{\n unitStack& attacker = fasterUnit();\n unitStack& defender = slowerUnit();\n defender.takeDamage( attacker.attack() );\n if ( defender.m_numberOfUnits > 0)\n {\n attacker.takeDamage( defender.attack() );\n }\n}\n</code></pre>\n\n<p>That's it for the moment. Hope this is useful.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T17:30:37.727",
"Id": "12547",
"ParentId": "12543",
"Score": "5"
}
},
{
"body": "<p>Adding to what has already been mentioned by others.</p>\n\n<ol>\n<li><p>You included only the items that you need from the <code>std</code> namespace.\nThis is a good practice.</p>\n\n<pre><code>using std::cout;\n...\n</code></pre></li>\n<li><p>In general, a class declaration goes in its own header file (.h or\n.hpp) and its implementation goes into a .cpp file.</p></li>\n<li><p>Using <code>const</code> global values is a good way of storing data. But as\nthis tiny game program evolves into something more serious, you\nwould realize that it is pragmatic to make these values\n<em>configurable</em>. For instance, <code>NUM_FIGHTS</code> need not be 1000 all the time but would be better off being a dynamic value. So, you can\nthink of reading all such <em>metadata</em> from a configuration file rather than\nhard-coding it in your program.</p>\n\n<pre><code>const int NUM_FIGHTS = 1000;\n...\n</code></pre></li>\n<li><p>If a variable can take only specific values, it might be OK here to\njust mention this in a comment. But in a large project where several\ndevelopers are involved, it is a sure-shot way of adding bugs to the\ncode. For example:</p>\n\n<pre><code>int m_numberWins; // Starts at zero, can be increased up to NUM_FIGHTS\n</code></pre>\n\n<p>This restriction needs to be enforced via code: </p>\n\n<pre><code>void unitStack::addWin()\n{\n if (m_numberWins < NUM_FIGHTS)\n m_numberWins += 1;\n}\n</code></pre>\n\n<p>You can also enforce the restriction via <em>assertions</em> (which approach to use? That should be the topic for another post). Same rule applies to <code>setHealth()</code> since health should never exceed <code>m_maxHealth</code>.</p></li>\n<li><p>You might like to start thinking about programming defensively when it comes to larger projects.. For example,\nif the <code>unitsLost</code> value passed to <code>loseUnits()</code> is more than\n<code>m_numberOfUnits</code>, the resulting value of <code>m_numberOfUnits</code> will be\nnegative (which does not make much sense in a game of <em>Heroes of\nMight and Magic 3</em>). Moral of the story: trust no one. Not even\nyourself. Make sure that all assumptions and boundary conditions are\nchecked and enforced in the code. It would be advisable to read more\nabout <em>Design By Contract</em> methodology in this context.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T18:38:10.680",
"Id": "12623",
"ParentId": "12543",
"Score": "4"
}
},
{
"body": "<p>I've been thinking this over for a few days. After thinking about it for a while, I think I'd make a fundamental change in how you're dealing with the health in a \"stack\".</p>\n\n<p>At least as you seem to be using it, a \"stack\" of basically just represents a \"pool\" of health points. For example, if you have a stack of 50 Xs, that basically means you have 50 times as much health as if you only had one. An individual unit, however, doesn't really seem to have much meaning beyond the health points it contributes to the stack.</p>\n\n<p>Assuming that's correct, I think I'd structure the \"stack\" a bit differently -- specifically, instead of having a number of units with a specific amount of health apiece, I would (at construction time) convert the number of units and health points per unit into a single pool of health points. At the conclusion of the battle, convert the remaining health on the winning team into the number of units remaining.</p>\n\n<p>This simplifies what you store for a stack, <em>and</em> (especially) the computation for \"takeDamage\". At construction you do something like <code>health_pool = max_health * num_units;</code> and <code>takeDamage</code> simplifies to something like: <code>health_pool -= dmg;</code> Since you can now take an arbitrary amount of damage at a time, you can eliminate <code>loseUnits</code> entirely (it becomes a side-effect of takeDamage -- if you damage you take exceeds the health of an individual, then you lose some units).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T20:25:46.200",
"Id": "20800",
"Score": "0",
"body": "Yeah, this could definitely work. the number of units in a stack only is used for two things; 1. determining if unitStack is dead, 2. generating damage. Both these things could de done using a health pool. Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T20:52:11.103",
"Id": "12642",
"ParentId": "12543",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "12544",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T15:38:29.193",
"Id": "12543",
"Score": "7",
"Tags": [
"c++"
],
"Title": "Heroes of Might and Magic 3 battle simulator"
}
|
12543
|
<p>We are building a interactive tile-based (32x32 px) (game) map where the user can move around. However we experience lag (some sort of a delay on the movement) and we need to work around this problem. The "hack/lag" also happen on a local server so it's not because of the traffic yet.
Any suggestions how we can make the rendering of the map and performance of the map faster?</p>
<p><em><strong>DISCLAIMER: The code is fast-written, we are beware of the security issues, please do not point them out</em></strong></p>
<p>map.php</p>
<pre><code><?php
session_start();
$_SESSION['angle'] = 'up';
$conn = mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db('hol', $conn) or die(mysql_error());
$query = mysql_query("SELECT x, y FROM hero WHERE id = 1");
$result = mysql_fetch_assoc($query);
$startX = $result['x'];
$startY = $result['y'];
$fieldHeight = 10;
$fieldWidth = 10;
//x = 0 = 4
//y = 0 = 4
$sql = "SELECT id, x, y, terrain FROM map WHERE x BETWEEN ".($startX-$fieldWidth)." AND ".($startX+$fieldWidth). " AND y BETWEEN ".($startY-$fieldWidth)." AND ".($startY+$fieldHeight);
$result = mysql_query($sql);
$map = array();
while($row = mysql_fetch_assoc($result)) {
$map[$row['x']][$row['y']] = array('terrain' => $row['terrain']);
}
ob_start();
echo '<table border=\'0\' cellpadding=\'0\' cellspacing=\'0\'>';
for ($y=$startY-$fieldHeight;$y<$startY+$fieldHeight;$y++) {
echo '<tr>';
for ($x=$startX-$fieldWidth;$x<$startX+$fieldWidth;$x++) {
if ($x == $startX && $y == $startY) {
echo '<td style="width:32px; height:32px; background-image:url(\'tiles/' . (isset($map[$x][$y]['terrain']) ? $map[$x][$y]['terrain'] : 'water') . '\');"><img src="char/medic_' . $_SESSION['angle'] . '.png" alt="" /></td>';
} else {
//echo '(' . $x . ',' . $y . ')';
echo '<td style="width:32px; height:32px; background-image:url(\'tiles/' . (isset($map[$x][$y]['terrain']) ? $map[$x][$y]['terrain'] : 'water') . '\');"></td>';
}
}
echo '</tr>';
}
echo '</table>';
$content = ob_get_contents();
ob_end_clean();
?>
<!DOCTYPE html>
<html>
<head>
<title>Map</title>
<meta charset="utf-8">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).keyup(function(e){
if (e.keyCode == 37) {
move("West");
return false;
}
if (e.keyCode == 38) {
move("North");
return false;
}
if (e.keyCode == 39) {
move("East");
return false;
}
if (e.keyCode == 40) {
move("South");
return false;
}
});
$(".direction").click(function() {
move($(this).text());
});
function move(newDirection)
{
var direction = newDirection;
$.ajax({
type: "POST",
url: "ajax/map.php",
data: { direction: direction },
success: function(data) {
$('#content').html(data);
}
});
}
/*
$("#content").click(function() {
var x = 3;
var y = 3;
$.ajax({
type: "POST",
url: "ajax.php",
data: { x: x, y: y },
success: function(data) {
$('#content').html(data);
}
});
});
*/
});
</script>
<style type="text/css">
td {margin: 0; border: none; padding: 0;}
img{
display:block;
margin:0;
}
.
</style>
</head>
<body>
<div id="content"><?php echo $content; ?></div>
<div class="result"></div>
<button class="direction">South</button>
<button class="direction">North</button>
<button class="direction">West</button>
<button class="direction">East</button>
</body>
</html>
</code></pre>
<p>ajax/map.php</p>
<pre><code><?php
session_start();
$conn = mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db('hol', $conn) or die(mysql_error());
//Get Player's current position
$query = mysql_query("SELECT x, y FROM hero WHERE id = 1");
$result = mysql_fetch_array($query);
$current_x = $result['x'];
$current_y = $result['y'];
switch ($_POST['direction']) {
case 'North':
if ($current_y - 1 < 0) {
echo 'Invalid path';
}
//Next tile
$x = $current_x;
$y = $current_y - 1;
$_SESSION['angle'] = 'up';
break;
case 'South':
if ($current_y + 1 > 500) {
echo 'Invalid path';
}
$x = $current_x;
$y = $current_y + 1;
$_SESSION['angle'] = 'down';
break;
case 'West':
$x = $current_x - 1;
$y = $current_y;
$_SESSION['angle'] = 'left';
break;
case 'East':
$x = $current_x + 1;
$y = $current_y;
$_SESSION['angle'] = 'right';
break;
}
$result = mysql_query("SELECT walkable FROM map WHERE x = $x AND y = $y");
$row = mysql_fetch_array($result);
//Is the next tile walkable?
if ($row['walkable'] == 1) {
//Update Player's position
mysql_query("UPDATE hero SET x=$x, y=$y WHERE id = 1");
$startX = $x;
$startY = $y;
} else {
$startX = $current_x;
$startY = $current_y;
}
$fieldHeight = 10;
$fieldWidth = 10;
//x = 0 = 4
//y = 0 = 4
$sql = "SELECT id, x, y, terrain FROM map WHERE x BETWEEN ".($startX-$fieldWidth)." AND ".($startX+$fieldWidth). " AND y BETWEEN ".($startY-$fieldWidth)." AND ".($startY+$fieldHeight);
$result = mysql_query($sql);
$map = array();
while($row = mysql_fetch_assoc($result)) {
$map[$row['x']][$row['y']] = array('terrain' => $row['terrain']);
}
ob_start();
echo '<table border=\'0\' cellpadding=\'0\' cellspacing=\'0\'>';
for ($y=$startY-$fieldHeight;$y<$startY+$fieldHeight;$y++) {
echo '<tr>';
for ($x=$startX-$fieldWidth;$x<$startX+$fieldWidth;$x++) {
if ($x == $startX && $y == $startY) {
echo '<td style="width:32px; height:32px; background-image:url(\'tiles/' . (isset($map[$x][$y]['terrain']) ? $map[$x][$y]['terrain'] : 'water') . '\');"><img src="char/medic_' . $_SESSION['angle'] . '.png" alt="" /></td>';
} else {
//echo '(' . $x . ',' . $y . ')';
echo '<td style="width:32px; height:32px; background-image:url(\'tiles/' . (isset($map[$x][$y]['terrain']) ? $map[$x][$y]['terrain'] : 'water') . '\');"></td>';
}
}
echo '</tr>';
}
echo '</table>';
$content = ob_get_contents();
ob_end_clean();
echo $content;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T17:01:41.617",
"Id": "20200",
"Score": "0",
"body": "I'll take another look at it in a bit, but maybe this will get you started. Maybe its `ob_start()`. I don't use it myself, mostly because I do not like the way it lets you have HTML in your PHP. But just the way it works makes me think it adds a lot of overhead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T17:29:54.617",
"Id": "20207",
"Score": "0",
"body": "Not according to: http://stackoverflow.com/questions/6934762/php-performance-difference-between-string-concat-and-buffering-contents"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T18:00:18.487",
"Id": "20208",
"Score": "0",
"body": "Yes, but string concatenation is different from PHP injection. Which is more or less what you have. Remove the echoes, close the PHP and start directly dumping the HTML, then only go back into PHP for the loops and specific variables you need to dump"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T18:01:09.577",
"Id": "20209",
"Score": "0",
"body": "I'm taking another look at it now. Hopefully something pops up"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T18:15:51.673",
"Id": "20210",
"Score": "0",
"body": "Yes unless you come up with something, you are very welcome to develop your answer above."
}
] |
[
{
"body": "<p>Besides what I already mentioned about output buffering, I don't really see anything wrong. And I can't prove output buffering is the culprit. You could try escaping the HTML, what I was calling \"PHP injection\" (sorry I had the wrong term) to see if that fixes it, but that would require some rewrite. Here's what I mean in case clarification is still needed:</p>\n\n<pre><code>?>\n<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n<? for ($y=$startY-$fieldHeight;$y<$startY+$fieldHeight;$y++) : ?>\n <tr>\n <? //etc... ?>\n </tr>\n<? endfor; ?>\n</table>\n</code></pre>\n\n<p>Only other thing I can think of is that maybe its your MySQL queries that are bogging you down. Try wrapping those in <code>microtime()</code>'s and see how long they are taking. If they aren't the culprit, try sprinkling <code>microtime()</code>'s liberally throughout your code to see if you can pinpoint it.</p>\n\n<p>That being said, this is test code as you pointed out. There are bound to be issues like lag and such with test code. Now that it works, even laggy as it is, you should see about making it more permanent. Who knows, while you are solidifying your code maybe something will occur to you. Or miracle of miracles, maybe it will fix itself. Not that we could ever be so lucky. Once its \"finalized\" if it is still laggy or has bugs, try reposting your question then. Maybe something will be more apparent with cleaner code. Sorry I can't be of more help.</p>\n\n<p><strong>Trivialities</strong></p>\n\n<p>These are some trivialities I would address. Not saying they are your problem, but they definitely contribute. Also not saying you didn't know about them, you'd probably get them while finalizing. Just pointing them out for completeness.</p>\n\n<p>These, and similar, are used quite frequently and could be saved as variables to reduce the need to retype and the minor overhead they cause.</p>\n\n<pre><code>$corrd = $map[$x][$y];\n$terrain = isset($coord['terrain']) ? $coord['terrain'] : 'water';\n$Ymin = $startY-$fieldHeight;\n</code></pre>\n\n<p>Maybe beyond scope of your project at the moment, but getting away from HTML tables and using external stylized spans and divs might also help. Example using terrain block.</p>\n\n<pre><code>//BEGINCSS\n.terrain { height: 35px; width: 35px; }\n.water { background-image: url('tiles/water'); }\n//ENDCSS\n\n<?php\n $coord = $map[$x][$y];\n $terrain = isset($coord['terrain']) ? $coord['terrain'] : 'water';\n?>\n<div class=\"row\"><!-- Replaces TR's -->\n <span class=\"terrain <? echo $terrain; ?>\"><img src=\"char/medic_<? echo $_SESSION['angle']; ?>.png\" alt=\"\" /></span><!-- Replaces TD's -->\n //more spans\n</div>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T10:55:48.223",
"Id": "20246",
"Score": "0",
"body": "Do you think I would gain performance by reconstructing the rendering, let's say I don't re render the tiles unless it's actually needed. And just move the character?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T13:22:55.037",
"Id": "20249",
"Score": "0",
"body": "@josmith: I'm not sure, it was just a suggestion. I'm honestly stumped as to why this is running slow. My last suggestion about using `microtime()` is probably your best bet for pinpointing it. All my suggestions so far are more for fine tuning and probably wont make a \"huge\" impact. But you never know. Its the development stage, sometimes you try something out and it doesn't work, sometimes it does. I'm not sure what you mean by \"Just move the character\". BTW: Researched `ob_start()` last night and you were right, this should not be your problem. Have you tried cleaning up the code yet?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T19:08:16.793",
"Id": "12550",
"ParentId": "12545",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T16:35:29.470",
"Id": "12545",
"Score": "1",
"Tags": [
"php",
"performance",
"mysql",
"ajax"
],
"Title": "Improve the performance of jquery/php generated map"
}
|
12545
|
<p>I'm trying to parse addresses out of blocks of text, and have the following expression to do so:</p>
<pre><code>/\d+\s(?:[sewnSEWN]\.?\s)?[\d\w]+\s(?:(?:[\d\w]+\s){0,3})?\w+\.?/
</code></pre>
<p>It will currently parse addresses such as:</p>
<p>300 E. Randolph St. Chicago, IL >> Returns 300 E. Randolph St.</p>
<p>5553 Bay Shore Drive >> Returns input</p>
<p>23 Joseph E Lowery Boulevard >> Returns input</p>
<p>513 Martin Luther King Jr Boulevard >> Returns input</p>
<p>This is exactly what I want. I was wondering, as this is the first expression I have ever written, if there was a way to shorten down the expression or refine it a little?</p>
|
[] |
[
{
"body": "<p>I don't know which implementation you are using, so translate this to relevant language when needed.</p>\n\n<p><code>\\w = [a-zA-Z0-9]</code> so <code>[\\d\\w]</code> is same as <code>[\\w]</code></p>\n\n<p>Note that <code>(?(?:[\\w]+\\s){0,3})?</code> is same as <code>(?:[\\w]+\\s){0,3}</code> because the expression inside is matched zero or more times.</p>\n\n<p>You can also add in the <code>\\w+\\s</code> at the beginning to the above expression, and make it repeat from 1 to 4.</p>\n\n<p>Here is a matching for your example, Knowing not much about your format, here is what I find odd.</p>\n\n<pre><code>/\n \\d+ # 513\n \\s\n (?:[sewnSEWN]\\.?\\s)? #\n (?:\\w+\\s){1,4} # Martin Luther King Jr \n \\w+ # Boulevard\n \\.?\n/\n</code></pre>\n\n<ul>\n<li>The spaces are restricted to a single space <code>\\s</code> is this that strict? Perhaps you want <code>\\s+</code></li>\n<li>If I understand you right, the portion after NSEW. directions are that there has to be atleast two words, and atmost 5 words separated by spaces. is this a correct interpretation?</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T18:45:54.950",
"Id": "20212",
"Score": "0",
"body": "I have it as single spaces because I assumed that's how standard addresses are broken up. The way I was trying to do it, the street name could contain at least one part (such as Randalph), and at most 4 different parts, and after the street name there would be the descripter, i.e. street, park, drive, etc. But they can be abbreviated, which is why I searched for the period after."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T18:49:04.820",
"Id": "20213",
"Score": "0",
"body": "@AndrewPeacock makes sense. If you are trying to match generic street names, what about the directions like NW, SE etc?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T18:51:23.897",
"Id": "20214",
"Score": "0",
"body": "I hadn't thought about that... Also, when I change `(?:(?:[\\w]+\\s){0,3})?` to `(?:[\\w]+\\s){0,3}?`, the second doesn't return the same result as the first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T18:54:00.807",
"Id": "20216",
"Score": "0",
"body": "@AndrewPeacock remove the `?` in your second expression."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T18:36:54.790",
"Id": "12549",
"ParentId": "12548",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "12549",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T17:44:58.987",
"Id": "12548",
"Score": "1",
"Tags": [
"regex",
"search"
],
"Title": "Regex Refinement"
}
|
12548
|
<p>i am new on java and i have not more knowledge about java. please help me for optimizing it as much as possible</p>
<pre><code>public void q1(String str, int[] arr) {
String local = "findnumber";
for(int i=0; i<arr.length; i++) {
if(str.equals(local) && arr[i] * 2 > 10) {
Integer in = new Integer(arr[i]);
in = in * 2;
System.out.print(in.toString());
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T07:43:41.640",
"Id": "20221",
"Score": "2",
"body": "Can u tell that what u r doing in this function so that picture may be more clear."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T08:09:13.483",
"Id": "20222",
"Score": "1",
"body": "-1: I don't think this is a well formulated question, in the sense that you have not explained what you have tried, and why you need to optimize it. From the way it looks, you want someone else to do your dirty work, instead of trying to understand how to optimize code in a particular circumstance. And as @Joonas Pulakka has mentioned there is a sister-site called Code Review where you can ask such questions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T08:33:38.597",
"Id": "20223",
"Score": "2",
"body": "Unless very few numbers are printed, your main bottleneck will be writing to the console. (Can be 10-100x more than your cpu cost here) Given your output has no spaces between the numbers and doesn't appear to be useful, I would try to find a way to avoid do this at all (which would take no time and be the fastest)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T20:06:22.677",
"Id": "20229",
"Score": "0",
"body": "Is this some sort of homework?"
}
] |
[
{
"body": "<p>You can extract the check if str.equals(local) out of the loop. This will safe most of the operations performed in the loop:</p>\n\n<pre><code>public void q1(String str, int[] arr) {\n String local = \"findnumber\";\n boolean string_matches = str.equals(local);\n for(int i=0; i<arr.length; i++) {\n if(string_matches && arr[i] * 2 > 10) {\n Integer in = new Integer(arr[i]);\n in = in * 2;\n System.out.print(in.toString());\n }\n }\n}\n</code></pre>\n\n<p>Or even you can return if it does not match:</p>\n\n<pre><code>public void q1(String str, int[] arr) {\n String local = \"findnumber\";\n if (!str.equals(local)) {\n return;\n }\n for(int i=0; i<arr.length; i++) {\n if(arr[i] * 2 > 10) {\n Integer in = new Integer(arr[i]);\n in = in * 2;\n System.out.print(in.toString());\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T07:41:02.187",
"Id": "12552",
"ParentId": "12551",
"Score": "2"
}
},
{
"body": "<p>Tip #1: Move the</p>\n\n<pre><code>if(str.equals(local))\n</code></pre>\n\n<p>up to line 3 (before for loop), so that, you can escape checking the same thing for each element of the array.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T07:44:19.103",
"Id": "20224",
"Score": "0",
"body": "another optimization could be arr[i] > 5 instead of arr[i] * 2 > 10"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T07:47:50.940",
"Id": "20225",
"Score": "0",
"body": "Insted of Integer in = new Integer(arr[i]); in = in * 2; use Integer in = arr[i]*2; (provided you are using java 1.5 and above."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T07:42:40.120",
"Id": "12553",
"ParentId": "12551",
"Score": "2"
}
},
{
"body": "<p>You can move the <code>str.equals(local)</code> since if that's false, it will never run inside the loop:</p>\n\n<pre><code>public void q1(String str, int[] arr) {\n if(str.equals(\"findnumber\")) {\n for(int i=0; i<arr.length; i++) {\n if(arr[i] > 5) {\n Integer in = new Integer(arr[i]);\n in = in * 2;\n System.out.print(in.toString());\n }\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p>EDIT: and as sudmong suggested, you can do less math by dividing 10 by 2.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T07:43:25.320",
"Id": "12554",
"ParentId": "12551",
"Score": "0"
}
},
{
"body": "<p>i) Instead of <code>arr[i] * 2 > 10</code> you can use <code>arr[i] > 5</code>.<br><br>\nii) Do the operation <code>str.equals(local)</code> outside the loop.</p>\n\n<pre><code>public void q1(String str, int[] arr) {\n String local = \"findnumber\";\n boolean isMatched = str.equals(local);\n for(int i=0; i<arr.length; i++) {\n if(isMatched && arr[i] > 5) {\n Integer in = new Integer(arr[i]);\n in = in * 2;\n System.out.print(in.toString());\n }\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T07:46:13.483",
"Id": "12555",
"ParentId": "12551",
"Score": "0"
}
},
{
"body": "<p>If your goal is to just print the numbers and you do not need them to be Integers you can use:</p>\n\n<pre><code>public void q1(String str, int[] arr) {\n if(!\"findnumber\".equals(str)) return;\n for(int i : arr) {\n if(i > 5) {\n System.out.print(i * 2);\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T07:46:39.227",
"Id": "12556",
"ParentId": "12551",
"Score": "6"
}
},
{
"body": "<p>First of all, you should first try to make your code readable and maintainable. That's the most important thing. Start by indenting it properly, and give meaningful names to your methods and variables.</p>\n\n<p>Now to the performance, there are many things that can be optimized, but it won't change much, unless this method is called billions of times:</p>\n\n<ul>\n<li>the local variable should be a constant</li>\n<li>the <code>str.equals(local)</code> test should be executed once, out of the loop</li>\n<li>you should not use Integer, but int: <code>int in = arr[i] * 2;</code></li>\n<li>the multiplication doesn't need to be computed twice</li>\n</ul>\n\n<p>Here's a complete optimized version:</p>\n\n<pre><code>private static final String FIND_NUMBER = \"findnumber\";\n\npublic void q1(String str, int[] arr) {\n if (FIND_NUMBER.equals(str)) {\n for (int i = 0; i < arr.length; i++) {\n int doubleValue = arr[i] * 2;\n if (doubleValue > 10) {\n System.out.print(doubleValue);\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T07:51:19.200",
"Id": "20226",
"Score": "0",
"body": "Shouldn't appending `StringBuilder`, and then dumping it to `System.out` be faster than calling `System.out.print()` so many times?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T07:47:20.830",
"Id": "12557",
"ParentId": "12551",
"Score": "4"
}
},
{
"body": "<p>Try this:<br/></p>\n\n<pre><code> public void q1(String str, int[] arr)\n {\n if(str.equals(\"findnumber\"))\n {\n String output = \"\";\n for(int i : arr) \n { \n if(i > 5)\n {\n output += (i*2) + \" \";\n }\n }\n System.out.println(output);\n }\n }\n</code></pre>\n\n<p>Print to the standard output at once, in cases where output is large it's quite good optimiaztion idea. Also you can use <code>StringBuilder</code> instead of <code>String</code> for large output.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T08:02:23.977",
"Id": "12558",
"ParentId": "12551",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T07:38:13.447",
"Id": "12551",
"Score": "-3",
"Tags": [
"java",
"optimization"
],
"Title": "java Optimize this function as much as possible"
}
|
12551
|
<p>Note, I choose not to use the Factory Pattern out of preference.</p>
<p>This is a ( M ) odel class in the MVC pattern.</p>
<p>Private functions return Booleans and public functions return strings which I then output to the browser from the Controller. The class returns a string from the invoke call. </p>
<p>Here is the only call to the class:</p>
<p><strong>Call</strong></p>
<pre><code>$model = new UserNew( new IUniversals() , new IDatabase(), new IText(), new IMessage() );
echo $model->invoke();
</code></pre>
<p><strong>Class</strong></p>
<pre><code>class MUserNew extends MUser // set mysql defaults
{
private $universal_object;
private $text_object;
private $message_object;
private $input_fields = array( 'name', 'email', 'pass' );
public function __construct( $universal_object, $text_object, $message_object )
{
parent::__construct();
$this->universal_object = $universal_object;
$this->text_object = $text_object;
$this->message_object = $message_object;
}
public function invoke()
{
$not_validated = $this->checkInput();
if( $this->universal_object->get( 'load' ) && ( $not_validated !== true ) )
{
return $not_validated;
}
else
{
$email_is_unique = $this->checkEmail();
if( ( $email_is_unique === true ) )
{
return $this->message_object->get( 'PASS' ) . $this->insertRecord() ;
}
else
{
return $email_is_unique;
}
}
}
private function checkInput()
{
if( !$this->text_object->checkEmpty() )
{
return $this->text_object->get( 'empty' );
}
foreach( $this->input_fields AS $pattern )
{
if( !$this->text_object->checkPattern( $pattern ) )
{
return $this->message_object->get( $pattern );
}
}
return true;
}
private function checkEmail()
{
if( $this->database_object->_pdoQuery( 'single', 'signup_check', array($this->text_object->get('email') ) ) )
{
return $this->$message_object->get( 'taken' );
}
else
{
return true;
}
}
private function insertRecord()
{
srand( time() );
$hash = crypt( $this->text_object->get( 'pass' ), substr( strval( rand() ), -2 ) );
$this->text_object->set('pass', $hash );
$this->database_object->_pdoQuery( 'single', 'signup_insert', array( '', $this->text_object->get('name'), $this->text_object->get('email'), $this->text_object->get('pass'), 0, 0 ) );
$this->database_object->_pdoQuery( 'none', 'bookmark_insert', array($result['id'], 'Facebook', 'http://www.facebook.com', 'facebook.com', 'social', 'http://static.ak.fbcdn.net/rsrc.php/yi/r/q9U99v3_saj.ico'));
return $hash;
}
</code></pre>
<p>}</p>
|
[] |
[
{
"body": "<p>Where do I begin?</p>\n\n<p>Simplest first. Make sure you assign your constructor a state (public, private, or protected). Most likely public.</p>\n\n<p>Now... Where are all these extra properties coming from? <code>$ISharedObject</code> is not even remotely similar to anything else, so it isn't a typo. And its not defined as a class property, so I can't even be sure this is supposed to be here. The class you provide does not extend a parent class, so it isn't from there. It just appeared in <code>invoke()</code> out of no where. The method it uses suggests that it is most likely a <code>$MessageObject</code> but I don't know.</p>\n\n<p>It looks like you've either copy-pasted this all together, or had a collaboration with someone else and you've crossed your naming schemes. <code>$MessageObject</code> and <code>$TextObject</code> looks like they should be <code>$message_object</code> and <code>$text_object</code> respectively. They should be renamed as such or vice-versa. It is probably easier to rename where they are defined, less to change, but up to you.</p>\n\n<p>You have a <code>$not_validated</code> and <code>$validated</code> variable, of which only the first was defined.</p>\n\n<p>If <code>checkEmail()</code> only ever returns a boolean, like its name suggests, then there is no need for absolute equality operators \"===\". Just <code>if( $email_is_unique )</code>. If it returns something other than a boolean, then it is doing too much and needs to be separated into multiple functions.</p>\n\n<p>Arrays and loops are your best friend for repititive code.</p>\n\n<pre><code>$patterns = array(\n 'name',\n 'email',\n 'pass',\n);\n\nforeach( $patterns AS $pattern ) {\n if( !$this->TextObject->checkPattern( $pattern ) ) {\n return $this->MessageObject->get( $pattern );\n }\n}\nreturn true;\n</code></pre>\n\n<p>Change these first few things and I'll take another look, but right now this is very confusing.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>\"This has irked me for a long time...code that is DRY ( Don't Repeat Yourself )...is less efficient then code that has some repetition. Dry is a good concept unless taken to extreme...as far as looping goes...either way is fine I think....I'll add the loop in as a matter of preference even though a tad bit less efficient.\"</p>\n\n<p>How do you figure this is less efficient?</p>\n\n<pre><code>$patterns = array( 'name', 'email', 'pass' ); \nforeach( $patterns AS $pattern ) \n{\n if( !$this->$text_object->checkPattern( $pattern ) ) \n {\n return $this->$message_object->get( $pattern );\n }\n}\n</code></pre>\n\n<p>Than this?</p>\n\n<pre><code>if( !$this->$text_object->checkPattern( 'name' ) ) \n{\n return $this->$message_object->get( 'name' );\n}\nif( !$this->$text_object->checkPattern( 'email' ) ) \n{\n return $this->$message_object->get( 'email' );\n}\nif( !$this->$text_object->checkPattern( 'pass' ) ) \n{\n return $this->$message_object->get( 'pass' );\n}\n</code></pre>\n\n<p>The first reduces the amount of code written, which in turn reduces the amount of times you can make mistakes, which in turn reduces the amount of lines you'll have to wade through should you ever need to debug it. It also automates similar tasks for any parameters you wish to throw at it so that if that task should ever need to change, you'll only ever have to do so once. Or should you ever wish to add to it, you only need to add a parameter to an array. Where did you hear that DRY is inefficient? I admit abusing it could get ridiculous, but you have to go out of your way to accomplish that.</p>\n\n<p>Anyways, here's what I have for your update.</p>\n\n<p>You still have that issue with variables and properties appearing out of thin air. <code>$validated</code> I'm assuming should be <code>$not_validated</code>. Though I, personally, would switch that around. I like imagining my variables like this to be asking a question \"validated?\" and not \"telling\" you its state. But thats a preference. <code>$TextObject</code> should probably be <code>$text_object</code>.</p>\n\n<p>Another thing I just noticed. You are declaring your properties like so: <code>$this->$text_object</code>; When they should be declared like so: <code>$this->text_object</code>; The first is called a variable variable. It states that whatever the value of <code>$text_object</code> is will be declared as the name of a new property. First of all, these are cosidered bad form, mostly because they are impossible to track and make your code unuseable by anyone but you. Not really, but pretty damn close, not even IDE's can track these. Here it is explained in code, hopefully more clear.</p>\n\n<pre><code>$a = 'apple';\n$b = 'banana';\n$this->a = $b;\n$this->$a = 'orange';\n$$a = 'tangerine';\n\necho $a;//apple\necho $b;//banana\necho $this->a;//banana\necho $this->apple;//orange\necho $apple;//tangerine\n//$this->apple and $apple just magically appeared, this is because they were set from the value of $a.\n</code></pre>\n\n<p>You have a couple of really long statements that could be made more legible. There are a few ways you can do this. The simplest is to bring the parameters out of the method call and convert them to variables in the local scope. This is pretty common and helps clean up code quite a bit.</p>\n\n<pre><code>$email = array( $this->TextObject->get('email') );\nif( $this->$database_object->_pdoQuery( 'single', 'signup_check', $email ) )\n</code></pre>\n\n<p>Another way, usually used in conjunction with the previous, is to use PHP's helpful nature to your advantage. PHP does not care about whitespace, so you can drop long statements like this to new lines and indent to your hearts content.</p>\n\n<pre><code>$this->$database_object->_pdoQuery(\n 'single',\n 'signup_insert',\n array(\n '',\n $this->TextObject->get('name'),\n $this->TextObject->get('email'),\n $this->TextObject->get('pass'),\n 0,\n 0\n )\n);\n//OR\n$name = $this->TextObject->get('name');\n$email = $this->TextObject->get('email');\n$pass = $this->TextObject->get('pass');\n$array = array(\n '',\n $name,\n $email,\n $pass,\n 0,\n 0\n);\n$this->$database_object->_pdoQuery(\n 'single',\n 'signup_insert',\n $array\n);\n</code></pre>\n\n<p>Last thing I want to mention is magic numbers. Those are numbers that appear out of thin air and could mean anything. Much like those variable variables I mentioned earlier, they are almost impossible to track down. To you, as the author, you probably know what these are at a glance. But to someone reading your code for the first time, they will not have a clue. This could even be you in a few months after you've started working on other projects. Take a look at the code above. Those zeroes \"0\" and empty strings '' don't mean anything. They just exist. They are magic. Declare them and set them as variables so people know what they do.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T20:34:22.397",
"Id": "20302",
"Score": "0",
"body": "class.IText.php - http://codereview.stackexchange.com/questions/12592/class-itext-analyzes-and-creates-text-from-a-post-call"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T21:14:02.623",
"Id": "20303",
"Score": "0",
"body": "@stack.user.0: Updated"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T22:24:16.593",
"Id": "20310",
"Score": "0",
"body": "@stack.user.0 Yes, DRY code can be less efficient, but that's like saying that code that uses functions is less efficient. You could always throw every statement one line after another with all kinds of copy and pasted snippets. It would probably be more efficient, but a .0000001% efficiency increase is rarely worth less maintainable code. Also, the two snippets (the loop and unwound loop) are not exactly a shining example of DRY. DRY refers to encapsulating functionality, not unwinding loops."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T23:36:18.693",
"Id": "20321",
"Score": "0",
"body": "we're just trying to say that the overhead is so minuscule as to be unnoticeable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T20:55:02.907",
"Id": "20439",
"Score": "0",
"body": "I look at overhead as a relative concept..in this case hitting the for loop 3 times with index lookup as opposed to 0 times...relative to this class...I'd say about.1% - the hashing done by crypt() I'm guessing is like 99.9% of the work...so it is updated."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T16:51:13.497",
"Id": "12583",
"ParentId": "12560",
"Score": "3"
}
},
{
"body": "<p>Its been a long while since I have seen your code for review. I remember when you were starting out and producing horrible code. It is very nice to see the massive improvement that you have made! This code looks quite reasonable.</p>\n<h2>The Good</h2>\n<ul>\n<li><p>Dependency Injection. You said that you didn't do it, but you have! You passed each dependency to the constructor here:</p>\n<pre><code> $model = new UserNew( new IUniversals() , new IDatabase(), new IText(), new IMessage() );\n</code></pre>\n<p>That is all there is to dependency injection, you have done it nice and simply.</p>\n</li>\n<li><p>Encapsulation/Interface Hiding:</p>\n<p>You have hidden all of the properties and given a simple interface to the user of the class with a limited number of public methods.</p>\n</li>\n</ul>\n<p>Keep doing those good things!</p>\n<h2>The Bad</h2>\n<ul>\n<li><p><code>invoke</code> does not have much meaning and is similarly named to the magic method <code>__invoke</code>.</p>\n<p>Its hard to tell what invoking a user will do. It looks like it is creating a user. <code>create</code> might be a more meaningful name.</p>\n</li>\n</ul>\n<h2>The Future</h2>\n<p>Things can always be done better, but endless improvement doesn't get things finished. I would recommend reading about the <a href=\"http://wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> and <a href=\"http://martinfowler.com/eaaCatalog/dataMapper.html\" rel=\"nofollow noreferrer\">Data Mappers</a>. This could help simplify and increase the re-usability and maintainability of this code even further. The data mapper could also remove your dependence on a database as your persistent storage (although a database is a very good place to store things).</p>\n<p>You have definitely come a long way, nice work.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T17:44:20.287",
"Id": "20539",
"Score": "0",
"body": "I'm staring to write more .js after reading http://shop.oreilly.com/product/0636920018421.do - more state / functionality is being implemented in .js."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T10:48:26.237",
"Id": "20613",
"Score": "0",
"body": "My library is [here](https://github.com/Evoke-PHP/Evoke-PHP) its using the MIT license. Its still in alpha at this stage."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T20:05:08.223",
"Id": "20671",
"Score": "0",
"body": "I see you are making dynamic function calls from your controller...but how do yo instantiate your models?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T20:17:52.403",
"Id": "20674",
"Score": "0",
"body": "Anyways...if you want to add my UploadImage class to your library...let me know and I can iron out to the specs you want...I think you have reviewed it before...but if not I an repost the updated version...thanks for your help again."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T05:02:10.193",
"Id": "12682",
"ParentId": "12560",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12583",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T20:02:52.847",
"Id": "12560",
"Score": "2",
"Tags": [
"php"
],
"Title": "class MUserNew | Add DRY, remove constants to mysql defaults"
}
|
12560
|
<p>I usually program in python/javascript and am very new to php. I would appreciate some advice on how to improve the following form script.</p>
<p>Since this is for a highly trafficked website, I want it to be extremely secure, reliable and optimized.</p>
<p>Feel free to point out minor issues as well.</p>
<pre><code><?php
// avoid errors when in production
// ini_set("display_errors", "0");
error_reporting(-1);
# get value from array
function get_string($array, $index, $default = '') {
if (isset($array[$index]) && strlen($value = trim($array[$index])) > 0) {
return get_magic_quotes_gpc() ? stripslashes($value) : $value;
} else {
return $default;
}
}
function test($field) {
global $errors, $required_error;
if ($field['value'] == '') {
if ($field['required']) {
$required_error = true;
}
return;
}
elseif ($field['validation'] == 'email' && !filter_var($field['value'], FILTER_VALIDATE_EMAIL)) {
array_push($errors, $field['value'] . ' is an invalid email address.');
}
elseif ($field['validation'] == 'number' && !preg_match('/^[0-9 ]+$/', $field['value'])) {
array_push($errors, $field['value'] . ' is an invalid number.');
}
elseif ($field['validation'] == 'alpha' && !preg_match('/^[a-zA-Z ]+$/', $field['value'])) {
array_push($errors, $field['value'] . ' contains invalid characters. This field only accepts letters and spaces.');
}
}
$post = filter_input_array( INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS );
$errors = array();
$required_error = false;
$ajax = get_string($post, "request_method") == 'ajax';
# select data that needs validation
$fields = array(
'fullname' => array(
'value' => get_string($post, "full-name"),
'validation' => 'alpha',
'required' => true,
),
'emailaddress' => array(
'value' => get_string($post, "email-address"),
'validation' => 'email',
),
'activites' => array(
'value' => get_string($post, "activites"),
'validation' => 'default',
),
'country' => array(
'value' => get_string($post, "country"),
'validation' => 'default',
),
'contactpreference' => array(
'value' => get_string($post, "contact-preference"),
'validation' => 'default',
),
'message' => array(
'value' => get_string($post, "message"),
'validation' => 'alpha',
),
);
// test each field
foreach ($fields as $field) {
test($field);
}
if (count($errors) or $required_error) {
if ($ajax){
echo 'FAIL';
return;
}
$template_dict = array(
'errors' => ''
);
if ($required_error == true) {
$template_dict['errors'] .= "<li>Please fill out all required fields</li>";
}
foreach ($errors as $error) {
$template_dict['errors'] .= "<li>$error</li>";
}
// show errors
echo $template_dict['errors'];
} else {
$template_dict = $fields;
// send mail
$formcontent = "Full Name: $fullname \nEmail Address: $emailaddress \nActivites: $activites \nCountry: $country \nContact preference: $contactpreference \nMessage: $message \n";
$formcontent = wordwrap($formcontent, 70, "\n", true);
$recipient = 'email@address.com'; $subject = "Form Name"; $mailheader = "From: $emailaddress \r\n";
mail($recipient, $subject, $formcontent, $mailheader);
if ($ajax) {
echo 'PASS';
return;
}
echo 'Success';
}
?>
</code></pre>
|
[] |
[
{
"body": "<p>I've tried to address as many things as I could think of, though I'm not sure how relevent a lot of them will be :).</p>\n\n<p>Anyway, on a lot of things I just glossed over the subject for brevity, however, if you have any questions or want me to defend any statements, I gladly will if prompted.</p>\n\n<p><strong>error_reporting</strong></p>\n\n<p>I tend to leave error_reporting and display_errors out of PHP scripts as much as possible. Those should ideally be server-wide settings more so than application specific. A development server should always have error_reporting(E_ALL) and display_errors = On and a production server should always have error_reporting(E_ALL) and display_errors = Off. If error reporting ever has to be lowered to accomdate variable doesn't exist or undefined index type notices, that's a sign of bad code.</p>\n\n<p><strong>Magic Quotes</strong></p>\n\n<p>If magic quotes is on, either turn it off, or if not possible, move servers. Magic quotes is an ancient, horrible mistake PHP made, and no server admin should ever have it enabled.</p>\n\n<p><strong>get_string</strong></p>\n\n<p>You're doing too much in this function. The name and the function signature gives the impression that it gets a string if it exists in an array, and otherwise returns the default.</p>\n\n<p>What is actually happening though is much more than this.</p>\n\n<p>Also, the logic in it is a bit misleading. What if you call it with a default that is not the empty string, but then an empty string is in the array? Because of the strlen check, the non empty default is going to be picked. Also, I would not expect this function to be calling trim.</p>\n\n<p>In my opinion, this function needs either better documentation, a better name, or both. (Or pull the multiple behaviors into multiple functions.)</p>\n\n<p>I would probably implement this function as follows:</p>\n\n<pre><code>function array_get(array $array, $key, $default = null)\n{\n return (array_key_exists($key, $array)) ? $array[$key] : $default;\n}\n</code></pre>\n\n<p>I might then build on top of this:</p>\n\n<pre><code>function array_get_string(array $array, $key, $default = '')\n{\n $val = array_get($array, $key);\n return (is_string($val)) ? $val : $default;\n}\n</code></pre>\n\n<p>Or, if you wanted to bake in the trim functionality:</p>\n\n<pre><code>function array_get_string(array $array, $key, $default = '', $trim = true)\n{\n $val = array_get($array, $key);\n if (is_string($val)) {\n return ($trim) ? trim($val) : $val;\n }\n return $default;\n}\n</code></pre>\n\n<p>Another example of how you could build on it:</p>\n\n<pre><code>function array_get_digits(array $array, $key, $default = 0)\n{\n $val = array_get($array, $key);\n if (is_int($val) || ctype_digit($val)) {\n return (int) $val;\n } else {\n return $default;\n }\n}\n</code></pre>\n\n<p><strong>test</strong></p>\n\n<p>Globals are evil. I'm too lazy to back it up in this post, but the key points:\n* ties your code to them (you must always use variables named $errors and $required_errors. What if you want to call test and have it populate a different set of variables?)\n* your code no longer gets along with code you didn't write. What if a different piece of code happens to use $errors and your code silently clobbers it?\n* much harder to maintain -- it's difficult to follow the mutation of a variable when it's done in a far off place with no easily traceable execution flow</p>\n\n<p>What you should do instead is to return an array containing the errors.</p>\n\n<p>Also, test is a bad name. <em>What</em> are you testing? Perhaps <code>validateField</code> or <code>testInputField</code> or something along those lines.</p>\n\n<p><strong>When sanitizing should happen</strong></p>\n\n<pre><code>$post = filter_input_array( INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS );\n</code></pre>\n\n<p>This is done too early. Your validations should see text as it actually is, not as valid HTML. SANITIZE is a bit of a misnomer here. It should actually be something like FILTER_ESCAPE_HTML or something. HTML escaping only makes sense in the context of HTML. Your validations are seeing text, not HTML.</p>\n\n<p>This becomes a lot more important if you're storing information in a database. Once you store text transformed, it becomes harder to search for it, and it becomes harder to predict the length of it.</p>\n\n<p>The length could actually apply to your situation as well. <code>a & b</code> is 5 characters, however, <code>a &#38; b</code> is 9. What if you had a field that had a max of 5 characters? Suddenly the user is very confused as to why his input is failing. (Also, <code>a &#38; b</code> is meaningless outside of HTML.) Since your email is plaintext, you would actually see <code>&#38;</code> in your email.</p>\n\n<p>In short, escape at the last possible moment.</p>\n\n<p><strong>Random design input</strong></p>\n\n<p>I might approach your forms a bit more abstractly. For example, I might take your array idea ($fields) and consider that a \"form\". Then a validateForm function could take all of the elements in the form and check them for errors. This function would return an array of any errors (or perhaps: <code>array('errors' => [errors], 'valid' => [valid field's values])</code>. This would still use most of the same code you have now, just structed a bit differently.</p>\n\n<p>Also, I would consider making 'validation' be an array. What if at some point in the future you want to apply multiple validations to a field? (\"If it's wrong in way X, show one message; if it's wrong in way Y, show a different message\").</p>\n\n<p>Another design point: I would make 'required' be handled like any other error. There's not really a reason to only validate until you come across the first empty required field, and this requires complicating the error handling code.</p>\n\n<p><strong>Type strictness</strong></p>\n\n<p>PHP's implicit type system is a bit odd at times. For example, <code>0 == ''</code> is true. That means that in situations like <code>$field['value'] == ''</code> you should likely use <code>$field['value'] === ''</code>.</p>\n\n<p>Or perhaps:</p>\n\n<pre><code>$field['value'] === '' || $field['value'] === null\n</code></pre>\n\n<p>I highly advise learning the type system and related materials (isset/empty/array_key_exists/etc). PHP has lots of little quirks that can bite you (and have bitten me many times before I became paranoid :p).</p>\n\n<p><strong>Optimizing</strong></p>\n\n<p>The script looks fine in terms of performance. The main time-taker in it will be the mail() call, and assuming your mail server is quick to respond, that shouldn't be significant.</p>\n\n<p><strong>mail</strong></p>\n\n<p>I like to use packages like Zend_Mail or PHPMailer. For a simple email with a simple server setup, though, <code>mail</code> should be fine. (For example, <code>mail</code> and SSL would be an unpleasant combination.)</p>\n\n<p>I might worry about whether or not mail succedes though. Might be nice to warn users that mailing failed.</p>\n\n<p><strong>Style</strong></p>\n\n<p><em>This section is 100% opinion</em></p>\n\n<hr>\n\n<p>array_push is pretty rare to see in modern code. There's borderline cases where it's actually better, but for visual reasons, most people prefer the $array[] syntax.</p>\n\n<p>The following are equivalent:</p>\n\n<pre><code>$arr[] = 5;\narray_push($arr, 5);\n</code></pre>\n\n<hr>\n\n<pre><code>if (count($errors) or $required_error)\n</code></pre>\n\n<p>Would usually be written as:</p>\n\n<pre><code>if (count($errors) || $required_error)\n</code></pre>\n\n<p>(Though or and || are not interchangeable, they are in this situation. In situations that do not explicitly call for <code>or</code>, <code>||</code> is typically used.)</p>\n\n<hr>\n\n<pre><code>if ($required_error == true)\n</code></pre>\n\n<p>Is a bit redundant. It should just be:</p>\n\n<pre><code>if ($required_error)\n</code></pre>\n\n<p>The only time to use == for true is when you're strictly checking:</p>\n\n<pre><code>if ($required_error === true) //true iff $required_error is boolean true. For example, $required_error = 1 would be false because 1 !== true.\n</code></pre>\n\n<hr>\n\n<p>I wouldn't mix <code>#</code> and <code>//</code> comments. Just a being-picky thing, but it looks a bit odd to have both in one file (or really both in one codebase). <code>//</code> is pretty much the standard in PHP, though both are just as well supported.</p>\n\n<hr>\n\n<p>I would consider using heredoc style comments. They can be parsed by IDEs like Netbeans and can be used to generate HTML documentation. For example:</p>\n\n<pre><code>/**\n * Takes an array, an index for the array and an optional $default and returns $array[$index]\n * if it exists, or otherwise $default.\n * \n * @param array $array The array from which to select the data\n * @param string|int $index The index of the array\n * @param mixed $default The value to return if $index is not in $array\n * @return string $array[$index] if it exists, otherwise, $default\n*/\nfunction get_string(array $array, $index, $default = '')\n</code></pre>\n\n<p>Depending on how clear names are, documentation is often not needed for small code bases, but it's very helpful when you come back a year later and have to figure out what's going on in a function.</p>\n\n<p>Note also that I made it so that <code>$array</code> must be an array. This is only possible in PHP for certain types (<code>array</code> and classes).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T20:04:24.163",
"Id": "20297",
"Score": "0",
"body": "That really was really enlightening. Thanks @Corbin for the thorough answer. Will spend the next few days implementing your suggestions! :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T07:46:28.903",
"Id": "12571",
"ParentId": "12561",
"Score": "3"
}
},
{
"body": "<p>Corbin did a really good job +1 for him. I just wanted to add a couple of things.</p>\n\n<p>Corbin mentioned \"or\" and \"||\" not being equivalent. He is correct, they accomplish the same thing, but \"or\" has a lower precedence than \"||\". So \"||\" is processed before \"or\" when computed in the same expression, think of PEMDAS in math. However, he might have been thinking about its other implementation as a pseudo \"else\" statement usually seen as <code>or die()</code>. This short-circuiting works but is frowned upon, and either way I would just suggest staying away from \"or\" all together. More than likely you will never need it.</p>\n\n<p><strong>My Suggestions</strong></p>\n\n<p>You should avoid declaring variables in statements. It is allowed, but could cause issues. For example, if not done on purpose PHP and your IDE will have no way of warning you because it is considered valid code. So the expression <code>if($isLoggedIn = TRUE)</code> is TRUE, and I'm sure you can see where this leads. So if you just don't do it then when you find it in your code you know it isn't supposed to be there. Another plus for not doing it is that it makes your code easier to read. Longer, but easier to read. And easier to read, means easier to debug :)</p>\n\n<pre><code>if (isset($array[$index]) && strlen($value = trim($array[$index])) > 0) { }\n//becomes\nif(isset($array[$index])) {\n $value = trim($array[$index]);\n if(strlen($value)) { }//You can also drop that greater than comparison ( 0 == FALSE )\n}\n</code></pre>\n\n<p>When checking if a value is empty, you can use PHP's <code>empty()</code> function.</p>\n\n<pre><code>if ($field['value'] == '') { }\n//OR\nif($field['value'] === '') { }\n//becomes\nif(empty($field['value'])) { }\n</code></pre>\n\n<p>When checking the same value for different states, it is much better to use a switch than multiple if/else statements. They are quicker and easier to read, not to mention that it saves repitition in your code.</p>\n\n<pre><code>switch($field['validation']) {\n case 'email':\n if(!filter_var($field['value'], FILTER_VALIDATE_EMAIL)) {\n array_push($errors, $field['value'] . ' is an invalid email address.');\n }\n break;\n case 'number':\n if(!preg_match('/^[0-9 ]+$/', $field['value'])) {\n array_push($errors, $field['value'] . ' is an invalid number.');\n }\n break;\n case 'alpha':\n if(!preg_match('/^[a-zA-Z ]+$/', $field['value'])) {\n array_push($errors, $field['value'] . ' contains invalid characters. This field only accepts letters and spaces.');\n }\n break;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T19:05:35.933",
"Id": "20280",
"Score": "1",
"body": "I actually was trying to hint that `or` should be avoided entirely, but going back and reading what I wrote, I can see how the shortcircuiting-abuse interpretation is there. Also, you should mention that empty has *a lot* of quirks. Like \"0\" being considered empty. I tend to avoid empty unless I'm fine with the quirks of it. (Can confuse a user quite a bit to see an error about an empty string when they provided 0.) Also, I seem to be in the minority on this one, but I avoid switch statements. I don't consider them very readable at all and much prefer if-else trees (just opinion though)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T20:08:42.617",
"Id": "20298",
"Score": "0",
"body": "I am quite used to using \"or\" in python and I guess it just seemed familiar. Never knew it had issues. Now I do :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T20:12:55.353",
"Id": "20300",
"Score": "0",
"body": "@Corbin: You are quite right about empty. Assumed variable would be quirk free. Bad of me I know. Switch statements, for me, have more to do with not wanting to repeat code whenever possible rather than legibility. However, I do also find them easier to read, thus my preference for them :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T20:20:43.533",
"Id": "20301",
"Score": "0",
"body": "Not sure if I understand how switch statements lead to less repeated code than if-else branches? They're basically the same construct represented with different syntax. Unless you're referring to the ability for switch statements to fall through?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T21:21:00.400",
"Id": "20304",
"Score": "0",
"body": "@Corbin: No not the fall through, don't like that feature honestly. No, its not much reduction but you only have to type the variable you are comparing once, \"`$field['validation']`\" in this case, which with me and my fat fingers and lysdexia that means less chance of typos."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T21:28:02.997",
"Id": "20305",
"Score": "0",
"body": "Ah. Seems like break and case would compensate for the lack of variable repetition. I suppose break and case are harder to typo than a variable name though :)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T22:18:59.063",
"Id": "20308",
"Score": "0",
"body": "@Corbin: Except `elseif( && == ){}` are also removed from each iteration as well. My if statement could be said to make that just `else && ==`. Which is exactly as long as `case :break;` So my point stands, its shortened exactly the length of the variable being compared :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T22:26:01.847",
"Id": "20311",
"Score": "0",
"body": "I think we're at the point now where we should just accept that it just comes down to personal preference, and apparently we just have different preferences :)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T22:58:17.050",
"Id": "20315",
"Score": "0",
"body": "@Corbin: indeed :)"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T15:57:33.253",
"Id": "12581",
"ParentId": "12561",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "12571",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T20:04:00.013",
"Id": "12561",
"Score": "2",
"Tags": [
"php",
"form"
],
"Title": "Need help optimizing & improving this php form script"
}
|
12561
|
<pre><code>import System.Environment (getArgs)
import Random
main = do
args <- getArgs
let len = length args
let n = if len < 1 then 10000 else read (args !! 0) :: Int
let fileName = if len < 2 then show n ++ "-output.txt" else args !! 1
str <- rndStr n
writeFile fileName (str)
-- writeFile fileName (rndStr n)
-- Couldn't match expected type `[Char]' with actual type `IO String'
rndStr :: Int -> IO String
rndStr n = sequence . replicate n . randomRIO $ (' ', '~')
</code></pre>
<p>This code works. It creates size n file of random chars. That's good.</p>
<p>I have 2 questions:<br>
1. Is my argument sanitizing ok? If not, how to make it better?<br>
2. Swapping <code>writeFile str</code> for <code>writeFile (rndStr n)</code> produces [Char] vs IO String error.
Why? Shouldn't it be the same?<br>
I manage this to work by accident, not because I know what I did.</p>
|
[] |
[
{
"body": "<p>Congratulations on your progress, :) Welcome to monads</p>\n\n<p>First thing you have to keep in mind is to restrict the time spent in imperative world. So take out as much stuff as you can from the do ..., and refactor them into smaller non-IO code.</p>\n\n<pre><code>import System.Environment (getArgs)\nimport System.Random\nimport Control.Monad\n</code></pre>\n\n<p>Another advice is to avoid magic numbers in your code. If there are any, they should be declared in a highly visible area along with their purpose rather than buried deep in the code.</p>\n\n<pre><code>minLen = 10000\n\nmain = do\n args <- getArgs\n writeFile (getFileName args) =<< rndStr (getFileSize args)\n where getFileSize [] = minLen\n getFileSize (x:xs) = read x :: Int\n getFileName [x] = x ++ \"-output.txt\"\n getFileName (x:y:[]) = y\n</code></pre>\n\n<p>As you can see, the reason you can't use rndStr directly is that rndStr uses IO. So it cannot be directly used as a function. You can think of it this way. rndStr returns some thing that is wrapped in a box. You need special constructs to unbox it, and the special construct is either <- . You might also notice that main has the same kind of signature. </p>\n\n<p>That isn't a really good analogy, and I am not the best teacher :). So if you really want to understand what happens, it might be better to read any simple monad tutorial.</p>\n\n<pre><code>rndStr :: Int -> IO String\nrndStr n = sequence . replicate n . randomRIO $ (' ', '~')\n</code></pre>\n\n<hr>\n\n<p>Try this approach if it makes better sense to you. When you start ghci, use this flag</p>\n\n<pre><code>ghci -XImplicitParams\n</code></pre>\n\n<p>On the prompt after loading your program, try to execute writeFile which was not accepting <code>(rndStr number)</code> earlier, but this time, instead of that expression, replace it by ?check</p>\n\n<pre><code>> writeFile (getFileName [\"5\"] ) ?check\n</code></pre>\n\n<p>You will get back some thing like</p>\n\n<pre><code><interactive>:0:32:\n Unbound implicit parameter (?check::String)\n arising from a use of implicit parameter `?check'\n In the second argument of `writeFile', namely `?check'\n In the expression: writeFile (getFileName [\"5\"]) ?check\n In an equation for `it': it = writeFile (getFileName [\"5\"]) ?check\n</code></pre>\n\n<p>Ignore every thing except the second line, the Unknown implict .. tells you that ghc expected any exprssion in place of ?check would be a string.</p>\n\n<p>Now try finding the type of our expression <code>(rndStr number)</code></p>\n\n<pre><code>> :t rndStr 5\nrndStr 5 :: IO String\n</code></pre>\n\n<p>As you can see, <code>rndStr number</code> has a different type <code>IO String</code> than the expected <code>String</code>. This is the reason you cant use <code>rndStr number</code> there, and why we have to do all that above.</p>\n\n<p>Note that my statement <code>writeFile (getFileName args) =<< rndStr (getFileSize args)</code> is really same as</p>\n\n<pre><code>do\nstr <- rndStr (getFileSize args)\nwriteFile (getFileName args) str\n</code></pre>\n\n<p>Try to work out how it is so.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T12:39:13.647",
"Id": "20247",
"Score": "0",
"body": "**Thanks for the answer :)**\nSub questions:\n1. I'll divide impure from pure f as much as I can/know. But why are we doing that? It's faster, compiler can optimize that code, less error prone, something else...?\n2. you could wrote `getFileSize` and `getFileName` at a same indent as `main`. It would work. But you used `where` so you don't pollute global name space. Right? Or there's something else to it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T12:56:16.043",
"Id": "20248",
"Score": "0",
"body": "`getFileName [] = show minLen ++ \"-output.txt\"` is needed because of _Non-exhaustive patterns in function getFileName_"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T14:30:19.340",
"Id": "20252",
"Score": "1",
"body": "@CoR 1) The names pure and impure should give you a hint :). Things that are in the impure land are harder to reuse or test (or even reason about). Always be on the look out for places where a general pattern that can be reused can be isolated. 2) I could have, and I debated it myself. The reason I went with the current is that it is too specific still (using minLen and \"-output.txt\"). If I can make it general enough, it should be in the top level. 3) yes, I missed it :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T04:13:35.160",
"Id": "12567",
"ParentId": "12566",
"Score": "2"
}
},
{
"body": "<p>For learning purposes, I am posting the evolution of the <code>rndStr</code> function I've used above.<br>\nCopy/paste code in a file, load it in <code>ghci</code>, and it will work. All comments are in the code. It shows the difference between [IO Char] and IO [Char], Haskell Platform 2011/2012 and (Eq a, Num a) vs Int. </p>\n\n<pre><code>import System.Random\nrndChar :: IO Char\nrndChar = randomRIO (' ', '~') -- ('a','z'), ('A', 'z'), (' ', '~') all printable chars\n\n-- bad f, don't know how to use [IO Char] \n--2011 str :: Num a => a -> [IO Char]\n--2012 str :: (Eq a, Num a) => a -> [IO Char]\nstr 0 = []\nstr n = rndChar : str (n-1)\n\n--2011 rndStr1 :: Num a => a -> [IO Char]\n--2012 rndStr1 :: (Eq a, Num a) => a -> IO [Char]\nrndStr1 n = sequence (str n)\n\n-- sequence :: Monad m => [m a] -> m [a]\n-- sequence xs -- sequence xs evaluates all monadic values in list xs, from left to right, and returns a list of \"contents\" of these monads, placing this list in a monad of same type.\n-- \"evaluating\" can be \"performing an action\", as in print\n\n\nrndStr2 n = sequence $ str n -- rndStr2' = sequence $ str n\n where\n str 0 = []\n str n' = randomRIO (' ', '~') : str (n'-1)\n\nrndStr3 n = let -- rndStr3 = let in ... in sequence $ str n\n str 0 = []\n str n' = randomRIO (' ', '~') : str (n'-1)\n in sequence $ str n\n\n--2011 rndStr4'' :: Num a => a -> [IO Char] -- must be wrapped in sequence\n--2012 rndStr4'' :: (Eq a, Num a) => a -> [IO Char]\nrndStr4'' n = case n of\n 0 -> []\n _ -> randomRIO (' ', '~') : rndStr4'' (n-1)\n\nrndStr4 :: (Eq a, Num a) => a -> IO [Char]\nrndStr4 n = sequence $ rndStr4'' n\n\n-- should be tail recursion because it returns acc as last f call\nrndStr2t n = sequence $ help n []\n where\n help 0 acc = acc -- brake tail recursion\n help x acc = help (x-1) (randomRIO (' ', '~') : acc)\n\nrndStr3t n = let\n help 0 acc = acc\n help n acc = help (n-1) (randomRIO (' ', '~') : acc)\n in sequence $ help n []\n\n\n--\nrndStr8 n = sequence (take n (repeat (randomRIO (' ', '~'))))\nrndStr8' n = sequence $ take n $ repeat $ randomRIO (' ', '~')\n\nrndStr9 n = sequence $ replicate n $ randomRIO (' ', '~')\nrndStr9' n = sequence . (replicate n) . randomRIO $ (' ', '~')\n\n--replicateM :: Monad m => Int -> m a -> m [a]\n--replicateM n action -- performs action n times, return results. \n--rndStr10 :: Int -> IO [Char]\nrndStr10 n = replicateM n (randomRIO (' ', '~'))\nrndStr10a n = replicateM n $ randomRIO (' ', '~')\n\n\n\n\n\n--2011 :: Num a => a -> IO [Char]\n--2012 :: (Eq a, Num a) => a -> IO [Char]\nrfN = [\n rndStr1, rndStr2, rndStr3, rndStr4, \n rndStr2t, rndStr3t\n ]\n\n-- :: Int -> IO [Char]\nrfI = [rndStr8,\n rndStr8',\n rndStr9,\n rndStr9',\n rndStr10]\n\ntf (x:xs) param = do\n print =<< (x param) -- (>>= print)\n if null xs then return () else tf2 xs param\n\n-- usage:\n-- tf rfI 10\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T18:56:04.097",
"Id": "12712",
"ParentId": "12566",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "12567",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T03:12:45.253",
"Id": "12566",
"Score": "1",
"Tags": [
"strings",
"haskell",
"random"
],
"Title": "Haskell: rndFile and [Char] vs IO String error"
}
|
12566
|
<p>I have this if else statement where I don't know how to remove the code duplication</p>
<pre><code>if(array_key_exists($key,$cachetable))
{
if($cachetable[$key] != $newdata[$key])
{
//data existed but is not valid
//update the cachetable
$cachetable[$key] == $newdata[$key]
}
}
else
{
//data didn't existed before in cache so add it now
//update the cachetable
$cachetable[$key] == $newdata[$key]
}
</code></pre>
|
[] |
[
{
"body": "<p>Modify the code to this:</p>\n\n<pre><code>//just use the AND operator (&&) to check if it's both existing AND valid\n//use strict comparison (===) whenever possible\nif(array_key_exists($key,$cachetable) && $cachetable[$key] === $newdata[$key]){\n //data exists and valid\n} else {\n //data doesn't exist or isn't valid\n //to assign data, use a single equal (=). \n //A double equal (==) is a loose comparison\n $cachetable[$key] = $newdata[$key];\n }\n</code></pre>\n\n<hr>\n\n<pre><code>//this one checks if it's not in the array\n//or if it does, it checks if it's not valid\n//when either one is true, the condition passes\nif(!array_key_exists($key,$cachetable) || $cachetable[$key] !== $newdata[$key]){\n //data doesn't exists or isn't valid\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T06:56:31.910",
"Id": "20239",
"Score": "0",
"body": "I thought of this myself but then thought that I should check $cachetable[$key] === $newdata[$key] only after doing the array_key_exists() otherwise some error would occur. was I wrong? is it possible to check both things in one if statement?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T06:59:32.013",
"Id": "20240",
"Score": "0",
"body": "as far as i know, if a condition fails in an AND (`&&`), PHP does not continue evaluating the rest of the conditions. therefore, `$cachetable[$key] === $newdata[$key]` is only evaluated when `array_key_exists($key,$cachetable)` returns true."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T06:59:55.193",
"Id": "20241",
"Score": "1",
"body": "The `&&` operator is a \"short circuit\" operator, meaning it only evaluates the expression to the right if the one to the left evaluated to `true`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T07:02:26.253",
"Id": "20242",
"Score": "0",
"body": "Ok, However I don't do anything when the data is valid, so maybe you could edit the answer to have only a if with the ! appended there"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T07:04:42.007",
"Id": "20243",
"Score": "0",
"body": "@nischayn22 updated"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T13:35:10.263",
"Id": "20250",
"Score": "1",
"body": "`if( ! array_key_exists($key, $cachetable) || $cachetable[$key] !== $newdata[$key]) { }` - removes need for else statement"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T06:53:51.557",
"Id": "12569",
"ParentId": "12568",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "12569",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T06:46:35.857",
"Id": "12568",
"Score": "2",
"Tags": [
"php",
"cache"
],
"Title": "Updating or adding data to an associative array as a cache"
}
|
12568
|
<p>This is a recursive descent parser for simple language with following grammar:<br>
PROGRAM <- {STATEMENT ';'}* RETURN_STMT ';'<br>
STATEMENT <- NAME_BINDING | TYPE_DECLARATION<br>
TYPE_DECLARATION <- named_param identifier<br>
NAME_BINDING <- identifier '=' EXPRESSION<br>
EXPRESSION <- (simple arithmetics with (), +-*/ and unary minus, arguments can be constants, named parameters or identifiers)<br>
RETURN_STMT = 'return' EXPRESSION {',' EXPRESSION}* ';'</p>
<p>Module entry point is <strong>parseGrammar</strong>, resulting AST represented as <strong>Program</strong></p>
<pre><code>module LangParser(parseGrammar, Token(..), Result(..)) where
import Control.Applicative
import Control.Monad
data Token =
Return |
Simple Char |
DecimalConst String |
HexConst String |
NamedParam String |
Identifier String |
LexError String |
EOF
deriving (Eq, Show)
data Op = ONop | OPlus | OMinus | OStar | OSlash | ONeg deriving (Show, Eq)
instance Ord Op where
compare ONeg _ = GT
compare _ ONeg = LT
compare OStar _ = GT
compare OSlash _ = GT
compare OPlus b
| b == OStar = LT
| b == OSlash = LT
| otherwise = GT
compare OMinus b
| b == OStar = LT
| b == OSlash = LT
| otherwise = GT
compare _ _ = error "invalid comparison"
data Expr =
EList Expr Expr |
EAdd Expr Expr |
ESub Expr Expr |
EMul Expr Expr |
EDiv Expr Expr |
ENeg Expr |
EIntConst Int |
EVariable String |
ENamedParam String
deriving Show
data Stmt =
SReturn [Expr] |
SDecl String String |
SBinding String Expr
deriving Show
type Program = [Stmt]
data ParserState = ParserState {
prog :: Program,
exprStack :: [Expr],
opStack :: [Op],
stmtIdent :: String,
stmtParam :: String,
rest :: [Token]
} deriving Show
data Result a = Error Token | State a deriving Show
instance Monad Result where
(Error e) >>= _ = Error e
(State a) >>= f = f a
return = State
instance Functor Result where
fmap _ (Error t) = Error t
fmap f (State a) = State (f a)
instance Applicative Result where
pure = return
(<*>) = ap
instance Alternative Result where
empty = Error EOF
Error _ <|> p = p
State x <|> _ = State x
epsilon :: ParserState -> Result ParserState
epsilon = State
term :: Token -> ParserState -> Result ParserState
term t state@ParserState {rest = (x:xs)}
| t == x = State state{rest = xs}
| otherwise = Error x
term _ ParserState {rest = []} = Error EOF
termS :: Char -> ParserState -> Result ParserState
termS c = term (Simple c)
termValue :: ParserState -> Result ParserState
termValue state@ParserState {rest = (DecimalConst x:xs)} = State state{exprStack = v : exprStack state, rest = xs}
where v = EIntConst (read x)
termValue state@ParserState {rest = (HexConst x:xs)} = State state{exprStack = v : exprStack state, rest = xs}
where v = EIntConst (read x)
termValue state@ParserState {rest = (NamedParam x:xs)} = State state{exprStack = ENamedParam x : exprStack state, rest = xs}
termValue state@ParserState {rest = (Identifier x:xs)} = State state{exprStack = EVariable x : exprStack state, rest = xs}
termValue ParserState {rest = (x:_)} = Error x
termValue ParserState {rest = []} = Error EOF
termIdent :: ParserState -> Result ParserState
termIdent state@ParserState {rest = (Identifier x:xs)} = State state{stmtIdent = x, rest = xs}
termIdent ParserState {rest = (x:_)} = Error x
termIdent ParserState {rest = []} = Error EOF
foldExpr :: Op -> ParserState -> Result ParserState
foldExpr _ state@ParserState{opStack = []} = State state
foldExpr stop state@ParserState{opStack = (op:_)} | op <= stop = State state
foldExpr stop state@ParserState{exprStack = (e:es), opStack = (ONeg:ops)}
= foldExpr stop state{ exprStack = ENeg e : es, opStack = ops }
foldExpr stop state@ParserState{exprStack = (e1:e2:es), opStack = (op:ops)}
= case op of
OPlus -> foldExpr stop state{ exprStack = EAdd e2 e1 : es, opStack = ops }
OMinus -> foldExpr stop state{ exprStack = ESub e2 e1 : es, opStack = ops }
OStar -> foldExpr stop state{ exprStack = EMul e2 e1 : es, opStack = ops }
OSlash -> foldExpr stop state{ exprStack = EDiv e2 e1 : es, opStack = ops }
_ -> error "invalid op in stack"
foldExpr _ _ = error "invalid state in fold"
exprS :: ParserState -> Result ParserState
exprS = expr >=> foldExpr ONop
expr :: ParserState -> Result ParserState
expr s = expr' s <|> (termNeg >=> expr') s
where
termNeg = termS '-' >=> (\state -> State state{opStack = ONeg : opStack state})
expr' st = (termValue >=> exprRest) st <|>
(termS '(' >=> exprS >=> termS ')' >=> exprRest) st
exprRest :: ParserState -> Result ParserState
exprRest s =
(termOp '+' >=> expr) s <|>
(termOp '-' >=> expr) s <|>
(termOp '*' >=> expr) s <|>
(termOp '/' >=> expr) s <|>
epsilon s
where
termOp c = termS c >=> foldExpr (op c) >=> (\state -> State state{opStack = op c : opStack state})
op '+' = OPlus
op '-' = OMinus
op '*' = OStar
op '/' = OSlash
op _ = error "bad op"
retexprs :: ParserState -> Result ParserState
retexprs = exprS >=> exprList
where
exprList s = (termS ',' >=> retexprs >=> action) s <|> epsilon s
action state@ParserState {exprStack = (e1:e2:es)} = State state{exprStack = EList e2 e1 : es}
action _ = error "2"
retStmt :: ParserState -> Result ParserState
retStmt = term Return >=> retexprs >=> termS ';' >=> action
where
action state@ParserState {exprStack = (e:es)} = State state{prog = SReturn (reverse $ unroll e []) : prog state, exprStack = es}
action _ = error "3"
unroll :: Expr -> [Expr] -> [Expr]
unroll (EList e1 e2) es = unroll e2 (e1:es)
unroll e es = e:es
nameBinding :: ParserState -> Result ParserState
nameBinding = termIdent >=> termS '=' >=> exprS >=> action
where
action state@ParserState {stmtIdent = ident, exprStack = (e:[])}
= State state{prog = SBinding ident e : prog state, exprStack = []}
action _ = error "invalid binding"
paramDecl :: ParserState -> Result ParserState
paramDecl = termNamedParam >=> termIdent >=> action
where
action state@ParserState{stmtParam = param, stmtIdent = ident}
= State state{prog = SDecl param ident: prog state}
termNamedParam state@ParserState {rest = (NamedParam x:xs)} = State state{stmtParam = x, rest = xs}
termNamedParam ParserState {rest = (x:_)} = Error x
termNamedParam ParserState {rest = []} = Error EOF
statements :: ParserState -> Result ParserState
statements s = (statement >=> termS ';' >=> statements) s <|> epsilon s
where statement st = paramDecl st <|> nameBinding st
parseProgram :: ParserState -> Result ParserState
parseProgram s = (statements >=> retStmt) s <|> retStmt s
parseGrammar :: [Token] -> Result ParserState
parseGrammar st = parseProgram (ParserState [] [] [] "" "" st)
</code></pre>
<p>I'm looking for code improvements. For example, repeated this lines looks ugly:</p>
<pre><code>NNN ParserState {rest = (x:_)} = Error x
NNN ParserState {rest = []} = Error EOF
</code></pre>
<p>Also, I would like to separate parser states for parsing statements and expressions. Writing two separate types will require doubling number of epsilon/term/termIdent functions, which I hope to avoid.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T03:20:51.343",
"Id": "20363",
"Score": "0",
"body": "Are your operators all supposed to have equal precedence? I think your code could be made to look much better if a little more order could be placed on `foldExpr`, `exprS`, `expr` and `exprRest`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T22:09:39.377",
"Id": "20376",
"Score": "0",
"body": "No, there is normal arithmetic precedence."
}
] |
[
{
"body": "<p>A suggested change, </p>\n\n<pre><code>data MyType = TValue | TIdent | TNamedParam\n\ntermX :: MyType -> ParserState -> Result ParserState\ntermX t state = case (t, rest state) of\n (TIdent, Identifier x:xs) -> vstate' x xs\n (TNamedParam, NamedParam x:xs) -> vstate' x xs\n (TValue, HexConst x:xs) -> vstate xs (v' x)\n (TValue, DecimalConst x:xs) -> vstate xs (v' x)\n (TValue, NamedParam x:xs) -> vstate xs (ENamedParam x)\n (TValue, Identifier x:xs) -> vstate xs (EVariable x)\n (_ , (x:_)) -> Error x\n (_ , []) -> Error EOF\n where v' = EIntConst . read\n vstate xs v = State state{exprStack = v: exprStack state, rest = xs}\n vstate' x xs = State state{stmtParam = x, rest = xs}\n\ntermValue = termX TValue\ntermIdent = termX TIdent\ntermNamedParam = termX TNamedParam\n</code></pre>\n\n<p>I think this is better than repeating the state@ again and again.</p>\n\n<p>I think the below might also be nice since it is avoiding the repetition of foldexpression</p>\n\n<pre><code>foldExpr _ state@ParserState{opStack = []} = State state \nfoldExpr stop state@ParserState{exprStack = ex, opStack = (x:ops)} = case process ex x of \n Just ev -> foldExpr stop state{ exprStack = ev, opStack = ops } \n Nothing -> State state\n where process (e:es) ONeg = Just $ ENeg e : es\n process (e1:e2:es) OPlus = Just $ EAdd e2 e1 : es\n process (e1:e2:es) OMinus = Just $ ESub e2 e1 : es\n process (e1:e2:es) OStar = Just $ EMul e2 e1 : es\n process (e1:e2:es) OSlash = Just $ EDiv e2 e1 : es\n process e y | y <= stop = Nothing\n</code></pre>\n\n<hr>\n\n<p>A slightly terse version of exprRest. I think the do notation is clearer here.</p>\n\n<pre><code>exprRest :: ParserState -> Result ParserState\nexprRest s = foldr (\\op acc ->\n (termOp op >=> expr) s <|> acc) (epsilon s) ['+', '-', '*', '/']\n where\n termOp c = termS c >=> foldExpr (op c) >=> \\state ->\n State state{opStack = op c : opStack state}\n op '+' = OPlus\n op '-' = OMinus\n op '*' = OStar\n op '/' = OSlash\n op _ = error \"bad op\"\n</code></pre>\n\n<hr>\n\n<p>Here is the only change I made, Look at this pattern,</p>\n\n<pre><code>((termOp '+' >=> expr) s) <|>\n ((termOp '-' >=> expr) s) <|>\n ((termOp '*' >=> expr) s) <|>\n ((termOp '/' >=> expr) s) <|>\nepsilon s\n</code></pre>\n\n<p>Which is same as</p>\n\n<pre><code>let myfn op = (termOp op >=> expr) s in\n((myfn '+') <|> (myfn '-') <|> (myfn '*') <|> (myfn '/') <|>\nepsilon s\n</code></pre>\n\n<p>This can be replaced with a fold</p>\n\n<pre><code>fold (\\opfn acc -> opfn <|> acc) (epsilon s) [myfn +, myfn -, myfn *, myfn /]\n</code></pre>\n\n<p>equivalently, ...</p>\n\n<hr>\n\n<p>So I used your question as an excuse to understand lenses. Here is the resulting code. See if you like it. (I don't claim it is good as I am still learning lenses)</p>\n\n<pre><code>{-# LANGUAGE TemplateHaskell, FlexibleContexts #-}\nmodule LangParser(parseGrammar, Token(..), Result(..)) where\nimport Control.Applicative\nimport Control.Monad\n\nimport Data.Lens.Template (makeLenses)\nimport Data.Lens.Lazy\n\ndata Token =\n Return |\n Simple Char |\n DecimalConst String |\n HexConst String |\n NamedParam String |\n Identifier String |\n LexError String |\n EOF\n deriving (Eq, Show)\n\ndata Op = ONop | OPlus | OMinus | OStar | OSlash | ONeg deriving (Show, Eq)\ninstance Ord Op where\n compare ONeg _ = GT\n compare _ ONeg = LT\n compare OStar _ = GT\n compare OSlash _ = GT\n compare OPlus b\n | b == OStar = LT\n | b == OSlash = LT\n | otherwise = GT\n compare OMinus b\n | b == OStar = LT\n | b == OSlash = LT\n | otherwise = GT\n compare _ _ = error \"invalid comparison\"\n\ndata Expr = EList Expr Expr |\n EAdd Expr Expr |\n ESub Expr Expr |\n EMul Expr Expr |\n EDiv Expr Expr |\n ENeg Expr |\n EIntConst Int |\n EVariable String |\n ENamedParam String\n deriving Show\n\ndata Stmt = SReturn [Expr] |\n SDecl String String |\n SBinding String Expr\n deriving Show\ntype Program = [Stmt]\n\ndata ParserState = ParserState { \n _prog :: Program, \n _exprStack :: [Expr], \n _opStack :: [Op],\n _stmtIdent :: String,\n _stmtParam :: String, \n _rest :: [Token] \n } deriving Show\n\n$( makeLenses [''ParserState])\n\ndata Result a = Error Token | State a\n deriving Show\n\ninstance Monad Result where\n (Error e) >>= _ = Error e\n (State a) >>= f = f a\n return = State\n\ninstance Functor Result where\n fmap _ (Error t) = Error t\n fmap f (State a) = State (f a)\n\ninstance Applicative Result where\n pure = return\n (<*>) = ap\n\ninstance Alternative Result where\n empty = Error EOF\n Error _ <|> p = p\n State x <|> _ = State x\n\nepsilon :: ParserState -> Result ParserState\nepsilon = State\n\nterm :: Token -> ParserState -> Result ParserState\nterm t state = case state ^. rest of\n (x:xs) -> if t == x then State (rest ^= xs $ state) else Error x \n [] -> Error EOF\n\ntermS :: Char -> ParserState -> Result ParserState\ntermS c = term (Simple c) \n\ndata MyType = TValue | TIdent | TNamedParam\n\ntermX :: MyType -> ParserState -> Result ParserState\ntermX t state = case (t, rest ^$ state) of\n (TIdent, Identifier x:xs) -> vstate' x xs\n (TNamedParam, NamedParam x:xs) -> vstate' x xs\n (TValue, HexConst x:xs) -> vstate xs (v' x)\n (TValue, DecimalConst x:xs) -> vstate xs (v' x)\n (TValue, NamedParam x:xs) -> vstate xs (ENamedParam x)\n (TValue, Identifier x:xs) -> vstate xs (EVariable x)\n (_ , (x:_)) -> Error x\n (_ , []) -> Error EOF\n where v' = EIntConst . read \n vstate xs v = State ( exprStack ^= v: (exprStack ^$ state) $ rest ^= xs $ state )\n vstate' x xs = State ( stmtParam ^= x $ rest ^= xs $ state)\n\nfoldExpr :: Op -> ParserState -> Result ParserState\nfoldExpr stop state = case opStack ^$ state of\n [] -> State state\n (x:ops) -> case process ex x of \n Just ev -> foldExpr stop (exprStack ^= ev $ opStack ^= ops $ state)\n Nothing -> State state\n where process (e:es) ONeg = Just $ ENeg e : es\n process (e1:e2:es) OPlus = Just $ EAdd e2 e1 : es\n process (e1:e2:es) OMinus = Just $ ESub e2 e1 : es\n process (e1:e2:es) OStar = Just $ EMul e2 e1 : es\n process (e1:e2:es) OSlash = Just $ EDiv e2 e1 : es\n process e y | y <= stop = Nothing\n ex = exprStack ^$ state\n\nexprS :: ParserState -> Result ParserState\nexprS = expr >=> foldExpr ONop\n\nexpr :: ParserState -> Result ParserState\nexpr s = expr' s <|> (termNeg >=> expr') s\n where \n termNeg s = termS '-' s >>= State . (opStack ^%= (ONeg :))\n expr' st = (termX TValue >=> exprRest) st <|> (termS '(' >=> exprS >=> termS ')' >=> exprRest) st\n\nunroll :: Expr -> [Expr] -> [Expr]\nunroll (EList e1 e2) es = unroll e2 (e1:es)\nunroll e es = e:es\n\nexprRest :: ParserState -> Result ParserState\nexprRest s = \n (termOp '+' >=> expr) s <|> \n (termOp '-' >=> expr) s <|> \n (termOp '*' >=> expr) s <|> \n (termOp '/' >=> expr) s <|> \n epsilon s\n where\n termOp c = termS c >=> foldExpr (op c) >=> State . (opStack ^%= (op c :))\n op '+' = OPlus\n op '-' = OMinus\n op '*' = OStar\n op '/' = OSlash\n op _ = error \"bad op\"\n\nretexprs :: ParserState -> Result ParserState\nretexprs s = do a <- exprS s\n b <- termS ',' a\n c <- retexprs b\n action c <|> epsilon s\n where \n action state = case getES state of\n (e1:e2:es) -> State (myprog state e1 e2 es)\n _ -> error \"2\"\n myprog state e1 e2 es = setES state (EList e2 e1 : es)\n\nretStmt :: ParserState -> Result ParserState\nretStmt s = do a <- term Return s\n b <- retexprs a\n c <- termS ';' b\n action c\n where\n action :: ParserState -> Result ParserState\n action state = case getES state of\n (e:es) -> State (myprog state e es)\n _ -> error \"3\"\n myprog state e es = prog ^= SReturn (reverse $ unroll e []) : (state ^. prog) $ setES state es\n\nnameBinding :: ParserState -> Result ParserState\nnameBinding s = do a <- termX TIdent s\n b <- termS '=' a\n c <- exprS b\n action c\n where \n action :: ParserState -> Result ParserState\n action state = case getES state of\n (e:[]) -> State (myprog state e)\n _ -> error \"invalid binding\"\n myprog state e = prog ^= SBinding (state ^. stmtIdent) e : (state ^. prog) $ setES state []\n\n\nparamDecl :: ParserState -> Result ParserState\nparamDecl s = do a <- termX TNamedParam s\n b <- termX TIdent a\n action b\n where\n action :: ParserState -> Result ParserState\n action state = State (prog ^= SDecl (state ^. stmtParam) (state ^. stmtIdent) : (state ^. prog) $ state)\n\nsetES state es = (exprStack ^= es) state\ngetES state = state ^. exprStack \n\nstatements :: ParserState -> Result ParserState\nstatements s = do b <- statement s\n c <- termS ';' b\n statements c <|> epsilon s\n where statement st = paramDecl st <|> nameBinding st\n\nparseProgram :: ParserState -> Result ParserState\nparseProgram s = do b <- statements s\n retStmt b <|> retStmt s\n\nparseGrammar :: [Token] -> Result ParserState\nparseGrammar st = parseProgram (ParserState [] [] [] \"\" \"\" st) \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T12:48:29.510",
"Id": "20341",
"Score": "0",
"body": "It's exactly how it supposed to be. In comparison left operand is always on operations stack and right operand is just taken from token stream. Left-associative operations with equal precedence should compare as GT, right-associative as LT. This is required for arithmetically correct :) parsing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T12:49:43.610",
"Id": "20342",
"Score": "0",
"body": "And I can't derive from Ord because OPlus and OMinus have equal precedence, but are different."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T15:45:55.243",
"Id": "20349",
"Score": "0",
"body": "So is it correct for Op to have an Ord instance? Isn't one of the requirements for an Ord class, a total ordering? I suppose, it may not lead to problems here, but I was taught to be very careful to only define instances of Typeclasses if you can provide the same guarantees of their interfaces."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T22:08:46.523",
"Id": "20375",
"Score": "0",
"body": "I see your point. Will remove Ord and change to plain comparison function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T22:16:16.840",
"Id": "20377",
"Score": "0",
"body": "Could you explain change in exprRest? I don't get how it works."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T19:21:12.983",
"Id": "20432",
"Score": "0",
"body": "@blaze updated. See if you can follow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T10:09:56.163",
"Id": "20611",
"Score": "0",
"body": "Thanks, got it now. Looks like this makes parser less explicit in self-describing grammar, but I need to think again about it."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T09:03:01.437",
"Id": "12611",
"ParentId": "12572",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "12611",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T07:55:35.617",
"Id": "12572",
"Score": "2",
"Tags": [
"haskell",
"parsing"
],
"Title": "Language parser in haskell"
}
|
12572
|
<p>I want to write better code.
This is a simple controller class for an administrator login.</p>
<p>Are there conventions or tips in PHP to rewrite this code and improve it?</p>
<pre><code><?php
class Administrators extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
if(!$this->session->userdata('logged_in')) {
redirect('/office/administrators/login');
} else {
redirect('/office/dashboard/');
}
}
public function login() {
if($this->session->userdata('logged_in')) {
redirect('/office/dashboard/');
}
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$a = new Administrator();
if($a->login($this->input->post('email'),$this->input->post('password'))) {
redirect('/office/dashboard/');
} else {
$this->messages->add('Unable to authenticate you', 'error');
}
}
$data['error_messages'] = $this->messages->get('error');
$this->load->view('/office/administrators/login', $data);
}
public function logout() {
$this->simpleloginsecure->logout();
redirect('office/administrators/login');
}
}
?>
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>the very first characters should be <code><?</code> to avoid whitespace from being sent in the response. This saves you from issues with header redirects. You should also omit the closing <code>?></code> for the same reason (whitespaces).</p>\n<blockquote>\n<p><a href=\"http://codeigniter.com/user_guide/helpers/url_helper.html\" rel=\"nofollow noreferrer\">In order for this function to work it must be used before anything is outputted to the browser since it utilizes server headers.</a></p>\n</blockquote>\n</li>\n<li><p>you can use the input class's post() to check for the post request.</p>\n<blockquote>\n<p><a href=\"http://codeigniter.com/user_guide/libraries/input.html\" rel=\"nofollow noreferrer\">The function (<code>post()</code>) returns FALSE (boolean) if there are no items in the POST.</a></p>\n</blockquote>\n</li>\n</ul>\n<p>Here's modified code with comments:</p>\n<pre><code><?php\n//should be the very first characters\n\nclass Administrators extends CI_Controller {\n\n public function __construct() {\n parent::__construct();\n }\n\n //factor out the login check to isolate the common logic\n //also, for understandability, boolean checks should be prefixed\n //with "is" or "has" like phrases \n //like "is it like this?", "[something] has this?"\n private function isLoggedIn(){\n return $this->session->userdata('logged_in');\n }\n\n public function index() {\n\n //use our new "isLoggedIn()"\n if(isLoggedIn()) {\n redirect('/office/dashboard/');\n } else {\n redirect('/office/administrators/login');\n } \n }\n\n public function login() {\n\n if(isLoggedIn()) {\n redirect('/office/dashboard/');\n } \n\n //you can use the input class's post() to check for the post request\n if($this->input->post()) {\n\n //for readability, it's more appropriate to\n //assign these values to verbose variables names...\n $administrator = new Administrator();\n $username = $this->input->post('email');\n $password = $this->input->post('password');\n\n //...so we know what arguments were sent\n if($administrator->login($username,$password)) {\n redirect('/office/dashboard/');\n } else {\n $this->messages->add('Unable to authenticate you', 'error');\n }\n }\n\n $data['error_messages'] = $this->messages->get('error'); \n $this->load->view('/office/administrators/login', $data);\n }\n\n public function logout() {\n $this->simpleloginsecure->logout();\n redirect('office/administrators/login');\n }\n\n}\n\n//remove the closing ?>.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T11:21:13.067",
"Id": "12574",
"ParentId": "12573",
"Score": "2"
}
},
{
"body": "<p>First Joseph's post. I agree with it mostly, but the first comment I'd like to clarify. A PHP opening tag should definitely be the first item on the page to avoid headers being sent prematurely, but the opening tag <code><?php</code> or <code><?</code> does not make a difference and depends upon your server. The traditional, long, PHP opener is usually the accepted norm because not all servers accept the later and it can cause compatibility issues. Such as if you were to include XML in your PHP then doing <code><?xml</code> might cause issues. However, most all servers have a setting that allows you to enable it \"<a href=\"http://www.php.net/manual/en/ini.core.php#ini.short-open-tag\" rel=\"nofollow noreferrer\">short_open_tag</a>\". People still use the shorter form, but it does not have any performance differences. I'm sure this is what he meant, but originally reading it I thought he was saying that switching to the short form did that. So there's clarification.</p>\n\n<p>Only other thing I want to point out is the following comment: \"you can use the input class's post() to check for the post request\". I'm not sure about CI, but unless it does the same <code>REQUEST_METHOD</code> check in its interior, then what you have there currently is fine. I just had a <a href=\"https://stackoverflow.com/questions/10999293/is-serverrequest-method-still-viable\">similar discussion</a> on SO about checking the <code>$_POST</code> vs checking the <code>REQUEST_METHOD</code> and it is much better to check the request method. Checking the post array will work, but only because it is a hack. From the looks of this CI statement it is a similar thing. But I'd suggest looking into it for clarification.</p>\n\n<p><strong>Now, here are my suggestions:</strong></p>\n\n<p>Don't override a parent method if you aren't going to extend it. The child class inherits it automagically. The only reason to call the constructor again, or any inherited method for that matter, is if you were going to change something, extend it, before or after the parent method. Example, say you wanted to change a property <code>$newProperty</code> before it was used in the parent constructor (constructor is a bad example think a normal method). Then you can set that property just before calling it so that the parent method can use that new value. Or say that your parent method has a local variable <code>$newVar</code> and you want to use it in your new class. Then you can save that variable as a property or do something with it immediately in local scope. In short, just delete your constructor it is unnecessary as is.</p>\n\n<pre><code>public function __construct() {\n $this->newProperty = 'jkl';//can be used in parent method\n parent::__construct();\n echo $newVar;//came from parent method\n $this->newVar = $newVar;\n}\n</code></pre>\n\n<p>Give your program some defaults instead of using if/else statements and/or calling methods multiple times. Doing this makes it easier to change functionality should you desire it. Say you didn't want to use redirect anymore, but maybe view instead, you'd have to change each occurrence of it. There's only two here, but if you had more it could be a pain.</p>\n\n<pre><code>public function index() {\n $redirect = '/office/dashboard/';\n\n if(!$this->session->userdata('logged_in')) {\n $redirect = '/office/administrators/login';\n }\n\n redirect( $redirect );\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T14:27:51.320",
"Id": "12578",
"ParentId": "12573",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "12578",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T10:59:19.600",
"Id": "12573",
"Score": "1",
"Tags": [
"php",
"performance",
"object-oriented",
"mvc",
"codeigniter"
],
"Title": "Controller for an Administrator User, can this be improved? (codeigniter)"
}
|
12573
|
<p>First off, I'm just learning Haskell and I'm not proficient in that language yet.</p>
<p>I wrote this Haskell module to look for files in a Linux filesystem. It can use regular expressions as search patterns. I wrote two variants: one of them sends the search results to stdout, the other (shown here) gives a list with the search results.</p>
<p>For example (in GHCi): <code>searchToList "conf" "." >>= return . take 1</code> (being "." my home directory) would give [".config"]</p>
<p>I made the function searchWriterT recursive using mapM_, but I know there is mapWriterT in the module Control.Monad.Writer.</p>
<p>Could anyone give me a hint about what I shall do to replace mapM_ with mapWriterT (if it's possible)?</p>
<p>Thanks in advance.</p>
<pre><code>module FileSearch where
import System.Directory (getDirectoryContents, doesDirectoryExist)
import Control.Monad (filterM, unless)
import Data.List ((\\))
import Text.Regex.Posix ((=~))
import Control.Monad.Writer
data Dir = Dir { path :: FilePath -- path of the current directory
, files :: [FilePath] -- files in the directory
, subdirs :: [FilePath] } -- subdirectories
deriving (Show)
dontSearch :: [FilePath]
dontSearch = ["/proc", "/sys"]
-- listDir takes the name of a directory and gives a Dir with
-- that name, a list of the files in the directory and a list of
-- its subdirectories, all prefixed with the path of the current
-- directory.
-- listDir will list neither /proc nor /sys
listDir :: FilePath -> IO Dir
listDir f
| f `elem` dontSearch = return Dir { path = f
, files = []
, subdirs = [] }
| otherwise = do
c' <- getDirectoryContents f
let c = map (appendPath f) (deleteDot c')
d <- filterM doesDirectoryExist c
return Dir { path = f
, files = (c \\ d)
, subdirs = d }
appendPath :: FilePath -> FilePath -> FilePath
-- if the path is "/", do not add another "/"
appendPath "/" y = concat ["/", y]
appendPath x y = concat [x, "/", y]
-- remove "." and ".." entries in directories
deleteDot :: [FilePath] -> [FilePath]
deleteDot = filter (`notElem` [".", ".."])
searchWriterT :: String -> FilePath -> WriterT [FilePath] IO ()
searchWriterT s f = do
d <- liftIO $ listDir f
let found = filter (=~ s) (files d)
tell found
unless (null (subdirs d)) $
mapM_ (searchWriterT s) (subdirs d)
searchToList :: String -> FilePath -> IO [FilePath]
searchToList s f = execWriterT (searchWriterT s f)
</code></pre>
|
[] |
[
{
"body": "<p><code>mapWriterT</code> is for transforming one <code>WriterT</code> into another. Its type is painfully generic, but allows you to transform pretty much everything about a WriterT.</p>\n\n<pre><code>mapWriterT :: (m (a, w) -> n (b, w')) -> WriterT w m a -> WriterT w' n b\n</code></pre>\n\n<p>So if you start with a <code>WriterT w m a</code>, and you want to end up with <code>WriterT w' n b</code> (in other words, you can transform all 3 type parameters), then you have to provide a function of the form<br>\n<code>m (a, w) -> n (b, w')</code>.</p>\n\n<hr>\n\n<p>Contrast this with <code>mapM_ :: (a -> m b) -> [a] -> m ()</code>. The purpose of <em>this</em> mapping is to take a <em>list</em> and perform monadic operations parameterized by the list's contents in sequential order.</p>\n\n<hr>\n\n<p>While there may be a way to write your function in terms of <code>mapWriterT</code>, it is a completely different kind of mapping than <code>mapM_</code>, so your request to \" replace mapM_ with mapWriterT\" doesn't really make much sense to me. Nevertheless, let's give it a spin.</p>\n\n<pre><code>newtype MatchedFiles = MatchedFiles { unwrapFiles :: [FilePath] } deriving Monoid\nnewtype SubDirs = SubDirs { unwrapDirs :: [FilePath] }\n\nfilesInDir :: String -> FilePath -> WriterT MatchedFiles IO SubDirs\nfilesInDir s f = do\n d <- liftIO $ listDir f\n let found = MatchedFiles $ filter (=~ s) (files d)\n subdirs = SubDirs $ subdirs d\n tell found\n return subdirs\n</code></pre>\n\n<p>OK, so here we've got a non-recursive <code>WriterT</code> that will simply <code>tell</code> the files that match the string at the given directory, and <code>return</code>s the subdirectories in that directory. I've used newtypes to help me not get the \"found files\" and \"subdirectories\" mixed up.</p>\n\n<p>Now, what is the transformation we want to perform on this?</p>\n\n<pre><code>searchWriterT :: String -> FilePath -> WriterT MatchedFiles IO ()\nsearchWriterT s f = mapWriterT mapper (filesInDir s f)\n where\n mapper :: IO (SubDirs, MatchedFiles) -> IO ((), MatchedFiles)\n mapper action = undefined\n</code></pre>\n\n<p>Assuming we want to write <code>searchWriterT</code> in terms of <code>mapWriterT</code> and <code>filesInDir</code>, I just followed the types and this is what we've got. Now, the question is, how to write <code>mapper</code>?</p>\n\n<pre><code>mapper action = do\n (SubDirs subdirs, files) <- action\n if null subdirs\n then return ((), files)\n else undefined\n</code></pre>\n\n<p>Clearly, if there are no \"subdirs\", then we are done, and we simply regurgitate the <code>files</code>. But what if there <em>are</em> subdirs? Well, you've already figured out what to do: use <code>mapM_</code> on the <code>subdirs</code>!</p>\n\n<pre><code>else runWriterT $ tell files >> mapM_ (searchWriterT s) subdirs\n</code></pre>\n\n<p>In fact, <code>mapM_</code> will take care of the <code>null</code> case for us: it won't do anything in the event of an empty list.</p>\n\n<pre><code>mapper action = do\n (SubDirs subdirs, files) <- action\n runWriterT $ tell files >> mapM_ (searchWriterT s) subdirs\n</code></pre>\n\n<hr>\n\n<p>Conclusion: <code>mapWriterT</code> felt kind of awkward for this problem, especially since inside the mapper we turned right around and used <code>runWriterT</code>. We didn't even get rid of <code>mapM_</code>, because <code>mapM_</code> embodies exactly what needs to be done for this problem.</p>\n\n<pre><code>searchWriterT s f = filesInDir s f >>= mapM_ (searchWriterT s) . unwrapDirs\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T05:37:56.123",
"Id": "20332",
"Score": "0",
"body": "Thank you so much for your detailed answer! I (wrongly) thought the \"map\" in \"mapWriterT\" meant that the function could be used to iterate over a list, although this is not visible when looking at the signature. I'm giving your alternative a try, it might even perform better than mine. With your answer I also discovered that I was checking lists for emptiness, but this is redundant when using \"map\"."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T22:48:14.003",
"Id": "12603",
"ParentId": "12584",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T17:29:00.817",
"Id": "12584",
"Score": "3",
"Tags": [
"haskell"
],
"Title": "Can I use mapWriterT instead of mapM/mapM_ (Haskell)?"
}
|
12584
|
<pre><code>SELECT p.name,m.name
FROM parts p
INNER JOIN Manufacturers m ON p.man_id=m.id
ORDER BY p.name DESC
</code></pre>
<p>If not, what should be done for its optimization?</p>
<p>Here is the two tables:</p>
<pre><code>CREATE TABLE `Manufacturers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB
CREATE TABLE `parts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
`man_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T15:36:37.700",
"Id": "20259",
"Score": "3",
"body": "Looks fine to me. Just make sure you have indexes on the `parts.man_id` and `Manufacturers.id` fields."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T15:39:28.697",
"Id": "20260",
"Score": "0",
"body": "it's hard to answer this without seeing the table-definitions and defined indexes/keys for both tables involved."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T15:42:29.693",
"Id": "20261",
"Score": "0",
"body": "See two tables below:\nCREATE TABLE `Manufacturers` (\n`id` int(11) NOT NULL AUTO_INCREMENT,\n`name` varchar(30) NOT NULL,\nPRIMARY KEY (`id`)\n) ENGINE=InnoDB\n\nCREATE TABLE `parts` (\n`id` int(11) NOT NULL AUTO_INCREMENT,\n`name` varchar(30) NOT NULL,\n`man_id` int(11) NOT NULL,\nPRIMARY KEY (`id`)\n) ENGINE=InnoDB"
}
] |
[
{
"body": "<pre><code>CREATE TABLE Manufacturers ( id int(11) NOT NULL AUTO_INCREMENT, \nname varchar(30) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB \n\nCREATE TABLE parts ( id int(11) NOT NULL AUTO_INCREMENT, name varchar(30) NOT NULL, \nman_id int(11) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB\n</code></pre>\n\n<p>your structure looks OK for performance, because you have index the common field where you make the join on. How ever, shouldn't you use PK and FK instead?. If you need to know a bigger description use the explain command to be sure that the index are correctly used.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T19:59:37.413",
"Id": "20296",
"Score": "1",
"body": "+1. However, I think the \"shouldn't you use a PK and FK instead?\" Should read, \"you should be using a foreign key.\" :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T16:59:20.957",
"Id": "12586",
"ParentId": "12585",
"Score": "4"
}
},
{
"body": "<p>The query is fine.</p>\n\n<p>You should consider adding an index on <code>parts.man_id</code>.</p>\n\n<p>The only thing I'd suggest is a small style improvement:<br>\nWhether you prefer left aligned or right aligned keywords doesn't matter much. But since joins are <em>part of</em> the FROM clause, I suggest you don't code that at the same indentation level.</p>\n\n<pre><code>SELECT p.name,m.name\nFROM parts p\n INNER JOIN Manufacturers m ON\n p.man_id=m.id\nORDER BY p.name DESC\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-23T13:08:58.730",
"Id": "12973",
"ParentId": "12585",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T15:35:48.210",
"Id": "12585",
"Score": "6",
"Tags": [
"optimization",
"mysql",
"sql"
],
"Title": "Has the following query been made in the optimum way?"
}
|
12585
|
<p>Is there a way to speed up the following python code:</p>
<pre><code>auxdict = {0:0}
divdict = {}
def divisors(n):
divisors = []
for i in range(1, int(n**0.5) + 1):
if (n % i == 0):
divisors.extend([i, n/i])
divisors = list(set(divisors))
divisors.sort()
return divisors
def aux(k):
if k in auxdict:
return auxdict[k]
else:
if not k in divdict:
divdict[k] = divisors(k)
r = sum(map(aux, divdict[k][:len(divdict[k])-1]))
auxdict[k] = (k+1)**3 - k**3 - r
return auxdict[k]
def lines(k):
result = 0
for i in range(int(k/2),0,-1):
result += int(k/i-1) * aux(i)
return (k+1)**3 - result - 1
for i in [10**6, 10**10]:
print i, lines(i)
</code></pre>
<p>It is a modified version of a Mathematica code I found. The code finds the maximum number of distinct lines in a 3D cube of lattices of size n: <a href="http://oeis.org/A090025" rel="nofollow">http://oeis.org/A090025</a></p>
<p>The problem is the code is very slow and doesn't work for larger values. I want to evaluate lines(10**10)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T16:22:19.933",
"Id": "20262",
"Score": "5",
"body": "Um, that first for loop will go over `10 ** 10 / 2` values; even if you could get each call to `aux` down to a millisecond that'd take two months. You'll need a different algorithm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T16:23:41.667",
"Id": "20263",
"Score": "0",
"body": "What OS is this to be run on?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T16:24:23.320",
"Id": "20264",
"Score": "0",
"body": "@Vijay I'm running Mac OS X 10.6 .. Does the OS type matter?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T16:26:36.300",
"Id": "20265",
"Score": "2",
"body": "You probably want to use `xrange` instead of `range` so you don't have a list of 5 billion integers. Not that it will help *all* that much."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T16:26:49.900",
"Id": "20266",
"Score": "0",
"body": "In Linux you could so something like: \nsort myfile.txt | uniq -uc <- call that using \"subprocess.Popen\", I assume in OSX there is a similar function... Assuming they are actually stored in \"lines\" in a file ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T16:30:52.833",
"Id": "20267",
"Score": "0",
"body": "How/where is this data stored before you have it in PY?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T16:37:01.860",
"Id": "20268",
"Score": "0",
"body": "there are better algorithm on the oeis page you linked"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T16:42:39.147",
"Id": "20269",
"Score": "0",
"body": "@Wooble I used xrange .. still very slow"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T16:42:56.773",
"Id": "20270",
"Score": "0",
"body": "@Vijay I'm not storing any data. As Dougal mentioned, the algorithm itself is slow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T16:43:08.710",
"Id": "20271",
"Score": "0",
"body": "@Simon Which one?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T16:46:38.643",
"Id": "20272",
"Score": "0",
"body": "@OsamaGamal I thought that perhaps you were reading the data in from a file, if you were then I would have another idea on how you could speed it up, where would the data originate from when this method is executed in the real world?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T16:51:37.097",
"Id": "20273",
"Score": "0",
"body": "@Vijay Check this: http://projecteuler.net/problem=388"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T16:56:42.230",
"Id": "20274",
"Score": "1",
"body": "`a(n) = Sum(moebius(k)*((floor(n/k)+1)^3-1), k=1..n)` Don't know if it is correct though"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T17:05:36.607",
"Id": "20275",
"Score": "0",
"body": "@OsamaGamal I'll whip something up... Or I'll find my PE login and grab my old solution :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T17:38:17.920",
"Id": "20277",
"Score": "0",
"body": "Don't you get overflow error with 10**10? I do..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T17:39:56.060",
"Id": "20278",
"Score": "0",
"body": "My laptop hangs and start asking for force closing apps after a while :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T18:03:49.027",
"Id": "20279",
"Score": "0",
"body": "@Wooble EDIT: You are right. I was thinking he could use a parallel algorithm, and I would have swore Amazon offer distributed computing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T19:21:02.530",
"Id": "20281",
"Score": "1",
"body": "use `sqrt(n)` instead of `n**0.5`. It's a bit faster"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T19:31:16.463",
"Id": "20284",
"Score": "1",
"body": "Also, if you are using python 2.x, integer division is the default. There is no need to type cast k/2 as `int()`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T19:58:40.203",
"Id": "20295",
"Score": "0",
"body": "@JoelCornett It's far better to do `k // 2` than using `k / 2` as integer division."
}
] |
[
{
"body": "<p>You can improve your divisors function:</p>\n\n<p><strong>Version 1:</strong> (not includes n)</p>\n\n<pre><code>def divisors(n):\n \"\"\"Return the divisors of n (including 1)\"\"\"\n if(n == 1):\n return (0)\n\n divs = set([1])\n r = floor(sqrt(n))\n if(r**2 == n):\n divs.add(r)\n\n f = 2\n step = 1\n if(n & 1 == 1):\n f = 3\n step = 2\n\n while(f <= r):\n if(n % f == 0):\n divs.add(n/f)\n divs.add(f)\n f = f + step\n\n return sorted(divs)\n</code></pre>\n\n<p><strong>Version 2:</strong> (includes n) from <a href=\"http://numericalrecipes.wordpress.com/2009/05/13/divisors/\" rel=\"nofollow\">here</a></p>\n\n<pre><code>def divisors2(n) :\n \"\"\"\n Generates all divisors, unordered, from the prime factorization.\n \"\"\"\n factors = factorI(n)\n ps = sorted(set(factors))\n omega = len(ps)\n\n def rec_gen(n = 0) :\n if n == omega :\n yield 1\n else :\n pows = [1]\n for j in xrange(factors.count(ps[n])) :\n pows += [pows[-1] * ps[n]]\n for q in rec_gen(n + 1) :\n for p in pows :\n yield p * q\n\n for p in rec_gen() :\n yield p\n</code></pre>\n\n<p>where <code>factorI</code> is:</p>\n\n<pre><code>def factorI(n):\n \"\"\"Returns the factors of n.\"\"\"\n lst = []\n num = int(n)\n if(num & 1 == 0):\n lst.append(2)\n num /= 2\n while(num & 1 == 0):\n lst.append(2)\n num /= 2\n\n factor = 3\n maxFactor = sqrt(num)\n while num>1 and factor <= maxFactor:\n if(num % factor == 0):\n num /= factor\n lst.append(factor)\n while(num % factor == 0):\n lst.append(factor)\n num /= factor\n maxFactor = sqrt(num)\n factor += 2\n\n if(num > 1):\n lst.append(num)\n return lst\n</code></pre>\n\n<p>For efficiency reasons you could also make generator functions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T19:26:08.733",
"Id": "20283",
"Score": "0",
"body": "I tried it .. It's 20seconds slower than mine for solving N=10**6 .. I'm not sure why"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T19:51:25.987",
"Id": "20292",
"Score": "0",
"body": "@OsamaGamal: There's an extra `pow()` operation at the beginning of this one. Also, the while loop is slower than iterating over the elements of `range()` or `xrange()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T05:16:06.653",
"Id": "20331",
"Score": "0",
"body": "Thats kind of weird. The first pow operations is just for checking for perfect squares. But the while loop must be faster, due to the heavily reduced interations. I will have a look at it if i found some time"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T05:41:48.087",
"Id": "20333",
"Score": "0",
"body": "Ok. Found another algorithm based on factorization. Will updating the post..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-25T14:59:25.073",
"Id": "21071",
"Score": "0",
"body": "That's better. Now it is running a little bit faster for 10**6. I just had to update the line number 5 in the aux(k) function to: divdict[k] = sorted(list(divisors(k)))"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T18:10:38.157",
"Id": "12588",
"ParentId": "12587",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12588",
"CommentCount": "20",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T16:19:07.707",
"Id": "12587",
"Score": "3",
"Tags": [
"python"
],
"Title": "Speeding up an algorithm for finding the number of distinct lines"
}
|
12587
|
<p>I am writing my first Android application and have mainly been using code examples online. However, I have been going hard at it for a while now and realize that I have some overlapping methods and such in my code.</p>
<p>I have three classes:</p>
<ol>
<li><code>AndroidBluetooth</code> (main activity)</li>
<li><code>BluetoothModel</code> (the class that holds all of the Bluetooth information)</li>
<li><code>DeviceList</code> (activity to prompt user for Bluetooth device selection) </li>
</ol>
<p>I still don't really know what I'm doing and don't want to blindly delete things, so if anyone sees any unneeded methods I'd appreciate your opinions.</p>
<p><strong>AndroidBluetooth:</strong></p>
<pre><code>public class AndroidBluetooth extends Activity {
/** Called when the activity is first created. */
private static BluetoothAdapter myBtAdapter;
private static BluetoothDevice myBtDevice;
private ArrayAdapter<String> btArrayAdapter;
private ArrayList<BluetoothDevice> btDevicesFound = new ArrayList<BluetoothDevice>();
private Button btnScanDevice;
private TextView stateBluetooth;
private ListView listDevicesFound;
private InputStream iStream;
private OutputStream oStream;
private BluetoothSocket btSocket;
private String newDeviceAddress;
private BroadcastReceiver mReceiver;
private static BluetoothSerialService mSerialService = null;
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE = 1;
private static TextView mTitle;
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
// Message types sent from the BluetoothReadService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
// Name of the connected device
private String mConnectedDeviceName = null;
/**
* Set to true to add debugging code and logging.
*/
public static final boolean D = true;
/**
* Set to true to log each character received from the remote process to the
* android log, which makes it easier to debug some kinds of problems with
* emulating escape sequences and control codes.
*/
public static final boolean LOG_CHARACTERS_FLAG = D && false;
/**
* Set to true to log unknown escape sequences.
*/
public static final boolean LOG_UNKNOWN_ESCAPE_SEQUENCES = D && false;
private static final String TAG = "ANDROID BLUETOOTH";
private static final int REQUEST_ENABLE_BT = 2;
// Member fields
//private final Handler mHandler;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private int mState;
//private EmulatorView mEmulatorView;
// Constants that indicate the current connection state
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_LISTEN = 1; // now listening for incoming connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
public static final int STATE_CONNECTED = 3; // now connected to a remote device
public int currentState;
public boolean customTitleSupported;
public BluetoothModel btModel;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
currentState = 0;
customTitleSupported = requestWindowFeature( Window.FEATURE_CUSTOM_TITLE );
// Set up window View
setContentView(R.layout.main);
stateBluetooth = new TextView(this);
myBtAdapter = null;
startBluetooth();
CheckBlueToothState();
customTitleBar( getText( R.string.app_name).toString(), stateBluetooth.getText().toString() );
}
public void customTitleBar( String left, String right ) {
if( right.length() > 30 ) right = right.substring( 0, 20 );
if( customTitleSupported ) {
getWindow().setFeatureInt( Window.FEATURE_CUSTOM_TITLE, R.layout.customlayoutbar );
TextView titleTvLeft = (TextView) findViewById( R.id.titleTvLeft );
TextView titleTvRight = (TextView) findViewById( R.id.titleTvRight );
titleTvLeft.setText( left );
titleTvRight.setText( right );
}
}
public boolean onCreateOptionsMenu( Menu menu ) {
MenuInflater inflater = getMenuInflater();
inflater.inflate( R.menu.option_menu, menu );
return true;
}
public boolean onOptionsItemSelected( MenuItem item ) {
switch( item.getItemId() ) {
case R.id.connect:
startActivityForResult( new Intent( this, DeviceList.class ), REQUEST_CONNECT_DEVICE );
return true;
case R.id.preferences:
return true;
default:
return super.onContextItemSelected( item );
}
}
private void CheckBlueToothState() {
if( myBtAdapter == null ) {
stateBluetooth.setText("Bluetooth NOT supported" );
} else {
if( myBtAdapter.isEnabled() ) {
if( myBtAdapter.isDiscovering() ) {
stateBluetooth.setText( "Bluetooth is currently " +
"in device discovery process." );
} else {
stateBluetooth.setText( "Bluetooth is Enabled." );
}
} else {
stateBluetooth.setText( "Bluetooth is NOT enabled" );
Intent enableBtIntent = new Intent( BluetoothAdapter.ACTION_REQUEST_ENABLE );
startActivityForResult( enableBtIntent, REQUEST_ENABLE_BT );
}
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(D) Log.d( TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceList.EXTRA_DEVICE_ADDRESS);
// Get the BLuetoothDevice object
BluetoothDevice device = myBtAdapter.getRemoteDevice(address);
// Attempt to connect to the device
btModel.connect(device);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
CheckBlueToothState();
}
}
//In SDK15 (4.0.3) this method is now public as
//Bluetooth.fetchUuisWithSdp() and BluetoothDevice.getUuids()
public ParcelUuid[] servicesFromDevice(BluetoothDevice device) {
try {
Class cl = Class.forName("android.bluetooth.BluetoothDevice");
Class[] par = {};
Method method = cl.getMethod("getUuids", par);
Object[] args = {};
ParcelUuid[] retval = (ParcelUuid[]) method.invoke(device, args);
return retval;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver() {
public void onReceive( Context context, Intent intent ) {
String action = intent.getAction();
if( BluetoothDevice.ACTION_FOUND.equals( action ) ) {
BluetoothDevice btDevice = intent.getParcelableExtra( BluetoothDevice.EXTRA_DEVICE );
btDevicesFound.add( btDevice );
btArrayAdapter.add( btDevice.getName() + "\n" + btDevice.getAddress() );
btArrayAdapter.notifyDataSetChanged();
}
}
};
public static void startBluetooth(){
try {
myBtAdapter = BluetoothAdapter.getDefaultAdapter();
myBtAdapter.enable();
} catch ( NullPointerException ex ) {
Log.e( "Bluetooth", "Device not available" );
}
}
public static void stopBluetooth() {
myBtAdapter.disable();
}
}
</code></pre>
<p><strong>BluetoothModel:</strong></p>
<pre><code>public class BluetoothModel {
// Debugging
private static final String TAG = "BluetoothModel";
private static final boolean D = true;
// Member fields
private final BluetoothAdapter myAdapter;
private final Handler myHandler;
private Context myContext;
private ConnectThread myConnectThread;
private ConnectedThread myConnectedThread;
private int myState;
// Constants that indicate the current connection state
public static final int STATE_NONE = 0;
public static final int STATE_LISTEN = 1;
public static final int STATE_CONNECTING = 2;
public static final int STATE_CONNECTED = 3;
public BluetoothModel( Context context, Handler handler ) {
myContext = context;
myAdapter = BluetoothAdapter.getDefaultAdapter();
myState = STATE_NONE;
myHandler = handler;
}
/**
* Set the connection state.
*
* @param state
*/
public synchronized void setState( int state ) {
if( D ) Log.d( TAG, "setState() " + myState + " -> " + state );
myState = state;
myHandler.obtainMessage( AndroidBluetooth.MESSAGE_STATE_CHANGE, state, -1 ).sendToTarget();
}
/**
* Get the connection state.
*
* @return
*/
public synchronized int getState() {
return myState;
}
/**
* Indicate that the connection attempt failed and notify the UI Activity.
*
*/
private void connectionFailed() {
setState(STATE_NONE);
// Send a failure message back to the Activity
Message msg = myHandler.obtainMessage(AndroidBluetooth.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(AndroidBluetooth.TOAST, "Unable to connect device");
msg.setData(bundle);
myHandler.sendMessage(msg);
}
/**
* Indicate that the connection was lost and notify the UI Activity.
*
*/
private void connectionLost() {
setState(STATE_NONE);
// Send a failure message back to the Activity
Message msg = myHandler.obtainMessage(AndroidBluetooth.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(AndroidBluetooth.TOAST, "Device connection was lost");
msg.setData(bundle);
myHandler.sendMessage(msg);
}
//private EmulatorView mEmulatorView;
/**
* Start the chat service. Specifically start AcceptThread to begin a
* session in listening (server) mode. Called by the Activity onResume() */
public synchronized void start() {
if (D) Log.d(TAG, "start");
// Cancel any thread attempting to make a connection
if (myConnectThread != null) {
myConnectThread.cancel();
myConnectThread = null;
}
// Cancel any thread currently running a connection
if (myConnectedThread != null) {
myConnectedThread.cancel();
myConnectedThread = null;
}
setState(STATE_NONE);
}
/**
* Start the ConnectThread to initiate a connection to a remote device.
* @param device The BluetoothDevice to connect
*/
public synchronized void connect(BluetoothDevice device) {
if (D) Log.d(TAG, "connect to: " + device);
// Cancel any thread attempting to make a connection
if (myState == STATE_CONNECTING) {
if (myConnectThread != null) {myConnectThread.cancel(); myConnectThread = null;}
}
// Cancel any thread currently running a connection
if (myConnectedThread != null) {myConnectedThread.cancel(); myConnectedThread = null;}
// Start the thread to connect with the given device
myConnectThread = new ConnectThread(device);
myConnectThread.start();
setState(STATE_CONNECTING);
}
/**
* Start the ConnectedThread to begin managing a Bluetooth connection
* @param socket The BluetoothSocket on which the connection was made
* @param device The BluetoothDevice that has been connected
*/
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
if (D) Log.d(TAG, "connected");
// Cancel the thread that completed the connection
if (myConnectThread != null) {
myConnectThread.cancel();
myConnectThread = null;
}
// Cancel any thread currently running a connection
if (myConnectedThread != null) {
myConnectedThread.cancel();
myConnectedThread = null;
}
// Start the thread to manage the connection and perform transmissions
myConnectedThread = new ConnectedThread(socket);
myConnectedThread.start();
// Send the name of the connected device back to the UI Activity
Message msg = myHandler.obtainMessage(AndroidBluetooth.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(AndroidBluetooth.DEVICE_NAME, device.getName());
msg.setData(bundle);
myHandler.sendMessage(msg);
setState(STATE_CONNECTED);
}
/**
* Stop all threads
*/
public synchronized void stop() {
if (D) Log.d(TAG, "stop");
if (myConnectThread != null) {
myConnectThread.cancel();
myConnectThread = null;
}
if (myConnectedThread != null) {
myConnectedThread.cancel();
myConnectedThread = null;
}
setState(STATE_NONE);
}
/**
* Write to the ConnectedThread in an unsynchronized manner
* @param out The bytes to write
* @see ConnectedThread#write(byte[])
*/
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (myState != STATE_CONNECTED) return;
r = myConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
/**
* This thread runs while attempting to make an outgoing connection
* with a device. It runs straight through; the connection either
* succeeds or fails.
*/
public class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
mmDevice = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(SPP_UUID);
} catch (IOException e) {
Log.e(TAG, "create() failed", e);
}
mmSocket = tmp;
}
public void run() {
Log.i(TAG, "BEGIN mConnectThread");
setName("ConnectThread");
// Always cancel discovery because it will slow down a connection
myAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
connectionFailed();
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() socket during connection failure", e2);
}
// Start the service over to restart listening mode
//BluetoothSerialService.this.start();
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothModel.this) {
myConnectThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
/**
* This thread runs during a connection with a remote device.
* It handles all incoming and outgoing transmissions.
*/
public class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "create ConnectedThread");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
//mEmulatorView.write(buffer, bytes);
// Send the obtained bytes to the UI Activity
//mHandler.obtainMessage(BlueTerm.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
String a = buffer.toString();
a = "";
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
/**
* Write to the connected OutStream.
* @param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
//mHandler.obtainMessage(BlueTerm.MESSAGE_WRITE, buffer.length, -1, buffer)
//.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
}
</code></pre>
<p><strong>DeviceList:</strong></p>
<pre><code>public class DeviceList extends Activity {
// Debugging
private static final String TAG = "DeviceListActivity";
private static final boolean D = true;
// Return Intent extra
public static String EXTRA_DEVICE_ADDRESS = "device_address";
// Member fields
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the window
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list);
// Set result CANCELED incase the user backs out
setResult(Activity.RESULT_CANCELED);
// Initialize the button to perform device discovery
Button scanButton = (Button) findViewById(R.id.button_scan);
scanButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
doDiscovery();
v.setVisibility(View.GONE);
}
});
// Initialize array adapters. One for already paired devices and
// one for newly discovered devices
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
// Find and set up the ListView for paired devices
ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);
// Find and set up the ListView for newly discovered devices
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
// Get the local Bluetooth adapter
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
// Get a set of currently paired devices
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices = getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(noDevices);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// Make sure we're not doing discovery anymore
if (mBtAdapter != null) {
mBtAdapter.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
/**
* Start device discover with the BluetoothAdapter
*/
private void doDiscovery() {
if (D) Log.d(TAG, "doDiscovery()");
// Indicate scanning in the title
setProgressBarIndeterminateVisibility(true);
setTitle(R.string.scanning);
// Turn on sub-title for new devices
findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
// If we're already discovering, stop it
if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBtAdapter.startDiscovery();
}
// The on-click listener for all devices in the ListViews
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter.cancelDiscovery();
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
// Set result and finish this Activity
setResult(Activity.RESULT_OK, intent);
finish();
}
};
// The BroadcastReceiver that listens for discovered devices and
// changes the title when discovery is finished
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle(R.string.select_device);
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = getResources().getText(R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
}
</code></pre>
|
[] |
[
{
"body": "<p>Things you can do :\n1) First follow a fixed convention to name your functions. Ex: CheckBlueToothState should be checkBlueToothState (notice small case) in your main activity\n2)BluetoothModel is doing lot of other stuff than just being a model. Things like estabilishing the connections should be moved to a new class probably called BluetoothConnectionManager. SO things like ConnectionManager and all should be moved to this class.</p>\n\n<p>Contract of a class should be precise. Class design is complete only when nothing can be taken out of it, and in BluetoothModel class particularly there are lot of things that can be moved out. Model should not be providing anything above that representing state of an object. Moving code of verifying connection to devices, connecting to devices, disconnetion from devices and else anything related to connection management should be moved to a separate class/module. State of objects should be represented by models and Activity should only be concerned with layout of UI and binding of data coming from utility functions (like ConnectionManager I mentioned) to UI. Activity should be more UI centric.</p>\n\n<p>Once you follow these rules all the redundancy in your code will be removed automatically.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T12:03:05.243",
"Id": "20336",
"Score": "0",
"body": "Thank you. I know what you're saying, but I am just confused about Android. My DeviceList activity is where I want devices to be found, so don't i need the bluetooth connection information there? Or are you saying just have an object of a BluetoothConnectionManager which gets passed around all of my Activitys?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T12:08:02.303",
"Id": "20337",
"Score": "0",
"body": "Also, you say ConnectionManager should be moved to the BluetoothConnectionManager class, but I have no object/class named ConnectionManager. Do you just mean everything that entails the connection? If so, then whats the point of my BluetoothModel class? If I move all of the methods for connection into a new class, the Model class will only have getState and setState methods."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T22:16:53.970",
"Id": "20378",
"Score": "0",
"body": "Sorry I meant ConnectThread and not ConnectionManager. BluetoothConnectionManager should be responsible for doing the connections and mantaining the paired devices list using a model (BluetoothModel here). All your activities should ask the data from BluetoothConnectionManager to show any data on UI. Activity is representation of UI and it should be as loosely coupled as possible from doin/maintaining device connections and all"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T02:45:23.617",
"Id": "12606",
"ParentId": "12590",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12606",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T19:21:32.687",
"Id": "12590",
"Score": "2",
"Tags": [
"java",
"android",
"bluetooth"
],
"Title": "Android Bluetooth device application"
}
|
12590
|
<p>I denotes independent, no dependencies.</p>
<pre><code><?php
/**
*Input - One Dimensional Non-Empty Post Array
*Ouput - Boolean on pass or fail
*/
class IText
{
private $text_array = array();
private $patterns = array(
'domain' => '/:\/\/(www\.)?(.[^\/:]+)/',
'prefix_url' => '/^(http:)|(https:)\/\//',
'url' => '/^.{1,2048}$/',
'tweet' => '/^.{1,40}$/',
'title' => '/^.{1,32}$/',
'name' => '/^.{1,64}$/',
'email' => '/^.{1,64}@.{1,255}$/',
'pass' => '/^.{6,20}$/'
);
public function __construct()
{
if ( count( $_POST ) === 0 )
{
echo "Hack Attempt";
return;
}
else
{
foreach( $_POST as $key => $value )
{
if( !is_scalar( $value ) )
{
echo "Hack Attempt";
return;
}
$this->text_array[ $key ] = htmlentities( $value );
}
}
}
public function get( $key ) // basic getter
{
return $this->text_array[ $key ];
}
public function set( $key, $value ) // basic setter
{
$this->text_array[ $key ] = $value;
}
public function checkPattern( $pattern ) // checks for pattern and returns bool
{
return ( ( boolean )preg_match( $this->patterns[ $pattern ], $this->text_array[ $pattern ] ) );
}
public function checkEmpty() // checks for empty and returns bool
{
return ( !in_array( '', $this->text_array, TRUE ) );
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I've tried to cover as many things I could. A few of my explanations are rather brief, so if you want me to explain or defend anything, let me know. And hopefully it doesn't read too ramble-y :).</p>\n\n<p><strong>IText</strong></p>\n\n<p>IName typically denotes an interface. It's not a naming scheme often used in PHP, but it's used often enough that you should avoid prefixing an I onto a class that isn't an interface. This is confusing. In fact, when I first saw the name, I was expecting an interface.</p>\n\n<p>As a developer consuming the class, it really is not all that important if it's \"independent\" since most IDEs will show the constructor signature. Interface vs abstract vs concrete tends to matter, but I do not feel that independent necessitates its own naming scheme.</p>\n\n<p><strong>mixed concerns</strong></p>\n\n<p>I'm not sure if I understand what your class is doing. Based on the name, it looks like you're trying to model a string. BUt what it's actually doing is sort-of processing POST.</p>\n\n<p>Instead of doing this, I would create validators that are separate from the model of a string (or the model of any data type really). Also, why hold an array of values inside of the object? Is the object meant to be some kind of repository or something?</p>\n\n<p>Once you get a lot of validations, or once you get a few very complicated ones, this class will grow to be unmanagable.</p>\n\n<p>Personally, I like the model of <a href=\"http://framework.zend.com/manual/en/zend.validate.html\" rel=\"nofollow\">Zend_Validate</a>. It completely separates the concept of data and the validation of data. In your class, storage, validation and manipulation have all been (needlessly) coupled. (Obviously storage and validation go together when storing things long term, but in this context, I mean storing as in storing in PHP-land.)</p>\n\n<p>A perfect example of your validation and storage coupling is your checkPattern method. What if you want to validate something as a URL, but it's not stored in <code>$_POST['url']</code>? What if you want to check <code>$_POST['website']</code>? Or what if you have an arbitrary <code>$url</code> that you want to check? Your code now does not facilitate that. It is directly tied to the expectation that the validation and the data will be stored with the same keys.</p>\n\n<p><strong>htmlentities</strong></p>\n\n<p>Your values are not being used in the context of HTML, so they should not be treated as HTML. Only treat HTML as HTML. In other words, don't escape data until it actually needs to be escaped. Your validations are going to be confused when they see <code>a &#38; b</code> instead of <code>a & b</code> (or any other substitutions htmlentities may make).</p>\n\n<p><strong>$_POST</strong></p>\n\n<p>A lot of the comments in the \"mixed concerns\" section, you're probably thinking \"but it's only meant to manipulate post?\"</p>\n\n<p>Well, what if at some point in the future, you have an arbitrary array you want to handle? There's no need to couple your code to $_POST. Instead, pass the array in to the constructor. (Well, in all honesty, I think your design is flawed, but if you do stick with it, pass the array in.) What if at some point in the future you have a JSON based API and you want to validate that? How would you do that with your current code?</p>\n\n<p><strong>technicalities</strong></p>\n\n<p>If nothing is posted (count($_POST) === 0), then text_array is going to be NULL. This will mean that every array access will issue a notice. You should initialize the member to an array either in the declaration or in the constructor. I would do it in the declaration:</p>\n\n<pre><code>private $text_array = array();\n</code></pre>\n\n<hr>\n\n<p>Also, you're assuming $_POST is one dimensional. If someone posts a form like:</p>\n\n<pre><code><input type=\"text\" name=\"test[]\" value=\"array\">\n</code></pre>\n\n<p>Then $_POST will look like:</p>\n\n<pre><code>array('test' => array('array'))\n</code></pre>\n\n<p>This means that you'll end up passing an array to htmlentities. In other words, don't assume that POST values are strings. (Though they are always either a string or an array.)</p>\n\n<hr>\n\n<p>in addPrefix, you've used textArray instead of text_array</p>\n\n<p><strong>Constants</strong></p>\n\n<p>Instead of using names of the validations, use class constants instead. This will mean that calling code doens't need to know the array keys, and that they can be changed if needed/wanted. It will also tend towards cleaner looking and more maintainable code since typos will be errors instead of falling through the cracks.</p>\n\n<p>For example:</p>\n\n<pre><code>const DOMAIN = \"domain\";\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>$text->checkPattern(IText::DOMAIN);\n</code></pre>\n\n<p><strong>Be paranoid</strong></p>\n\n<p>Never assume anything in code. In particular, don't assume that a variable will be the type that you expect or that an array key will exist.</p>\n\n<p>Note that these both basically only apply to user data since if you create the data, you can know with certainty what it is.</p>\n\n<p>Consider your checkPattern method:</p>\n\n<pre><code>public function checkPattern( $pattern ) // pattern checker returns bool\n {\n return ( preg_match( $this->patterns[ $pattern ], $this->text_array[ $pattern ] ) ); \n }\n</code></pre>\n\n<p>What if an invalid pattern name is provided? Then suddenly you have at least 3 notices (two that the array key does not exist, and one that preg_match received an empty pattern).</p>\n\n<p>You should be safe guarding things like this:</p>\n\n<pre><code>public function checkPattern($pattern)\n{\n if (!array_key_exists($pattern, $this->patterns)) {\n //Pattern doesn't exist\n throw new Exception(\"Invalid pattern provided: \" . $pattern);\n }\n if (!array_key_exists($pattern, $this->text_array[$pattern])) {\n //data doesn't exist\n return false;\n } else if (!is_scalar($this->text_array[$pattern])) {\n //If this were checked on construction, this would not be necessary\n throw new Exception(\"The data stored for {$pattern} is not a scalar, but it's being treated as such\");\n }\n return (bool) ( preg_match( $this->patterns[ $pattern ], $this->text_array[ $pattern ] ) ); \n}\n</code></pre>\n\n<p>Also, while I'm at it, your comment is a lie. preg_match returns an int, not a bool. A wrong comment is significantly worse than no comment.</p>\n\n<p><strong>Final suggestions</strong></p>\n\n<p>I would consider decoupling your data and validations. What you could do is create a \"Form\" that encapsulates all of this. Basically your form would have elements and each element would have validations. The form would then be capable of taking in an arbitrary array and telling you if it's valid per the specification of the form.</p>\n\n<p>If you want a few ideas on this, you could look at <a href=\"http://framework.zend.com/manual/en/zend.form.html\" rel=\"nofollow\">Zend_Form</a>. It has a lot of limitations, and the rendering side of it can be a bit hard to get along with, but overall, it's a fairly decent modeling of a form. Zend_Form is likely not the best, just Zend Framework happens to be what I'm familiar with.</p>\n\n<p><strong>Edit: URL handling</strong></p>\n\n<p>Just noticed that you've used a regex to extract out the domain from a url. Instead of doing that, you might want to use <a href=\"http://php.net/parse_url\" rel=\"nofollow\">parse_url</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T00:46:41.757",
"Id": "20327",
"Score": "0",
"body": "@Corbin, just to say that your review was an inspiration! Tks, I mean it! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T01:42:45.397",
"Id": "20356",
"Score": "0",
"body": "@stack.user.0 The idea isn't to resemble Zend. That wasn't meant to be a \"why doesn't your code look like ZF's?\" Was meant more as \"if you want some examples to look at....\" Anyway, you shouldn't worry about number of files or file sizes. Instead, you should focus on maintainable, extendable code. (Not extendable as in inheritance, but rather ability to continue to use in the future.) A lot of files will slow down execution since it requires a lot of disk IO, however, there are various ways around it (opcode caches for example), and worrying about that is very rarely necessary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T01:44:00.417",
"Id": "20357",
"Score": "0",
"body": "And yes, $_POST can be empty in the sense of count($_POST) === 0. If that's the case, the foreach loop will never run, leaving the object's member NULL. (Also, on a technical note, $_POST can actually be disabled as odd as it is.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T01:46:12.863",
"Id": "20359",
"Score": "0",
"body": "Making a note that it should be one dimensional is not sufficient. You should code defensively. That is, either handle multidimensional arrays, or put code in place to trigger errors if an array is not single dimensional. If you alter the code to accept a generic array, then the note would be understandable, however, that then just moves the responsibility out of the class (and thus it should still be checked really). You can't control whether $_POST is single or multi-dimensional, so the note doesn't make sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T01:46:46.013",
"Id": "20360",
"Score": "0",
"body": "\"I cast to an int but did not change my comment\" There's no need to cast when it already returns an int. Perhaps I misunderstood that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T01:53:11.513",
"Id": "20361",
"Score": "0",
"body": "\"I need to settle on returning bools or ints\" It's not the same thing. An int has 2^32 possibilities whereas a bool has two possibilities. Usually it's apparent which one makes sense. My rule of thumb is to use a bool when I can, and use an int if I absolutely have to. It would depend on the situation, but if this decision is being made extremely often, it may be a sign that exceptions are not being used properly. (I hate to state that as an absolute though -- overusing exceptions is worse than not using them at all.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T05:18:16.780",
"Id": "20394",
"Score": "0",
"body": "It's not about building a library; it's about creating high quality code. There seems to be a conflict here between pragmatism and my obsession with code design. There is obviously a time when getting the job done is more important than getting the job done perfectly. This is codereview though. I'm not trying to say that your code should look exactly like ZF, or that anything is particularly *wrong* with your code. I just am trying to explain that there are certain tenets of OOP that are time proven to create more maintainable, more re-usable code, and your code ignores a few of those."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T05:21:51.923",
"Id": "20396",
"Score": "0",
"body": "@stack.user.0 That's exactly why you would never pass a PDOStatement to json_encode. Using the same logic, you should never pass a mutlidimensional array to your class because it will cause nasty errors. Defensive coding shouldn't be an afterthought; it should be a necessity. `I have client side checks to verify non-emptiness. And it can not be multi-dimensional...because I never set it that way` A few things: Client side checks are worthless for actual validation. They're used to provide better experience to the user, not to actually 'validate' anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T05:23:32.513",
"Id": "20397",
"Score": "0",
"body": "And second: `because I never set it that way` **You do not control $_POST** I can post whatever I want to your site. Same goes with GET. In fact, sometimes just for kicks, I check how sites will react to things like `index.php?page[]=`. That will make `$_GET['page']` an array, and unless that's checked for, *at least* one notice will be issued."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T20:44:41.613",
"Id": "20436",
"Score": "0",
"body": "Updates: 1 Removed URL/Domain Processing to related class. 2. Returned Bool in both cases for consistency 3. Added in Defensive code for User Data (POSTED data)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T20:45:24.700",
"Id": "20438",
"Score": "0",
"body": "I realy don't like the defensive code...looks like paranoia..and adds all this nesting in my code...don't know why someone would hack my post instead of just use my JavaScript required front-end (client)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T22:51:43.073",
"Id": "20444",
"Score": "0",
"body": "@stack.user.0 Paranoid type checking is just one of the factors of a loosely typed language. And they would do it because they're evil. All of them. Seriously. Ok, maybe not seriously. But, you will have that .1% of malicious users that you have to watch out for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T22:53:04.447",
"Id": "20445",
"Score": "0",
"body": "And it doesn't have to add nesting. It can usually be handled quite seamlessly. Also, you should be throwing exceptions instead of echoing. Echoing tells the user that something went wrong, but it tells your code nothing. (Also, once again, consider passing in POST and consider doing htmlentities only when you're outputting HTML.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T14:49:09.880",
"Id": "20501",
"Score": "0",
"body": "in my code base echoing like this is caught by a handler which writes it to console.log...I've read the whole chapter on try/catch/throw (via B Stroustrup ) and all its glory...but I don't need it yet...app is too small"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T17:08:57.340",
"Id": "20528",
"Score": "0",
"body": "@stack.user.0 I suppose whatever works, works, but don't forget that exceptions interrupt execution and echoing does not. In other words, unless you're careful, you may end up using an invalid instance of the class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T17:53:19.770",
"Id": "20542",
"Score": "0",
"body": "If I had the time I would store the attack vector (IP address...etc ), block the user and raise a flag...but I'll do that when I have time. Security can be and endless pursuit...as I'm sure there is always someone that can hack a site no matter how vigilant you are."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T18:23:41.873",
"Id": "20554",
"Score": "0",
"body": "Yes, security can be an endless pursuit, but echoing out an error and then doing nothing about it is equivalent to finding an intruder in your house, saying something to him and then going back to sleep. Exceptions interrupt execution and you are forced to deal with them. (I'm not saying you need to handle absolutely everything -- in fact, you would be fine just ignoring an array entries of $_POST. I'm trying to show that echoing a random error and then letting execution continue only alerts the user that there was an error, not your code.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T18:57:06.500",
"Id": "20562",
"Score": "0",
"body": "working on .js MVC here...http://codereview.stackexchange.com/questions/12695/mvc-control-module-architecture-design-structure-review"
}
],
"meta_data": {
"CommentCount": "18",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T21:01:07.413",
"Id": "12595",
"ParentId": "12592",
"Score": "2"
}
},
{
"body": "<blockquote>\n <p>\"Also, while I'm at it, your comment is a lie. preg_match returns an\n int, not a bool. A wrong comment is significantly worse than no\n comment.\" - Corbin</p>\n</blockquote>\n\n<p>Beat me to it. Also, nice review. Looks like I've got another competitor :) Agree 100% with what Corbin has said.</p>\n\n<p>Only one thing to add. <code>addPrefix()</code> is named <em>odd</em>. I would consider <code>getUrl</code> instead. You are not really prefixing anything, you are retrieving something. As a script running this, I won't know what you do to it within the method, I only know what I get back, and that's a URL.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T21:58:34.300",
"Id": "20307",
"Score": "0",
"body": "If only there were a lot more competitors on CR :p. It's always so slow on CR. Anyway, `addPrefix` does not return anything. Though there is a major problem with it... If it's called more than once then it will be appended more than once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T22:19:48.890",
"Id": "20309",
"Score": "0",
"body": "Point taken, probably would be better if it just returned it :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T21:38:32.233",
"Id": "12598",
"ParentId": "12592",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "12595",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T20:08:52.943",
"Id": "12592",
"Score": "0",
"Tags": [
"php"
],
"Title": "class IText - Validates text from Ajax POST | Add consistent return type, defensive coding, functional focus"
}
|
12592
|
<p>I had a task for a programmer position which I failed. I am a newbie programmer and I accept that. The only problem is that employer never told me what the actual problem with the code is. So maybe community will be able to give few hints on how to improve it.</p>
<p>The task was to write code which would parse a given webpage, fetch all the images and save it to given directory. Webpage address and directory are command line parameters. Performance was a critical issue for this task.</p>
<pre><code>require 'open-uri'
require 'nokogiri'
class Grab
def runner(url, path)
threads = []
doc = Nokogiri::HTML(open("http://#{url}"))
img_srcs = doc.css('img').map{ |i| i['src'] }.uniq
img_srcs = rel_to_abs(url, img_srcs)
img_srcs.each do |img_src|
threads << Thread.new(img_src) do
name = img_src.match(/^http:\/\/.*\/(.*)$/)[1]
image = fetch img_src
save(image, name, path)
end
end
threads.each{ |thread| thread.join }
end
def fetch(img_src)
puts "Fetching #{img_src}\n"
image = open(img_src)
end
def save(image, name, path)
File.open("#{path}/#{name}", "wb"){ |file| file.write(image.read) }
end
def rel_to_abs(url, img_srcs)
img_srcs.each_with_index do |img_src, index|
img_srcs[index] = "http://#{url}/#{img_src}" unless img_src.match(/http:\/\//)
end
img_srcs
end
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T20:22:35.240",
"Id": "20799",
"Score": "9",
"body": "Most \"newbie programmers\" wouldn't be able to write the code that you did. You probably don't want to work for these people anyway! (Unless the job was something other than entry-level...)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-30T18:10:23.320",
"Id": "79892",
"Score": "0",
"body": "Did the interviewer ask you to write code to accomplish the task, or simply get the task done? You could, for example, [use wget](http://stackoverflow.com/a/20116215/1157100) to get it done with one line of shell code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-07T20:19:16.560",
"Id": "215599",
"Score": "0",
"body": "This is awesome, tell those people to shove it."
}
] |
[
{
"body": "<p>I'm not familiar with Ruby, just a hint: If I'm right the code creates one thread for every <code>img</code> tag which could be too much. For example, the source of yahoo.com contains more than one hundred <code>img</code> tags which means 100+ threads and 100+ connections to the same host. You should use a thread pool with a queue which limits the number of parallel threads and parallel connections. </p>\n\n<p>Furthermore, you should use <a href=\"http://en.wikipedia.org/wiki/HTTP_persistent_connection\">keep-alive connections</a> to download more than one image with one TCP connection. (I don't know whether Ruby supports it or not nor that the code above uses it or not.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-17T13:52:52.623",
"Id": "28093",
"Score": "0",
"body": "Just a quick note : the Ruby interpreter (at least the reference implementation) does not use system threads but so called \"green threads\". I think it's not really an issue to create a hundred threads. Your point holds for the http requests, though."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T21:28:35.883",
"Id": "12597",
"ParentId": "12593",
"Score": "10"
}
},
{
"body": "<p>Few minor issues:</p>\n\n<ol>\n<li><p>It will be cool if you support URL parameter with protocol (HTTP/HTTPS):</p>\n\n<pre><code>doc = Nokogiri::HTML(open(\"http://#{url}\"))\n</code></pre></li>\n<li><p>For URL manipulations you can use standard tools - URI::HTTP/URI:HTTPS instead regexps:</p>\n\n<pre><code>name = img_src.match(/^http:\\/\\/.*\\/(.*)$/)\nimg_srcs[index] = \"http://#{url}/#{img_src}\" unless img_src.match(/http:\\/\\//)\n</code></pre></li>\n<li><p>This is a little unsecure operation, you should escape name:</p>\n\n<pre><code>File.open(\"#{path}/#{name}\", \"wb\")\n</code></pre></li>\n<li><p>You ignore links with HTTPS protocol:</p>\n\n<pre><code>img_src.match(/http:\\/\\//)\n</code></pre></li>\n<li><p>This is not the Ruby way:</p>\n\n<pre><code>img_srcs.each_with_index do |img_src, index|\n img_srcs[index] = \"http://#{url}/#{img_src}\" unless img_src.match(/http:\\/\\//)\nend\nimg_srcs\n</code></pre>\n\n<p>A little simpler</p>\n\n<pre><code>img_srcs.map do |src|\n src.match(/http:\\/\\//) ? \"http://#{url}/#{src}\" : src\nend\n</code></pre></li>\n<li><p>You load page uneffiсiently:</p>\n\n<pre><code>image = open(img_src)\n</code></pre>\n\n<p>So for every image temp file created. This may not be an efficient way.</p>\n\n<pre><code>open(\"http://stackoverflow.com/questions/1878891/how-to-load-a-web-page-and-search-for-a-word-in-ruby\").class\n=> Tempfile\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T15:20:53.313",
"Id": "68717",
"Score": "0",
"body": "I wouldn't call point 3 a minor security issue. It's an arbitrary file overwrite condition."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T21:44:13.770",
"Id": "12599",
"ParentId": "12593",
"Score": "12"
}
},
{
"body": "<p>I am not a ruby-developer either, but here are a few questions I have after reading your code,</p>\n\n<pre><code>require 'open-uri'\nrequire 'nokogiri'\n\nclass Grab\n def runner(url, path)\n threads = []\n doc = Nokogiri::HTML(open(\"http://#{url}\"))\n</code></pre>\n\n<p>I assume you are getting an array here</p>\n\n<pre><code> img_srcs = doc.css('img').map{ |i| i['src'] }.uniq\n</code></pre>\n\n<p>The rel_to_abs method is odd. I think what you really need is a map .(explained why in that method)</p>\n\n<pre><code> img_srcs = rel_to_abs(url, img_srcs)\n</code></pre>\n\n<p>Why did you choose to do the rel_to_abs outside, but extraction of name inside?</p>\n\n<pre><code> img_srcs.each do |img_src|\n threads << Thread.new(img_src) do\n</code></pre>\n\n<p>What happens when the name extraction fails?\nAlso you assume that the name extracted is a valid file name. Is that always the case? (What happens if it is a query?) And I much rather prefer a smaller match like <code>.*\\/([^\\/]+)$</code></p>\n\n<pre><code> name = img_src.match(/^http:\\/\\/.*\\/(.*)$/)[1]\n</code></pre>\n\n<p>Your fetch implementation feels like it is partly done. I would prefer fetch to either read the image or move the opening of uri completely to save. Right now, the resource (an open connection) is acquired in one method, and used in another, while you could have done both in one go, and avoided that. (I suppose there is nothing wrong in that, but it just feels wrong.)</p>\n\n<pre><code> image = fetch img_src\n save(image, name, path)\n</code></pre>\n\n<p>If it were upto me, I would move the entire name processing and saving into a <code>save_to_disk(url,image-src,path)</code> and do the entire processing there. It would also have the advantage of not having to change a relative <code>mypath</code> to <code>http://domain/myapth</code> format, and then again extracting the <code>mypath</code>.</p>\n\n<pre><code> end\n end\n threads.each{ |thread| thread.join }\n end\n\n def fetch(img_src)\n puts \"Fetching #{img_src}\\n\"\n</code></pre>\n\n<p>Here, I would much rather see <code>open(src).read</code> so that the open connection is not exposed outside.</p>\n\n<pre><code> image = open(img_src)\n end\n\n def save(image, name, path)\n File.open(\"#{path}/#{name}\", \"wb\"){ |file| file.write(image.read) }\n end\n</code></pre>\n\n<p>This particular method feels rather odd. All you need is a map that checks if img_src matches http:// and if not, returns an updated version. Here you are mutating a data structure within a foreach loop (it works I agree) while you have no reason to do that.</p>\n\n<pre><code> def rel_to_abs(url, img_srcs)\n img_srcs.map do |img_src|\n case img_src\n when /http:\\/\\// then img_src\n else \"http://#{url}/#{img_src}\" \n end\n end\n end\nend\n</code></pre>\n\n<p>And any reason you preferred to do the invocation in Grab.runner rather than Grab.initialize? with the later, you have to do <code>(Grab.new).runner(url,path)</code> instead of <code>Grab.new(url,path)</code></p>\n\n<p>But these are all minor. I wouldn't reject some one based on these. So I don't know.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T22:00:49.807",
"Id": "12600",
"ParentId": "12593",
"Score": "4"
}
},
{
"body": "<p>IMO it's just rude that you took the time to write a code and got no feedback at all. Your code is not bad, but there's always room for improvement, hints:</p>\n\n<ol>\n<li>make it more functional, </li>\n<li>use specific libraries for the task, </li>\n<li>return something useful for the main method (the saved file paths?), </li>\n<li>use module URI to work with urls.</li>\n</ol>\n\n<p>Anyway, given enough time and access to documentation, that's what I would have written:</p>\n\n<pre><code>require 'nokogiri'\nrequire 'typhoeus'\n\nclass Spider\n def self.download_images(url, destination_path, options = {})\n base_url = URI.join(url, \"/\").to_s\n body = Typhoeus::Request.get(url).body\n imgs = Nokogiri::HTML(body).css(\"img\")\n image_srcs = imgs.map { |img| img[\"src\"] }.compact.uniq\n\n hydra = Typhoeus::Hydra.new(:max_concurrency => options[:max_concurrency] || 50)\n image_paths = image_srcs.map do |image_src|\n image_url = URI.join(base_url, image_src).to_s\n path = File.join(destination_path, File.basename(image_url))\n request = Typhoeus::Request.new(image_url)\n request.on_complete { |response| File.write(path, response.body) }\n hydra.queue(request)\n path\n end\n hydra.run\n image_paths\n end\nend\n</code></pre>\n\n<p>Note: Images with the same file name will be overwritten, it has not been considered for simplicity. You'd just use <code>group_by</code> to add \"-n\" suffixes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T18:35:59.883",
"Id": "12639",
"ParentId": "12593",
"Score": "12"
}
},
{
"body": "<p>Bit rude of them to leave you hanging.</p>\n\n<p>Anyway, my 2c would be that the code is actually quite alright, but I'd argue, it's a basic web crawler and they've outlined that performance is a key goal, so half of the problem to solve would be to improve cache performance, i.e. to detect cache hits between runs (also to reduce effort of resuming from a crashed run.. in the event of a crash). This could be as simple as organising downloads correctly and checking for the existence of files (although you would need to be wary of only doing atomic writes for that to work). </p>\n\n<p>Overall, could be a plethora of reasons to not hire, it's not always the code, so don't take it too hard.</p>\n\n<p>Either way, if you are mainly concerned with feedback on the code, the main issues that flag for me are:</p>\n\n<h2>No error handling</h2>\n\n<p>I'd wager, if you failed based on code and not on solution flaws, it would probably be based on lack of error handling, or as below, maybe providing a comment about how x,y,z could fail. In this situation, you're dealing with threading, network and file IO, each of which is potential dynamite and should be well error handled if it's to be performant. (E.g. if a thread throws an exception, you could lose of all your work and have to start the crawl from the beginning again :( ) Ofcourse depending on the interview process, you may have been quizzed on such things, so it could be irrelevant.</p>\n\n<h2>Lack of any commenting</h2>\n\n<p>Depending on how harsh you think they were judging you & the time constrains of the code (in interview vs do it and send), they may have expected you to provide commentary in your code. It's probably not the biggest issue in interviews though from what I've seen.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-22T02:12:53.230",
"Id": "78435",
"Score": "0",
"body": "I've worked at places that considered comments code smell. It was really painful to get comments laser code review so I stopped writing them. Unfortunately, this habit stuck :("
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-17T07:18:34.207",
"Id": "17633",
"ParentId": "12593",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "12599",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T20:42:27.023",
"Id": "12593",
"Score": "22",
"Tags": [
"beginner",
"ruby",
"parsing",
"interview-questions"
],
"Title": "Parse webpage and save fetched images to a directory"
}
|
12593
|
<p>I have some code here that changes the font size depending on what link you clicked and it works perfectly, I now want to add another feature but need some help. I want to add current font size which changes as you press bigger or smaller.</p>
<p>jQuery:</p>
<pre><code>$(document).ready(function() {
function change_size(element, size) {
var current = parseInt(element.css('font-size'));
if (size == 'smaller') {
var new_size = current - 4;
} else if (size == 'bigger') {
var new_size = current + 4;
}
element.css('font-size', new_size + 'px');
}
$('#smaller').click(function() {
change_size($('p'), 'smaller');
});
$('#bigger').click(function() {
change_size($('p'), 'bigger');
});
});
</code></pre>
<p>HTML:</p>
<pre><code><body>
Font size: <a href="#" id="smaller">Smaller</a> | <a href="#" id="bigger">Bigger</a> Current Font Size:<span class="current_size"></span>
<p>This is some text</p>
<p>This is some more text</p>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="external.js"></script>
</body>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T22:35:36.827",
"Id": "20312",
"Score": "0",
"body": "I'm a bit confused on what the post is saying. Is the problem that it doesn't work? Or that you're looking for suggestions on how to improve the code? The code looks like it should work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T22:43:50.783",
"Id": "20313",
"Score": "0",
"body": "Sorry I didn't explain it well, the code works perfectly.. I just want to add another feature to it. I want to have a current font size div that shows the current size as you change it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T22:49:15.033",
"Id": "20314",
"Score": "0",
"body": "Ah ok! Rereading it, I can see that now. Guess I was somehow missing that :). Just add code that pulls the size, then use that to put it in a div. You can then do that on document ready and whenever you change the size."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T01:55:07.367",
"Id": "20328",
"Score": "0",
"body": "All you need to do to add the size is set it right after setting the element size."
}
] |
[
{
"body": "<p>I felt that this code would be good as a jQuery plugin, so I went ahead and altered your code until I was satisfied. I left in some comments that are applicable to your code, but I would encourage someone else (and may do it myself still, I don't know yet) to give an actual review.</p>\n\n<pre><code>(function ($, console) {\n 'use strict';\n\n var defaultOptions = {\n //markup is what will be used to create the font sizer widget; you can do this a million better ways, but I felt this was easy to understand.\n //I'd consider enhancing it to take a jQuery object or a function that returns a string or a jQuery object, but all of that would make this more complex.\n //At the very least, this way makes for progressive enhancement as opposed to breakage when JS is disabled.\n markup: 'Font size: <a href=\"#smaller\" data-make=\"smaller\">Smaller</a> | <a href=\"#bigger\" data-make=\"bigger\">Bigger</a> Current Font Size:<span data-id=\"current_size\"></span>',\n markupClickFilter: 'a', //if you change the markup of this widget to something where you use elements other than A tags for buttons, you may wish to change this\n affects: null, //required: this is a jQuery object representing the elements that this widget affects\n size: null, //override for initial size of affected elements\n increment: 4\n };\n $.fn.fontSizer = function (options) {\n //initialize / preconditions\n var opts = $.extend({}, defaultOptions, options),\n $currentSize, //$ for element in markup if it exists\n sizeChange = function () {}; //noop to avoid null check when using this, meh...\n if (!opts.affects || !opts.affects.length) {\n //should always UI test in a modern browser that provides console\n console.error('failed to initialize fontSizer: must provide affects property');\n return this; //jQuery plugins are expected to follow this convention\n }\n\n //widget setup\n this.html(opts.markup); //again, this setup functionality could be done better in many ways\n $currentSize = this.find('[data-id=current_size]'); //for example to not use magic strings like this\n if ($currentSize.length) {\n sizeChange = function () { //this could also be a trigger\n $currentSize.html(opts.affects.css('font-size'));\n };\n }\n\n //set initial size and update $currentSize\n if (opts.size !== null) {\n opts.affects.css({\n 'font-size': opts.size\n });\n }\n sizeChange();\n\n return this.on('click', opts.markupClickFilter, function (e) {\n var size = parseFloat(opts.affects.css('font-size')), //parseFloat is more correct than parseInt\n make = $(this).data('make'),\n fixed = parseFloat(make); //minor enhancement: allow fixed sizing\n\n if (make === 'smaller') { //preference: always use ===\n size -= opts.increment; //a new variable was unnecessary, if you feel you must, you should at least declare it at the top of the function\n } else if (make === 'bigger') {\n size += opts.increment;\n } else if (fixed !== 0) {\n size = make; //using make instead of fixed here allows things like make === '1.5em'\n }\n\n //update size (and set $currentSize)\n opts.affects.css({\n 'font-size': size\n });\n sizeChange();\n\n //this prevents the annoying hashchange and extra history step that isn't doing anything useful\n e.preventDefault();\n });\n };\n}(jQuery, console || {error: function () {}}));\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>(function ($) {\n 'use strict';\n $(function () {\n $('#sizer').fontSizer({\n affects: $('p.basic')\n });\n $('#sizer2').fontSizer({\n affects: $('p.custom'),\n markup: 'Font size: <a href=\"#small\" data-make=\"12px\">Small</a> | <a href=\"#lg\" data-make=\"24px\">Large</a> | <a href=\"#xl\" data-make=\"36px\">XL</a> Current Font Size:<span data-id=\"current_size\"></span>'\n });\n });\n}(jQuery));\n</code></pre>\n\n<p>Html for usage example:</p>\n\n<pre><code><div id=\"sizer\">Enable Javascript for a font resizer</div>\n\n<p class='basic'>some text</p>\n<p class='basic'>some text</p>\n<p class='basic'>some text</p>\n\n<div id=\"sizer2\">Enable Javascript for a font resizer</div>\n\n<p class='custom'>some text</p>\n<p class='custom'>some text</p>\n<p class='custom'>some text</p>\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/yPHny/1/\" rel=\"nofollow\">JsFiddle</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T01:53:06.277",
"Id": "12604",
"ParentId": "12601",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12604",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-14T22:21:58.360",
"Id": "12601",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "jQuery Font Switcher"
}
|
12601
|
<p>So I am using the following</p>
<pre><code><?php
function LuhnCalc($number) {
$chars = array_reverse(str_split($number, 1));
$odd = array_intersect_key($chars, array_fill_keys(range(1, count($chars), 2), null));
$even = array_intersect_key($chars, array_fill_keys(range(0, count($chars), 2), null));
$even = array_map(function($n) { return ($n >= 5)?2 * $n - 9:2 * $n; }, $even);
$total = array_sum($odd) + array_sum($even);
return ((floor($total / 10) + 1) * 10 - $total) % 10;
}
print LuhnCalc($_GET['num']);
?>
</code></pre>
<p>however it seems that BPAY which is version 5 of MOD 10 which for the record I cant find what the documentation for. seems to not be the same as MOD10</p>
<p>the following numbers where tested 2005,1597,3651,0584,9675</p>
<pre><code>bPAY
2005 = 20052
1597 = 15976
3651 = 36514
0584 = 05840
9675 = 96752
</code></pre>
<p>MY CODE </p>
<pre><code>2005 = 20057
1597 = 15974
3651 = 36517
0584 = 05843
9675 = 96752
</code></pre>
<p>as you can see none, of them match the BPAY numbers</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T07:01:11.257",
"Id": "20399",
"Score": "2",
"body": "This may get better traction on StackOverflow where there's a much larger user base. (And this is off topic for CR as CR questions are expected to contain code that currently works.)"
}
] |
[
{
"body": "<p>First off, welcome to CodeReview, where your questions may take a while to get answered. Hang in there, we'll get to them. I had to look this up because I've never heard of it before, but my math isn't half bad, so I'm confident in my answer.</p>\n\n<p>Your check numbers are mostly fine. I'd be more concerned about those your checking against. By mostly, I mean that the return value for the last is zero not two. That last number is probably just a typo on your part because you clarify that none of your numbers matches those that you're comparing them to, yet that last one does. Also, for completeness I'd like to mention that if you do not pass these numbers as strings to your function you could get undesired results. I found that out the hard way with your third number. I was getting range out of bounds errors because <code>str_split()</code> only returned an array with one value. This is because, for some reason, the leading zero deleted all but the five when passed to the function. Odd that, I'll have to look further into it. Anyways, make sure the numbers you pass to your function are strings to avoid this error.</p>\n\n<p><strong>Now, I do have some suggestions to make.</strong></p>\n\n<p>The luhn algorithm states that a zero prepended to the beginning of an odd lengthed string will allow you to process it without corrupting the data. Not that this matters in this instance, you are only processing four digit numbers. Either way, that array reversal is unnecessary. Should you start needing to process multi-length integers, then you can just prepend the zero.</p>\n\n<p>This is so much more convoluted than it needs to be... You don't need two separate arrays, you can do this with one and a loop. Which also removes the need for array_map.</p>\n\n<pre><code>$length = count( $chars );\nfor( $i = 0; $i < $length; $i++ ) {\n if( $i % 2 ) {\n $value = $chars[ $i ] * 2;\n $chars[ $i ] = $value >= 10 ? $value - 9 : $value;\n }\n}\n</code></pre>\n\n<p>If you are trying to avoid loops and if statements, don't. I find the above much easier to read than your run-on PHP functions. Even if it does save processing time, not sure if it does, I don't think it'd be worth it.</p>\n\n<p>Your formula is also more convulted than it needs to be. I've not seen the one you're currently using before. Not that that's saying much, I did just say I've only recently looked it up. But there are two simpler ones. The first, is easier for us to do in our head than program so I wont describe it here, look it up on wikipedia. But the second is easy enough to program and goes like this: perform the above loop. I'm assuming you know what it does so I won't explain it here. Sum up all array values. Multiply that by 9. And your answer is the modulo of 10. So <code>$total * 9 % 10</code>. Much easier than <code>( floor( $total / 10 ) + 1 ) * 10 - $total ) % 10</code>. You can even do that one in your head if pressed.</p>\n\n<p>Hope this helps!</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>Here's my suggestions in code.</p>\n\n<pre><code>function LuhnCalc( $number ) {\n $chars = str_split( $number );\n $length = count( $chars );\n if( $length % 2 ) {\n $chars = '0' . $chars;//should work, not tested\n //$chars = array_reverse( $chars );\n }\n for( $i = 0; $i < $length; $i++ ) {\n if( $i % 2 ) {\n $value = $chars[ $i ] * 2;\n $chars[ $i ] = $value >= 10 ? $value - 9 : $value;\n }\n }\n $total = array_sum( $chars );\n return $total * 9 % 10;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T06:10:33.957",
"Id": "20398",
"Score": "0",
"body": "Sorry I tried what you said, and I could not get it working, Could you do a sample script please."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T13:10:09.600",
"Id": "20475",
"Score": "0",
"body": "I've created it using the suggestions I mentioned and added it to the edit section on the bottom of my answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T21:56:15.333",
"Id": "12627",
"ParentId": "12605",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T02:13:12.170",
"Id": "12605",
"Score": "2",
"Tags": [
"php"
],
"Title": "Luhn - bPAY mod10v5"
}
|
12605
|
<p>I want to realize caching in WCF web service. I'm using the following code:</p>
<pre><code>public interface ICache<T> : IDisposable where T : class
{
string Name { get; }
CacheItemPolicy CacheItemPolicy { get; set; }
long Count { get; }
bool IsDisposed { get; }
void AddOrUpdate(string key, T value);
bool TryGetValue(string key, out T value);
T GetValue(string key);
bool TryRemove(string key, out T value);
void Remove(string key);
bool ContainsKey(string key);
}
public class MemoryCacheWrapper<T> : ICache<T> where T : class
{
private readonly MemoryCache _memoryCache;
private CacheItemPolicy _cacheItemPolicy;
private bool _isDisposed;
public MemoryCacheWrapper(string name, NameValueCollection config = null)
{
_memoryCache = config != null ? new MemoryCache(name, config) : new MemoryCache(name);
_isDisposed = false;
}
public string Name
{
get { return _memoryCache.Name; }
}
public long CacheMemoryLimitInBytes
{
get { return _memoryCache.CacheMemoryLimit; }
}
public long PhysicalMemoryLimit
{
get { return _memoryCache.PhysicalMemoryLimit; }
}
public TimeSpan PollingInterval
{
get { return _memoryCache.PollingInterval; }
}
public CacheItemPolicy CacheItemPolicy
{
get
{
return _cacheItemPolicy;
}
set
{
if (value != null)
{
_cacheItemPolicy = value;
}
}
}
public void AddOrUpdate(string key, T value)
{
_memoryCache.Set(key, value, CacheItemPolicy);
}
public bool TryGetValue(string key, out T value)
{
bool result = false;
value = default(T);
object item = _memoryCache.Get(key);
if (item != null)
{
value = (T)item;
result = true;
}
return result;
}
public T GetValue(string key)
{
return (T)_memoryCache.Get(key);
}
public bool TryRemove(string key, out T value)
{
bool result = false;
value = default(T);
object item = _memoryCache.Remove(key);
if (item != null)
{
result = true;
value = (T)item;
}
return result;
}
public void Remove(string key)
{
_memoryCache.Remove(key);
}
public bool ContainsKey(string key)
{
return _memoryCache.Contains(key);
}
public long Count
{
get { return _memoryCache.GetCount(); }
}
~MemoryCacheWrapper()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!this._isDisposed)
{
if (disposing)
{
_memoryCache.Dispose();
}
}
_isDisposed = true;
}
public bool IsDisposed
{
get { return _isDisposed; }
}
}
</code></pre>
<p>This is my service:</p>
<pre><code>[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class PremieraInteraction : IPremieraInteraction
{
private ICache<InfoLevel> _cacheInfoLevel = new MemoryCacheWrapper<InfoLevel>("MyCache");
public string GetPlacesInfoForSession(int levelId, int clientId, int sessionId)
{
var key = CacheUtils.GenerateKeyForCache(JobName.PlacesInfoForSession.ToString(),clientId, sessionId, levelId);
JavaScriptSerializer serializer = new JavaScriptSerializer();
InfoLevel cachedInfoLevel;
if (_cacheInfoLevel.TryGetValue(key, out cachedInfoLevel))
return serializer.Serialize(new { Success = true, Count = cachedInfoLevel.AllPlacesCount, Free = cachedInfoLevel.FreePlaces });
return serializer.Serialize(new { Success = false, Message = "Some error" });
}
}
</code></pre>
<p>What you think about this code?<br>
This is not bad that I create <code>MemoryCacheWrapper</code> inside service and not static?<br>
Also, <code>MemoryCacheWrapper</code> are generic. In the future, I need to create several <code>MemoryCacheWrapper</code> instances:</p>
<pre><code> private ICache<InfoLevel> _cacheInfoLevel = new MemoryCacheWrapper<InfoLevel>("MyCache");
private ICache<OtherObject> _cacheOtherObject= new MemoryCacheWrapper<OtherObject>("MyCache");
</code></pre>
<p>Any suggestions are helpful.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T01:36:33.293",
"Id": "20818",
"Score": "0",
"body": "Are you self-hosting the service or are you using IIS to host the service?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-26T11:51:55.913",
"Id": "21128",
"Score": "0",
"body": "@Kane: I'm using IIS. Sorry fo delay."
}
] |
[
{
"body": "<p>I think you have created an unuseful abstraction. Mostly your methods only calling the underlaying MemoryCache instance and you have created something weird: IDisposable wrapper over a static instance. Of yourse the MemoryCache can be disposed but not this way. You have a service with InstanceContextMode.Single then you should only call dispose or provide oppurtunity to call the Dispose method when your service stops.</p>\n\n<p>Insted of your wrapper i would create some extension method for the typed get/remove logic wrappings:</p>\n\n<pre><code>public static class MemoryCacheExtensions\n{\n public static bool TryGetValue<T>(this MemoryCache _memoryCache, string key, out T value)\n {\n var item = _memoryCache.Get(key);\n if (item != null)\n {\n value = (T)item;\n return true;\n }\n\n value = default(T);\n return false;\n }\n\n public static T GetValue<T>(this MemoryCache _memoryCache, string key)\n {\n return (T)_memoryCache.Get(key);\n }\n\n public static bool TryRemove<T>(this MemoryCache _memoryCache, string key, out T value)\n {\n var item = _memoryCache.Remove(key);\n if (item != null)\n {\n value = (T)item;\n return true;\n }\n value = default(T);\n return result;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T18:53:57.947",
"Id": "24870",
"ParentId": "12610",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T08:38:16.513",
"Id": "12610",
"Score": "3",
"Tags": [
"c#",
"cache",
"wcf"
],
"Title": "caching in WCF web service"
}
|
12610
|
<p>I wanted to make a class that connects to my server and returns a value, a URL in this case. As Android 4.0 doesn't let me run network task on the main UI thread (rightly so) I have made this.</p>
<p>Please give me your feedback as to if it is thread safe or not and ways to improve it. I have never used <code>ExecutorService</code> or <code>Future</code> before so I would be grateful to know if I am using it correctly. I would also like to know if this is blocking the thread that called <code>getDownloadURL</code>.</p>
<pre><code>public class DownloadURLServerGetter implements DownloadURLGetter {
private ServerAdapter serverAdapter;
private String id;
@Inject
public DownloadURLServerGetter(ServerAdapter serverAdapter) {
this.serverAdapter = serverAdapter;
}
@Override
public synchronized String getDownloadURL(String id) throws IOException {
this.id = id;
final ExecutorService service;
final Future<String> task;
service = Executors.newFixedThreadPool(1);
task = service.submit(new MyCallable());
try {
return task.get();
} catch (InterruptedException e) {
throw new IOException(e);
} catch (ExecutionException e) {
throw new IOException(e);
}
}
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
HttpResponse resp = serverAdapter.get("blobs/" + id);
String url = EntityUtils.toString(resp.getEntity());
return Parser.parseURL(url);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your method seems thread safe, but you are blocking <code>getDownloadURL()</code> because <code>task.get()</code> will only return once the underlying job finishes. Try reading up on Java's <code>future</code> and see how you can use them more efficient and correct.</p>\n\n<p>Your executor service should most likely only be created once for your application.</p>\n\n<p>By the way: if you pass <code>ServerAdapter</code> and <code>id</code> to <code>MyCallable</code> (as constructor arguments) you no longer need to keep <code>getDownloadURL</code> synchronized or <code>MyCallable</code> non-static.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T11:07:22.000",
"Id": "20335",
"Score": "0",
"body": "thank you for that. I realised I was blocking the calling thread. I have actually modified the thread that was calling this method so it seems to work pretty well at the moment tho as you pointed out there is room for improvement."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T11:01:23.460",
"Id": "12614",
"ParentId": "12613",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "12614",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T09:40:34.120",
"Id": "12613",
"Score": "1",
"Tags": [
"java",
"multithreading",
"android",
"thread-safety"
],
"Title": "Thread Safe Server Querier"
}
|
12613
|
<p>I have a list view which display in each view a Album's name, the associated Artist and the album art. </p>
<p>Here is the code of my <code>ListFragment</code> which display this list:</p>
<pre><code>public class AlbumsFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
AlbumsAdapter mAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.albums_fragment_layout, container, false);
return myFragmentView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAdapter = new AlbumsAdapter(getActivity(), null);
setListAdapter(mAdapter);
getLoaderManager().initLoader(0, null, this);
}
static final String[] ALBUM_SUMMARY_PROJECTION = { MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM, MediaStore.Audio.Albums.ARTIST, MediaStore.Audio.Albums.ALBUM_ART,};
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String select = null;
return new CursorLoader(getActivity(), MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,ALBUM_SUMMARY_PROJECTION, select, null, null);
}
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter.swapCursor(data);
}
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
}
</code></pre>
<p>Here is my custom <code>CursorAdapter</code>'s code:</p>
<pre><code>public class AlbumsAdapter extends CursorAdapter {
private final LayoutInflater mInflater;
public AlbumsAdapter(Context context, Cursor c) {
super(context, c);
mInflater=LayoutInflater.from(context);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
if (holder == null) {
holder = new ViewHolder();
holder.albumTitle = (TextView) view.findViewById(R.id.albumTextView);
holder.artistName = (TextView) view.findViewById(R.id.artistTextView);
holder.coverAlbum = (ImageView)view.findViewById(R.id.album_cover);
holder.column1 = cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM);
holder.column2 = cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ARTIST);
holder.column3 = cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM_ART);
view.setTag(holder);
}
holder.albumTitle.setText(cursor.getString(holder.column1));
holder.artistName.setText(cursor.getString(holder.column2));
Bitmap coverBitmap = BitmapFactory.decodeFile(cursor.getString(holder.column3));
holder.coverAlbum.setImageBitmap(coverBitmap);
}
static class ViewHolder {
TextView albumTitle;
TextView artistName;
ImageView coverAlbum;
int column1;
int column2;
int column3;
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final View view=mInflater.inflate(R.layout.albums_row,parent,false);
return view;
}
}
</code></pre>
<p>As you can see, I use already the trick of the <code>ViewHolder</code> to avoid calling <code>findViewById</code> too often.</p>
<p>But the problem is that my list is still very slow. What can I do to optimize it even more? For instance I could load in priority the Albums' title and Artists' names and display them and then, load in a second time the cover (asynchronously).</p>
<p>I've also tried to scale down the resolution of the Cover's Bitmap before displaying them in the <code>ImageViews</code>, but I saw no improvement :/</p>
<p>Do you have any idea how to make this list less laggy? Any advice is welcome.</p>
|
[] |
[
{
"body": "<p>Your lag will be coming from this line:</p>\n\n<pre><code> Bitmap coverBitmap = BitmapFactory.decodeFile(cursor.getString(holder.column3));\n</code></pre>\n\n<p>Your right about doing it asyncrhonously.\nYou could also scale the image.</p>\n\n<p>What you'll want to do is:</p>\n\n<ul>\n<li>spawn a new thread</li>\n<li>use a handler for when the bitmap has decoded</li>\n<li>set the bitmap on the imageview in the callback</li>\n</ul>\n\n<p>You could set the image to a spinner whilst it is loading.</p>\n\n<p>An example of something similar is:</p>\n\n<p><a href=\"http://blog.blundellapps.co.uk/imageview-with-loading-spinner/\" rel=\"nofollow noreferrer\">http://blog.blundellapps.co.uk/imageview-with-loading-spinner/</a></p>\n\n<p>And an example of image scaling is:</p>\n\n<p><a href=\"http://developer.android.com/training/displaying-bitmaps/load-bitmap.html#load-bitmap\" rel=\"nofollow noreferrer\">http://developer.android.com/training/displaying-bitmaps/load-bitmap.html#load-bitmap</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-18T19:47:21.227",
"Id": "430837",
"Score": "0",
"body": "stumbled upon this and got some kind of malware popping up from clicking his link"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T13:39:55.357",
"Id": "431042",
"Score": "1",
"body": "@BigTLarrity thanks for the heads up. I didn't renew my .com domain only my .co.uk, I've updated the link. (some bad person seems to have bought the original then)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T13:41:25.683",
"Id": "431043",
"Score": "0",
"body": "lol theres some rascals around aint there :P at least it is sorted now, hope i haven't been pwned haha xD"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-07-05T07:31:37.527",
"Id": "13334",
"ParentId": "12615",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T11:10:40.160",
"Id": "12615",
"Score": "3",
"Tags": [
"java",
"optimization",
"performance",
"android",
"asynchronous"
],
"Title": "Efficient Album Cover loading for ListView"
}
|
12615
|
<p>I have <code>Polygon</code>s on Google Maps API V3, and I would like to write this shorter:</p>
<pre><code>var myCoordinates = [
new google.maps.LatLng(52.210722,21.007330),
new google.maps.LatLng(52.211695,21.007030),
new google.maps.LatLng(52.212707,21.006718),
new google.maps.LatLng(52.214166,21.006246),
new google.maps.LatLng(52.215152,21.005957),
new google.maps.LatLng(52.215889,21.005796),
new google.maps.LatLng(52.216986,21.005442),
new google.maps.LatLng(52.217085,21.007201),
new google.maps.LatLng(52.217098,21.007781),
new google.maps.LatLng(52.217098,21.008886),
new google.maps.LatLng(52.217059,21.009218),
new google.maps.LatLng(52.216967,21.012158),
new google.maps.LatLng(52.216960,21.012716),
new google.maps.LatLng(52.216789,21.014819),
new google.maps.LatLng(52.215862,21.015269),
new google.maps.LatLng(52.214896,21.015977),
new google.maps.LatLng(52.213667,21.016771),
new google.maps.LatLng(52.213338,21.016997),
new google.maps.LatLng(52.213154,21.017190),
new google.maps.LatLng(52.212963,21.017437),
new google.maps.LatLng(52.212819,21.017662),
new google.maps.LatLng(52.212635,21.017286),
new google.maps.LatLng(52.212510,21.016836),
new google.maps.LatLng(52.212352,21.016042),
new google.maps.LatLng(52.212220,21.015387),
new google.maps.LatLng(52.211944,21.014336),
new google.maps.LatLng(52.211609,21.012437),
new google.maps.LatLng(52.210722,21.007330)
];
var polyOptions = new google.maps.Polygon({
path: myCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 0,
strokeWeight: 3,
fillColor: "#94C11F",
fillOpacity: 0.5,
clickable: false
});
var it = new google.maps.Polyline(polyOptions);
it.setMap(map);
var myCoordinates2 = [
new google.maps.LatLng(52.188629,20.98085),
new google.maps.LatLng(52.188031,20.984788),
new google.maps.LatLng(52.187926,20.984788),
new google.maps.LatLng(52.187827,20.984852),
new google.maps.LatLng(52.187636,20.984949),
new google.maps.LatLng(52.187386,20.985099),
new google.maps.LatLng(52.185295,20.986483),
new google.maps.LatLng(52.185189,20.986547),
new google.maps.LatLng(52.185097,20.98659),
new google.maps.LatLng(52.184966,20.98658),
new google.maps.LatLng(52.184828,20.986558),
new google.maps.LatLng(52.184709,20.986494),
new google.maps.LatLng(52.184571,20.986333),
new google.maps.LatLng(52.183953,20.985539),
new google.maps.LatLng(52.183821,20.985389),
new google.maps.LatLng(52.182394,20.984026),
new google.maps.LatLng(52.182841,20.982052),
new google.maps.LatLng(52.182926,20.981827),
new google.maps.LatLng(52.183321,20.982106),
new google.maps.LatLng(52.183367,20.982074),
new google.maps.LatLng(52.183394,20.981977),
new google.maps.LatLng(52.183361,20.981902),
new google.maps.LatLng(52.18294,20.981591),
new google.maps.LatLng(52.183676,20.97923),
new google.maps.LatLng(52.183972,20.979263),
new google.maps.LatLng(52.185452,20.979767),
new google.maps.LatLng(52.187031,20.980293),
new google.maps.LatLng(52.18861,20.98084)
];
var polyOptions2 = new google.maps.Polygon({
path: myCoordinates2,
strokeColor: "#FF0000",
strokeOpacity: 0,
strokeWeight: 3,
fillColor: "#94C11F",
fillOpacity: 0.5,
clickable: false
});
var it2 = new google.maps.Polyline(polyOptions2);
it2.setMap(map);
var myCoordinates2a = [
new google.maps.LatLng(52.183209,20.979037),
new google.maps.LatLng(52.182591,20.981172),
new google.maps.LatLng(52.182538,20.981462),
new google.maps.LatLng(52.182446,20.981988),
new google.maps.LatLng(52.182058,20.983533),
new google.maps.LatLng(52.180262,20.981548),
new google.maps.LatLng(52.180966,20.978898),
new google.maps.LatLng(52.180795,20.978243),
new google.maps.LatLng(52.181249,20.978297),
new google.maps.LatLng(52.18219,20.978587),
new google.maps.LatLng(52.182709,20.978769),
new google.maps.LatLng(52.18319,20.979016)
];
var polyOptions2a = new google.maps.Polygon({
path: myCoordinates2a,
strokeColor: "#FF0000",
strokeOpacity: 0,
strokeWeight: 3,
fillColor: "#94C11F",
fillOpacity: 0.5,
clickable: false
});
var it2a = new google.maps.Polyline(polyOptions2a);
it2a.setMap(map);
var myCoordinates2b = [
new google.maps.LatLng(52.188789,21.014442),
new google.maps.LatLng(52.188828,21.016932),
new google.maps.LatLng(52.188157,21.017253),
new google.maps.LatLng(52.187802,21.014571),
new google.maps.LatLng(52.188749,21.014442)
];
var polyOptions2b = new google.maps.Polygon({
path: myCoordinates2b,
strokeColor: "#FF0000",
strokeOpacity: 0,
strokeWeight: 3,
fillColor: "#94C11F",
fillOpacity: 0.5,
clickable: false
});
var it2b = new google.maps.Polyline(polyOptions2b);
it2b.setMap(map);
</code></pre>
|
[] |
[
{
"body": "<p>How about:</p>\n\n<pre><code>// Just the raw data ...\nvar myCoordinates = [\n [52.210722, 21.007330],\n [52.212707, 21.006718],\n [52.214166, 21.006246],\n [52.215152, 21.005957],\n [52.215889, 21.005796],\n [52.216986, 21.005442],\n [52.217085, 21.007201],\n [52.217098, 21.007781],\n [52.217098, 21.008886],\n [52.217059, 21.009218],\n [52.216967, 21.012158],\n [52.216960, 21.012716],\n [52.216789, 21.014819],\n [52.215862, 21.015269],\n [52.214896, 21.015977],\n [52.213667, 21.016771],\n [52.213338, 21.016997],\n [52.213154, 21.017190],\n [52.212963, 21.017437],\n [52.212819, 21.017662],\n [52.212635, 21.017286],\n [52.212510, 21.016836],\n [52.212352, 21.016042],\n [52.212220, 21.015387],\n [52.211944, 21.014336],\n [52.211609, 21.012437],\n [52.210722, 21.007330]\n];\n\nvar myCoordinates2 = [\n [52.188629, 20.98085],\n [52.188031, 20.984788],\n [52.187926, 20.984788],\n [52.187827, 20.984852],\n [52.187636, 20.984949],\n [52.187386, 20.985099],\n [52.185295, 20.986483],\n [52.185189, 20.986547],\n [52.185097, 20.98659],\n [52.184966, 20.98658],\n [52.184828, 20.986558],\n [52.184709, 20.986494],\n [52.184571, 20.986333],\n [52.183953, 20.985539],\n [52.183821, 20.985389],\n [52.182394, 20.984026],\n [52.182841, 20.982052],\n [52.182926, 20.981827],\n [52.183321, 20.982106],\n [52.183367, 20.982074],\n [52.183394, 20.981977],\n [52.183361, 20.981902],\n [52.18294, 20.981591],\n [52.183676, 20.97923],\n [52.183972, 20.979263],\n [52.185452, 20.979767],\n [52.187031, 20.980293],\n [52.18861, 20.98084]\n];\n\nvar myCoordinates2a = [\n [52.183209, 20.979037],\n [52.182591, 20.981172],\n [52.182538, 20.981462],\n [52.182446, 20.981988],\n [52.182058, 20.983533],\n [52.180262, 20.981548],\n [52.180966, 20.978898],\n [52.180795, 20.978243],\n [52.181249, 20.978297],\n [52.18219, 20.978587],\n [52.182709, 20.978769],\n [52.18319, 20.979016]\n];\n\nvar myCoordinates2b = [\n [52.188789, 21.014442],\n [52.188828, 21.016932],\n [52.188157, 21.017253],\n [52.187802, 21.014571],\n [52.188749, 21.014442]\n];\n</code></pre>\n\n<p>And the restructured functionality:</p>\n\n<pre><code>function mapToLatLng(source, index, array) {\n return new google.maps.LatLng(source[0], source[1])\n}\n\nfunction toLatLng(array) {\n return array.map(mapToLatLng);\n}\n\nfunction newPolyOptions(path) {\n return new google.maps.Polygon({\n path:path,\n strokeColor:\"FF0000\",\n strokeOpacity:0,\n strokeWeight:3,\n fillColor:\"#94C11F\",\n fillOpacity:0.5,\n clickable:false\n });\n}\n\nfunction newPolyLine(polyOptions) {\n var polyLine = new google.maps.Polyline(polyOptions);\n polyLine.setMap(map);\n return polyLine;\n}\n\nvar it = newPolyLine(newPolyOptions(toLatLng(myCoordinates)));\nvar it2 = newPolyLine(newPolyOptions(toLatLng(myCoordinates2)));\nvar it2a = newPolyLine(newPolyOptions(toLatLng(myCoordinates2a)));\nvar it2b = newPolyLine(newPolyOptions(toLatLng(myCoordinates2b)));\n</code></pre>\n\n<p>Or you could also compress it in one function.</p>\n\n<pre><code>function newPolyLine(path) {\n var polyLine = new google.maps.Polyline(new google.maps.Polygon({\n path:path.map(\n function(source, index, array) {\n return new google.maps.LatLng(source[0], source[1]);\n }),\n strokeColor:\"FF0000\",\n strokeOpacity:0,\n strokeWeight:3,\n fillColor:\"#94C11F\",\n fillOpacity:0.5,\n clickable:false\n }));\n polyLine.setMap(map);\n return polyLine;\n};\n\nvar it = newPolyLine(myCoordinates);\nvar it2 = newPolyLine(myCoordinates2);\nvar it2a = newPolyLine(myCoordinates2a);\nvar it2b = newPolyLine(myCoordinates2b);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T12:14:59.520",
"Id": "20338",
"Score": "0",
"body": "i will try this and let u know"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T12:18:16.877",
"Id": "20339",
"Score": "0",
"body": "Sure, i also compressed it int a single method. Just edited my post."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T14:29:23.830",
"Id": "20344",
"Score": "0",
"body": "works perfect, thx a lot mate"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T12:03:40.483",
"Id": "12617",
"ParentId": "12616",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "12617",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T11:20:01.117",
"Id": "12616",
"Score": "3",
"Tags": [
"javascript",
"google-maps"
],
"Title": "Polygons on Google Maps"
}
|
12616
|
<p>I am currently writing my first Android application, and am having trouble grasping how to structure it. From my previous programming experience I was planning on using a MVC design but now I don't know if I can implement that. </p>
<p>My program consists of several different activities which all need access to a single Bluetooth connection. I currently have two activities written along with another class (<code>AndroidBluetooth</code> is my main page, <code>DeviceList</code> is a pop up which lets you connect to a device, and <code>BluetoothModel</code> is where I have been storing all of my Bluetooth information). </p>
<p>Is there some way to initialize objects at the start of a program so that every activity can access them? My code is attached below; I know that there is a lot of overlapping methods, I need to clean it up a bit.</p>
<p><strong>AndroidBluetooth:</strong></p>
<pre><code>// Member fields
//private final Handler mHandler;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private int mState;
//private EmulatorView mEmulatorView;
// Constants that indicate the current connection state
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_LISTEN = 1; // now listening for incoming connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
public static final int STATE_CONNECTED = 3; // now connected to a remote device
public int currentState;
public boolean customTitleSupported;
public BluetoothModel btModel;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
currentState = 0;
customTitleSupported = requestWindowFeature( Window.FEATURE_CUSTOM_TITLE );
// Set up window View
setContentView(R.layout.main);
stateBluetooth = new TextView(this);
myBtAdapter = null;
startBluetooth();
checkBlueToothState();
customTitleBar( getText( R.string.app_name).toString(), stateBluetooth.getText().toString() );
}
public void customTitleBar( String left, String right ) {
if( right.length() > 30 ) right = right.substring( 0, 20 );
if( customTitleSupported ) {
getWindow().setFeatureInt( Window.FEATURE_CUSTOM_TITLE, R.layout.customlayoutbar );
TextView titleTvLeft = (TextView) findViewById( R.id.titleTvLeft );
TextView titleTvRight = (TextView) findViewById( R.id.titleTvRight );
titleTvLeft.setText( left );
titleTvRight.setText( right );
}
}
public boolean onCreateOptionsMenu( Menu menu ) {
MenuInflater inflater = getMenuInflater();
inflater.inflate( R.menu.option_menu, menu );
return true;
}
public boolean onOptionsItemSelected( MenuItem item ) {
switch( item.getItemId() ) {
case R.id.connect:
startActivityForResult( new Intent( this, DeviceList.class ), REQUEST_CONNECT_DEVICE );
return true;
case R.id.preferences:
return true;
default:
return super.onContextItemSelected( item );
}
}
private void checkBlueToothState() {
if( myBtAdapter == null ) {
stateBluetooth.setText("Bluetooth NOT supported" );
} else {
if( myBtAdapter.isEnabled() ) {
if( myBtAdapter.isDiscovering() ) {
stateBluetooth.setText( "Bluetooth is currently " +
"in device discovery process." );
} else {
stateBluetooth.setText( "Bluetooth is Enabled." );
}
} else {
stateBluetooth.setText( "Bluetooth is NOT enabled" );
Intent enableBtIntent = new Intent( BluetoothAdapter.ACTION_REQUEST_ENABLE );
startActivityForResult( enableBtIntent, REQUEST_ENABLE_BT );
}
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(D) Log.d( TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceList.EXTRA_DEVICE_ADDRESS);
// Get the BLuetoothDevice object
BluetoothDevice device = myBtAdapter.getRemoteDevice(address);
// Attempt to connect to the device
btModel.connect(device);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
checkBlueToothState();
}
}
//In SDK15 (4.0.3) this method is now public as
//Bluetooth.fetchUuisWithSdp() and BluetoothDevice.getUuids()
public ParcelUuid[] servicesFromDevice(BluetoothDevice device) {
try {
Class cl = Class.forName("android.bluetooth.BluetoothDevice");
Class[] par = {};
Method method = cl.getMethod("getUuids", par);
Object[] args = {};
ParcelUuid[] retval = (ParcelUuid[]) method.invoke(device, args);
return retval;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver() {
public void onReceive( Context context, Intent intent ) {
String action = intent.getAction();
if( BluetoothDevice.ACTION_FOUND.equals( action ) ) {
BluetoothDevice btDevice = intent.getParcelableExtra( BluetoothDevice.EXTRA_DEVICE );
btDevicesFound.add( btDevice );
btArrayAdapter.add( btDevice.getName() + "\n" + btDevice.getAddress() );
btArrayAdapter.notifyDataSetChanged();
}
}
};
public static void startBluetooth(){
try {
myBtAdapter = BluetoothAdapter.getDefaultAdapter();
myBtAdapter.enable();
} catch ( NullPointerException ex ) {
Log.e( "Bluetooth", "Device not available" );
}
}
public static void stopBluetooth() {
myBtAdapter.disable();
}
}
</code></pre>
<p><strong>DeviceList:</strong></p>
<pre><code>// Return Intent extra
public static String EXTRA_DEVICE_ADDRESS = "device_address";
// Member fields
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the window
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list);
// Set result CANCELED incase the user backs out
setResult(Activity.RESULT_CANCELED);
// Initialize the button to perform device discovery
Button scanButton = (Button) findViewById(R.id.button_scan);
scanButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
doDiscovery();
v.setVisibility(View.GONE);
}
});
// Initialize array adapters. One for already paired devices and
// one for newly discovered devices
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
// Find and set up the ListView for paired devices
ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);
// Find and set up the ListView for newly discovered devices
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
// Get the local Bluetooth adapter
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
// Get a set of currently paired devices
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices = getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(noDevices);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// Make sure we're not doing discovery anymore
if (mBtAdapter != null) {
mBtAdapter.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
/**
* Start device discover with the BluetoothAdapter
*/
private void doDiscovery() {
if (D) Log.d(TAG, "doDiscovery()");
// Indicate scanning in the title
setProgressBarIndeterminateVisibility(true);
setTitle(R.string.scanning);
// Turn on sub-title for new devices
findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
// If we're already discovering, stop it
if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBtAdapter.startDiscovery();
}
// The on-click listener for all devices in the ListViews
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter.cancelDiscovery();
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
// Set result and finish this Activity
setResult(Activity.RESULT_OK, intent);
finish();
}
};
// The BroadcastReceiver that listens for discovered devices and
// changes the title when discovery is finished
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle(R.string.select_device);
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = getResources().getText(R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
}
</code></pre>
<p><strong>BluetoothModel:</strong></p>
<pre><code>public class BluetoothModel {
// Debugging
private static final String TAG = "BluetoothModel";
private static final boolean D = true;
// Member fields
private final BluetoothAdapter myAdapter;
private final Handler myHandler;
private Context myContext;
private ConnectThread myConnectThread;
private ConnectedThread myConnectedThread;
private int myState;
// Constants that indicate the current connection state
public static final int STATE_NONE = 0;
public static final int STATE_LISTEN = 1;
public static final int STATE_CONNECTING = 2;
public static final int STATE_CONNECTED = 3;
public BluetoothModel( Context context, Handler handler ) {
myContext = context;
myAdapter = BluetoothAdapter.getDefaultAdapter();
myState = STATE_NONE;
myHandler = handler;
}
/**
* Set the connection state.
*
* @param state
*/
public synchronized void setState( int state ) {
if( D ) Log.d( TAG, "setState() " + myState + " -> " + state );
myState = state;
myHandler.obtainMessage( AndroidBluetooth.MESSAGE_STATE_CHANGE, state, -1 ).sendToTarget();
}
/**
* Get the connection state.
*
* @return
*/
public synchronized int getState() {
return myState;
}
/**
* Indicate that the connection attempt failed and notify the UI Activity.
*
*/
private void connectionFailed() {
setState(STATE_NONE);
// Send a failure message back to the Activity
Message msg = myHandler.obtainMessage(AndroidBluetooth.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(AndroidBluetooth.TOAST, "Unable to connect device");
msg.setData(bundle);
myHandler.sendMessage(msg);
}
/**
* Indicate that the connection was lost and notify the UI Activity.
*
*/
private void connectionLost() {
setState(STATE_NONE);
// Send a failure message back to the Activity
Message msg = myHandler.obtainMessage(AndroidBluetooth.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(AndroidBluetooth.TOAST, "Device connection was lost");
msg.setData(bundle);
myHandler.sendMessage(msg);
}
/**
* Start the chat service. Specifically start AcceptThread to begin a
* session in listening (server) mode. Called by the Activity onResume() */
public synchronized void start() {
if (D) Log.d(TAG, "start");
// Cancel any thread attempting to make a connection
if (myConnectThread != null) {
myConnectThread.cancel();
myConnectThread = null;
}
// Cancel any thread currently running a connection
if (myConnectedThread != null) {
myConnectedThread.cancel();
myConnectedThread = null;
}
setState(STATE_NONE);
}
/**
* Start the ConnectThread to initiate a connection to a remote device.
* @param device The BluetoothDevice to connect
*/
public synchronized void connect(BluetoothDevice device) {
if (D) Log.d(TAG, "connect to: " + device);
// Cancel any thread attempting to make a connection
if (myState == STATE_CONNECTING) {
if (myConnectThread != null) {myConnectThread.cancel(); myConnectThread = null;}
}
// Cancel any thread currently running a connection
if (myConnectedThread != null) {myConnectedThread.cancel(); myConnectedThread = null;}
// Start the thread to connect with the given device
myConnectThread = new ConnectThread(device);
myConnectThread.start();
setState(STATE_CONNECTING);
}
/**
* Start the ConnectedThread to begin managing a Bluetooth connection
* @param socket The BluetoothSocket on which the connection was made
* @param device The BluetoothDevice that has been connected
*/
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
if (D) Log.d(TAG, "connected");
// Cancel the thread that completed the connection
if (myConnectThread != null) {
myConnectThread.cancel();
myConnectThread = null;
}
// Cancel any thread currently running a connection
if (myConnectedThread != null) {
myConnectedThread.cancel();
myConnectedThread = null;
}
// Start the thread to manage the connection and perform transmissions
myConnectedThread = new ConnectedThread(socket);
myConnectedThread.start();
// Send the name of the connected device back to the UI Activity
Message msg = myHandler.obtainMessage(AndroidBluetooth.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(AndroidBluetooth.DEVICE_NAME, device.getName());
msg.setData(bundle);
myHandler.sendMessage(msg);
setState(STATE_CONNECTED);
}
/**
* Stop all threads
*/
public synchronized void stop() {
if (D) Log.d(TAG, "stop");
if (myConnectThread != null) {
myConnectThread.cancel();
myConnectThread = null;
}
if (myConnectedThread != null) {
myConnectedThread.cancel();
myConnectedThread = null;
}
setState(STATE_NONE);
}
/**
* Write to the ConnectedThread in an unsynchronized manner
* @param out The bytes to write
* @see ConnectedThread#write(byte[])
*/
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (myState != STATE_CONNECTED) return;
r = myConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
/**
* This thread runs while attempting to make an outgoing connection
* with a device. It runs straight through; the connection either
* succeeds or fails.
*/
public class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
mmDevice = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(SPP_UUID);
} catch (IOException e) {
Log.e(TAG, "create() failed", e);
}
mmSocket = tmp;
}
public void run() {
Log.i(TAG, "BEGIN mConnectThread");
setName("ConnectThread");
// Always cancel discovery because it will slow down a connection
myAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
connectionFailed();
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() socket during connection failure", e2);
}
// Start the service over to restart listening mode
//BluetoothSerialService.this.start();
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothModel.this) {
myConnectThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
/**
* This thread runs during a connection with a remote device.
* It handles all incoming and outgoing transmissions.
*/
public class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "create ConnectedThread");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
//mEmulatorView.write(buffer, bytes);
// Send the obtained bytes to the UI Activity
//mHandler.obtainMessage(BlueTerm.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
String a = buffer.toString();
a = "";
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
/**
* Write to the connected OutStream.
* @param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
//mHandler.obtainMessage(BlueTerm.MESSAGE_WRITE, buffer.length, -1, buffer)
//.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You should be able to add the instantiated object to your intents. This way, you should be able to access it in other Activities or Services.\nYou might want to investigate on services if you want the app to do something consistently and should be able to get information from the service via intent.</p>\n\n<p>As for MVC see: <a href=\"https://stackoverflow.com/questions/2925054/mvc-pattern-in-android\">https://stackoverflow.com/questions/2925054/mvc-pattern-in-android</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T12:30:13.283",
"Id": "12633",
"ParentId": "12618",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12633",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T12:28:56.023",
"Id": "12618",
"Score": "1",
"Tags": [
"java",
"android",
"bluetooth"
],
"Title": "MVC in Android development for Bluetooth application"
}
|
12618
|
<p>I have learned a little Python for a few projects at work. This is my first <em>finished</em> application and I was hoping someone would take a look at it. I would love some tips on the mistakes I've made.</p>
<pre><code>################################################################################
#Monthly Rollover System #
#Written by Ryan Hanson 2012 #
# #
################################################################################
#Python Imports
import sys
#PyQt4 Imports
from PyQt4 import QtCore, QtGui, QtSql #@UnusedImport
#UI Imports
from main import Ui_MainWindow
from popup import Ui_Dialog
#Variables
dbhost = "192.168.1.39"
dbname = "material"
dbuser = "fab"
dbpswd = "doylefab"
#This Runs First
class launch(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
#Prepare the first window
self.main = Ui_MainWindow()
self.main.setupUi(self)
#Set the icon and select the first tab
self.setWindowIcon(QtGui.QIcon("icons/main.png"))
self.setWindowTitle("Material Tracking")
self.main.tabs.setCurrentIndex(0)
#Make db accessible to the whole app - I am not sure this is the best way to do this?
global db
db = QtSql.QSqlDatabase.addDatabase("QMYSQL");
#Host name and Database
db.setHostName(dbhost)
db.setDatabaseName(dbname)
db.setUserName(dbuser)
db.setPassword(dbpswd)
ok = db.open()
#ok is true if the database can be connected to
if ok:
self.materialQuery = QtSql.QSqlQuery(db)
materialdata = "select id, material, d1, d2, d3 from material_tbl"
if self.materialQuery.exec_(materialdata):
self.materialchange(1)
#Set the range for the slider so all records can be navigated to.
self.main.horizontalSlider.setRange(1, self.materialQuery.size())
self.main.modelMaterial = QtSql.QSqlTableModel()
self.main.modelMaterial.setTable("inventory_view")
self.main.modelMaterial.select()
self.main.tableMaterial.setModel(self.main.modelMaterial)
#Is there a better way to set columns?
self.main.tableMaterial.setColumnWidth(0, 50)
self.main.tableMaterial.setColumnWidth(1, 200)
self.main.tableMaterial.setColumnWidth(2, 75)
self.main.tableMaterial.setColumnWidth(3, 100)
self.main.tableMaterial.setColumnWidth(4, 100)
self.main.tableMaterial.setColumnWidth(5, 100)
#########CONNECTIONS###############################################################################
self.main.horizontalSlider.valueChanged.connect(self.materialchange)
self.main.tableMaterial.doubleClicked.connect(self.dblclickMaterial)
self.main.lineSearch.textChanged.connect(self.filterMaterial)
self.main.buttonReceive.clicked.connect(self.received)
self.main.buttonUsed.clicked.connect(self.used)
#########END IF THE CONNECTION FAILS###############################################################
else:
self.dberror()
def materialchange(self, index):
if db.isOpen():
#Seek to the next record and load the proper data
self.materialQuery.seek(index-1)
mat = self.materialQuery.value(0).toString()
self.main.lineId.setText(mat)
self.main.lineMaterial.setText(self.materialQuery.value(1).toString())
self.main.lined1.setText(self.materialQuery.value(2).toString())
self.main.lined2.setText(self.materialQuery.value(3).toString())
self.main.lined3.setText(self.materialQuery.value(4).toString())
self.main.modelreceived = QtSql.QSqlTableModel()
self.main.modelreceived.setTable("received_tbl")
self.main.modelreceived.setFilter('mat_id = {0}'.format(mat))
self.main.modelreceived.select()
self.main.tablereceived.setModel(self.main.modelreceived)
#Is there a better way to set columns?
self.main.tablereceived.setColumnWidth(0, 50)
self.main.tablereceived.setColumnWidth(1, 50)
self.main.tablereceived.setColumnWidth(2, 75)
self.main.tablereceived.setColumnWidth(3, 125)
self.main.tablereceived.setColumnWidth(4, 125)
self.main.modelused = QtSql.QSqlTableModel()
self.main.modelused.setTable("used_tbl")
self.main.modelused.setFilter('mat_id = {0}'.format(mat))
self.main.modelused.select()
self.main.tableused.setModel(self.main.modelused)
#Is there a better way to set columns?
self.main.tableused.setColumnWidth(0, 50)
self.main.tableused.setColumnWidth(1, 50)
self.main.tableused.setColumnWidth(2, 75)
self.main.tableused.setColumnWidth(3, 125)
self.main.tableused.setColumnWidth(4, 125)
else:
self.dberror()
def dblclickMaterial(self, index):
row = index.row()
kid = self.main.modelMaterial.data(self.main.modelMaterial.index(row, 0)).toString()
i=0
self.materialQuery.seek(i)
#This is probably a relatively slow way to find the right record. Any suggestions?
while self.materialQuery.value(0).toString() <> kid:
i+=1
self.materialQuery.seek(i)
self.materialchange(i+1)
self.main.tabs.setCurrentIndex(1)
self.main.horizontalSlider.setSliderPosition(i+1)
def filterMaterial(self):
r=0
R=self.main.modelMaterial.rowCount()
c=0
C=self.main.modelMaterial.columnCount()
s=0
search = str(self.main.lineSearch.text())
#Loop though all columns on all rows and hide rows where none of the columns match the search term.
while r < R:
while c<C:
if search.lower() not in str(self.main.modelMaterial.data(self.main.modelMaterial.index(r, c)).toString()).lower():
s += 1
c += 1
if s==C:
self.main.tableMaterial.setRowHidden(r, True)
else:
self.main.tableMaterial.setRowHidden(r, False)
c=0
r +=1
s=0
def received(self):
def accept():
mat = self.main.lineId.text()
qty = self.popup.dialog.lineQty.text()
notes = self.popup.dialog.lineNotes.text()
insertQuery = QtSql.QSqlQuery(db)
#There are two tables used to track material, one that records details about each load we receive and the other that keeps a running total of what we should have on hand.
insertdata = "INSERT INTO `material`.`received_tbl` (`id`, `mat_id`, `quantity`, `date`, `note`) VALUES (NULL, {0}, {1}, CURRENT_TIMESTAMP, '{2}');".format(mat, qty, notes)
if insertQuery.exec_(insertdata):
inventoryQuery=QtSql.QSqlQuery(db)
inventorydata = "Update inventory_tbl set quantity = (quantity + {0}) where mat_id = {1}".format(qty, mat)
if inventoryQuery.exec_(inventorydata):
print("{0} Received.".format(qty))
self.main.modelMaterial.select()
if self.main.lineSearch <> "":
self.filterMaterial()
else:
print(inventoryQuery.lastError().text())
QtGui.QMessageBox.about(self, "Fail...", 'There was a problem and this operation did not complete...')
else:
print(insertQuery.lastError().text())
QtGui.QMessageBox.about(self, "Fail...", 'There was a problem and this operation did not complete...')
self.popup = QtGui.QDialog()
self.popup.show()
self.popup.dialog = Ui_Dialog()
self.popup.dialog.setupUi(self.popup)
self.popup.setWindowTitle("Received")
self.popup.setWindowIcon(QtGui.QIcon("icons/main.png"))
self.popup.dialog.buttonBox.accepted.connect(accept)
#Almost exactly the same as received but it updates the used table and subtracts from the total.
def used(self):
def accept():
mat = self.main.lineId.text()
qty = self.popup.dialog.lineQty.text()
notes = self.popup.dialog.lineNotes.text()
insertQuery = QtSql.QSqlQuery(db)
insertdata = "INSERT INTO `material`.`used_tbl` (`id`, `mat_id`, `quantity`, `date`, `note`) VALUES (NULL, {0}, {1}, CURRENT_TIMESTAMP, '{2}');".format(mat, qty, notes)
if insertQuery.exec_(insertdata):
inventoryQuery=QtSql.QSqlQuery(db)
inventorydata = "Update inventory_tbl set quantity = (quantity - {0}) where mat_id = {1}".format(qty, mat)
if inventoryQuery.exec_(inventorydata):
print("{0} Used.".format(qty))
self.main.modelMaterial.select()
if self.main.lineSearch <> "":
self.filterMaterial()
else:
print(inventoryQuery.lastError().text())
QtGui.QMessageBox.about(self, "Fail...", 'There was a problem and this operation did not complete...')
else:
print(insertQuery.lastError().text())
QtGui.QMessageBox.about(self, "Fail...", 'There was a problem and this operation did not complete...')
self.popup = QtGui.QDialog()
self.popup.show()
self.popup.dialog = Ui_Dialog()
self.popup.dialog.setupUi(self.popup)
self.popup.setWindowTitle("Used")
self.popup.setWindowIcon(QtGui.QIcon("icons/main.png"))
self.popup.dialog.buttonBox.accepted.connect(accept)
#Called when the database encounters a connection problem.
def dberror(self):
print(db.lastError().text())
QtGui.QMessageBox.about(self, "Fail...", 'Could not connect...')
sys.exit()
#This is in place to unload material query.
def closeEvent(self, event):
print("Unloading Material Query...")
self.materialQuery.finish()
print("Have a nice day!")
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = launch()
myapp.show()
sys.exit(app.exec_())
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T19:31:56.883",
"Id": "57446",
"Score": "1",
"body": "you had better change your Database username and password. that is my first review"
}
] |
[
{
"body": "<p>Some really obvious stuff popped up in a casual pylint check over your code. As well as some further, more advanced ideas for changing your code below.</p>\n\n<pre><code>db = QtSql.QSqlDatabase.addDatabase(\"QMYSQL\");\n</code></pre>\n\n<p>The semi-colon is not necessary in python.</p>\n\n<pre><code>while self.materialQuery.value(0).toString() <> kid:\nif self.main.lineSearch <> \"\":\nif self.main.lineSearch <> \"\":\n</code></pre>\n\n<p>The <> operator is frowned upon, and is going to be removed. Your code will not be forwards-compatible.</p>\n\n<pre><code>r=0\nR=self.main.modelMaterial.rowCount()\nc=0\nC=self.main.modelMaterial.columnCount()\ns=0\ns==C:\nc<C:\n</code></pre>\n\n<p>PEP8 standard specifies that you have to have spaces before and after assignment, equality and comparison operators, among others. You're not getting any benefit if you scrunch stuff up like that. This isn't C.</p>\n\n<pre><code>#Is there a better way to set columns?\nself.main.tableMaterial.setColumnWidth(0, 50)\nself.main.tableMaterial.setColumnWidth(1, 200)\nself.main.tableMaterial.setColumnWidth(2, 75)\nself.main.tableMaterial.setColumnWidth(3, 100)\nself.main.tableMaterial.setColumnWidth(4, 100)\nself.main.tableMaterial.setColumnWidth(5, 100)\n</code></pre>\n\n<p>Yes, it's called a loop. Such as:</p>\n\n<pre><code>COL_WIDTHS_CONST = {\n 0: 50,\n 1: 200,\n 2: 75,\n 3: 100,\n 4: 100,\n 5: 100,\n}\ndef set_widths(self, colDict):\n for column in colDict:\n self.main.tableMaterial.setColumnWidth(column , colDict[column])\n\n# Somewhere in your init code:\nself.set_widths(self, COL_WIDTHS_CONST):\n</code></pre>\n\n<p>Move stuff out of your init method. Even if all the magic happens in the init method, you can't put all the low-level code there. Make separate functions. e.g.</p>\n\n<ol>\n<li>SetupMainWindow</li>\n<li>SetupDatabase</li>\n<li>GetMaterialData (From the database)</li>\n<li>ConnectEvents</li>\n<li>ConfigureGUIElements (You put your column/row width setting code here)</li>\n</ol>\n\n<p>The fact that you had so many comments in your giant 40 line init method should be telling of the fact that it was doing too much in one spot, and you had to use comments to divide it into separate groupings.</p>\n\n<p>Another thing I noticed. You seem to be mixing your data retrieval, presentation and control logic all in the same pieces of code. You should move code out into separate functions. If you have a method that is more than a few lines, then odds are it does too much, or it repeats.</p>\n\n<p>Move the SQL code out of your code, and into constants. It makes making changes to your SQL a little more manageable.</p>\n\n<p>One last thing. It's something I see often with sloppy coders that don't use a proper IDE for python development. Trailing whitespace.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T01:04:05.177",
"Id": "58222",
"Score": "1",
"body": "Hey thanks for the write up! I made a lot off mistakes in this piece of code. Lots of the things you suggested I fix, I don't do any more. Thank you for taking the time to look at it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T21:19:05.140",
"Id": "35723",
"ParentId": "12619",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T13:47:15.337",
"Id": "12619",
"Score": "3",
"Tags": [
"python",
"sql",
"mysql"
],
"Title": "Monthly rollover system"
}
|
12619
|
<p>I have two <code>.on()</code> functions for separate dynamically added elements, they are:</p>
<pre><code>$('body').on('click', 'img', function() {
modal(content[$('li.active a').attr("href")].images[$("img").index(this)]);
});
$('body').on('click', 'img', function() {
closeM();
});
</code></pre>
<p>The second function, I have shortened to</p>
<pre><code>$("body").on("click", "#close", closeM);
</code></pre>
<p>In looking at the jQuery documentation for <code>.on()</code>, I saw that I can do something like:</p>
<pre><code>$("body").on({
click: function(){
},
mouseenter: function() {
}
});
</code></pre>
<p>I was wondering if I could either do something like that with my previous two functions, or if there was any other way of shortening/combining them.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T18:23:25.080",
"Id": "20352",
"Score": "0",
"body": "[JsFiddle: example of using selector for event map style of `on` method](http://jsfiddle.net/LU38z/)"
}
] |
[
{
"body": "<p>You could just do both operations inside the anonymous function (that you are sending as third parameter).</p>\n\n<pre><code>$('body').on('click', 'img', function() {\n modal(content[$('li.active a').attr(\"href\")].images[$(\"img\").index(this)]);\n closeM();\n});\n</code></pre>\n\n<p>Also, I would consider simplifying the first instruction by breaking it down into smaller pieces.<br>\nAll compressed together as it is, it is some serious black magic and should be quite tough to read or maintain by anyone else.</p>\n\n<hr>\n\n<p>But <code>$(\"body\").on(\"click\", \"#close\", closeM);</code> is very simple, and also much more contained because it applies to the only element with id <code>#close</code> in the HTML, instead of to all the images. So I would prefer to leave it separate.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T16:27:47.607",
"Id": "20350",
"Score": "0",
"body": "The only problem with putting the both events in the same `.on()` is that `closeM()` is called when a `div` with `#close` is called, instead of an image. So short of breaking up the parameters in the `modal()` call, there isn't much I can do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T12:33:46.087",
"Id": "20472",
"Score": "0",
"body": "I believe so. But then, if they apply to two different things I find it better that they are explicitly separate."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T16:21:47.260",
"Id": "12621",
"ParentId": "12620",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12621",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T16:10:26.617",
"Id": "12620",
"Score": "0",
"Tags": [
"javascript",
"jquery"
],
"Title": "Consolidate .on function"
}
|
12620
|
<p>I've created a simple daily task scheduler but I'd like to change this to a general task scheduler accepting more advanced schedules.</p>
<p>I'd like to have some critiques from other sets of eyes on my current implementation before I continue.</p>
<pre><code>public class ScheduleJob
{
#region PRIVATE VARIABLES
private readonly Timer _timer;
private Action _job;
private int _setHour;
private int _setMin;
#endregion
#region CONSTRUCTOR
public ScheduleJob()
{
_timer = new Timer();
_setHour = 0;
_setMin = 0;
}
#endregion
#region PUBLIC METHODS
public void SetTimeofDay(int in_hour, int in_min)
{
_setHour = in_hour;
_setMin = in_min;
}
public void SetJob(Action in_task)
{
_job = in_task;
}
public void Start()
{
try
{
int PeriodMin = GetHour() * 60 + GetMin(); //minute
_timer.Interval = PeriodMin * 60 * 1000; //millisecond
_timer.Elapsed += _timer_Elapsed;
_timer.Start();
IsRunning = true;
}
catch (Exception)
{
IsRunning = false;
}
}
public void Stop()
{
if (_timer != null)
_timer.Stop();
IsRunning = false;
}
#endregion
#region PRIVATE METHODS
private void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
_timer.Enabled = false;
_job(); //perform the job
int PeriodMin = 24 * 60;
_timer.Interval = PeriodMin * 60 * 1000;
_timer.Enabled = true;
}
private int GetHour()
{
int _nowHour = DateTime.Now.Hour;
if (_nowHour > _setHour)
{
return (24 - (_nowHour - _setHour));
}
else
{
return (_setHour - _nowHour);
}
}
private int GetMin()
{
int _nowMin = DateTime.Now.Minute;
if (GetHour() == 0)
{
if ((_setMin - _nowMin) <= 0)
{
return (24 * 60) + Math.Abs(_setMin - _nowMin);
}
}
return (_setMin - _nowMin);
}
#endregion
#region PROPERTIES
public bool IsRunning { get; set; }
#endregion
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T21:57:58.577",
"Id": "20353",
"Score": "1",
"body": "How about you start by running StyleCop on this and correcting the problems. This will find lots of stuff for sure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T08:21:57.177",
"Id": "72027",
"Score": "0",
"body": "The [KetticScheduler view class](http://www.kettic.com/winforms_ui/csharp_guide/scheduler_view.shtml) provides Workday view to highlight working time in Windows application to set work scheduling."
}
] |
[
{
"body": "<p>Just a small comment from me. I'm not so sure about the need for the method SetJob(). It seems like there is a requirement for this method to be called before the Start() and once called you wouldn't call it again? </p>\n\n<p>Hence perhaps I might look at moving this to the constructor that would hopefully imply this concept? Also that way you can't change the job. This is of course made with the assumption you aren't looking at changing jobs once a new ScheduledJob has been setup.</p>\n\n<p>Also probably what Stylecop might pick up anyway as suggested by Leonid;</p>\n\n<ul>\n<li>I personally wouldn't recommend using an _ for a variable within a method i.e. _nowMin</li>\n<li>Same applies for the private method _timer_elapsed()</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T09:36:42.043",
"Id": "20366",
"Score": "0",
"body": "Exactly what I would have said."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T23:28:00.073",
"Id": "12629",
"ParentId": "12625",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T21:04:31.063",
"Id": "12625",
"Score": "7",
"Tags": [
"c#",
"scheduled-tasks"
],
"Title": "Simple Job Scheduler Class"
}
|
12625
|
<p>Can this time converter be written more efficiently? I'm new to Java, and I would like to know.</p>
<h2>main</h2>
<pre><code>import javax.swing.JFrame;
public class main {
public static void main(String[] args) {
window wn = new window();
wn.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
wn.setSize(275, 170);
wn.setVisible(true);
}
}
</code></pre>
<h2>time</h2>
<pre><code>public class time {
private int hour;
private int minute;
private String ampm;
public void setTime(int h, int m, String t) {
hour = ((h>=0 && h<=24) ? h : 0);
minute = ((m>=0 && m<=60) ? m : 0);
ampm = t;
}
public String to24h() {
if (ampm == "PM") {
hour += 12;
}
return String.format("%02d:%02d", hour, minute);
}
}
</code></pre>
<h2>window</h2>
<pre><code>import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JComboBox;
@SuppressWarnings("serial")
public class window extends JFrame {
private JLabel label;
private JTextField hours;
private JTextField minutes;
private JTextField output;
private JButton twelve_button;
public time timeConvert = new time();
int tHours;
int tMinutes;
private String[] times = {"AM", "PM"};
private JComboBox combo;
String tAMPM;
public window() {
super("Time Converter");
setLayout(new FlowLayout());
label = new JLabel("Time");
add(label);
hours = new JTextField(2);
add(hours);
label = new JLabel(":");
add(label);
minutes = new JTextField(2);
add(minutes);
combo = new JComboBox(times);
add(combo);
twelve_button = new JButton("Convert to 24 hours");
add(twelve_button);
output = new JTextField(10);
output.setEditable(false);
add(output);
label = new JLabel("It's my 'hello world' of java development!");
add(label);
label = new JLabel("by jackwilsdon");
add(label);
theHandler handler = new theHandler();
hours.addActionListener(handler);
minutes.addActionListener(handler);
twelve_button.addActionListener(handler);
}
private class theHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == twelve_button) {
if (hours.getText() != null && minutes.getText() != null) {
try {
tHours = Integer.parseInt(hours.getText());
tMinutes = Integer.parseInt(minutes.getText());
tAMPM = (String)combo.getSelectedItem();
timeConvert.setTime(tHours, tMinutes, tAMPM);
if (tHours > 12) {
output.setText("Please enter a 12 hour number!");
} else if (tMinutes > 60) {
output.setText("Please enter a 12 hour number!");
} else {
output.setText(timeConvert.to24h());
}
}
catch(NumberFormatException nFE) {
output.setText("Please enter a number!");
}
}
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>hours.getText() != null && minutes.getText() != null\n</code></pre>\n\n<p>You should also assert if the string is empty using method <code>hours.getText().isEmpty()</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T02:05:55.973",
"Id": "12630",
"ParentId": "12626",
"Score": "2"
}
},
{
"body": "<p>You asked about efficiency, which I am not an expert in. However, if you are going to share your code here, it would be nice if you could adapt it to the <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html\" rel=\"nofollow noreferrer\">Java code style conventions</a>.<br>\nIn short: you should use <a href=\"http://c2.com/cgi/wiki?PascalCase\" rel=\"nofollow noreferrer\">PascalCase</a> for your class names, so...</p>\n\n<ul>\n<li><code>Main.java</code> instead of <del>main.java</del></li>\n<li><code>Time.java</code> instead of <del>time.java</del></li>\n<li><code>Window.java</code> instead of <del>window.java</del></li>\n</ul>\n\n<p>Also, using single-letter names for your parameters is discouraged <em>(borderline</em> in the case of the fairly obvious <code>int h</code> and <code>int m</code>, <em>bad</em> in the case of <code>String t</code>). Why not <code>hours</code>, <code>minutes</code>, and <code>halfOfDaySuffix</code>? I'm sure you could find an even better term for the latter with a little research.</p>\n\n<p>If you haven't already, make sure you organize your code into one or more package(s), e.g. put <code>package com.jackwilsdon.TimeConversion;</code> at the beginning of your files. This helps avoid name clashing problems (for instance with <a href=\"http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/Time.html\" rel=\"nofollow noreferrer\"><code>java.sql.Time</code></a>).</p>\n\n<p>In regard to <code>to24h()</code>: <strong>Never</strong> compare two Strings with the <code>==</code> (reference equals) operator in Java. This will only work in a narrow range of scenarios, read the <a href=\"https://stackoverflow.com/questions/767372/java-string-equals-versus\">full explanation on StackOverflow</a>. You need to use the <a href=\"http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#equals%28java.lang.Object%29\" rel=\"nofollow noreferrer\"><code>String.equals</code></a> method instead.</p>\n\n<p>But while we are at it, you shouldn't be using a <code>String</code> to represent AM/PM anyway - it will stop working if you pass in the wrong string, for instance <code>pm</code> instead of <code>PM</code> by mistake. Instead, restrict the possible values by creating an <a href=\"http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html\" rel=\"nofollow noreferrer\"><code>Enum</code></a>:</p>\n\n<pre><code>public enum DayHalf {\n AM,\n PM\n}\n</code></pre>\n\n<p>Then (in <code>Window</code>), you can change <code>tAMPM</code>'s type from <code>String</code> to <code>DayHalf</code> - the following line will stop working:</p>\n\n<pre><code>tAMPM = (String)combo.getSelectedItem();\n</code></pre>\n\n<p>So you need to use <code>combo = new JComboBox(DayHalf.values());</code> instead of <code>combo = new JComboBox(times);</code> and change the above line to </p>\n\n<pre><code>tAMPM = (DayHalf)combo.getSelectedItem();\n</code></pre>\n\n<p>If you are passing in <code>AM</code> or <code>PM</code>, hours above <code>12</code> are not acceptable - neither are minutes above <code>59</code>! Hence, your conditions are erroneous; also, silently failing by setting the fields to <code>0</code> isn't a robust solution. You should throw an <code>IllegalArgumentException</code> if the values are out of range.</p>\n\n<p>Your updated <code>setTime</code> method would look something like this:</p>\n\n<pre><code>public void setTime(int hours, int minutes, DayHalf halfOfDaySuffix) {\n if (hours < 0 || hours > 12 || minutes < 0 || minutes > 59)\n throw new IllegalArgumentException(\"hours or minutes out of allowed range!\");\n hour = hours;\n minute = minutes;\n dayHalf = halfOfDaySuffix;\n}\n</code></pre>\n\n<p>Regarding your JFrame (<code>Window.java</code>, should probably be called <code>TimeConversionWindow.java</code>), you should adjust the obviously copied-and-pasted error message:</p>\n\n<pre><code>else if (tMinutes > 60) {\n output.setText(\"Please enter a 12 hour number!\");\n}\n</code></pre>\n\n<p>to \"Please enter less than 60 minutes!\" or similar. Note that your condition (<code>tMinutes > 60</code>) is incorrect once again and should be changed to <code>> 59</code>.</p>\n\n<p>A couple of other adjustments will be required, but they are easy to figure out. I'd argue that performance is nearly irrelevant in this scenario, read up on <a href=\"http://en.wikipedia.org/wiki/Bottleneck\" rel=\"nofollow noreferrer\">bottlenecks</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T18:56:08.610",
"Id": "45960",
"Score": "0",
"body": "There are many magic numbers like `0`, `12`, `59` this all should be `final` fields like `maxMinutesInHour` etc."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T18:09:58.827",
"Id": "12665",
"ParentId": "12626",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "12665",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T21:38:54.420",
"Id": "12626",
"Score": "1",
"Tags": [
"java",
"beginner",
"datetime",
"converting"
],
"Title": "Time converter in Java"
}
|
12626
|
<p>I have been using a slightly modified Hamming Distance algorithm for approximate String Matching for patterns and wondering if there is something better out there. The <em>t</em> being the length of the text and <em>p</em> being the length of the pattern the worst case is roughly O(t*p). Which from looking at other Fuzzy String matching seems to be in norm. </p>
<pre><code> final int mismatches = 1;
final String text = "bubbles";
final String pattern = "bu";
for(int iter = 0; iter < text.length() - pattern.length() + 1; iter++)
{
int missed = 0;
int ator = 0;
do
{
if(text.charAt(iter + ator) != pattern.charAt(ator))
{
missed++;
}
}while(++ator < pattern.length() && missed <= mismatches);
if(missed <= mismatches)
{
System.out.println("Index: " + iter + " Pattern: " + text.substring(iter, iter + pattern.length()));
}
}
</code></pre>
<p>The output being indexes 0 bu, 2 bb, and 3 bl. The last two being mismatches with the tolerance of 1.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T09:12:06.083",
"Id": "20364",
"Score": "0",
"body": "Please describe your slight modification: Hamming distance is only defined for equal-length strings."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T09:54:53.660",
"Id": "20367",
"Score": "0",
"body": "Furthermore, *what’s the question here?* If you just want your code reviewed – it looks good, there’s nothing obvious that I’d change, except obviously to put the functionality in its own method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T17:25:31.837",
"Id": "20372",
"Score": "0",
"body": "The modification is that it can work for Strings of different lengths. Sorry I did not put that much emphasis on the question. For this type of pattern matching with substations but not also insertions (like a Levenshtein Distance), is this code reasonable, is there something that could be changed, or is there a more appropriate algorithm?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T14:29:03.190",
"Id": "22068",
"Score": "0",
"body": "Looks like ['Save Humanity' Challenge](https://www.interviewstreet.com/challenges/dashboard/#problem/4f304a3d84b5e) and already answered [here](http://codereview.stackexchange.com/questions/13383/approximate-string-matching-interview-question/13388#13388)."
}
] |
[
{
"body": "<p>It looks fine. Some readability improvements:</p>\n\n<ol>\n<li><p>I'd rename some variables first:</p>\n\n<ul>\n<li><p><code>mismatches</code> should be <code>tolerance</code>, <code>mismatchTolerance</code> or <code>allowedMismatches</code>. For me <code>mismatches</code> sounds like a counter but it never changes which is confusing somehow.</p></li>\n<li><p><code>iter</code> and <code>ator</code> do not make the code easier to read. <code>textIndex</code> (maybe <code>searchIndex</code>) and <code>patternIndex</code> would be better since they are more meaningful and explains the purpose.</p></li>\n</ul></li>\n<li><p>Then extract out some named variables like</p>\n\n<ul>\n<li><code>final int textIndexMax = text.length() - pattern.length() + 1;</code></li>\n<li><code>final char textChar = text.charAt(textIndex + patternIndex);</code></li>\n<li><code>final char patternChar = pattern.charAt(patternIndex);</code></li>\n<li><code>final String match = text.substring(textIndex, textIndex + pattern.length());</code></li>\n</ul>\n\n<p>Reference: <em>Chapter 6. Composing Methods</em>, <em>Introduce Explaining Variable</em> in <em>Refactoring: Improving the Design of Existing Code</em> by Martin Fowler</p>\n\n<blockquote>\n <p>Put the result of the expression, or parts of the expression, \n in a temporary variable with a name that explains the purpose.</p>\n</blockquote></li>\n<li><p>The condition of the <code>do-while</code> loop could be rewritten as a usual (and a not so complex, therefore an easier to understand and less error-prone) <code>for (i = 0; i < x; i++)</code> loop and a <code>break</code> statement.</p></li>\n</ol>\n\n<p>Here is my version:</p>\n\n<pre><code>final int mismatchTolerance = 1;\nfinal String text = \"bubbles\";\nfinal String pattern = \"bu\";\n\nfinal int textIndexMax = text.length() - pattern.length() + 1;\nfor (int textIndex = 0; textIndex < textIndexMax; textIndex++) {\n int missed = 0;\n\n for (int patternIndex = 0; patternIndex < pattern.length(); patternIndex++) {\n final char textChar = text.charAt(textIndex + patternIndex);\n final char patternChar = pattern.charAt(patternIndex);\n if (textChar != patternChar) {\n missed++;\n }\n if (missed > mismatchTolerance) {\n break;\n }\n }\n\n if (missed <= mismatchTolerance) {\n final String match = text.substring(textIndex, textIndex + pattern.length());\n System.out.println(\"Index: \" + textIndex + \" Match: \" + match);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-29T15:54:22.727",
"Id": "13196",
"ParentId": "12632",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T06:08:30.930",
"Id": "12632",
"Score": "2",
"Tags": [
"java",
"strings"
],
"Title": "Pattern Matching with Mismatch"
}
|
12632
|
<p>I created my first Ruby program. Even though it works, I wondered whether I could do something different/better?</p>
<pre><code>#!/usr/bin/ruby
class LuhnyBinChecker
def initialize(number)
@number = number
end
def check
createNumberArray
doubleSecond
sumNumbers
getResult
end
def createNumberArray
@numberArray = @number.scan(/\d/).map { |c| c.to_i }
end
def doubleSecond
puts "Checker: doubling every second number from the right.."
i = @numberArray.length - 1
pos = 0
while i >= 0
if pos.modulo(2) == 1
@numberArray[i] = @numberArray[i] * 2
end
i = i - 1
pos = pos + 1
end
end
def sumNumbers
puts "Checker: calculating the sum.."
@sum = 0
@numberArray.each do |i|
if i > 9
@sum = @sum + splittedSum(i) # treat numbers >= 10 individually
# e.g. 12 -> 1 + 2 = 3
else
@sum = @sum + i
end
end
end
def splittedSum(number)
numberAsString = number.to_s()
splittedNumbers = numberAsString.scan(/\d/).map { |c| c.to_i }
splittedSum = 0
splittedNumbers.each do |n|
splittedSum = splittedSum + n
end
return splittedSum
end
def getResult
if @sum.modulo(10) == 0
puts "Credit card number is valid"
else
puts "Credit card number is not valid"
end
end
end
class CreditCard
def setCardNumber(number)
@cardNumber = number
end
def getCardNumber
if @cardNumber!= nil
@cardNumber
end
end
def verify
puts "Verifying card number now..."
checker = LuhnyBinChecker.new(@cardNumber)
checker.check
end
end
if __FILE__ == $0
card = CreditCard.new
puts "Please enter the credit card number to check:"
gets # input card number
input = $_
if input.match(/[a-z]/i) != nil || input.match(/\d/) == nil
puts "Please enter only numbers."
exit
end
card.setCardNumber(input)
puts "You entered: " + card.getCardNumber
card.verify
end
</code></pre>
<p><b>Edit:</b> here are two input/output examples:</p>
<pre>michael@michael-linlap /media/Data/development/private/scripts $ ruby LuhnyBin.rb
Please enter the credit card number to check:
1111 1111 1111 1111 1111
You entered: 1111 1111 1111 1111 1111
Verifying card number now...
Checker: doubling every second number from the right..
Checker: calculating the sum..
Credit card number is valid</pre>
<pre>michael@michael-linlap /media/Data/development/private/scripts $ ruby LuhnyBin.rb
Please enter the credit card number to check:
fooobar1111
Please enter only numbers.</pre>
|
[] |
[
{
"body": "<p>Welcome to ruby :), here are a few changes you might want to consider.</p>\n\n<pre><code>#!/usr/bin/ruby\n\nclass LuhnyBinChecker\n\n def initialize(number)\n @number = number\n end\n</code></pre>\n\n<p>Try to keep your methods pure without i/o, and collect the i/o in some portion that is dedicated to it. It helps later while you refactor the code. It is also nicer to not to rely on member variables too much, and preserve the referential transparency of functions where possible.</p>\n\n<pre><code> def check\n arr = digits(@number)\n puts \"Checker: doubling every second number from the right..\"\n arr = doubleSecond(arr)\n puts \"Checker: calculating the sum..\"\n getResult(sumNumbers(arr))\n end\n</code></pre>\n\n<p>Always be on the lookout for things you can refactor and reuse.</p>\n\n<pre><code> def digits(n)\n n.to_s().scan(/\\d/).map{ |c| c.to_i }\n end\n</code></pre>\n\n<p>Two ways of doing the doubleSecond, I prefer the second way, and I think that is a more ruby way. But as a beginner, you might understand the first better. Choose which ever you like.</p>\n\n<pre><code> def doubleSecond(arr)\n #arr.each_with_index do |item, i|\n # arr[i] = arr[i] * 2 if (i %2 == 0)\n #end\n arr.zip((1..@number.length).to_a()).map do |e|\n e[1] * ((e[0] % 2) + 1)\n end\n end\n\n # treat numbers >= 10 individually \n # e.g. 12 -> 1 + 2 = 3\n def sumNumbers(arr)\n arr.map{|i|\n i > 9 ? splittedSum(i) : i\n }.inject(0,:+)\n end\n</code></pre>\n\n<p>You can think of <code>Array.inject(0,:+)</code> as <code>Array.sum()</code></p>\n\n<pre><code> def splittedSum(number)\n digits(number).inject(0,:+)\n end\n\n def getResult(sum)\n sum.modulo(10) == 0\n end\nend\n</code></pre>\n\n<p>It is nicer to have a guarantee that a CreditCard will always contain a number rather than to check for nil in the getter method.</p>\n\n<pre><code>class CreditCard\n attr_reader :number\n def initialize(number)\n @number = number\n end\n\n def verify\n (LuhnyBinChecker.new(@number)).check\n end\nend\n</code></pre>\n\n<p>You can use abort if some conditions fail to satisfy.</p>\n\n<pre><code>if __FILE__ == $0\n puts \"Please enter the credit card number to check:\"\n input = gets() # input card number\n abort \"Please enter only numbers.\" if input !~/(\\d+\\s)+/\n card = CreditCard.new(input)\n puts \"You entered: \" + card.number\n puts \"Verifying card number now...\"\n if card.verify()\n puts \"Credit card number is valid\"\n else\n puts \"Credit card number is valid\"\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T14:11:22.200",
"Id": "20411",
"Score": "0",
"body": "actually, your scan function doesn't work.. `LuhnyBin.rb:17:in `digits': private method `scan' called for 54737527746:Fixnum (NoMethodError)` .. how can I fix that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T17:56:43.290",
"Id": "20421",
"Score": "0",
"body": "Updated. the digits should convert its input to string before scanning (as in your numberAsString)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T19:58:10.907",
"Id": "20433",
"Score": "0",
"body": "Converting the numbers to a String before scanning works. Thanks :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T16:37:59.517",
"Id": "12637",
"ParentId": "12634",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "12637",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T14:10:47.170",
"Id": "12634",
"Score": "2",
"Tags": [
"ruby"
],
"Title": "LuhnyBin - my first Ruby script"
}
|
12634
|
<p>My web application is simply supposed to take a search query, run a script on it that returns product information and then post it in an "endless" fashion on a web page, making one page with no pagination that is "infinitely" scrollable.</p>
<p>The web scraper I use, called Fletcher, which helps return usable results is slow to fetch each product matching the query. But, as soon as it returns information, I want to update my web page without refreshing it.</p>
<p>I'm thinking of the best way to do this so I don't have to refresh the page, but I don't know exactly where to start. I've had Ajax recommended and I find Backbone.js intriguing, but, really, I know I can do this with Erb, Ruby, Rails, and not too much else.</p>
<p>Please take a look at what I have. Any kind of code review at all will be helpful.</p>
<p><a href="https://gist.github.com/bfd1dad329d446a35da4" rel="nofollow noreferrer">GitHub</a></p>
<p>Application Controller:</p>
<pre><code>class ApplicationController < ActionController::Base
# before_filter :authorize
protect_from_forgery
private
def current_cart
Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create
session[:cart_id] = cart.id
cart
end
protected
require 'open-uri'
def authorize
unless User.find_by_id(session[:user_id])
redirect_to login_url, notice: "Please log in"
end
end
def nokoSearch (keywords, vendor)
# def available (info)
# if (info!=nil)
# else
# info = ""
# end
# end
@product_links = Array.new
@name = ""
@description = ""
@image = ""
@price = ""
keywords = keywords.split(' ').join('+')
noko_links = Array.new
base_url = "http://www.amazon.com/s/url=search-alias%3Daps"
keyword_url = base_url + "&field-keywords=" + keywords
page = Nokogiri::HTML(open(keyword_url))
@product_links = page.css("a").select{|link| link['class'] == "title"}
@product_links.compact! # get rid of nils
@product_links.each do |link|
fletchedProduct = Fletcher.fetch link['href']
@name = fletchedProduct.name
@description = fletchedProduct.description
if (fletchedProduct.image != nil)
@image = fletchedProduct.image[:src]
end
@price = fletchedProduct.prices
InfiniteProduct.create(:name => @name, :description => @description, :image => @image, :price => @price)
end
end
end
</code></pre>
<p>index.html.erb for the view:</p>
<pre><code><% @infinite_products.each do |infinite_product| %>
<li class="span3">
<div class="thumbnail">
<%= image_tag(infinite_product.image) %>
<div class="caption">
<h5><%= sanitize(infinite_product.name) %></h5>
<p><%= sanitize(infinite_product.description) %></p>
<p><a class="btn primary details" href="#" rel="ajax/1.html"><i class="icon-zoom-in"></i></a> <a class="btn addto" href="#" rel="1">Add to <i class="icon-shopping-cart"></i></a> <span class="label label-info price"><%= infinite_product.price %></span></p>
</div>
</div>
</li>
<% end %>
</code></pre>
<p>Controller:</p>
<pre><code>class InfiniteProductsController < ApplicationController
# GET /infinite_products
# GET /infinite_products.json
def index
#nokoSearch("batman", "amazon")
@infinite_products = InfiniteProduct.order(:name)
respond_to do |format|
format.html # index.html.erb
format.json { render json: @infinite_products }
end
end
# GET /infinite_products/1
# GET /infinite_products/1.json
def show
@infinite_product = InfiniteProduct.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @infinite_product }
end
end
# GET /infinite_products/new
# GET /infinite_products/new.json
def new
@infinite_product = InfiniteProduct.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @infinite_product }
end
end
# GET /infinite_products/1/edit
def edit
@infinite_product = InfiniteProduct.find(params[:id])
end
# POST /infinite_products
# POST /infinite_products.json
def create
@infinite_product = InfiniteProduct.new(params[:infinite_product])
respond_to do |format|
if @infinite_product.save
format.html { redirect_to @infinite_product, notice: 'Infinite product was successfully created.' }
format.json { render json: @infinite_product, status: :created, location: @infinite_product }
else
format.html { render action: "new" }
format.json { render json: @infinite_product.errors, status: :unprocessable_entity }
end
end
end
# PUT /infinite_products/1
# PUT /infinite_products/1.json
def update
@infinite_product = InfiniteProduct.find(params[:id])
respond_to do |format|
if @infinite_product.update_attributes(params[:infinite_product])
format.html { redirect_to @infinite_product, notice: 'Infinite product was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @infinite_product.errors, status: :unprocessable_entity }
end
end
end
# DELETE /infinite_products/1
# DELETE /infinite_products/1.json
def destroy
@infinite_product = InfiniteProduct.find(params[:id])
@infinite_product.destroy
respond_to do |format|
format.html { redirect_to infinite_products_url }
format.json { head :no_content }
end
end
end
</code></pre>
|
[] |
[
{
"body": "<p>You can't do this without javascript because Rails is a server side language while you should work client side where the language to be used is Javascript.</p>\n\n<p>Basically you should:</p>\n\n<p>1-)Know when an user is near to the bottom of the page</p>\n\n<p>2-)Send an ajax request to the url that returns informations (in json format so it will have to load a lot less data and will be easier to parse the result)</p>\n\n<p>3-)Manipulate the DOM adding the new result returned by the ajax function.</p>\n\n<p>Here there are some plugins in jQuery (a library written in javascript)\n<a href=\"http://www.jquery4u.com/tutorials/jquery-infinite-scrolling-demos/#.T-NgN7R1Aak\" rel=\"nofollow\">http://www.jquery4u.com/tutorials/jquery-infinite-scrolling-demos/#.T-NgN7R1Aak</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T18:14:19.610",
"Id": "20791",
"Score": "0",
"body": "Thanks for taking the time to answer Matteo. Do you know how to use the form_tag and text_field_tag helpers in a .html.erb file to send an ajax GET request to a url and use the text_field's contents as params?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T21:58:28.363",
"Id": "20810",
"Score": "0",
"body": "i don't think using rails method is the best way since they'll only create some javascript code, anyway i think that there's an attribute :remote to use ajax in forms while i advise you to use directly jquery"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T21:59:05.023",
"Id": "20811",
"Score": "0",
"body": "really it should be quite simple using one of the jquery code i've posted to you"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T17:59:56.073",
"Id": "12896",
"ParentId": "12635",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T15:15:09.413",
"Id": "12635",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails",
"web-scraping",
"pagination"
],
"Title": "Infinitely scrolling display of web-scraped search results"
}
|
12635
|
<p>I have been writing a small extension to the <a href="http://www.google.com/recaptcha" rel="nofollow">reCaptcha library</a>.</p>
<pre><code>class Captcha
{
private $config;
public $error;
public function __construct(array $config)
{
include './library/recaptchalib.php';
$this->config = $config;
}
public function render($error = null, $use_ssl = false)
{
return recaptcha_get_html($this->config['recaptcha']['public_key'],
$error, $use_ssl);
}
public function check()
{
$resp = recaptcha_check_answer ($this->config['recaptcha']['private_key'],
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
$this->error = $resp->error;
return false;
}
}
}
</code></pre>
<p>What do you think? Is it anything to have? Anything I can improve/change?</p>
|
[] |
[
{
"body": "<ol>\n<li><p>The <code>$error</code> field should be <code>private</code> (<a href=\"https://stackoverflow.com/questions/1568091/why-use-getters-and-setters\">Why use getters and setters?</a>). Currently users of the <code>Captcha</code> class can modify the value of the <code>$error</code> field directly which. It's not a good idea to allow them to do this.</p></li>\n<li><p>What's the point of returning with <code>false</code> in the <code>check</code> function when the response is not valid while if it's valid the function does not return with <code>true</code>?</p></li>\n<li><p>The <code>render</code> and <code>check</code> functions seems somehow temporarily coupled. See: <em>Clean Code (by Robert C. Martin), G31: Hidden Temporal Couplings</em></p>\n\n<p>References:</p>\n\n<ul>\n<li><em>Effective Java Second Edition, Item 38: Check parameters for validity</em> (I know that this is a Java book but this chapter applicable to PHP too.)</li>\n<li><a href=\"https://stackoverflow.com/questions/3393616/function-method-argument-validation-standards\">Function/method argument validation standards</a></li>\n</ul></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T10:31:38.887",
"Id": "20408",
"Score": "0",
"body": "1. True\n2. if (!$captcha->check()) { } Will only be executed If the captcha isn't correctly entered, thus If I enter a correct code, it would not be FALSE = thus the condition wouldn't be executed, I am quite sure it's opposite way, but for more convenience I'll add the return true at the bottom. \n3. Where can I find that reference?\n4. Sure. But what exactly do I need to validate?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T16:36:31.277",
"Id": "20523",
"Score": "0",
"body": "3. It's a book, I don't know any online resource for that but here is similar article: [Temporal Coupling in Java and Some Solutions](http://hamletdarcy.blogspot.hu/2008/09/temporal-coupling-in-java-and-some.html)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T16:59:07.690",
"Id": "20526",
"Score": "0",
"body": "@josmith: I've removed the 4th issue from the answer because I missed the `array` keyword. Sorry for the inconvenience."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-07T18:13:21.490",
"Id": "113344",
"Score": "1",
"body": "+1 just for the reference to \"Clean Code\". That book is worth a read for sure."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T18:08:47.543",
"Id": "12638",
"ParentId": "12636",
"Score": "3"
}
},
{
"body": "<p><strong>include</strong></p>\n\n<p>Every time an object is created the recaptcha stuff is included. This means that if you try to make two objects, you're going to get some very nasty function already defined errors. include the recaptcha stuff at a file level instead of in the constructor. Also, consider using require_once. <code>require</code> because the file is required, and <code>once</code> because you have no way of knowing if it's already been included by any other code (though avoiding *_once is sometimes a good idea).</p>\n\n<p><strong>check()</strong></p>\n\n<p>Pass in the parameters instead of coupling the class to POST.</p>\n\n<p>What if you want the fields to be named something else? What if by some weird chance you want to do it on an arbitrary array instead of $_POST? I would probably even take in the <code>$_SERVER['REMOTE_ADDR']</code> just for completeness.</p>\n\n<p><strong>Never assume user input exists</strong></p>\n\n<p>I'm too lazy to explain it for the 3rd time in 2 days, so read the last section of <a href=\"https://codereview.stackexchange.com/questions/12647/php-dynamic-insert-mysql-is-there-a-better-way-than-this/12649#12649\">this</a>.</p>\n\n<p><strong>Don't bother with the config array</strong></p>\n\n<p>It's a lot more transparent if you just take in what you need explicitly. If you do end up taking in an array, then do like palacsint said and validate it.</p>\n\n<p><strong>Suggested design</strong></p>\n\n<p>By no means am I saying that this is perfect; this is just the approach I would most likely take.</p>\n\n<pre><code><?php\n\n//Having it in the include path means you don't have to depend on the library folder being in the right place\n//(it can, however, mean more disk IO)\nrequire_once 'recaptchalib.php';\n\nclass Captcha\n{\n\n private $_publicKey;\n private $_privateKey;\n private $_ssl;\n\n private $_error = null;\n\n //(it's just a habit of mine to use $_ for private/protected)\n\n public function __construct($publicKey, $privateKey, $ssl = false)\n {\n $this->_publicKey = $publicKey;\n $this->_privateKey = $privateKey;\n }\n\n public function render()\n {\n return recaptcha_get_html($this->_publicKey, $this->_error, $this->_ssl);\n }\n\n public function check($challenge, $response, $ipAddr = null)\n {\n\n if ($ipAddr === null) {\n $ipAddr = $_SERVER['REMOTE_ADDR'];\n }\n\n $resp = recaptcha_check_answer ($this->_privateKey, $ipAddr, $challenge, $response);\n\n if (!$resp->is_valid) {\n $this->_error = $resp->error;\n return false;\n }\n\n return true;\n\n }\n\n public function getError()\n {\n return $this->_error;\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T10:36:35.710",
"Id": "20409",
"Score": "0",
"body": "Include: How about If I Include the File somewhere else and not in the class like in a bootstrap file?\ncheck() - I guess so, but I'd make the OPTIONAL parameters, agreed?\nI'll have a look over the user input...\nHow should I validate the config array?\nSuggested design: Thanks for your contribution, I'll make some changes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T10:58:01.260",
"Id": "20410",
"Score": "0",
"body": "Added a snippet on validation, the question is How much validation do I need to do? Have a look on updated question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T18:22:37.020",
"Id": "20422",
"Score": "0",
"body": "@josmith It's fine to include the file elsewhere, as long as you can be certain that the code has been loaded by the time the check or render methods are called. As for the check params, I would probably leave them non-optional. I like to separate objects from their data source. Leaving the extraction from post outside of the object makes it much more explicit. And, it seems more logical to group that data extraction with the rest of your data extraction."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T18:23:14.010",
"Id": "20423",
"Score": "0",
"body": "Also, leaving anything $_POST related outside of the class creates a better, less coupled class, but allowing for defaults would certainly allow easier use of the object, and ease of use is part of design after all. (Have to go at the moment, but will address validation later -- the short answer is that you need to be 100% certain that the object is in a usable state.)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T06:34:24.453",
"Id": "12651",
"ParentId": "12636",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T15:32:33.980",
"Id": "12636",
"Score": "3",
"Tags": [
"php",
"object-oriented",
"captcha"
],
"Title": "A small extension to the reCaptcha library"
}
|
12636
|
<p>I am wondering if anyone has any ideas for improving the following. Personally I am 'happy' with it, apart from the first <code>for</code> loop. I was thinking of another way of writing this, but perhaps it is ok.</p>
<pre><code>def findnodepaths(nodepaths, graph, *nodes):
# nodepaths == list()
# graph == defaultdict(set)
# *nodes == 'foo','bar',... possible items in the graph
nodeset = set(nodes) & set(graph.keys())
# nodeset == nodes that are in the graph ... avoids try / if
nodepaths = [(nodeA,weight,nodeB) for nodeA in nodeset for (nodeB,weight) in graph[nodeA]]
for path in nodepaths:
# for every item in list
*xs, nodeA = path
# nodeA == last value added, xs == all the rest
for (nodeB,weight) in graph[nodeA]:
# search again ... just like we all ready have
if nodeB not in xs:
# if new val not in the triple / quadruple ...
nodepaths.append( path + (weight,nodeB) )
# add new item to list based on its match
# repeat until no new paths can be found
return nodeset, nodepaths
# return nodes that were found + all of their paths
</code></pre>
|
[] |
[
{
"body": "<p>I have no way to test this, but is this what you are looking for?</p>\n\n<pre><code>def findnodepaths(nodepaths, graph, *nodes):\n\n nodeset = set(nodes) & set(graph.keys())\n nodepaths = [(nodeA,weight,nodeB) for nodeA in nodeset\n for (nodeB,weight) in graph[nodeA]]\n\n newnp = [path + (weight,nodeB) for path in nodepaths\n for (nodeB,weight) in graph[nodeA] if nodeB not in path[::-1][1:]]\n\n return nodeset, (nodepaths + newnp)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T00:24:05.210",
"Id": "20383",
"Score": "0",
"body": "Very nearly. The for loop that I use `for path in nodepaths` effectively creates a loop, that constantly updates the `nodepaths` until it can not find any more links in the graph (a dictionary). I was wondering how if this for loop could be written any other way?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T23:38:43.587",
"Id": "12644",
"ParentId": "12641",
"Score": "0"
}
},
{
"body": "<pre><code>def findnodepaths(nodepaths, graph, *nodes):\n</code></pre>\n\n<p>By python convention, you should really separate the words with underscores. i.e. <code>find_node_paths</code>. I'd also wonder if it makes sense to take *nodes, rather then expecting a list to be sent in. </p>\n\n<pre><code># nodepaths == list()\n</code></pre>\n\n<p>Its not clear why you pass this in, rather then just make it here</p>\n\n<pre><code># graph == defaultdict(set)\n# *nodes == 'foo','bar',... possible items in the graph\n</code></pre>\n\n<p>This sort of documentation should be in a doctoring, not comments</p>\n\n<pre><code> nodeset = set(nodes) & set(graph.keys())\n</code></pre>\n\n<p><code>set(graph.keys()) == set(graph)</code>, although you may prefer to be explicit. </p>\n\n<pre><code># nodeset == nodes that are in the graph ... avoids try / if \n\n nodepaths = [(nodeA,weight,nodeB) for nodeA in nodeset for (nodeB,weight) in graph[nodeA]]\n</code></pre>\n\n<p>I'd store a path as a list, not a tuple. </p>\n\n<pre><code> for path in nodepaths:\n# for every item in list\n</code></pre>\n\n<p>That's not a very helpful comment, the syntax already told me that.</p>\n\n<pre><code> *xs, nodeA = path\n# nodeA == last value added, xs == all the rest\n</code></pre>\n\n<p>consider renaming your variable rather then using comments</p>\n\n<pre><code> for (nodeB,weight) in graph[nodeA]:\n</code></pre>\n\n<p>Parens are unnecessary</p>\n\n<pre><code># search again ... just like we all ready have\n</code></pre>\n\n<p>Again, noisy comment</p>\n\n<pre><code> if nodeB not in xs:\n# if new val not in the triple / quadruple ...\n nodepaths.append( path + (weight,nodeB) )\n</code></pre>\n\n<p>You shouldn't be modifying lists currently having a for loop operating on them. Its considered bad style</p>\n\n<pre><code># add new item to list based on its match\n# repeat until no new paths can be found\n\n return nodeset, nodepaths\n# return nodes that were found + all of their paths\n</code></pre>\n\n<p>I'd write this as a recursive function:</p>\n\n<pre><code>def _findnodepaths(graph, path, weights):\n for node, weight in graph[path[-1]]:\n if node not in path:\n yield _findnodepaths(graph, path + [node], weights + [node])\n yield path\n\ndef findnodepaths(graph, nodes):\n nodeset = set(nodes) & set(graph)\n subgraph = dict( (key, value) for key, value in graph.items())\n\n nodepaths = []\n for key in graph:\n nodepaths.extend(_findnodepaths(subgraph, [key], [])\n return nodeset, node paths\n</code></pre>\n\n<p>Whether that's better or not is subjective, I think it shows the algorithm better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T00:55:06.767",
"Id": "20384",
"Score": "0",
"body": "thanks for the break down. I must admit the documentation was only for this site. I'm interested in your comment about modifying lists while working on them. That part made me happy :) ... is it a purely stylistic guide? Agree about the list being passed in. I have changed that already. Thank you for the re-write. It is fascinating seeing how others would approach a problem. Algorithm wise, does it seem ok though?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T01:16:16.577",
"Id": "20385",
"Score": "0",
"body": "one question: why are you creating a subgraph? if the graph contains 1000 keys, this is a bit pointless no? am i missing something?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T01:36:04.050",
"Id": "20386",
"Score": "0",
"body": "@user969617, adding to the list works in the current implementation, but I believe no guarantees are made that it will always work. I figured the subgraph might simplify the code a bit, but it didn't really work out that way."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T00:24:26.433",
"Id": "12645",
"ParentId": "12641",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "12645",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T20:40:44.093",
"Id": "12641",
"Score": "1",
"Tags": [
"python",
"pathfinding"
],
"Title": "Finding node paths"
}
|
12641
|
<p>I would appreciate some quick comments on this basic mergesort code.
Am I missing a big block in the langage?</p>
<h2>First solution</h2>
<pre><code>open System
open System.Windows
open System.Collections.Generic
let shuffle (l:'a array) =
let ileft = LinkedList<int>(seq { 0 .. (l.Length - 1)})
let rec pick (ar:'a array) r =
match ileft.Count with | 0 -> r
| n -> let ik = ileft |> Seq.nth (rnd.Next(n))
ileft.Remove(ik) |> ignore
pick ar (ar.[ik]::r)
pick l []
let rec merge (ar1:'a array) (ar2:'a array) =
let rec index (islastfromAr1, ilast, jlast) = seq {
let inext, jnext = ilast + 1, jlast + 1
match inext < ar1.Length, jnext < ar2.Length with
| true , true -> let indexnext = if ar1.[inext] < ar2.[jnext] then
(true, inext, jlast)
else
(false, ilast, jnext)
yield Some(indexnext)
yield! index indexnext
| false, true -> let indexnext = (false, ilast, jnext)
yield Some(indexnext)
yield! index indexnext
| true , false -> let indexnext = (true, inext, jlast)
yield Some(indexnext)
yield! index indexnext
| false, false -> yield None
}
let mergeindex = index (false, -1, -1)
[for (formar1, i,j) in mergeindex |> Seq.choose (id) -> if formar1 then ar1.[i] else ar2.[j] ]
and mergesort = function
| [| |] -> [||]
| [|a|] -> [|a|]
| ar -> let ar1 = ar.[0 .. ar.Length / 2 - 1]
let ar2 = ar.[ar.Length / 2 .. ar.Length - 1]
merge (mergesort ar1) (mergesort ar2) |> List.toArray
let testval = ( [|1 .. 100|] |> shuffle |> List.toArray)
let test4 = mergesort testval
</code></pre>
<h2>Second solution</h2>
<p>a shorter, mutable state version of it</p>
<pre><code>let rec mergemutable (ar1:'a array) (ar2:'a array) =
let inext, jnext = ref 0 , ref 0
[ for k in [1 .. (ar1.Length + ar2.Length)] ->
match !inext < ar1.Length, !jnext < ar2.Length with
| true , true -> if ar1.[!inext] < ar2.[!jnext] then
inext := !inext + 1
ar1.[!inext - 1]
else
jnext := !jnext + 1
ar2.[!jnext - 1]
| false, true -> jnext := !jnext + 1
ar2.[!jnext - 1]
| true , false -> inext := !inext + 1
ar1.[!inext - 1 ]
| _ -> failwith "should not happen"
]
and mergesortmutable = function
| [| |] -> [||]
| [|a|] -> [|a|]
| ar -> let ar1 = ar.[0 .. ar.Length / 2 - 1]
let ar2 = ar.[ar.Length / 2 .. ar.Length - 1]
(mergemutable (mergesortmutable ar1) (mergesortmutable ar2) ) |> List.toArray
let testmutable = mergesortmutable ( [|1 .. 100|] |> shuffle |> List.toArray)
</code></pre>
<p>It is much faster.</p>
<h2>Third solution</h2>
<p>Another one with no extraneous allocations</p>
<pre><code>let mergesortmutable2 ar =
let mutable sarlast = ref (Array.copy ar)
let mutable sarcurr = ref (Array.copy ar)
let rec mergemutable (sarcurr:'a array ref) (sarlast:'a array ref) s (s1,e1) (s2,e2) =
let mutable inext, jnext = s1 , s2
for k in [1 .. ((e1-s1+1) + (e2-s2+1)) ] do
match inext <= e1, jnext <= e2 with
| true , true -> if (!sarlast).[inext] < (!sarlast).[jnext] then
(!sarcurr).[(s+(k-1))] <- (!sarlast).[inext]
inext <- inext + 1
else
(!sarcurr).[(s+(k-1))] <- (!sarlast).[jnext]
jnext <- jnext + 1
| false, true -> (!sarcurr).[(s+(k-1))] <- (!sarlast).[jnext]
jnext <- jnext + 1
| true , false -> (!sarcurr).[(s+(k-1))] <- (!sarlast).[inext]
inext <- inext + 1
| _ -> failwith "should not happen"
(s1,e2)
and mergesortmutable (sarcurr:'a array ref) (sarlast:'a array ref) (s,e) =
match s, e with
| s, e when s >= e -> s,e
| _ -> let m = (e-s+1) / 2
let ar1 = (mergesortmutable sarlast sarcurr (s, s + m - 1))
let ar2 = (mergesortmutable sarlast sarcurr (s + m, e))
let ret = mergemutable sarcurr sarlast s ar1 ar2
ret
do mergesortmutable sarcurr sarlast (0, ar.Length - 1) |> ignore
!sarcurr
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T05:00:26.343",
"Id": "20393",
"Score": "1",
"body": "I'd put the code that does the split in a separate function. Though something about your merge code rubs me the wrong way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T07:36:50.180",
"Id": "20400",
"Score": "0",
"body": "i also wonder if that is not the kind of stuff where one should use mutable variable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T08:05:47.687",
"Id": "20469",
"Score": "1",
"body": "the array being a ref type already, no need to enclose it in a ref"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T15:19:32.727",
"Id": "20506",
"Score": "2",
"body": "Have you googled \"f# merge sort\"? [Here](http://fdatamining.blogspot.com/2010/03/test.html) is a particularly good one."
}
] |
[
{
"body": "<p>I'm just learning F# myself, but here is what I currently notice:</p>\n\n<ol>\n<li><p>Your <code>merge</code> function is very large. It should be split into multiple small functions that are responsible for a single action.</p></li>\n<li><p><code>match</code> is preferred to <code>if</code>:</p></li>\n</ol>\n\n<blockquote>\n<pre><code>if ar1.[inext] < ar2.[jnext] then\n (true, inext, jlast)\nelse\n (false, ilast, jnext)\n</code></pre>\n</blockquote>\n\n<p>can be written as:</p>\n\n<pre><code>match ar1.[inext] with\n| i when i < ar2.[jnext] -> (true, inext, jlast)\n| _ -> (false, ilast, jnext)\n</code></pre>\n\n<ol start=\"3\">\n<li><code>islastfromAr1</code> is never used. This parameter can probably be removed.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-16T16:41:19.433",
"Id": "150085",
"ParentId": "12643",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T21:32:28.800",
"Id": "12643",
"Score": "4",
"Tags": [
"sorting",
"comparative-review",
"f#",
"mergesort"
],
"Title": "Three implementations of mergesort in F#"
}
|
12643
|
<p>I've just completed a JavaScript module and I've got a strong feeling that this is borderline spaghetti code. My task was to build a tagging form which adds selected tags to hidden outputs to be sent to a server.</p>
<pre><code>var tags = [];
var createdTags;
var addedTags = [];
var isNewTag, selectedTag, i;
$("#created-tags").attr("value", "[]");
$.ajax({
type: "GET",
cache: false,
dataType: 'json',
url: "/portal/index.php/movies/get_tags",
success:
function(response) {
$("#tags-typealong").autocomplete({
source: response,
minLength: 1,
select: function (event, ui) {
event.preventDefault();
selectedTag = ui.item;
//tags = current tags
tags = $.parseJSON($('#tags').attr('value'));
isNewTag = true;
//is tag already added?
for(i = 0; i < tags.length; i++) {
if(selectedTag.id == tags[i].id)
isNewTag = false;
}
//update addedTags if new
if(isNewTag) {
tags.push(selectedTag);
addedTags.push(selectedTag.id);
add_tag_render(selectedTag.name);
}
//update dom for tag_form.js
$("#tags").attr("value", JSON.stringify(tags));
$("#added-tags").attr("value", JSON.stringify(addedTags));
$("#tags-typealong").val('');
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $("<li></li>")
.data( "item.autocomplete", item )
.append( '<a>' + item.name + '</a>' )
.appendTo(ul);
}
}
});
$("#tags-typealong").keyup(function (event) {
var isNew = true;
if(event.keyCode == 32) {
//get updated tag selections
var tagName = $(this).val();
tagName = tagName.slice(0, -1);
createdTags = $.parseJSON($('#created-tags').attr('value'));
tags = $.parseJSON($('#tags').attr('value'));
//check tags from db
for(i = 0; i < tags.length; i++) {
if(tags[i].name == tagName)
isNew = false;
}
//check existing created tags
for(i = 0; i < createdTags.length; i++) {
if(createdTags[i] == tagName)
isNew = false;
}
if(isNew) {
add_tag_render(tagName);
createdTags.push(tagName);
$("#created-tags").attr("value", JSON.stringify(createdTags));
}
$("#tags-typealong").val('');
//TODO!
//is tagname in db already?
}
});
function add_tag_render(tagName) {
$(".tag-container").append('<div class="selected-tag"><div class="selected-tag-name">' + tagName + '</div><div class="remove-tag"></div></div>');
$("#tags-typealong").appendTo(".tag-container");
$("#tags-typealong").focus();
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><code>.attr('value')</code> is bad. Always. You should use <code>.val()</code> instead.</li>\n<li><code>var i;</code> can go into the callback function instead of whatever scope you are in at the very beginning.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T09:15:52.083",
"Id": "20401",
"Score": "0",
"body": "It's not leaking a global `i` since its declared at the top with the other `var` statements."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T09:17:52.173",
"Id": "20402",
"Score": "0",
"body": "Ah, indeed. Well, it should be inside the callback function - no need to put it in a broader scope than necessary. Especially since the outermost scope in his code might very well be the global scope."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T09:28:20.457",
"Id": "20404",
"Score": "0",
"body": "That's true, although that `i` is being used in both the AJAX callback and the `keyup` event callback. A new `i` could be declared in each scope, but I think for this code it's not too bad."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T09:04:49.480",
"Id": "12654",
"ParentId": "12646",
"Score": "2"
}
},
{
"body": "<p>On the whole I don't think there's anything I would have done very differently. However, there are numerous ways your existing code can be improved (but not restructured, so I'm only going to talk about your code in its current form).</p>\n\n<p>So let's start right at the beginning:</p>\n\n<pre><code>var tags = [];\nvar createdTags;\nvar addedTags = [];\nvar isNewTag, selectedTag, i;\n</code></pre>\n\n<p>The first thing that leaps out at me is the mixed style. Not a problem, but it would probably be sensible to stick to one. I (and <a href=\"http://www.jslint.com/\" rel=\"nofollow\">JSLint</a>) prefer the style of \"one <code>var</code> statement per scope\". The next thing I notice is that <code>tags</code> is assigned a value later on, so there is no point assigning it a value here. To sum up that paragraph in code:</p>\n\n<pre><code>var tags,\n createdTags,\n addedTags = [],\n isNewTag, \n selectedTag,\n i;\n</code></pre>\n\n<p>On the next line you set the value of what is presumably an <code>input</code> element. The <code>val</code> method was designed specifically for that, so should probably be used here (and in the numerous other places you use <code>attr</code>):</p>\n\n<pre><code>$(\"#created-tags\").val(\"[]\");\n</code></pre>\n\n<p>The next line is your call to <code>ajax</code>. This can be shortened considerably because there is a jQuery method, <a href=\"http://api.jquery.com/jQuery.getJSON/\" rel=\"nofollow\">getJSON</a>, that behaves exactly the same as your <code>ajax</code> call (<em>update</em> - as pointed out in the comments, this isn't quite equivalent. It doesn't set the <code>cache</code> option. If it's important the the <code>cache</code> option is set then you'll have to stick with <code>$.ajax</code>):</p>\n\n<pre><code>$.getJSON(\"/portal/index.php/movies/get_tags\", function(response) {\n //Your success event handler\n});\n</code></pre>\n\n<p>Let's look at the body of your <code>keyup</code> event callback. The first thing that I notice here is the fact that you are searching the DOM for some elements every time it's called. Since <code>keyup</code> is probably triggered quite often, it would be more efficient to cache the results of your selectors. I would add the following declarations to the <code>var</code> statement at the top:</p>\n\n<pre><code>var tagsElem = $(\"#tags\"),\n createdTagsElem = $(\"#created-tags\"),\n tagsTypealong = $(\"#tags-typealong\");\n</code></pre>\n\n<p>You can then use those identifiers in the <code>keyup</code> event callback (and the AJAX success callback) instead of having to search the DOM for those elements every time.</p>\n\n<p>In the <code>keyup</code> callback you use both the jQuery <code>$.parseJSON</code> method and the native <code>JSON.stringify</code> method. Since you're using a native JSON method for stringifying, I would suggest using the equivalent native method for parsing too, <code>JSON.parse</code>, since it's going to be faster then that jQuery version. And don't forget to polyfill the native JSON methods so you can support older browsers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T09:36:29.193",
"Id": "20405",
"Score": "0",
"body": "`$.getJSON` does not use `cache:false`. Besides that, I think using `$.ajax()` is more readable since every argument is on the same indentation level."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T09:39:25.603",
"Id": "20406",
"Score": "0",
"body": "Ahh, good point. I tend to prefer the shorthand versions, but you are right - if the `cache` option needs to be set in this case then there's no choice but `$.ajax`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T09:48:09.627",
"Id": "20407",
"Score": "0",
"body": "Or `$.ajaxSetup({cache:false});`.. that might actually be a good idea since usually you don't want any AJAX caching."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T09:29:35.103",
"Id": "12655",
"ParentId": "12646",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12655",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T00:45:08.840",
"Id": "12646",
"Score": "2",
"Tags": [
"javascript",
"beginner",
"jquery",
"modules",
"autocomplete"
],
"Title": "Module to support autocomplete for movie tags"
}
|
12646
|
<p>I have a dynamic form that users can add extra fields too. The group of fields are added and the input name stays the same but gets a incremental number attached to it. So for my insert php file I just check to see if the next value is set and if so it inserts all the required info. But this code doesn't look very 'streamlined' to me. Is there a better way?</p>
<pre><code>mysql_select_db("inventory", $con);
if( !isset($_POST['productid2']) ) {
$sql="INSERT INTO shipped (id, type, client, product, color, quantity)
VALUES ('$_POST[productid]','$_POST[type]','$_POST[client]','$_POST[product]','$_POST[color]','$_POST[quantity]')";
}
if( isset($_POST['productid2']) ) {
$sql="INSERT INTO shipped (id, type, client, product, color, quantity)
VALUES ('$_POST[productid]','$_POST[type]','$_POST[client]','$_POST[product]','$_POST[color]','$_POST[quantity]'),
('$_POST[productid2]','$_POST[type2]','$_POST[client2]','$_POST[product2]','$_POST[color2]','$_POST[quantity2]')";
}
if( isset($_POST['productid3']) ) {
$sql="INSERT INTO shipped (id, type, client, product, color, quantity)
VALUES ('$_POST[productid]','$_POST[type]','$_POST[client]','$_POST[product]','$_POST[color]','$_POST[quantity]'),
('$_POST[productid2]','$_POST[type2]','$_POST[client2]','$_POST[product2]','$_POST[color2]','$_POST[quantity2]'),
('$_POST[productid3]','$_POST[type3]','$_POST[client3]','$_POST[product3]','$_POST[color3]','$_POST[quantity3]')";
}
// And I have like this 5 more times, the code gets longer each time!
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T02:05:29.677",
"Id": "20387",
"Score": "3",
"body": "Before you think about optimisation it would be a good idea to read up on [SQL injection](http://php.net/manual/en/security.database.sql-injection.php). Your code is wide open to attack at the moment"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T02:16:19.460",
"Id": "20388",
"Score": "0",
"body": "@Clive the form fields are all select type and are validated before being posted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T02:24:31.167",
"Id": "20389",
"Score": "1",
"body": "That won't stop an attacker from posting to the form with harmful values"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T09:20:02.967",
"Id": "20403",
"Score": "0",
"body": "Not using the `mysql` extension at all would also be a good idea."
}
] |
[
{
"body": "<p><strong>Array based approach</strong></p>\n\n<p>Instead of appending a number to the field, use an array based approach:</p>\n\n<pre><code><form action=\"\" method=\"POST\">\n <b>Product 1</b><br\n <label>Product Id <input type=\"text\" name=\"products[0][id]\"></label>\n <br>\n <label>Product Type <input type=\"text\" name=\"products[0][type]\"></label>\n <br> \n <b>Product 2</b><br>\n <label>Product Id <input type=\"text\" name=\"products[1][id]\"></label>\n <br>\n <label>Product Type <input type=\"text\" name=\"products[1][type]\"></label>\n</form>\n</code></pre>\n\n<p>Now if you were to submit this to PHP and do <code>print_r($_POST['products']);</code>, you would get something like the following:</p>\n\n<pre><code>array(\n 0 => array(\n 'id' => '...',\n 'type' => '...',\n ),\n 1 => array(\n 'id' => '...',\n 'type' => '...',\n )\n)\n</code></pre>\n\n<p>This allows you to do the logic for the insertion once, and then use a loop to do all of the fields.</p>\n\n<p>The (pseudo) code would be like:</p>\n\n<pre><code>$products = (isset($_POST['products']) && is_array($_POST['products'])) ? $_POST['products'] : array();\n\n//Note that I've assumed the id column is an int, and the type column is a string.\n//In real schema, I would expect type to also be an int, but I want to illustrate proper escaping.\n//(There is more on this in a later section)\n$query = \"INSERT INTO products (id, type) VALUES (%d, '%s')\";\n\nforeach ($products as $product) {\n //Ensure that $product contains a valid entry, and if it does not, store errors somewhere\n if (valid entry) {\n $res = mysql_query(sprintf($query, (int) $product['id'], mysql_real_escape_string($product['type'])));\n if (!$res) {\n //Log an error about the query failing\n }\n }\n}\n</code></pre>\n\n<p><strong><a href=\"http://en.wikipedia.org/wiki/SQL_injection\">SQL Injection</a></strong></p>\n\n<p>Put all the validation on the client side you want, but at the end of the day, it's bypassable. In fact, a user doesn't even have to use a browser, much less use JavaScript. A user can send your server anything he wants. After all, at the end of the day, HTTP is a text based protocol.</p>\n\n<p>Also, properly escaping isn't just about security. It's also about correctness.</p>\n\n<pre><code>$string = \"The other day, someone said, \"Hello my name is Fred!\"\"; //Syntax error!\n</code></pre>\n\n<p>Not escaping SQL is the same concept as this. This isn't a security issue; it's just wrong. Escaping SQL is the same concept as doing:</p>\n\n<pre><code>$string = \"The other day, someone said, \\\"Hello my name is Fred!\\\"\";\n</code></pre>\n\n<p>The escaping is necessary so that the SQL server can parse the query correctly in the same way that escaping in PHP is necessary so that the PHP engine can parse the script correctly.</p>\n\n<p>The reason that SQL injection is a security concern is user input. If you don't properly escape, users can change your code.</p>\n\n<p>It's hard to make a <em>brief</em> PHP-injection example, but hopefully the concept is there. An attempt at an example:</p>\n\n<pre><code>eval(\"\\$x = 5 + {$_POST['input']};\");\n</code></pre>\n\n<p>That's all good and fine as long as <code>$_POST['input'] === \"5\";</code> or some other kind of innocent value. However, consider if <code>$_POST['input'] === \"5; evilFunction()\"</code>. Suddenly the eval is:</p>\n\n<pre><code>eval(\"\\$x = 5 + 5; evilFunction();\");\n</code></pre>\n\n<p>This is the broad concept of SQL injection. (Various articles on the internet will explain it much better than me though :p.)</p>\n\n<p><em>(<code>eval</code> should very rarely [arguably, never] actually be used -- this is just to illustrate a point)</em></p>\n\n<p>Anyway, the solution is very simple. Anything that is going to be a string needs to be run through mysql_real_escape_string before being interpolated into a query. Likewise, anything that is not a string should be handled as the proper type:</p>\n\n<pre><code>$query = \"INSERT INTO tbl (stringField, intField) VALUES ('%s', '%d')\";\n$qry = sprintf($query, \n mysql_real_escape_string($someString), //make sure the string field is properly escaped\n (int) $someInt //make sure the int field is an int\n );\n</code></pre>\n\n<p><strong><a href=\"http://php.net/pdo\">PDO</a></strong></p>\n\n<p>I would advise everyone to move away from the old mysql extension. The mysql_* functions are a very thin wrapper around the C API, and though there is not anything particularly <em>wrong</em> with them, <em>PDO</em> is just better.</p>\n\n<p>In particular, PDO:</p>\n\n<ul>\n<li>Offers a cleaner <a href=\"http://is.php.net/manual/en/class.pdo.php\">API</a></li>\n<li>Offers better error handling (the ability to have failed queries throw exceptions is wonderful)</li>\n<li>Handles <a href=\"http://is.php.net/manual/en/pdo.begintransaction.php\">transactions</a> SQL-dialect agnostically (for the most part)</li>\n<li><a href=\"http://is.php.net/manual/en/pdo.drivers.php\">Different RDBMS</a> can be changed out relatively easily (switching from mysql_* to Postresql is extremely painful. Switching from PDO with MySQL to PDO with Postresql isn't pleasant, but is care is taken to stay as dialect-agnostic as possible, it's reasonably easy)</li>\n<li><a href=\"http://php.net/manual/en/pdo.prepare.php\">Prepared statements</a></li>\n</ul>\n\n<p>Prepared statements deserve their own sublist:</p>\n\n<ul>\n<li>100% safe from SQL injection (if used correctly, of course)</li>\n<li>Better performance for batched queries</li>\n<li>Various other minor things</li>\n</ul>\n\n<p>Prepared statements work vaguely like:\n* Create a parameterized statement\n* Let the SQL server handle putting the variables into place</p>\n\n<p>The second point is the important one. Since the server is putting the paramters into place, it's impossbile for something to be misinterpretted.</p>\n\n<p>An example will be a lot more useful:</p>\n\n<pre><code>//create the connection\n$db = new PDO(\"mysql:host=localhost;dbname=database_name\", \"username\", \"password\");\n//I like for failed queries to throw exceptions.\n//If you're not comfortable with exception handling, you would want to omit the following line.\n$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n\n$products = (isset($_POST['products']) && is_array($_POST['products'])) ? $_POST['products'] : array();\n\n//Create the prepared statement -- in a way this is like having SQL create a temporary function\n$insertStmt = $db->prepare(\"INSERT INTO products (id, type) VALUES (:id, :type)\");\n\nforeach ($products as $product) {\n //Ensure that $product contains a valid entry, and if it does not, store errors somewhere\n if (valid entry) {\n //Execute the statement -- this is similar to calling the temporary function\n //Note that a new array is created in case $product contains an extra key. For example,\n //if there were a $product['extra'] field, then using $insertStmt->execute($product) would\n //cause an error since there would be an extra paramater that MySQL would not know what\n //to do with.\n $insertStmt->execute(array(\n 'id' => $product['id'],\n 'type' => $product['type']\n ));\n }\n}\n</code></pre>\n\n<p><strong>Don't assume user input is there</strong></p>\n\n<p>Never assume anything from the client side. What I mean in this particular instance is to never assume a key exists in $_POST, $_GET, $_COOKIE, etcetra.</p>\n\n<p>Just because <code>isset($_POST['productid2'])</code> is true does not mean that the <code>type2</code> key for <code>$_POST</code> is set. This goes back to the note earlier about people being able to send your client whatever they want.</p>\n\n<p>I could make your script issue all kinds of index undefined and mysql_query() errors if I wanted by making a form like the following:</p>\n\n<pre><code><form action=\"http://yoursite.tld/somepage.php\" method=\"POST\">\n <input type=\"text\" name=\"productid2\" value=\"let there be errors!\">\n <input type=\"submit\">\n</form>\n</code></pre>\n\n<p>My approach is to be paranoid on user provided values. Something intersting to note is that $_GET/$_POST/$_COOKIE/$_REQUEST values will always be either a string or an array (unless somewhere in your script you have something like: <code>$_POST['int'] = 5;</code>). This means that if you're not expecting an array, you should make sure you're getting a string.</p>\n\n<pre><code>$type = (isset($_POST['type']) && is_string($_POST['type'])) ? $_POST['type'] : null;\nif ($type === null) {\n echo 'Please provide a type';\n} else {\n //do some other validations on $type\n}\n</code></pre>\n\n<p>If you want to be a bit more flexible, you could use is_scalar instead of is_string.</p>\n\n<p>The broad idea is that you never want to access an array by key <code>$k</code> unless you are certain that <code>array_key_exists($k, $arr)</code> is true. When <code>$arr</code> is something user provided, you can never be certain of that unless you explicitly check it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T17:07:30.887",
"Id": "20420",
"Score": "1",
"body": "Quite possibly the best answer I have ever received. I will be bookmarking this for future reading! Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T22:54:05.583",
"Id": "20446",
"Score": "0",
"body": "@mcflause Glad I could help :)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T16:25:22.210",
"Id": "20521",
"Score": "0",
"body": "I think there are some browsers that do not support form arrays, so I'd be careful of this. Otherwise good review +1! I'll see if I can't find that link somewhere and post it back here for verification."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T17:07:30.040",
"Id": "20527",
"Score": "0",
"body": "@showerhead It's PHP that makes it an array, not the browser. All that needs to happen on the browser side is that the form data needs to be correctly created. Considering it would be harder for a browser to get it wrong than to get it right, I would imagine that all browsers do it correctly. But I'm not sure if it's specified behavior by the HTML/HTTP standards. (I do know for sure though that IE 7+, Chrome, FF 3+ all handle it fine -- not sure about older versions or Opera/Safari.)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T05:07:42.837",
"Id": "12649",
"ParentId": "12647",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "12649",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T01:56:10.747",
"Id": "12647",
"Score": "5",
"Tags": [
"php",
"mysql"
],
"Title": "PHP dynamic insert - mysql. Is there a better way than this?"
}
|
12647
|
<p>This question is always on my mind. I usually alter the array while looping through its keys, based on my gut feelings:</p>
<pre><code>foreach (array_keys($array) as $key) {
$array[$key] = perform_changes_on($array[$key]);
}
</code></pre>
<p>I'm aware of other methods, though. The array item can be passed by reference on the foreach call:</p>
<pre><code>foreach ($array as &$item) {
$item = perform_changes_on($item);
}
</code></pre>
<p>Finally, the array can be modified directly during the loop:</p>
<pre><code>foreach ($array as $key => $value) {
$array[$key] = perform_changes_on($value);
}
</code></pre>
<p>What are the performance and security implications of each approach? Is there a recommended approach?</p>
<p>UPDATE: What I'm actually worried about is that the two last approaches modify the array while I'm looping it.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T10:11:40.893",
"Id": "70368",
"Score": "0",
"body": "http://stackoverflow.com/questions/10057671/how-foreach-actually-works is helpful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-22T02:11:02.493",
"Id": "283376",
"Score": "3",
"body": "OP gave actual code and yet it's closed because the code is not part of a \"concrete implementation\"? honestly, what ?"
}
] |
[
{
"body": "<p>I can't really help you with the performance bit, only tell you to wrap them in <code>microtime()</code> tags and see which one performs better for you. Systems are slightly different. The one suggestion I can give you is to remove <code>array_keys()</code> from your code.</p>\n\n<p><strong>!!UPDATE!!</strong></p>\n\n<p>If you were following Corbin and my argument below, then I finally have an answer for you. I was getting for and foreach confused. For and while loops <strong>do</strong> call any functions passed in as arguments on every iteration, foreach <strong>does not</strong>. Which is why its better to call functions such as <code>strlen()</code> and <code>count()</code>, just to give a couple of examples, outside of a for or while loop. The overhead we were experiencing was not from foreach but from <code>array_keys()</code>. When <code>array_keys()</code> is called it must generate a new array, which is why it is almost twice as slow. So it is best to drop the <code>array_keys()</code> function all-together and just iterate over the array and retrieve the key value pair. Sorry for any confusion this may have caused.</p>\n\n<p>Sources:</p>\n\n<ul>\n<li><a href=\"http://www.phpbench.com/\" rel=\"nofollow noreferrer\">http://www.phpbench.com/</a></li>\n<li><a href=\"https://stackoverflow.com/questions/3430194/performance-of-for-vs-foreach-in-php\">https://stackoverflow.com/questions/3430194/performance-of-for-vs-foreach-in-php</a></li>\n<li><a href=\"https://stackoverflow.com/questions/1740575/php5-does-the-copy-of-an-array-for-a-foreach-incur-overhead\">https://stackoverflow.com/questions/1740575/php5-does-the-copy-of-an-array-for-a-foreach-incur-overhead</a></li>\n</ul>\n\n<p><strong>!!END OF UPDATE!!</strong></p>\n\n<p>To the best of my knowledge there is no security risk with any of those implementations. You are iterating a construct that already exists. Any security issues would have happened before this point. Except of course if you are using user supplied data, such as GET and POST. These you should sanitize and validate before using, which is something you could do with one of those foreach loops. Or you could also check out <a href=\"http://php.net/manual/en/function.filter-input-array.php\" rel=\"nofollow noreferrer\"><code>filter_input_array()</code></a> and its cousins.</p>\n\n<p>I know I personally would not use the second implementation due to the lack of legibility. At least with the first and third implementations you can visually see that a value is being changed. The second is not readily obvious. However, it is most likely the more efficient. I have used both the first and third myself, but more often use the third. Think it has to do with what mood I'm in. Hope this helps, I'm interested to hear what others might have to say :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T17:11:38.520",
"Id": "20530",
"Score": "0",
"body": "\"Arguments given to foreach are declared on each iteration, so you are technically calling array_keys() every time foreach is looped.\" Nope, it will only call array_keys once in this context. (Perhaps before PHP5 it had this behavior, but I do not think so as this would very easily end up in infinite loops.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T18:09:20.653",
"Id": "20547",
"Score": "0",
"body": "@Corbin: **Nope**, still an issue. Don't believe me, run some tests on it and you'll see for yourself. PHP creates an iterator object for the first parameter each time it loops so that it can perform `each()` on each iteration of it. It is recreated, but the pointer stays the same. That's why if you changed the value of the array by reference it would be immediately available upon the next iteration :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T18:20:24.407",
"Id": "20553",
"Score": "0",
"body": "Can you provide an example? Just tried to get it to call array_keys (well, `f`) twice, and could never get it to."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T18:35:48.693",
"Id": "20558",
"Score": "0",
"body": "Potentially relevant: http://stackoverflow.com/questions/4043569/php-foreach-function-performance"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T19:17:46.157",
"Id": "20564",
"Score": "0",
"body": "@Corbin: I'm honestly not sure then. I've seen someone else claiming the exact opposite, and my speed tests seem to prove it. The foreach with the \"recreated\" array always seems to take longer. Ran a test of over a hundred iterations and all seem conclusive that something extra is being performed in the background. I'm still looking around for that post, hopefully I can find it. I need to start keeping a repository of these posts..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T23:39:54.263",
"Id": "20596",
"Score": "0",
"body": "It's easy to prove that the function is not called over and over again. Just use `foreach(f($arr) as $v) { }` with an `echo` in `f`. However, if there is actually a performance difference, no idea what that is from."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T00:23:01.293",
"Id": "20604",
"Score": "0",
"body": "Did some very rough testing a minute ago, and the results are quite odd. `foreach(f($x) ...)` is significantly faster for small arrays, and `$fx = f($x); foreach ($fx ...)` is faster for large arrays. There must be some very odd low level stuff going on >.<."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T12:58:02.903",
"Id": "20619",
"Score": "0",
"body": "I was not able to find that post, but as you have seen with your own speed tests \"something\" is going on. So the while my reasoning behind it is wrong, its still better to separate the creation of the array from the loop. Or at the very least it won't hurt anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T01:22:44.953",
"Id": "20689",
"Score": "0",
"body": "You're neglecting the case where it's faster to inline the function :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T02:57:07.553",
"Id": "20820",
"Score": "0",
"body": "@Corbin: Alright, finally figured it out. See update above..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T03:21:39.550",
"Id": "20821",
"Score": "0",
"body": "\"The overhead we are experiencing is not from foreach but from array_keys() which requires some setup time that drastically decreases its performance.\" does not make sense (nor is it drastic), but definitely better than before the edit :). (Sorry for being 'that guy', just there's a lot of misinformation about a few edges of PHP, and it makes me sad :p.) Also, you should edit out the `Arguments given to foreach...` part :)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T03:34:16.413",
"Id": "20823",
"Score": "0",
"body": "Drastic was perhaps misleading, I meant so relatively speaking. I don't see how that didn't make sense, but I edited it to, hopefully, clarify. Continue being that guy. I'd rather someone caught me now, rather than years down the line after having given many people the wrong information."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T03:42:08.510",
"Id": "20825",
"Score": "0",
"body": "I suppose reading back on it now that I read it with the wrong context in mind. I think it's a lot clearer now, but I think it was me over thinking things and misunderstanding it before. Though the paragraph still sounds like it's comparing for and foreach's performances instead of `foreach (array_keys($arr) ... )` compared to `$keys = array_keys($arr); foreach ($keys)` compared to `foreach ($array as ...)`.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T03:43:29.647",
"Id": "20826",
"Score": "0",
"body": "The answer might also be a bit misleading to people who don't read the comments since `foreach (f() ...)` compared to `$vals = f(); foreach ($vals ... )` is essentially the same performance whereas `foreach (array_keys($array) ...)` and `foreach ($array as $k => $v)` will have different performances (not because of a function call, but because of what the function is doing -- basically recreating a language construct in a hacky way. As you said, if you do the array_keys approach, the keys have to all be copied.)"
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T14:48:29.930",
"Id": "12699",
"ParentId": "12652",
"Score": "2"
}
},
{
"body": "<p>This sounds like a place for <a href=\"http://www.php.net/manual/en/function.array-map.php\"><code>array_map()</code></a>.</p>\n\n<pre><code>$array = array_map('perform_changes_on', $array);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T17:55:53.393",
"Id": "20543",
"Score": "0",
"body": "nice, but sometimes i won't change _every_ item in the array. I just tried to make the example simpler..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T11:46:57.877",
"Id": "20616",
"Score": "1",
"body": "`perfom_changes_on` doesn't have to change every element. Note that there are other [array functions](http://www.php.net/manual/en/ref.array.php), some more powerful than others. [array_reduce](http://www.php.net/manual/en/function.array-reduce.php) can help a lot, for example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-08T18:31:43.553",
"Id": "131703",
"Score": "0",
"body": "Doesn't this involve a function call for every element? May not be the best performance wise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-08T20:34:01.497",
"Id": "131727",
"Score": "0",
"body": "@Tom: I wouldn't say the overhead of function call is notable. Maintainability is way more important than very small performance gains (that I'm not even sure if they even do exist). But if you think that writing 100,000 lines program without functions is a best way of programming, by all means do it. Just don't be surprised when nobody wants to maintain the code, and you won't understand what you wrote a day later."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T15:23:38.587",
"Id": "12701",
"ParentId": "12652",
"Score": "10"
}
},
{
"body": "<p>I'd go with your second approach:</p>\n\n<pre><code>foreach ($array as &$item) {\n $item = perform_changes_on($item); \n}\n</code></pre>\n\n<p>Or even better:</p>\n\n<pre><code>function perform_changes_on(&$item) {\n// ...\n}\n\nforeach ($array as &$item) {\n perform_changes_on($item); \n}\n// ...\n</code></pre>\n\n<p>Working on each item (by reference) seems the safest one, since you're not accessing the array's structure, but its single elements instead (which, I take, is what you want to do).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T11:13:00.597",
"Id": "12726",
"ParentId": "12652",
"Score": "0"
}
},
{
"body": "<p>When using <code>foreach($array as &$item)</code> never ever forget the <code>unset($item);</code> after the foreach or you will get into serious trouble trying to use <code>$item</code> later. It should be habitual to avoid this trap.</p>\n\n<p>In general you should avoid <code>foreach ...&</code> and do <code>array_walk($array, function (&$item) {...</code> so that the reference is strictly confined inside the closure.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T17:02:07.073",
"Id": "20656",
"Score": "0",
"body": "thanks for the answer, I'm using array_keys to avoid the trap, but do I need to use it? I mean, `foreach ($array as $key => $item)` should let me change `$array[$key]` value, but who knows how php works internally... that's the question, actually."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T16:57:44.923",
"Id": "12746",
"ParentId": "12652",
"Score": "3"
}
},
{
"body": "<p>If you are worried about modifying the array while looping, don't because foreach copies the array. Try </p>\n\n<pre><code>$array = array('foo');\nforeach ($array as $k => &$item) {\n $array[] = 'bar';\n}\nvar_dump($array);\n</code></pre>\n\n<p>And see it terminates just fine. <code>foreach ($array as $k => &$v)</code> is a shorthand for <code>foreach (array_keys($array) as $k) $v = &$array[$k]</code> so while there still is a copy of the array (that's why I used <code>&$item</code> in my example so you can see, if you modify the array then it'll be modified in the reference!</p>\n\n<pre><code>$array = array('foo', 'bar');\nforeach ($array as $k => $item) {\n echo \"$item\\n\";\n if (!$k) {\n $array[1] = 'baz';\n }\n}\n$array = array('foo', 'bar');\nforeach ($array as $k => &$item) {\n echo \"$item\\n\";\n if (!$k) {\n $array[1] = 'baz';\n }\n}\n</code></pre>\n\n<p>the first dump foo and bar, the second foo and baz.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T01:46:21.850",
"Id": "20691",
"Score": "0",
"body": "\"foreach ($array as $k => $v) is a shorthand for foreach (array_keys($array) as $k) $v = &$array[$k]\" On a very picky note, that's not a shorthand as much as a difference in calling a function and a language construct (though for practical reasons, I suppose it's a shorthand). Also, it would be shorthand for a copy, not a reference. (Also, PHP is copy-on-write, so you can typically ignore extra copies.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T05:46:59.503",
"Id": "20696",
"Score": "0",
"body": "Obviously that wanted to be `foreach ($array as $k => &$v)` edited and fixed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T13:31:30.577",
"Id": "20718",
"Score": "0",
"body": "Would like to point out that `if(!$k)` is TRUE for 0, otherwise this statement is always false. So essentially you are overwriting the second array element before ever seeing it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T16:39:20.217",
"Id": "20726",
"Score": "0",
"body": "I do that and by doing that, I am demonstrating that the first foreach works from a copy and the second doesn't."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T03:33:23.047",
"Id": "20822",
"Score": "0",
"body": "@chx You might want to run your first snippet then. $item is a copy of a value from $array. `$array` is never copied (though all elements of `$array` will be copied if the foreach loop completes). The first snippet will dump foo and baz just like the second one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T03:36:33.090",
"Id": "20824",
"Score": "0",
"body": "(Note that in your answer you've used dump to mean the outputting during the loop whereas I've used it to mean outputting the entire array after the loop. Basically as in: http://paste.ee/p/hzqGz -- in short, I'm responding to your comment under the assumption that it's along the lines of what you posted in your answer: \"foreach copies the array.\")"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T06:58:15.840",
"Id": "20832",
"Score": "0",
"body": "Funny. I ran that snippet. I get foo, bar, foo, baz."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-20T19:37:07.203",
"Id": "178380",
"Score": "0",
"body": "@chx, Isn't this just an implementation detail that might be changed in the future? The documentation (specification) doesn't state that `foreach` must perform as such."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-06T13:33:39.143",
"Id": "250580",
"Score": "0",
"body": "@Corbin: I suppose @chx means that all `$item`s for every key-value-pair will be copied at instantiation, so that even though `$array[1]` will be altered to `baz` in the first loop, the second loop will still print `bar` as the value of `$item` even though in the actual array it will have already been updated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T19:35:07.957",
"Id": "431955",
"Score": "0",
"body": "Although the first snippet works on 5.x the way Chx describes (copying the array, iterating over the copy). As of PHP 7.0 the array is no longer copied. The snippet will instead iterate until the memory limit is reached. A good StackOverflow answer that goes into detail on this can be found here: https://stackoverflow.com/questions/10057671/how-does-php-foreach-actually-work/14854568#14854568"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T00:19:49.150",
"Id": "12756",
"ParentId": "12652",
"Score": "20"
}
}
] |
{
"AcceptedAnswerId": "12756",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T07:16:18.363",
"Id": "12652",
"Score": "34",
"Tags": [
"php",
"object-oriented",
"array",
"php5"
],
"Title": "Modifying an array during a foreach loop"
}
|
12652
|
<p>This is the code I'm using at the moment</p>
<pre><code>/*
* Adjust content height so that it always fills browser height
*
* written by Tom Jenkinson
*/
jQuery(document).ready(function() {
refreshContentSize(); //run initially
$(window).resize(function() { //run whenever window size changes
refreshContentSize();
});
setInterval('refreshContentSize()', 500); // in case content size changes. THIS IS WHAT I WANT TO CHANGE
});
function refreshContentSize()
{
var startPos = $("#content").position();
var topHeight = startPos.top;
var contentHeight = $("#content").outerHeight(true);
var footerHeight = $("#footer").outerHeight(true);
var viewportHeight = $(window).height();
var spaceForContent = viewportHeight - footerHeight - topHeight;
if (spaceForContent <= contentHeight)
{
var newHeight = 0;
}
else
{
var newHeight = spaceForContent - contentHeight;
}
$("#filler").css('height', newHeight);
return;
}
</code></pre>
<p>The site is <a href="http://wncba.co.uk/results" rel="nofollow">http://wncba.co.uk/results</a> and the script is at <a href="http://wncba.co.uk/results/javascript/fill-pagev2.js" rel="nofollow">http://wncba.co.uk/results/javascript/fill-pagev2.js</a>.</p>
<p>At the moment you can see that I'm using a timer to keep calling the <code>refreshContentSize()</code>. I am doing this because some of the content on the page can change dynamically meaning the page height will change.</p>
<p>Is there a handle for this like jquery's 'resize' so I don't need the timer?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-08T04:21:14.163",
"Id": "269349",
"Score": "1",
"body": "From my understanding, you're trying to resize the height of your content. What I would use is VH (viewport height) and VW (viewport width) units for the contents container. For its children, I would use %."
}
] |
[
{
"body": "<p>I can't really verify what the code does since when I checked, the filler is always 0px. But I assume your code checks for the surrounding elements in an interval and updates the filler height accordingly. </p>\n\n<p>I have some tips for your code:</p>\n\n<pre><code>//shorthand .ready using the jQuery namespace\n//and using the $ as the inner namespace\njQuery(function ($) {\n\n //cache repeatedly used references\n var content = $(\"#content\"),\n footer = $(\"#footer\"),\n $window = $(window),\n filler = $(\"#filler\");\n\n // - place functions inside the ready handler to avoid globals\n // - always hand over a function reference to a timer and never an eval-able string\n // - since 500ms is fast enough, resize and an init wouldn't be needed\n // a human sees 200ms as \"instant\" and at least 700ms a significant lag\n // somewhere in between is the \"sweet spot\"\n setInterval(function () {\n var startPos = content.position(),\n topHeight = startPos.top,\n contentHeight = content.outerHeight(true),\n footerHeight = footer.outerHeight(true),\n viewportHeight = $window.height(),\n spaceForContent = viewportHeight - footerHeight - topHeight,\n //JS has a function scope. Any variable declared anywhere is visible\n //everywhere in the containing function. Therefore, it's better to\n //declare them outside operations\n newHeight = 0; //default to 0\n\n //overwrite 0 if conditions state otherwise\n if (spaceForContent > contentHeight) {\n newHeight = spaceForContent - contentHeight\n }\n\n //so it's 0 or some other value\n filler.css('height', newHeight);\n\n }, 500);\n});\n</code></pre>\n\n<p>Packed version:</p>\n\n<pre><code>jQuery(function ($) {\n var content = $(\"#content\"),\n footer = $(\"#footer\"),\n $window = $(window),\n filler = $(\"#filler\");\n setInterval(function () {\n var startPos = content.position(),\n topHeight = startPos.top,\n contentHeight = content.outerHeight(true),\n footerHeight = footer.outerHeight(true),\n viewportHeight = $window.height(),\n spaceForContent = viewportHeight - footerHeight - topHeight,\n newHeight = 0;\n if (spaceForContent > contentHeight) {\n newHeight = spaceForContent - contentHeight\n }\n filler.css('height', newHeight)\n }, 500)\n});\n</code></pre>\n\n<p>You might want to check out <a href=\"http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observers\" rel=\"nofollow\">Mutation Observers API</a> which gives you the ability to listen to changes in the DOM. It's not yet supported across browsers but just included it if ever you are interested.</p>\n\n<p>Also, I think it's better that you rethink your layout - one which only relies on plain HTML and CSS.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T14:35:48.207",
"Id": "20414",
"Score": "0",
"body": "Thanks. The Mutation Observers API looks really interesting. The site was originally just html and css but then I thought I'd make it look a bit neater with some js. It should still look and work fine if js is disabled though. I've seen the '$' being passed into the function before but never understood what it meant. Please can you explain what the 'inner namespace' is and how the '$' relates to it. Thanks :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T14:59:30.333",
"Id": "20415",
"Score": "1",
"body": "@TomJenkinson jQuery uses 2 global namespaces, `jQuery` and `$`. But other frameworks also use `$` which causes conflicts. Also, developers tend to use `$` more often since it's shorter. To address both issues, use the `jQuery` global to initiate the DOM ready callback. Inside the callback, jQuery passes itself as first parameter. To address the second issue, we use `$` for the passed jQuery. That way, the local `$` inside the callback is jQuery, while the `$` outside can be used by any framework."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T14:03:00.300",
"Id": "12658",
"ParentId": "12656",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "12658",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T12:01:51.020",
"Id": "12656",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"html",
"html5",
"dom"
],
"Title": "Detecting when the contents of a web page changes"
}
|
12656
|
<p>I am playing around with brute force attack on my home network. I wrote the following script with Python. However progress is a little slow. Does anyone have a suggestion how to make this faster?</p>
<pre><code>import socket
import urllib2, base64
import sys
import time
def afunction(password_start):
#-------------------------------------------------------------------------- ONLY ONCE
charset = 'abcdefghijklmnopqrstuvwxyz0123456789'
request = urllib2.Request("http://192.168.178.25/parse.html")
num = len(charset)**3
print "Trying to crack parse.html...\n"
# STATUS VARIABLES
totspeed = 0
c= 0
total = 36**6
#GET THE INDEXES TO START WHERE THEY SHOULD
first_time = True
ilist = []
for i in password_start:
for index, j in enumerate(charset):
if i == j:
ilist.append(index)
#USERNAME
usrname = 'admin'
#-------------------------------------------------------------------------- LOOP
for idx, l in enumerate(charset):
_q = idx
if idx < ilist[0] and first_time:
continue
for idx2, m in enumerate(charset):
_w = idx2
if idx2 < ilist[1] and first_time:
continue
for idx3, n in enumerate(charset):
_e = idx3
if idx3 < ilist[2] and first_time:
continue
at = time.time()
for idx4,o in enumerate(charset):
if idx4 < ilist[3] and first_time:
continue
for idx5, p in enumerate(charset):
if idx5 < ilist[4] and first_time:
continue
for idx6, q in enumerate(charset):
if idx6 < ilist[5] and first_time:
continue
#PASSWORD
passwd = l+m+n+o+p+q
first_time = False
#LOGGING IN
base64string = base64.encodestring('%s:%s' % (usrname,passwd)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
try:
result = urllib2.urlopen(request)
print "Login succes!! Username: %s"%usrname," Password: %s"%passwd
sys.exit()
#EVERY FAILED PASSWORD GOES IN HERE
except urllib2.HTTPError:
continue
#IF A NETWORK ERROR OCCURS, IT WILL BE CAUGHT WITH AN EXCEPTION
except socket.error:
print "\n Sleeping for a moment. Conncection is reset by peer...\n"
time.sleep(60)
afunction(passwd)
except urllib2.URLError:
if time.localtime()[3] < 21:
print "Connection has been lost. Try again in 10 minutes"
start3 = passwd
time.sleep(600)
afunction(passwd)
else:
start3 = passwd
print "Connection has been terminated at: %s\n"% time.ctime()
print "Todays cracking ended with: %s"%start3
print "Cracking will continue at 6 AM\n"
while time.localtime()[3] != 6:
time.sleep(600)
time.sleep(300)
afunction(passwd)
#STATUS UPDATE
bt = time.time()
totpasswd = num/((bt-at))
totspeed +=int(totpasswd)
c+=1
average = totspeed / c
aa = (36-(_q+1) )
bb = (36-(_w+1) )
cc = (36-(_e+1) )
if aa == 0: aa = 1
if bb == 0: bb = 1
if cc == 0: cc = 1
passwordsleft = ( aa * 36**5) +( bb * 36**4) + ( cc * 36**3) + (36**3) + (36**2) + 36.
estimatation = ((passwordsleft/average) / 3600 ) / 13.
print usrname,"::::",l+m+n+'xxx',"::::", " Processed %d passwords / sec"%totpasswd, "::::"," Estimated time left: %d days"%estimatation,"::::"," Passwords Left: %d"%passwordsleft, "::::"," Done: %.2f %%"%((passwordsleft/total)*100)
#RUN SCRIPT
afunction('aziaaa')
</code></pre>
<p>This is the output:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>admin :::: fajxx :::: Processed 737 passwords / sec :::: Estimated time left: 25 hours :::: Passwords Left: 52056468 :::: Done: 13.91 %
admin :::: fakxx :::: Processed 648 passwords / sec :::: Estimated time left: 25 hours :::: Passwords Left: 52055172 :::: Done: 13.91 %
admin :::: falxx :::: Processed 848 passwords / sec :::: Estimated time left: 24 hours :::: Passwords Left: 52053876 :::: Done: 13.91 %
admin :::: famxx :::: Processed 734 passwords / sec :::: Estimated time left: 23 hours :::: Passwords Left: 52052580 :::: Done: 13.91 %
</code></pre>
</blockquote>
<p>Following is similar code, but with the httlip library:</p>
<pre class="lang-python prettyprint-override"><code>import sys
import time
import base64
import string
import httplib
def afunction(password_start):
#-------------------------------------------------------------------------- ONLY ONCE
charset = 'abcdefghijklmnopqrstuvwxyz0123456789'
h = httplib.HTTP('192.168.178.25')
num = len(charset)**2
print "Trying to crack parse.html...\n"
# STATUS VARIABLES
totspeed = 0
c= 0
total = 36**5
#GET THE INDEXES TO START WHERE THEY SHOULD
first_time = True
ilist = []
for i in password_start:
for index, j in enumerate(charset):
if i == j:
ilist.append(index)
#USERNAME
userid = 'admin'
#-------------------------------------------------------------------------- LOOP
for idx, l in enumerate(charset):
_q = idx
if idx < ilist[0] and first_time:
continue
for idx2, m in enumerate(charset):
_w = idx2
if idx2 < ilist[1] and first_time:
continue
for idx3, n in enumerate(charset):
_e = idx3
if idx3 < ilist[2] and first_time:
continue
at = time.time()
for idx4,o in enumerate(charset):
if idx4 < ilist[3] and first_time:
continue
for idx5, p in enumerate(charset):
if idx5 < ilist[4] and first_time:
continue
#PASSWORD
passwd = l+m+n+o+p
first_time = False
auth = 'Basic ' + string.strip(base64.encodestring(userid + ':' + passwd))
h.putrequest('GET', '/parse.html')
h.putheader('Authorization', auth )
h.endheaders()
if h.getreply()[0] == 401:
continue
elif h.getreply()[0] == 200:
print "Login succes!! Username: %s"%userid," Password: %s"%passwd
sys.exit()
else:
print "Conncection lost..."
sys.exit()
#STATUS UPDATE
bt = time.time()
dt = bt - at
totpasswd = num/dt
totspeed +=int(totpasswd)
c+=1.
average = totspeed / c
aa = (36-(_q+1) )
bb = (36-(_w+1) )
cc = (36-(_e+1) )
if aa == 0: aa = 1
if bb == 0: bb = 1
if cc == 0: cc = 1
passwordsleft = ( aa * 36**4) +( bb * 36**3) + ( cc * 36**2) + (36**2) + 36.
estimatation = ((passwordsleft/average) / 3600. )
print userid,"::::",l+m+n+'xx',"::::", " Processed %d passwords / sec"%totpasswd, "::::"," Estimated time left: %d hours"%estimatation,"::::"," Passwords Left: %d"%passwordsleft, "::::"," Done: %.2f %%"%(100-(((passwordsleft/total))*100))
print "No password found.. Try something else.... "
#RUN SCRIPT
afunction('aaiaa')
#afunction('a47aaa')
</code></pre>
<p>The output is considerably slower:</p>
<blockquote>
<pre class="lang-python prettyprint-override"><code>admin :::: aatxx :::: Processed 34 passwords / sec :::: Estimated time left: 380 hours :::: Passwords Left: 60441588 :::: Done: 0.04 %
admin :::: aauxx :::: Processed 30 passwords / sec :::: Estimated time left: 389 hours :::: Passwords Left: 60440292 :::: Done: 0.04 %
admin :::: aavxx :::: Processed 28 passwords / sec :::: Estimated time left: 399 hours :::: Passwords Left: 60438996 :::: Done: 0.04 %
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T17:44:16.203",
"Id": "123124",
"Score": "0",
"body": "Instead of that nested mess of for-loops, check out [itertools](http://docs.python.org/library/itertools.html) ; I suspect a usage of [.product()](http://docs.python.org/library/itertools.html#itertools.product) is what you want."
}
] |
[
{
"body": "<ul>\n<li>move the code that generates passwords and makes connections, retry logic to separate functions</li>\n<li>make multiple requests using the same tcp connection (urllib doesn't support persistent connections, you could use httplib directly instead)</li>\n<li>make multiple connections in parallel (using threads/processes and/or some async library e.g., <a href=\"http://docs.python-requests.org/\" rel=\"nofollow\"><code>requests.async</code></a></li>\n</ul>\n\n<p>Here's the code: <a href=\"https://gist.github.com/zed/0a8860f4f9a824561b51\" rel=\"nofollow\">Brute force basic http authorization using httplib and multiprocessing</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T16:13:26.513",
"Id": "20419",
"Score": "0",
"body": "ok. I tried with threads before though, but its considerably slower. let me try to find the code and i'll post it. I'll have a look to your other suggestions. thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T14:45:12.033",
"Id": "20500",
"Score": "0",
"body": "Well as you can see, I tried to implement the httplib library but the code is remarkably slower. Is the \"h = httplib.HTTP('192.168.178.25')\" taking care of the same tcp connection as you suggested?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T22:20:02.240",
"Id": "20588",
"Score": "0",
"body": "@apfz: [httplib + multiprocessing](https://gist.github.com/0a8860f4f9a824561b51) processes ~1100 passwords per second (the server produces max ~1200 replies/s without errors)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T11:28:50.743",
"Id": "20614",
"Score": "0",
"body": "that is a really really nice pythonic code you linked me to. Your help is greatly appreciated, as I have learned much about Python this way. I got a similar passwords/sec as with the code I posted, I guess thats about the limit my network can go then. Again, thanks for being really helpful!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T21:03:34.907",
"Id": "20677",
"Score": "0",
"body": "@apfz: [I've cleaned up the code slightly](https://gist.github.com/0a8860f4f9a824561b51). You could tweak number of processes in the pool until passwords/sec rate levels off."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T14:52:52.243",
"Id": "12661",
"ParentId": "12659",
"Score": "4"
}
},
{
"body": "<pre><code>import sys\nimport time\nimport base64\nimport string\nimport httplib\n\ndef afunction(password_start):\n</code></pre>\n\n<p>That's a pretty inspecific name for your function</p>\n\n<pre><code> # ONLY ONCE\n charset = 'abcdefghijklmnopqrstuvwxyz0123456789'\n h = httplib.HTTP('192.168.178.25')\n</code></pre>\n\n<p>I'd put constants like charset and the ip address into global c onstants.</p>\n\n<pre><code> num = len(charset)**2\n</code></pre>\n\n<p>The name <code>num</code> is not very specific, so its hard to tell what this is supposed to be. Its also not used until much later, so why define it here?</p>\n\n<pre><code> print \"Trying to crack setparm.htm...\\n\"\n\n # STATUS VARIABLES\n totspeed = 0\n c= 0\n</code></pre>\n\n<p>The speed of light? Don't use single letter variables unless maybe inside quick for loops</p>\n\n<pre><code> total = 36**5\n</code></pre>\n\n<p>Why not use <code>len(charset)</code> here?</p>\n\n<pre><code> #GET THE INDEXES TO START WHERE THEY SHOULD\n first_time = True\n\n ilist = []\n for i in password_start:\n for index, j in enumerate(charset):\n if i == j:\n ilist.append(index)\n</code></pre>\n\n<p>Actually this whole list can be written as <code>ilist = [charset.index(char) for char in password_start]</code></p>\n\n<pre><code> #USERNAME\n userid = 'admin'\n</code></pre>\n\n<p>I'd make this a global constnat</p>\n\n<pre><code> #-------------------------------------------------------------------------- LOOP\n for idx, l in enumerate(charset):\n _q = idx\n</code></pre>\n\n<p>Why store it in <code>idx</code> only to copy it over? Use <code>for _q, l in ...</code></p>\n\n<pre><code> if idx < ilist[0] and first_time:\n continue\n for idx2, m in enumerate(charset):\n _w = idx2\n if idx2 < ilist[1] and first_time:\n continue\n for idx3, n in enumerate(charset):\n _e = idx3\n if idx3 < ilist[2] and first_time:\n continue\n at = time.time()\n for idx4,o in enumerate(charset):\n if idx4 < ilist[3] and first_time:\n continue\n for idx5, p in enumerate(charset):\n if idx5 < ilist[4] and first_time:\n continue\n</code></pre>\n\n<p>Yuck! You shouldn't to have nested for loops like this. I'll show you how to rewrite it later.</p>\n\n<pre><code> #PASSWORD\n passwd = l+m+n+o+p\n first_time = False\n\n auth = 'Basic ' + string.strip(base64.encodestring(userid + ':' + passwd))\n\n h.putrequest('GET', '/protect/setvar.htm')\n h.putheader('Authorization', auth )\n h.endheaders()\n if h.getreply()[0] == 401:\n continue\n elif h.getreply()[0] == 200:\n print \"Login succes!! Username: %s\"%userid,\" Password: %s\"%passwd\n sys.exit()\n else:\n print \"Conncection lost...\"\n sys.exit()\n</code></pre>\n\n<p>You may to include more information about what error happened. This whole section is ripe for being moved into another function</p>\n\n<pre><code> #STATUS UPDATE\n bt = time.time()\n dt = bt - at\n totpasswd = num/dt\n totspeed +=int(totpasswd)\n</code></pre>\n\n<p>Why are you adding speeds rather then just tracking time from the start?\n c+=1.\n average = totspeed / c\n aa = (36-(_q+1) )\n bb = (36-(_w+1) )\n cc = (36-(_e+1) )\n if aa == 0: aa = 1\n if bb == 0: bb = 1\n if cc == 0: cc = 1\n passwordsleft = ( aa * 36**4) +( bb * 36**3) + ( cc * 36*<em>2) + (36</em>*2) + 36.\n estimatation = ((passwordsleft/average) / 3600. )\n print userid,\"::::\",l+m+n+'xx',\"::::\", \" Processed %d passwords / sec\"%totpasswd, \"::::\",\" Estimated time left: %d hours\"%estimatation,\"::::\",\" Passwords Left: %d\"%passwordsleft, \"::::\",\" Done: %.2f %%\"%(100-(((passwordsleft/total))*100))</p>\n\n<pre><code> print \"No password found.. Try something else.... \"\n\n#RUN SCRIPT\nafunction('aaiaa')\n#afunction('a47aaa')\n</code></pre>\n\n<p>For generating the objects, I'd use a class liek this:</p>\n\n<pre><code>class PasswordGenerator(object):\n def __init__(self, password_start):\n self._state = [CHARSET.index(char) for char in password_start]\n\n def __iter__(self):\n return self\n\n def next(self):\n # convert indexes in password string\n password = ''.join(CHARSET[index] for index in self._state)\n\n # try incrementing the password state, starting at the last char\n for index in range(len(self._state) - 1, 0, -1):\n self._state[index] += 1\n\n if self._state[index] == len(CHARSET):\n # if we've tried all the characters in the last position\n # reset and continue\n self._state[index] = 0\n else:\n # we're good, return the password\n return password\n else:\n # signal the end of passwords\n raise StopIteration\n\n def count(self):\n \"\"\"\n Return the number of passwords not yet generated\n \"\"\"\n total = 0\n for index, count in enumerate(self._state):\n total += (len(CHARSET) - count)*len(CHARSET)**(len(self._state)- index)\n return total\n</code></pre>\n\n<p>Lightly tested. The idea is that this object can generate the passwords of any length, and you use a single for loop instead of several nested ones.</p>\n\n<p>I also tried using eventlet to speed up the processing. The idea is to use multiple requests at the same time. But this in my case made things slower. I speculate this is because I'm justting a localhost server on my desktop, and thus I'm not spending a lot of time waiting for network traffic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T11:33:24.653",
"Id": "20615",
"Score": "0",
"body": "Some Python masters here at stackexchange. Thanks a lot! Your tips are really straightforward, will not make these mistakes again! I realise now to make the variables a bit more clearer before I post as well. Thanks for helping me out!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-28T21:27:48.647",
"Id": "167171",
"Score": "1",
"body": "Are you sure you need a class? Using `yield` would simplify the code immensely, but you would not be able to implement `count`... it is up to you if it is worth the tradeoff"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T16:27:54.423",
"Id": "12706",
"ParentId": "12659",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T14:06:15.117",
"Id": "12659",
"Score": "3",
"Tags": [
"python",
"performance",
"http",
"authentication"
],
"Title": "Brute force HTTP with Python"
}
|
12659
|
<p>I think it is quite OK already, but from a design-pattern perspective, it would be interesting to hear if I have done it right. I'm also interested to know whether the implementation is OK from a best-practice C++ point of view.</p>
<p>I made a helper class in order to easily position objects in cocos2d-x. The client can use the class like this:</p>
<pre><code>restartButton->setPosition(
Positioner()
.withSize(restartButton->getContentSize())
.withAlignment(HorizontalAlign::LEFT)
.withAlignment(VerticalAlign::TOP)
.withMargin(Position::LEFT, 1)
.withContainer(ccp(0.0,0.0), contentSize)
.build()
);
</code></pre>
<p>Here is the helper class:</p>
<pre><code>class VerticalAlign
{
public:
enum ALIGNMENT
{
TOP,
CENTER,
BOTTOM
};
};
class HorizontalAlign
{
public:
enum ALIGNMENT
{
LEFT,
CENTER,
RIGHT
};
static HorizontalAlign::ALIGNMENT
from(VerticalAlign::ALIGNMENT alignment)
{
switch (alignment)
{
case VerticalAlign::TOP:
return HorizontalAlign::RIGHT;
break;
case VerticalAlign::BOTTOM:
return HorizontalAlign::LEFT;
break;
case VerticalAlign::CENTER:
return HorizontalAlign::CENTER;
break;
default:
std::cerr << "unexpected/unsupported alignment!\n";
throw new std::exception();
}
}
};
class Position
{
public:
enum POSITION
{
LEFT,
TOP,
RIGHT,
BOTTOM,
NR_POSITIONS
};
};
// origo for positions are at center,center (i.e. pos = 5,5 and size = 10,10 gives a top,left,right,bottom=5,5,15,15)
class Positioner
{
public:
Positioner()
:
mHorizontalAlignemnt(HorizontalAlign::CENTER),
mVerticalAlignemnt(VerticalAlign::CENTER),
mContainerSize(cocos2d::CCSize(0.0,0.0)),
mContainerOrigo(ccp(0.0, 0.0))
{
mMargins.resize(Position::NR_POSITIONS);
}
virtual
~Positioner()
{
}
Positioner &
withContainer(cocos2d::CCPoint containerOrigo, cocos2d::CCSize containerSize)
{
mContainerSize = containerSize;
mContainerOrigo = containerOrigo;
return *this;
}
Positioner &
withSize(cocos2d::CCSize size)
{
mSize = size;
return *this;
}
Positioner &
withAlignment(HorizontalAlign::ALIGNMENT align)
{
mHorizontalAlignemnt = align;
return *this;
}
Positioner &
withAlignment(VerticalAlign::ALIGNMENT align)
{
mVerticalAlignemnt = align;
return *this;
}
Positioner &
withMargin(Position::POSITION marginAt, double margin)
{
mMargins[marginAt] = margin;
return *this;
}
// returns origo of a rectangle with given size and vertically and horizontally aligned within a given container such that it meets the given margins
// however, alignment takes precedence over margins (i.e. if centered then will be positioned centered even if it does not meet the margins given)
CCPoint build()
{
return ccp(xOrigo(), yOrigo());
}
private:
double xOrigo(HorizontalAlign::ALIGNMENT align, double marginLeft, double marginRight, double size, double containerOrigo, double containerSize)
{
switch (align)
{
case HorizontalAlign::LEFT:
return containerOrigo + size / 2.0 + marginLeft;
break;
case HorizontalAlign::RIGHT:
return containerOrigo - size / 2.0 - marginRight + containerSize;
break;
case HorizontalAlign::CENTER:
return containerOrigo + containerSize / 2.0;
break;
default:
std::cerr << "unexpected/unsupported alignment!\n";
throw new std::exception();
}
}
double xOrigo()
{
return xOrigo(mHorizontalAlignemnt, mMargins[Position::LEFT], mMargins[Position::RIGHT], mSize.width, mContainerOrigo.x, mContainerSize.width);
}
double yOrigo()
{
return xOrigo(HorizontalAlign::from(mVerticalAlignemnt), mMargins[Position::TOP], mMargins[Position::BOTTOM], mSize.height, mContainerOrigo.y, mContainerSize.height);
}
HorizontalAlign::ALIGNMENT mHorizontalAlignemnt;
VerticalAlign::ALIGNMENT mVerticalAlignemnt;
cocos2d::CCSize mContainerSize;
cocos2d::CCPoint mContainerOrigo;
cocos2d::CCSize mSize;
std::vector<double> mMargins;
};
</code></pre>
|
[] |
[
{
"body": "<p>This is kind of a cross between an actual answer, and a really extended comment to @LokiAstari's.</p>\n\n<p>As far as the \"fluent interface\" (I <em>really</em> hate that phrase) goes, I think you need to look at two things: the average case and the worst case. I'd agree with @Loki's statement that in the worst case, the \"fluent\" interface is truly horrible. The code ends up so long it borders on ridiculous. </p>\n\n<p>That leaves only the average case as its hope for redemption. <em>If</em> a default-constructed <code>Positioner</code> object has most of the right setting most of the time, so you <em>usually</em> only need:</p>\n\n<pre><code>Positioner().withSize(restartButton->getContentSize()).build())\n</code></pre>\n\n<p>Then it <em>might</em> be acceptable.</p>\n\n<p>I'd note, however, that this still doesn't seem to provide any real advantage over @Loki's approach of using <code>Location</code>, <code>Margins</code> and <code>Container</code>. If the default values for margins (for example) are adequate, you can provide default values in the ctor for <code>Margin</code> just as easily as in the default constructor for <code>Positioner</code>. If the <code>Positioner</code> shown above is usually adequate, then his can also use defaults for the other arguments, so it'll end up as:</p>\n\n<pre><code>Positioner(restartButton->getContentSize())\n</code></pre>\n\n<p>I see at least one other substantial advantage for representing the <code>Location</code>, <code>Margins</code> and <code>Container</code> as classes of their own: even when the default values aren't adequate, you're likely to use the <em>same</em> margins (for example) in quite a few different places. By creating and naming a set of margins, you gain readability <em>and</em> centralize information about a set of margins in one place so they're easy to change consistently. Just for example, you might easily have one set of margins in one form, and a different set of margins in a different form.</p>\n\n<pre><code>Location TL(HorizontalAlign::Left, VerticalAlign::TOP);\n\nMargins order_entry(0, 1, 0, 0);\nMargins week_totals(1, 2, 1, 1);\n\nPositioner(order_button.getContentSize(), TL, order_entry);\n\nPositioner(totals_button.getContentSize(), TL, week_totals);\n</code></pre>\n\n<p>To summarize, it appears to me that the \"fluent interface\" (did I mention how much I <strong>hate</strong> that phrase?) will nearly <em>always</em> result in code that's longer and harder to read or understand than simply providing arguments to the constructor, in this case in the form of other objects representing the parts of an entire \"position\".</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T00:21:39.420",
"Id": "12678",
"ParentId": "12662",
"Score": "1"
}
},
{
"body": "<p>Let me offer a different point of view.</p>\n\n<p>Using a builder, in itself, is fine.</p>\n\n<p>Loki’s alternative works nicely but if you’ve got more complex objects it doesn’t scale any more. A builder can then be used as an alternative to keep the actual object (not the builder, the built object) immutable.</p>\n\n<p>To make it clear: <em>in this case</em> I’d probably go with Loki’s approach – and I’d use this approach as much as possible but sometimes a builder yields clearer code.</p>\n\n<p>But when you use a builder, make sure that you don’t fall into the trap of constructing an unfinished object: that is, the <code>build</code> method should make sure that the constructed object is <em>valid</em> and <em>complete</em>, and should raise an exception if that’s not the case. That way, you’ve made sure <em>via the type system</em> that the resulting object will be in a valid state.</p>\n\n<p>Furthermore, having a <code>build</code> method is Java cruft. In C++, you can just define an implicit conversion to the type you want to build. Although there are normally good reasons <em>against</em> implicit conversions, they don’t apply in this particular case – the conversion is safe (if you make it safe, see above) and should never lead to confusion.</p>\n\n<p>With that, I’d replace <code>build</code> by the following:</p>\n\n<pre><code>operator CCPoint() const\n{\n verify_object_is_valid();\n return ccp(xOrigo(), yOrigo());\n}\n</code></pre>\n\n<p>And the usage is shortened a bit:</p>\n\n<pre><code>restartButton->setPosition(\n Positioner().withSize(restartButton->getContentSize())\n .withAlignment(HorizontalAlign::LEFT)\n .withAlignment(VerticalAlign::TOP)\n .withMargin(Position::LEFT, 1)\n .withContainer(ccp(0.0,0.0), contentSize));\n</code></pre>\n\n<p>(Reformatting also helps.)</p>\n\n<p>But note that this is still longer, and not actually clearer, than Loki’s alternative code without a builder.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T20:27:38.047",
"Id": "20573",
"Score": "0",
"body": "Great suggestion with the implicit conversion. \"but sometimes a builder yields clearer code.\" what's your rule-of-thumb/criteria for ctors vs builders? I tend to go for builders if > 4-5 parameters and/or I want to delegate partially built objects and/or the construction is heavy in logic (separate construction from app-logic). I tend to use ctors for objects with 1-3 config-params. While constructors gives combinatorial explosions and/or a myriad of either unnamed alternative constructors or a pool of silly classes PositionerHorizontalAlignCenterVerticalAlignCenterWithNoMargins(container)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T20:29:44.537",
"Id": "20574",
"Score": "0",
"body": "@j-a I have no real rule of thumb, the choice comes up too rarely. I’ve used a builder previously when I wanted the actual object to be immutable and the construction was performed in multiple steps (notably for a complex graph structure) or modifying the actual object was expensive (think `String` vs. `StringBuilder`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T12:01:26.870",
"Id": "20756",
"Score": "0",
"body": "@j-a I think Loki just used `Positioner` and `CCPoint` interchangeably in his code example. In practice, the code could have been made to work via an implicit conversion as well. I’ll complement my answer when I find time, at the moment I’m unfortunately *very* busy because of looming deadlines, sorry."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T08:29:02.277",
"Id": "12684",
"ParentId": "12662",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12684",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T15:19:06.120",
"Id": "12662",
"Score": "2",
"Tags": [
"c++",
"design-patterns"
],
"Title": "Helper class for easily positioning objects in cocos2d-x"
}
|
12662
|
<p>I'm preparing for an interview so I'm trying to solve some problems to stretch my mind. Here is one:</p>
<blockquote>
<p>Describe how you could use a single array to implement three stacks.</p>
</blockquote>
<p>And here is my implementation:</p>
<pre><code>class StackUnderflowError extends RuntimeException {
public StackUnderflowError(String msg) {
super(msg);
}
}
class ThreeStacks<T>{
private T[] array;
private int firstIndex = 0;
private int secondIndex = 1;
private int thirdIndex = 2;
public ThreeStacks(Class<T> classT, int capacity) {
array = (T[])Array.newInstance(classT, capacity);
}
void push(T data, int stack){ //enum to select the stack
switch(stack)
{
case 1: pushOne(data);
break;
case 2: pushTwo(data);
break;
case 3: pushThree(data);
break;
default: throw new IllegalArgumentException("stack");
}
}
T pop(int stack){
switch(stack){
case 1: return popOne();
case 2: return popTwo();
case 3: return popThree();
default: throw new IllegalArgumentException("stack");
}
}
private void pushOne(T data) {
if (firstIndex > array.length - 1) {
throw new StackOverflowError("firstStack");
} else{
array[firstIndex] = data;
firstIndex += 3;
}
}
private void pushTwo(T data) {
if (secondIndex > array.length - 1) {
throw new StackOverflowError("secondStack");
} else{
array[secondIndex] = data;
secondIndex += 3;
}
}
private void pushThree(T data) {
if (thirdIndex > array.length - 1) {
throw new StackOverflowError("thirdStack");
} else{
array[thirdIndex] = data;
thirdIndex += 3;
}
}
private T popOne() {
firstIndex -= 3;
if(firstIndex < 0){
throw new StackUnderflowError("fristStack");
}
return array[firstIndex];
}
private T popTwo() {
secondIndex -= 3;
if(secondIndex < 0){
throw new StackUnderflowError("fristStack");
}
return array[secondIndex];
}
private T popThree() {
thirdIndex -= 3;
if(thirdIndex < 0){
throw new StackUnderflowError("fristStack");
}
return array[thirdIndex];
}
}
</code></pre>
<p>And test:</p>
<pre><code> ThreeStacks<String> threeStacks = new ThreeStacks<>(String.class, 1024);
threeStacks.push("1", 1);
threeStacks.push("2", 2);
threeStacks.push("3", 3);
threeStacks.push("4", 1);
threeStacks.push("5", 2);
threeStacks.push("6", 3);
System.out.println( threeStacks.pop(1) );
System.out.println( threeStacks.pop(2) );
System.out.println( threeStacks.pop(2) );
System.out.println( threeStacks.pop(1) );
//System.out.println( threeStacks.pop(1) );
</code></pre>
<p><strong>How can I improve this?</strong> A few thoughts:</p>
<ul>
<li>use array instead of switch (stacks' indexes)</li>
<li>use enum to choose stack</li>
<li>use ArrayList (if interviewer agrees)</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-20T06:47:11.973",
"Id": "24117",
"Score": "0",
"body": "Do not forget to add `break` in your `switch`"
}
] |
[
{
"body": "<p><em>How can I improve this?</em></p>\n\n<p>This question is a rather interesting one. By upping the count of stacks to three, we can no longer be assured of an optimal utilization of the array (for two, each stack could start from one of the ends).</p>\n\n<p>So the problem here is that of optimal utilization of the array, Your solution divides the array equally into three, so that even if there is space left in one of the stacks, your other stacks are unable to use it.</p>\n\n<p>Perhaps it would be profitable to consider the more general case of storing <code>n</code> stacks in the array.</p>\n\n<p>If you think about it, the problem is remarkably similar to memory allocation or file space allocation in a hard disk. This would be my approach. I assume that the array is an array of integers.</p>\n\n<ul>\n<li>Use reverse end of the array as a normal stack - call it S.</li>\n<li><p>When adding a new (tag,number) <code>(i,x)</code> to the stacks, check if the previous number was added to the same stack <code>i</code>.</p>\n\n<ul>\n<li>If it was, just push it to S</li>\n<li>If not, <code>count</code> the entries of the stack S,\n<ul>\n<li>Write the current stack S to the free cells from the beginning.</li>\n<li>Write the tag (say <code>j</code>) of the stack currently stored in S to the first free cell from the beginning say <code>A[c]</code>.</li>\n<li>Write <code>count</code> to the next free cell <code>A[c+1]</code>.</li>\n<li>Reset S, save <code>i</code> as the current tag, add <code>x</code> to beginning of S</li>\n<li>A block should look like <code>x,x,x,x,x,[0,1,2,3,..,tag,count],_,_</code></li>\n</ul></li>\n<li>Repeat.</li>\n</ul></li>\n</ul>\n\n<p>Reading an entry <code>(i,y?)</code> of stack <code>i</code> is simple,</p>\n\n<ul>\n<li>First check to see if the stack S is the one we need, if so, return the last element from the other end of S</li>\n<li>If not,\n<ul>\n<li>Go to the last element of A, and read the length and tag. </li>\n<li>If the tag is not the one we are looking for, \n<ul>\n<li>skip <code>length</code> entries and read the next tag and length</li>\n<li>repeat until the tag we want is found.</li>\n</ul></li>\n</ul></li>\n<li>If it is, then return immediately previous non-null entry in the block.</li>\n</ul>\n\n<p>This has the problem that the blocks may become fragmented. This can be alleviated by having a compaction triggered once in a while (so that its cost is amortized) to compact the blocks.</p>\n\n<hr>\n\n<p>One improvement is to not use the reverse end as the stack of current tag, but just use the current free cell from the beginning itself. It has the advantage of avoiding copying when the tag is switched.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T20:15:58.597",
"Id": "20434",
"Score": "0",
"body": "But in this solution there is a trade-off between memory and performance. Here is another one http://pastebin.com/r3prLS78"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T20:20:26.280",
"Id": "20435",
"Score": "0",
"body": "Paste it as another answer here :) that way, we have a track of good solutions with trade-offs in the same site."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T20:45:17.153",
"Id": "20437",
"Score": "0",
"body": "@lukas the pasted algorithm is better than the one here I think."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T19:20:01.220",
"Id": "12667",
"ParentId": "12663",
"Score": "1"
}
},
{
"body": "<p>Solution that I found</p>\n\n<p>In this approach, any stack can grow as long as there is any free space in the array.\nWe sequentially allocate space to the stacks and we link new blocks to the previous block. This means any new element in a stack keeps a pointer to the previous top element of that particular stack.</p>\n\n<p>In this implementation, we face a problem of unused space. For example, if a stack deletes some of its elements, the deleted elements may not necessarily appear at the end of the array. So, in that case, we would not be able to use those newly freed spaces.\nTo overcome this deficiency, we can maintain a free list and the whole array space would be given initially to the free list. For every insertion, we would delete an entry from the free list. In case of deletion, we would simply add the index of the free cell to the free list.</p>\n\n<p>In this implementation we would be able to have flexibility in terms of variable space utilization but we would need to increase the space complexity.</p>\n\n<pre><code> int stackSize = 300;\n int indexUsed = 0;\n int[] stackPointer = {-1,-1,-1};\n StackNode[] buffer = new StackNode[stackSize * 3];\n void push(int stackNum, int value) {\n int lastIndex = stackPointer[stackNum];\n stackPointer[stackNum] = indexUsed;\n indexUsed++;\n buffer[stackPointer[stackNum]]=new StackNode(lastIndex,value);\n }\n\nint pop(int stackNum) {\n int value = buffer[stackPointer[stackNum]].value;\n int lastIndex = stackPointer[stackNum];\n stackPointer[stackNum] = buffer[stackPointer[stackNum]].previous;\n buffer[lastIndex] = null;\n indexUsed--;\n return value;\n }\n int peek(int stack) { return buffer[stackPointer[stack]].value; }\n boolean isEmpty(int stackNum) { return stackPointer[stackNum] == -1; }\n\nclass StackNode {\n public int previous;\n public int value;\n public StackNode(int p, int v){\n value = v;\n previous = p;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T20:26:03.793",
"Id": "12668",
"ParentId": "12663",
"Score": "3"
}
},
{
"body": "<p>The implementation you have basically splits your array into 3 equal sub-arrays, and each stack can only use the elements of its subarray. It would be roughly the same as setting the first index to 0, the second index to array.length/3, and the third to array.length*2/3. Instead, you're working based on modular congrence; the first stack uses indices where that have a modulo by 3 of 0, the second stack 1 and the third stack 2.</p>\n\n<p>\"Improving\" it depends on what you want to improve; space efficiency or performance? You could create a stack for which any number of unused indices could store values of any one stack, by implementing two \"slide\" helper methods:</p>\n\n<pre><code>private void SlideRight(int index, int stackNum)\n{\n //keep a count of all elements in the array and make sure this operation\n //will not push an element \"off the edge\"\n if(totalCount + offset > array.length) throw new StackOverflowException();\n\n for(int i=totalCount-1; i>index; i--)\n array[i] = array[i-1];\n\n for(int j=stackNum; j<stacks.length; j++)\n stacks[j]++;\n}\n\nprivate void SlideLeft(int index, int stackNum)\n{\n for(int i=index; i<totalCount-1; i++)\n array[i] = array[i+1];\n\n for(int j=stackNum; j<stacks.length; j++)\n stacks[j]++;\n}\n</code></pre>\n\n<p>These can be used to push and pop values into any stack, up to the full capacity of the array:</p>\n\n<pre><code>public int[] stacks = new int[3]{0,0,0};\n\npublic void Push(int value, int stackNum)\n{\n SlideRight(stacks[stackNum-1], stackNum);\n array[stacks[stackNum-1]] = value;\n stacks[stackNum-1]++;\n totalCount++;\n}\n\npublic void Pop(int stackNum)\n{\n int result = array[stacks[stackNum-1]]\n SlideLeft(stacks[stackNum-1], stackNum);\n stacks[stackNum-1]--;\n totalCount--;\n return result;\n}\n</code></pre>\n\n<p>The downside is having to perform count-N swaps to insert a value into index N (which basically means that pushing or popping from stack X is bound in time to the number of elements in stacks higher than X).</p>\n\n<p>Another option is to use the array to implement a simple \"hashset\"-like structure (with 3 \"hashes\"; one per stack). The general is to create a Node struct, which your primary array will hold copies of. Each Node holds the actual value pushed, and the index of the next lower Node in that stack. To push, create a Node, assign the value and the index of the current \"top\" node of that Stack, then put that Node in the first available spot in the array (which you must keep track of because elements can be added/removed from pretty much anywhere) and remember its location as the new \"top\". To pop, do the opposite; go to the remembered \"top\" index, get that Node, then clear that index (checking to see if it's a lower index than the currently-known \"first available\"), and set the \"top\" node to the popped node's \"next\" index. The advantage is O(1) access in most cases (pushing a node, which requires determining the next null index of the array for the next push, is worst-case linear); the disadvantage is extra space necessary to maintain the links between nodes of a stack.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T18:41:57.010",
"Id": "12711",
"ParentId": "12663",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12668",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T15:51:08.580",
"Id": "12663",
"Score": "3",
"Tags": [
"java",
"interview-questions"
],
"Title": "Describe how you could use a single array to implement three stacks"
}
|
12663
|
<pre><code>(define (merge-sort lst (lt? <))
(define (truthy=? a b)
(eq? (not a) (not b)))
(let sort ((lst lst)
(size (length lst))
(flip #f))
(define (merge l r (res '()))
(cond ((null? l) (append-reverse r res))
((null? r) (append-reverse l res))
((truthy=? (lt? (car r) (car l)) flip)
(merge l (cdr r) (cons (car r) res)))
(else
(merge (cdr l) r (cons (car l) res)))))
(if (<= size 1) lst
(let*-values (((mid) (quotient size 2))
((l r) (split-at lst mid)))
(merge (sort l mid (not flip))
(sort r (- size mid) (not flip)))))))
</code></pre>
<p>Tested with Racket and Guile; requires SRFIs <a href="http://srfi.schemers.org/srfi-1/srfi-1.html">1</a> and <a href="http://srfi.schemers.org/srfi-11/srfi-11.html">11</a>. (If you want to use this for Guile, you will need to adjust the syntax used for optional arguments.)</p>
<p>This version is tailored for Scheme in a number of ways:</p>
<ul>
<li>The length of the list is calculated only once, at the beginning. At each split, the length of the split parts is passed to each recursive call.</li>
<li>The merge step uses a right-unfold rather than a left-unfold, to be tail-recursive. This results in a reversed list at each step.</li>
<li>Rather than reverse the list at each merge, I just keep a flag saying whether the lists are reversed. The merging step takes this flag into account and then does the right kind of merge to maintain sort stability.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T19:53:01.093",
"Id": "20569",
"Score": "0",
"body": "I'm not entirely certain of the protocol here, but are you actually asking a question, or do you just want a general critique?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T19:55:16.840",
"Id": "20570",
"Score": "0",
"body": "@RobertHarvey I'm looking for general critique of style, as well as ways to make the code even more performant (algorithmically speaking, not so much micro-optimisation-wise). I actually do have a more performant version of this code, which I'll post as an answer. Soon. :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T18:13:42.763",
"Id": "21949",
"Score": "0",
"body": "Since you bother to call out the gotcha with `lt?`, why not fix the code like so: `(eq? (and (lt? (car r) (car l)) #t) flip)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-23T16:12:03.120",
"Id": "78619",
"Score": "0",
"body": "@MartinNeal Mostly because, if I'm going there, I may as well define an XNOR operation. Which I'm still considering doing. :-) But actually, I think I can adapt your idea to use `not` instead, so that instead of using `(and foo #t)`, I'm just using `(not foo)` (and swapping the branches, of course). Edit coming up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-23T16:22:12.827",
"Id": "78621",
"Score": "0",
"body": "I ended up creating a `truthy=?` that uses `not`. It's like XNOR with a more readable name. :-D"
}
] |
[
{
"body": "<p>Four years, 1400 views, and two dozen upvotes before a review on a site dedicated to code reviews points toward unreviewability as a prominent feature of the code. What hinders reviewability is, I think, the high level of cognitive load the code places on anyone reading it. </p>\n\n<h2>Reading</h2>\n\n<ol>\n<li><p>The cognitive load begins at the top level. Merge-sort is a well documented algorithm. Like many people interested in programming, I wrote an implementation for an algorithms class. It makes a good assignment because the details are non-trivial (and discovering those details was serious work seventy years ago when the John Von-Neumann for which computing's Von-Neumann Architecture is named, did so...\"how serious?\" one might ask and the answer would be \"Manhattan Project serious\"). I imagine I'm like some other people in that I've forgotten the ins and outs of my implementation and recycled whatever synapses were storing the pseudo-code to something else. For me, merge-sort is vaguely familiar in a sort of \\$\\mathcal{O}(n\\log n)\\$ sort of way since that's the fact that's most likely to be relevant at the <code>sorting</code> level of abstraction.</p></li>\n<li><p>For the purposes of this review, I'll say that the next level down is the top level of the implementation. Here the question claims a clever implementation detail: calculating the length of the list only once. I don't recall how my implementation calculated length or whether it did...I think I used vectors/arrays rather than lists [I wrote it in either Clojure or Racket]. Anyway, being clever makes the code harder to review.</p></li>\n<li><p>At the next level down, the structure induces additional cognitive load. At best the mixture of <code>define</code> and <code>let/let*</code> is inconsistent style. At worst, the <code>let</code>'s just make for less readable code of the sort that made nested <code>define</code>'s worth implementing in Scheme itself.</p></li>\n<li><p>Finally, there's variable names. </p></li>\n</ol>\n\n<h2>Advice</h2>\n\n<ol>\n<li><p>Help the reader by commenting the code. Don't require expertise in merge-sort as a pre-requisite to understanding. Consider using something like the <a href=\"http://www.htdp.org/2001-01-18/Book/node14.htm\" rel=\"nofollow noreferrer\">HtDP Program Recipe</a> as a starting point. Explain the algorithm and use the terms of that explanation in the implementation. </p></li>\n<li><p>I'm reminded of Kernighan's Lever: <em>Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?</em> Looking at the code, it isn't obvious where the innovation is implemented. Even after I obtain some level of merge-sort knowledge, I still have detective work to understand the innovation. Make the innovation explicit.</p></li>\n<li><p>Make everything explicit using <code>define</code> rather than <code>let/let*</code> the syntax is better and the high level concepts can be articulated together rather than mixed in among the implementation details, e.g. <code>merge</code> can be defined alongside <code>truthy=?</code>, <code>mid</code>, etc.</p></li>\n<li><p>There's no need to name parameters/variables using the criteria for minified JavaScript. <code>l</code> and <code>r</code> might be abstractions 'left' and 'right' but left and right are not abstractions that are explicit in the code. It's only via research that a reader might possibly make the connection.</p></li>\n</ol>\n\n<p>A bit more on Item <em>2</em>: If performance is a concern the question of why lists and parameter passing rather than vectors or some other data structure seems relevant. Going further, benchmarking is probably the best justification for added complexity:</p>\n\n<blockquote>\n <p>Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%. </p>\n</blockquote>\n\n<p>Fast sorting seems to be a place where using an FFI is the road to meaningful improvement for interestingly sized data.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-23T19:04:47.237",
"Id": "147918",
"ParentId": "12666",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T18:29:22.890",
"Id": "12666",
"Score": "26",
"Tags": [
"sorting",
"scheme",
"mergesort"
],
"Title": "Merge sort in Scheme"
}
|
12666
|
<p>This class holds message types that are sent to the client which knows what to do with them. It is basically a small registry pattern where I can consolidate message types. <code>|P|</code> and <code>|F|</code> are read by the client...and I use these for simple data passing when I don't need the complexity of JSON. The programmer is expected to know which messages types are available.</p>
<p>I've added in a <code>array_key_exists()</code> as a defensive measure against a progammer calling a message that does not exit. I did this as someone said this is best practice...I'm looking for a second opinion...as in this case it is not a big deal but overall "defensive coding" would increase my library size / efficiency by 10-20%. Can I take this out?</p>
<pre><code><?php
class IMessage
{
private $PASS = '|P|';
private $FAIL = '|F|';
private $messages = array();
public function __construct()
{
$this->messages['PASS'] = $this->PASS;
$this->messages['name'] = $this->FAIL . 'name';
$this->messages['email'] = $this->FAIL . 'email_s';
$this->messages['pass'] = $this->FAIL . 'pass';
$this->messages['url'] = $this->FAIL . 'url';
$this->messages['title'] = $this->FAIL . 'title';
$this->messages['tweet'] = $this->FAIL . 'tweet';
$this->messages['empty'] = $this->FAIL . 'empty';
$this->messages['same'] = $this->FAIL . 'same';
$this->messages['taken'] = $this->FAIL . 'taken';
$this->messages['validate'] = $this->FAIL . 'validate';
}
public function get( $type )
{
if( !array_key_exists($type, $this->messages ) )
{
echo "Programmer Error: You called a key that does not exist";
}
else
{
return $this->messages[ $type ];
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Well, you are doing this a little redundantly...</p>\n\n<pre><code>$keys = array(\n 'name',\n 'email',\n //etc...\n);\n\n$messages = array(\n 'PASS' => $this->PASS,\n);\n\nforeach( $keys AS $key ) { $messages[ $key ] = $this->FAIL . $key; }\n\n$this->messages = $messages;\n</code></pre>\n\n<p>Also, your get function has a fatal error. You currently have a check to see if a key exists, and if it doesn't it will output an error message. This is incomplete, if that key doesn't exist it will output the error message then PHP will throw an undefined index error because <code>$key</code> does not exist. To avoid this you should have it return that error message when you set it or have it return FALSE. I think such a check is good, since it seems you are dealing with user supplied information. If this was a private method and you knew the information you were passing it was reliable, then I would say its unnecessary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T18:11:59.703",
"Id": "20549",
"Score": "0",
"body": "@stack.user.0 I didn't mean to comment on its lack of content, only to point out that there is a fatal error that will occur because of it. Will change answer so it is more clear"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T18:24:51.627",
"Id": "20555",
"Score": "0",
"body": "@stack.user.0 Sorry gotdistracted for a moment. The answer is updated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T18:31:41.167",
"Id": "20556",
"Score": "0",
"body": "thanks..good catch...this is programmer supplied input..not a site user...a programmer will write object->get()...considering that programmer might be me...a check is indeed a good idea. \nI just need to put it an else statement. done."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T18:55:52.517",
"Id": "20561",
"Score": "0",
"body": "If you do .js need input on http://codereview.stackexchange.com/questions/12695/mvc-control-module-architecture-design-structure-review"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T19:22:17.210",
"Id": "20565",
"Score": "0",
"body": "@stack.user.0: *very lightly* mostly basic needs and minor AJAX. I can take a look at it and give you my perspective from a purely PHP point of view though. Should translate relatively well."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T16:14:33.487",
"Id": "12705",
"ParentId": "12669",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12705",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-17T20:59:45.550",
"Id": "12669",
"Score": "1",
"Tags": [
"php"
],
"Title": "class IMessge - returns user message types | loop similar items"
}
|
12669
|
<p>I have a file with an specific format. It's divided in stripes of 1058816 bytes:</p>
<ul>
<li>4096 bytes with only a 64 bit unsigned integer.</li>
<li>An array of 512 64 bit unsigned integer.</li>
<li>An array of 512 32 bit unsigned integer.</li>
<li>An array of 512 elements with 2048 bytes each one.</li>
</ul>
<p>I have to read the file, change some values and write it again.</p>
<p>This is what I'm doing to work with it:</p>
<pre><code>struct Segment {
char bytes[2048];
};
struct Metadata {
uint64_t serial;
};
class Stripe {
uint8_t ptr[STRIPE_SIZE];
Metadata *metadata;
uint64_t *hash_array;
uint32_t *size_array;
Segment *segment_array;
do_something(fstream_obj)
{
fstream_obj.read(ptr, STRIPE_SIZE);
metadata = new(ptr) COSSMetadata;
hash_array = new(ptr + METADATA_BYTES) uint64_t[ARRAY_SIZE];
size_array = new(ptr + METADATA_BYTES + HASH_ARRAY_BYTES) uint32_t[ARRAY_SIZE];
segment_array = new(ptr + METADATA_BYTES + HASH_ARRAY_BYTES + SIZE_ARRAY_BYTES) Segment[ARRAY_SIZE];
// .... code to change the the values.....
fstream_obj.write(ptr, STRIPE_SIZE);
}
};
</code></pre>
<p>I have more experience with C. I'm not sure if this is the best to do what I want. I think that is faster, because I'm not doing any conversion and the information in ptr already is in the format of the structures. I want to hear opinios of more experience C++ coderes.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T02:28:28.717",
"Id": "20448",
"Score": "0",
"body": "@user315052 Sorry, my example is broken, I'll fix it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T02:33:03.397",
"Id": "20449",
"Score": "0",
"body": "And looking on it better, the pointer arithmetic is broken too :)"
}
] |
[
{
"body": "<p>Placement <code>new</code> is probably the way to go, but you're invoking undefined behaviour because your data buffers may have a different alignment than what you create with placement <code>new</code> and force in there.</p>\n\n<p>By using these sort of members:</p>\n\n<pre><code>class Stripe {\n std::tr1::aligned_storage<sizeof(Metadata),std::tr1::alignment_of<Metadata>::value> metadata_area;\n Metadata* metadata;\n public:\n Stripe()\n : metadata(0) /*...*/\n {\n }\n void postConstructionInit() {\n if (metadata)\n metadata->~Metadata();\n metadata = new(&metadata_area) Metadata();\n }\n ~Stripe() {\n if (metadata)\n metadata->~Metadata();\n }\n};\n</code></pre>\n\n<p>You can get around that problem, while still allowing late initialisation.</p>\n\n<p>Note that if you can manage to write your initialisation code in the constructor, you can make your life easier:</p>\n\n<pre><code>class Stripe {\n Metadata metadata;\n public:\n Stripe()\n : metadata() /* actual initialisation */\n {\n }\n // note that in this case, no explicit destructor implementation is *required*\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T02:23:50.853",
"Id": "12675",
"ParentId": "12674",
"Score": "2"
}
},
{
"body": "<p>I'm not 100% sure how idiomatic this is, but since your data is so structured, it might be worth representing the entire structure as just that: a <a href=\"https://en.wikipedia.org/wiki/Plain_old_data_structure\" rel=\"nofollow\">POD</a> <code>struct</code> that contains the exact sizes and layout desired.</p>\n\n<pre><code>struct Metadata {\n uint64_t serial;\n char _padding_[METADATA_BYTES - 8];\n};\n\nstruct Segment {\n char bytes[2048];\n};\n\nstruct Stripe {\n Metadata metadata;\n uint64_t hash_array[512];\n uint32_t size_array[512];\n Segment segment_array[512];\n};\n</code></pre>\n\n<p>(There is probably a better way of doing the padding.)</p>\n\n<p>This means that the layout in memory is exactly the same as the layout on disk, and <code>new Stripe</code> will allocate the appropriate amount of memory with all the components contiguous as desired, without having to do the specific placement yourself. This means you can just allocate the structure, then <code>file.read(stripe, sizeof(Stripe))</code> and <code>file.write(stripe, sizeof(Stripe))</code> directly.</p>\n\n<p>You could put a wrapper class around it:</p>\n\n<pre><code>class Stripe {\n Stripe_struct data;\n\n // methods...\n}\n</code></pre>\n\n<p>Or just convert the original <code>Stripe</code> struct to a class itself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T18:11:35.783",
"Id": "20548",
"Score": "0",
"body": "I like this solution. I don't know what I did that horrible thing at first :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T03:07:14.157",
"Id": "12676",
"ParentId": "12674",
"Score": "4"
}
},
{
"body": "<p>Well, if you are reading and writing to the same file you could just seekp(loc) to the required bit you want to change and write just those bits. Or you could just copy the file and edit the copy as I've described.</p>\n\n<p>To copy quickly:</p>\n\n<pre><code> std::ifstream fromf(from.string(), std::ios::binary);\n if (fromf.fail())\n {\n ; // Error...\n return;\n }\n std::ofstream tof(to.string(), std::ios::binary);\n if (tof.fail())\n {\n ; // Error...\n return;\n }\n tof << fromf.rdbuf();\n</code></pre>\n\n<p>Hopefully, you don't have to worry about endianness of the file. If you do that you might have to swap bytes of individual integers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T03:18:00.263",
"Id": "12677",
"ParentId": "12674",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "12676",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T02:02:32.027",
"Id": "12674",
"Score": "2",
"Tags": [
"c++"
],
"Title": "Writing structured file in C++"
}
|
12674
|
<p>I am trying to use jQuery to make calculations with a table containing football data. Can I improve what I have done here? Is my code well-structured and executed, or does it need improvements?</p>
<p><a href="http://jsfiddle.net/userdude/kCanv/" rel="nofollow">http://jsfiddle.net/userdude/kCanv/</a></p>
<p><strong>HTML - Table</strong></p>
<pre><code><table id="table-pts">
<thead>
<tr>
<th colspan="3">&nbsp;</th>
<th colspan="5">HOME</th>
<th colspan="5">AWAY</th>
<th colspan="5">SUMMARY</th>
<th colspan="2">&nbsp;</th>
</tr>
<tr>
<th>Pos</th>
<th class="team">Team</th>
<th>GP</th>
<th>W</th>
<th>D</th>
<th>L</th>
<th>F</th>
<th>A</th>
<th>W</th>
<th>D</th>
<th>L</th>
<th>F</th>
<th>A</th>
<th>W</th>
<th>D</th>
<th>L</th>
<th>F</th>
<th>A</th>
<th>GD</th>
<th>Pts</th>
</tr>
</thead>
<tbody>
<tr id="1" class="edit_tr">
<td></td>
<td class="team">
&nbsp;
</td>
<td><span id="summary_GP_1"></span></td>
<td>
<span id="home_w_1" class="text">1</span>
<input type="text" value="1" class="editbox" id="home_w_input_1"/>
</td>
<td>
<span id="home_d_1" class="text">3</span>
<input type="text" value="3" class="editbox" id="home_d_input_1"/>
</td>
<td>
<span id="home_l_1" class="text">2</span>
<input type="text" value="2" class="editbox" id="home_l_input_1"/>
</td>
<td>
<span id="home_f_1" class="text">4</span>
<input type="text" value="4" class="editbox" id="home_f_input_1"/>
</td>
<td>
<span id="home_a_1" class="text">76</span>
<input type="text" value="76" class="editbox" id="home_a_input_1"/>
</td>
<td>
<span id="away_w_1" class="text">8</span>
<input type="text" value="8" class="editbox" id="away_w_input_1"/>
</td>
<td>
<span id="away_d_1" class="text">9</span>
<input type="text" value="9" class="editbox" id="away_d_input_1"/>
</td>
<td>
<span id="away_l_1" class="text">10</span>
<input type="text" value="10" class="editbox" id="away_l_input_1"/>
</td>
<td>
<span id="away_f_1" class="text">11</span>
<input type="text" value="11" class="editbox" id="away_f_input_1"/>
</td>
<td>
<span id="away_a_1" class="text">12</span>
<input type="text" value="12" class="editbox" id="away_a_input_1"/>
</td>
<td><span id="summary_w_1" ></span></td>
<td><span id="summary_d_1" class="text"></span></td>
<td><span id="summary_l_1" class="text"></span></td>
<td><span id="summary_f_1" class="text"></span></td>
<td><span id="summary_a_1" class="text"></span></td>
<td><span id="summary_GD_1" class="text"></span></td>
<td><span id="summary_Pts_1" class="text"></span></td>
</tr>
<tr id="2" class="edit_tr">
<td></td>
<td class="team">
&nbsp;
</td>
<td><span id="summary_GP_2"></span></td>
<td>
<span id="home_w_2" class="text">1</span>
<input type="text" value="1" class="editbox" id="home_w_input_2"/>
</td>
<td>
<span id="home_d_2" class="text">3</span>
<input type="text" value="3" class="editbox" id="home_d_input_2"/>
</td>
<td>
<span id="home_l_2" class="text">2</span>
<input type="text" value="2" class="editbox" id="home_l_input_2"/>
</td>
<td>
<span id="home_f_2" class="text">4</span>
<input type="text" value="4" class="editbox" id="home_f_input_2"/>
</td>
<td>
<span id="home_a_2" class="text">76</span>
<input type="text" value="76" class="editbox" id="home_a_input_2"/>
</td>
<td>
<span id="away_w_2" class="text">8</span>
<input type="text" value="8" class="editbox" id="away_w_input_2"/>
</td>
<td>
<span id="away_d_2" class="text">9</span>
<input type="text" value="9" class="editbox" id="away_d_input_2"/>
</td>
<td>
<span id="away_l_2" class="text">10</span>
<input type="text" value="10" class="editbox" id="away_l_input_2"/>
</td>
<td>
<span id="away_f_2" class="text">11</span>
<input type="text" value="11" class="editbox" id="away_f_input_2"/>
</td>
<td>
<span id="away_a_2" class="text">12</span>
<input type="text" value="12" class="editbox" id="away_a_input_2"/>
</td>
<td><span id="summary_w_2" ></span></td>
<td><span id="summary_d_2" class="text"></span></td>
<td><span id="summary_l_2" class="text"></span></td>
<td><span id="summary_f_2" class="text"></span></td>
<td><span id="summary_a_2" class="text"></span></td>
<td><span id="summary_GD_2" class="text"></span></td>
<td><span id="summary_Pts_2" class="text"></span></td>
</tr>
</tbody>
</table>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>#table-pts {
color: #333;
text-align: center;
font-size: 12px;
width: 100%;
}
#table-pts tbody tr {
border-bottom: 1px solid #dddcdc;
padding: 10px;
line-height: 30px;
}
#table-pts tbody td{
vertical-align: middle;
padding: 5px 0;
}
#table-pts thead tr th{
text-align: center;
line-height: 30px;
background: #233825;
color: #FFF;
border-left: 1px solid #CCC;
width: 30px;
}
#table-pts .table-team{
width: 10px;
text-align: left;
padding: 3px 7px 3px 7px;
}
#table-pts .editbox{
display: none;
border: 1px solid #CCC;
text-align: center;
}
#table-pts .odd{background: #fafafa;}
.table-hl
{
width: 70px;
}
#table-pts input{
width: 20px;
}
</code></pre>
<p><strong>jQuery</strong></p>
<pre><code>$(document).ready(function(){
$(".edit_tr").click(function(){
var ID = $(this).attr('id');
$("#home_w_"+ID).hide();
$("#home_d_"+ID).hide();
$("#home_l_"+ID).hide();
$("#home_f_"+ID).hide();
$("#home_a_"+ID).hide();
$("#away_w_"+ID).hide();
$("#away_d_"+ID).hide();
$("#away_l_"+ID).hide();
$("#away_f_"+ID).hide();
$("#away_a_"+ID).hide();
$("#home_w_input_"+ID).show();
$("#home_d_input_"+ID).show();
$("#home_l_input_"+ID).show();
$("#home_f_input_"+ID).show();
$("#home_a_input_"+ID).show();
$("#away_w_input_"+ID).show();
$("#away_d_input_"+ID).show();
$("#away_l_input_"+ID).show();
$("#away_f_input_"+ID).show();
$("#away_a_input_"+ID).show();
}).change(function(){
// calculate point in table football
var ID = $(this).attr('id');
var home_w = parseInt($("#home_w_input_"+ID).val());
var home_d = parseInt($("#home_d_input_"+ID).val());
var home_l = parseInt($("#home_l_input_"+ID).val());
var home_f = parseInt($("#home_f_input_"+ID).val());
var home_a = parseInt($("#home_a_input_"+ID).val());
var away_w = parseInt($("#away_w_input_"+ID).val());
var away_d = parseInt($("#away_d_input_"+ID).val());
var away_l = parseInt($("#away_l_input_"+ID).val());
var away_f = parseInt($("#away_f_input_"+ID).val());
var away_a = parseInt($("#away_a_input_"+ID).val());
var summaryW = home_w + away_w;
var summaryD = home_d + away_d;
var summaryL = home_l + away_l;
var summaryF = home_f + away_f;
var summaryA = home_a + away_a;
var summaryGD = summaryF + summaryA;
var summaryPts = summaryW * 3 +summaryD * 1;
var summaryGP = summaryW + summaryD + summaryL;
/* var dataString = 'id='+ ID + '&home_w='+ home_w + '&home_d='+ home_d + '&home_l='+ home_l + '&home_f='+ home_f + '&home_a='+ home_a + '&away_w='+ away_w + '&away_d='+ away_d + '&away_l='+ away_l + '&away_f='+ away_f + '&away_a='+ away_a + '&action=edit_pts';
$("#home_w_"+ID).html('<img src="load.gif"/>');
$.ajax({
type: "POST",
url: "table_pts_action_ajax.php",
data: dataString,
cache: false,
success: function(html)
{*/
// live update in my table football
$("#home_w_"+ID).html(home_w);
$("#home_d_"+ID).html(home_d);
$("#home_l_"+ID).html(home_l);
$("#home_f_"+ID).html(home_f);
$("#home_a_"+ID).html(home_a);
$("#away_w_"+ID).html(away_w);
$("#away_d_"+ID).html(away_d);
$("#away_l_"+ID).html(away_l);
$("#away_f_"+ID).html(away_f);
$("#away_a_"+ID).html(away_a);
$("#summary_w_"+ID).html(summaryW);
$("#summary_d_"+ID).html(summaryD);
$("#summary_l_"+ID).html(summaryL);
$("#summary_f_"+ID).html(summaryF);
$("#summary_a_"+ID).html(summaryA);
$("#summary_GD_"+ID).html(summaryGD);
$("#summary_Pts_"+ID).html(summaryPts);
$("#summary_GP_"+ID).html(summaryGP);
});
$("#table-pts tbody tr").each(function(){
// page is load finish.. calculate point in table football
var ID = $(this).attr('id');
var txtHomeW = parseInt($("#home_w_"+ID).text());
var txtHomeD = parseInt($("#home_d_"+ID).text());
var txtHomeL = parseInt($("#home_l_"+ID).text());
var txtHomeF = parseInt($("#home_f_"+ID).text());
var txtHomeA = parseInt($("#home_a_"+ID).text());
var txtAwayW = parseInt($("#away_w_"+ID).text());
var txtAwayD = parseInt($("#away_d_"+ID).text());
var txtAwayL = parseInt($("#away_l_"+ID).text());
var txtAwayF = parseInt($("#away_f_"+ID).text());
var txtAwayA = parseInt($("#away_a_"+ID).text());
var summaryW = parseInt(txtHomeW+txtAwayW);
var summaryD = parseInt(txtHomeD+txtAwayD);
var summaryL = parseInt(txtHomeL+txtAwayL);
var summaryF = parseInt(txtHomeF+txtAwayF);
var summaryA = parseInt(txtHomeA+txtAwayA);
var summaryGD = parseInt(summaryF-+summaryA);
var summaryPts = parseInt(summaryW * 3 + summaryD * 1);
var summaryGP = parseInt(summaryW + summaryD + summaryL);
$(this).find("#summary_w_"+ID).text(summaryW);
$(this).find("#summary_d_"+ID).text(summaryD);
$(this).find("#summary_l_"+ID).text(summaryL);
$(this).find("#summary_f_"+ID).text(summaryF);
$(this).find("#summary_a_"+ID).text(summaryA);
$(this).find("#summary_GD_"+ID).text(summaryGD);
$(this).find("#summary_Pts_"+ID).text(summaryPts);
$(this).find("#summary_GP_"+ID).text(summaryGP);
});
// Edit input box click action
$(".editbox").mouseup(function(){
return false;
});
// Outside click action
$(document).mouseup(function(){
$(".editbox").hide();
$(".text").show();
});
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T06:07:39.347",
"Id": "20466",
"Score": "3",
"body": "You need to use classes where you've got all of those `id`s being repetitively called. If you use a class, you can use DOM traversal techniques like `$.siblings('.summary_w_d')` instead of looping exhaustively over each row like that. When you see that kind of thing, it really should be refactored."
}
] |
[
{
"body": "<p>If you see lines that look awfully similar in your code, usually it's a strong smell and cry for some refactoring. Much of your code could be generalize to be handled by a few helper functions.</p>\n\n<p>Also, using some arrays (or other data structures) to list the elements to watch and modify, you could easily iterate over them and pass them to these helper functions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T05:04:11.843",
"Id": "12683",
"ParentId": "12679",
"Score": "5"
}
},
{
"body": "<p>I second @haylem's suggestions, and add:</p>\n\n<h2>Invalid ids</h2>\n\n<p>The ids of your <code>tr</code> are invalid. <a href=\"http://www.w3.org/TR/html4/types.html#type-name\" rel=\"nofollow noreferrer\">They must begin with a letter</a>. Perhaps <code>line1</code> instead of <code>1</code>?<br>\nThen your other ids could be classes, and you could target them as <code>#line2 .home_a</code> instead of <code>#home_a_1</code>.</p>\n\n<h2>Register handlers with <code>.on()</code></h2>\n\n<p>You should also use JQuery 1.7's <code>.on()</code> syntax:</p>\n\n<pre><code>$('#table-pts .edit_tr').on({\n 'click': function () {\n //...\n },\n 'change': function() {\n //...\n }\n});\n</code></pre>\n\n<h2>Use <code>+</code> to coerce numbers, not <code>parseInt(a)</code></h2>\n\n<p>Use the unary operator <code>+</code> to coerce numeric values. It is not only easier, but also safer than <code>parseInt()</code>: <a href=\"https://stackoverflow.com/a/2243631/148412\">https://stackoverflow.com/a/2243631/148412</a></p>\n\n<p>So,<br>\n<code>var home_w = +$(\"#home_w_input_\"+ID).val();</code><br>\ninstead of<br>\n<code>var home_w = parseInt($(\"#home_w_input_\"+ID).val());</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T14:23:41.543",
"Id": "12887",
"ParentId": "12679",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T04:03:07.287",
"Id": "12679",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"html",
"css"
],
"Title": "Calculations with a table containing football data"
}
|
12679
|
<p>Please review the following code and list all the coding errors and poor coding practices that you can see in this code.</p>
<pre><code>function output()
{
// Check authorization
if(is_authorized())
{
$authorized = true;
include('/path/to/' . $_REQUEST['module'] . '.php');
}
echo "<ul>"
$conn = mysql_connect( "dbserver.com:6789", "dbyuser", "dbpassWd" );
mysql_select_db( "kum", $conn ); // selects a database
$q = " SELECT * FROM main WHERE id > " . $_GET["id"]. ";";
$res = mysql_query( $q, $conn);
while( $row = mysql_fetch_assoc( $res ) )
{
echo "<li>".$row['description']."</li>";
}
echo "</ul><br><ul>";
$q = " SELECT * FROM main WHERE id < " . $_GET["id"]. ";";
$res = mysql_query( $q, $conn);
while( $row = mysql_fetch_assoc( $res ) )
{
// Display the status if it is authorized, otherwise display N/A
echo "<li>".$row['description']. "(" .
$authorized ? $row['status'] : "N/A" . ")</li>";
}
echo "</ul>";
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T04:55:30.047",
"Id": "20451",
"Score": "0",
"body": "Will post a proper answer later, but a few things jump out at me. Namely, SQL injection, your `include` is open to cross directory including, you don't check that any of the keys are set in your array accesses, and you don't escape your HTML output."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T04:56:11.310",
"Id": "20452",
"Score": "2",
"body": "Can you please explain it little more ... ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T05:06:41.230",
"Id": "20458",
"Score": "0",
"body": "Other than the first section, http://codereview.stackexchange.com/questions/12647/php-dynamic-insert-mysql-is-there-a-better-way-than-this/12649#12649 should explain it for the most part."
}
] |
[
{
"body": "<ul>\n<li>magic strings,</li>\n<li>DB connection not closed,</li>\n<li>DB errors not handled,</li>\n<li>no prepared statements with safe query parameters,</li>\n<li>injectable request and query parameters,</li>\n<li>mix of UI and logic code,</li>\n<li>no HTML encoding,</li>\n<li>2 of the 3 comments are very redundant with the line they comment.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T04:57:41.667",
"Id": "20453",
"Score": "0",
"body": "+1. However: \"no prepared statements with safe query parameters\" Not strictly necessary, but yes, PDO or MySQLi is much better than mysql_*. And for \"DB connection not closed\" -- scripting languages are used for a reason :). (A much better critique might be that some random output method has no business making a DB connection in the first place."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T04:59:27.297",
"Id": "20454",
"Score": "0",
"body": "@Corbin: thanks. Regarding the better critique, that's what I mean by the mix of UI and logic code. That's utterly wrong. I'm not sure I get the point about scripting languages. If you mean that it's OK to whip up a script to query a DB and not care to close the DB or check errors, that's fair enough, but then I'm not sure the OP would ask for a review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T05:01:56.557",
"Id": "20455",
"Score": "0",
"body": "@Corbin: also, you're right, prepared statements are not necessary, it's more the lack of parameterized queries that bugged me at first sight. (also OK, I guess, if it's a script for personal use, but that coupled with the _GET/_REQUEST makes me think there's really potential for trouble :) )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T05:02:04.607",
"Id": "20456",
"Score": "0",
"body": "Checking for errors is definitely necessary, however, assuming the script is short lived, there's really no point in explicitly closing the connection. mysql_connect resources have a bit special handling, but most resources will be closed automatically when the scope of the function ends. (We should probably just accept this as opinion, really. There's definitely no down side to explicitly closing the connection. From a purely logical point of view, I can't particularly defend my laziness. I'm just lazy :p.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T05:03:03.123",
"Id": "20457",
"Score": "0",
"body": "Even for personal use I would escape query parameters. Escaping isn't just about security; it's also about correctness. A user (or yourself if it's a personal script) may forget that `O'Reilly` is going to break the script."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T05:07:04.367",
"Id": "20459",
"Score": "0",
"body": "@Corbin: I'd say it should be a reflex, a second nature. It's like learning to not go at a red light. If you get into your mind that it's OK to run it at midnight when there's no one in sight, you're conditioning yourself and diminishing your reflexes's usefulness for when that big fat truck will clean you up. Same for code. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T05:09:15.533",
"Id": "20461",
"Score": "0",
"body": "But a truck will kill you, and not closing the connection will affect absolutely nothing 99.9999999% of the time. A more accurate analogy may: You *should* look both ways before you cross because a giant chuck may clean you up, however, if you step in front of a truck, PHP will *likely* (but not always) hoist you up out of the road and move you out of the path :)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T05:11:17.353",
"Id": "20462",
"Score": "0",
"body": "@Corbin: was talking about the parameterized queries. And I'd still apply the principle to closing connections, as one day you may switch languages and have lost that reflex of looking both ways because you expect PHP to save you, and it won't be there. (and expecting PHP to save you, in the first place, seems very misguided to me... :) )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T05:50:17.513",
"Id": "20464",
"Score": "0",
"body": "Depending on the language, that expectation may still be there. For example RAII in C++. But yes, I do agree that depending on PHP to save you is a very bad idea. Like I said before, I have no logical (or valid) argument for not closing it. I'm just lazy, and 99% of the time, it will be fine. (Even lazy people like me though should understand the implications of not closing it, so my initial response should have been much different. Additionally, you are correct: on a code review site, it is definitely valid to suggest best practices, and that includes closing resources explicitly.)"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T04:55:28.097",
"Id": "12681",
"ParentId": "12680",
"Score": "5"
}
},
{
"body": "<p><strong>REQUEST / GET Array</strong></p>\n\n<p>Would suggest not using the REQUEST array. Because this data is so easy to hijack it is a poor choice. Better to simply use the right array (GET, POST, COOKIE, SESSION) and if it could be one of a number of them, then set up statement(s) to return the correct one. Also, I would not immediately use any value from any user provided array directly in my program. It should be sanitized and validated first. Check out PHP's <code>filter_input()</code> function. Here's an example of it.</p>\n\n<pre><code>$id = filter_input( INPUT_GET, 'id', INPUT_SANITIZE_NUMBER_INT );\n//Equivalent to sanitizing and validating $id = $_GET['id'];\n</code></pre>\n\n<p><strong>Variables</strong></p>\n\n<p>Make sure your variables are available for each instance a function might be run! Right now <code>$authorized</code> is only ever defined if the contents of that first if statement are processed. Because of this, if <code>is_authorized()</code> fails then your second mysql while loop would produce errors because <code>$authorized</code> was never defined. Also, that variable need not be separate from that function. <code>is_authorized()</code> obviously returns a boolean, or something that can be used as a boolean, should be the former rather than the later. Since <code>$authorized</code> needs to always be set, and its value is dependent upon that function, why not just set it to the return value of that function?</p>\n\n<pre><code>$authorized = is_authorized();\nif( $authorized ) { }\n</code></pre>\n\n<p><strong>Ternary Operations</strong></p>\n\n<p>Ternary operations are good for simple things, such as setting a variable. What they are not good for is long statements, string concatenation, and other such more complicated tasks. They can do it, but they lead to illegible code and mistakes. I mainly point this out because your ternary operation is flawed. Currently it will not end the parenthesis or end the list item because that is considered part of the \"else\" statement in the ternary operation. A better way to perform your ternary operation would be to remove it from the string and declare it beforehand. This will prevent all such mishaps in the future and is easier to read.</p>\n\n<pre><code>$status = $authorized ? $row['status'] : 'N/A';\n</code></pre>\n\n<p><strong>PHP Strings</strong></p>\n\n<p>Once this is done then you can insert it into the string. Let me also point out that there are two types of PHP strings. Strings that are processed for variables and entities and strings that aren't. The first uses double quotes (\"\") to enclose a string and add a little bit of overhead to PHP, unnoticeable really, so that it knows to search that string for items to escape. The later uses single quotes ('') and is only ever used for holding static strings. There is no overhead to these strings because PHP ignores them. That being said, you are telling PHP that all of your string have variables and entities in them to be escaped, so PHP has to process them. As I said, the overhead isn't really noticeable, but it is there and unnecessary. So I would write that echo statement you had your ternary operation in like so:</p>\n\n<pre><code>echo \"<li>{$row['description']}($status)</li>\";\n//OR\necho '<li>' . $row['description'] . \"($status)</li>\";\n//OR EVEN\necho '<li>' . $row['description'] . '(' . $status . ')</li>';\n</code></pre>\n\n<p>Out of all of those I prefer the first implementation, but it is a matter of preference. Honestly this bit on strings might be considered preference as well, but I believe this optimization is standard and that my examples are also easier to read, minus the third which is more or less the same.</p>\n\n<p><strong>Haylem and Corbin</strong></p>\n\n<p>I mostly agree with them, but I believe an explanation is in order instead of just all these terms you might not have heard of before, or don't understand.</p>\n\n<p><strong>\"no prepared statements with safe query parameters\" Not strictly necessary, but yes, PDO or MySQLi is much better than mysql_*.</strong></p>\n\n<p>From my understanding mysql is also getting <a href=\"http://kr.php.net/manual/en/mysqlinfo.api.choosing.php\" rel=\"nofollow\">deprecated</a>. But maybe I've heard wrong. Don't do much with MySQL to know, so keep your eye out for this. It is good for learning the basics on though. Continue what you are doing, just be aware that there are better, and safer (security wise), solutions out there that you should eventually look into. And that eventually you may have to change any mysql code.</p>\n\n<p><strong>DB connection not closed\" -- scripting languages are used for a reason</strong></p>\n\n<p>I still agree that it should be closed. This will prevent the connection from being used after you are done with it. Not sure how it is done, but I still think it is a valid concern. Sure PHP is very forgiving and should close it for you, but I believe writing the extra line won't hurt and can only help.</p>\n\n<p><strong>some random output method has no business making a DB connection in the first place</strong></p>\n\n<p>What they are talking about here is called Separation of Concerns. In my opinion its the first step to learning OOP. Don't be concerned with OOP quite yet, but it is a good idea to start learning this concept. Basically it states that functions should only be concerned with one thing. A well written function can be described using its name only and should not do anything its name does not imply. From your output function I would expect it to only \"output\" information, never to connect to a database and retrieve it. I would instead expect to see a <code>connectToDB()</code> function, or something similar. And maybe a <code>fetch()</code> function for those mysql queries. So your output function would more closely resemble this (all suggestions implemented here):</p>\n\n<pre><code>connectToDB();\n\n$id = filter_input( INPUT_GET, 'id', INPUT_SANITIZE_NUMBER_INT );\n$res1 = fetch(\" SELECT * FROM main WHERE id > $id;\");\n$res2 = fetch(\" SELECT * FROM main WHERE id < $id;\");\n\nfunction output( $res1 , $res2 )\n{\n // Check authorization\n $authorized = is_authorized();\n if( $authorized )\n {\n include('/path/to/' . $_REQUEST['module'] . '.php');\n }\n echo \"<ul>\"\n\n while( $row = $res1 )\n {\n echo \"<li>\".$row['description'].\"</li>\";\n }\n\n echo \"</ul><br><ul>\";\n\n while( $row = $res2 )\n {\n // Display the status if it is authorized, othewise display N/A\n $status = $authorized ? $row['status'] : \"N/A\";\n echo \"<li>{$row['description']}($status)</li>\";\n }\n\n echo \"</ul>\";\n}\n</code></pre>\n\n<p>Even this is not fully optimized, but it will give you an idea and a place to start. Further optimization might see those while statements turned into a single function so that it could be reused. Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T00:14:40.443",
"Id": "20600",
"Score": "0",
"body": "(Warning: mini-rant incoming :p) The single vs double quotes psuedo-myth needs to die. There is no meaningful performance impact at all. If 1ns really matters, then PHP is the wrong language. Single quotes should be used when they're more readable, and double quotes should be used when they're more readable. That's it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T00:15:36.917",
"Id": "20602",
"Score": "0",
"body": "Oh, and the `while( $row = $res1 )` will be an infinite loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T12:59:30.670",
"Id": "20620",
"Score": "0",
"body": "@Corbin: Not if it performs the `mysql_fetch_assoc()` as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T13:05:51.253",
"Id": "20621",
"Score": "0",
"body": "@Corbin: It's not really a \"myth\" if it does indeed effect performance. However, I did specifically say that it was negligible. I'm not really implying to do this for the speed advantage but because PHP offers a built-in string processor and it is not being used in this script. I gave reasons to use the processor version, which are sound if you realize that by using double quotes with no reason you will find that you need to escape characters you would not need to if you were just using single quotes. Sometimes it does not matter, then I say use whichever quotes you want."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T22:25:52.157",
"Id": "20681",
"Score": "0",
"body": "Well, part of my pet peeve with people addressing the string differences is when it's just a blind \"double quotes are slow!\" It's not nearly as simple as your paragraph (though it is a good explanation without diving into details). Strings are parsed during the lexing phase, not run time. \"a{$v}$b\" becomes a string with interpolation, and 'a' . $v . 'b' is concatenation. At run time, \"a\" . $v . \"b\" and 'a' . $v . 'b' are identical in performance (though the lexing phase will take longer to parse the double quotes). Anyway, just me being overly picky :)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T08:51:29.227",
"Id": "20842",
"Score": "1",
"body": "To anyone curious the mysql extension is definitely being deprecated: http://kr.php.net/manual/en/mysqlinfo.api.choosing.php. (I'm fairly sure this page just appeared in the past day or two.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T13:26:32.087",
"Id": "20870",
"Score": "0",
"body": "@Corbin: Will edit post with the link"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T16:02:28.493",
"Id": "12704",
"ParentId": "12680",
"Score": "1"
}
},
{
"body": "<p>showerhead and haylem covered this question quite thoroughly, but there's a few more things I think should be added or expounded upon.</p>\n\n<p><strong>Be extremely careful when including based on user input</strong></p>\n\n<p>This was mentioned a few times by both people mentioned, but considering how big of security hole it can be, I feel that it deserves a lot more attention than anyone gave it.</p>\n\n<p>You should <strong>NEVER</strong> include a file blindly based on user input.</p>\n\n<p>What if I go to: <code>page.php?module=../some/secret</code></p>\n\n<p>Suddenly <code>/path/some/secret.php</code> just got included. The <code>.php</code> extension would limit a lot of the damage this could do (<code>page.php?module=../path/to/some/config.ini</code>), but the hole is still there.</p>\n\n<p>I tend to be extremely strict with file name handling. I typically only allow <code>a-z</code>, <code>A-Z</code>, <code>0-9</code>, <code>-</code>, and <code>_</code>. That way you know that it will be a semi-logical file name, and you know that it will not be able to traverse directories.</p>\n\n<p>For example:</p>\n\n<pre><code>$module = (isset($_GET['module']) && is_string($_GET['module'])) ? $_GET['module'] : null;\nif (!preg_match('/^[a-zA-Z0-9_-]$/', $module)) {\n $module = false;\n}\n</code></pre>\n\n<p>You should also check if the file is readable before including it. Otherwise, a user may see an ugly error message, or, best case, you open up the possibility of a huge log file of meaningless errors. (Production servers should never have <code>display_errors = On</code>, but they should have <code>error_reporting = E_ALL</code>.)</p>\n\n<p><strong>Don't assume (user provided) array keys are set</strong></p>\n\n<p>showerhead touched on this:</p>\n\n<blockquote>\n <p>Also, I would not immediately use any value from any user provided array directly in my program. It should be sanitized and validated first.</p>\n</blockquote>\n\n<p>But I think one of the reasons behind this should be explained a bit more.</p>\n\n<p>When you access an array, if the key does not exist, then a notice is triggered about the array key not existing. As such, you should always make sure you are 100% certain that an array key exists. The only way to do this on user controlled inputs is explicity checked. The filter_input method is a favorite of many, but if you wanted to it \"raw\", you can use <code>isset</code>.</p>\n\n<pre><code>$val = (isset($_GET['val'])) ? $_GET['val'] : null;\n</code></pre>\n\n<p>It's guaranteed that every value of a $_GET/$_POST/etc array will be either a string or an array, thus it's a good idea to check type too. Using an array as a string will trigger quite a few errors in most scripts.</p>\n\n<pre><code>$val = (isset($_GET['val']) && is_string($_GET['val'])) ? $_GET['val'] : null;\n</code></pre>\n\n<p><code>array_key_exists</code> is worth mentioning here too. It does basically the same thing, except it can be used when a value in an array may be false.</p>\n\n<pre><code>$a = array('foo' => null);\n\nif (isset($a)) { echo 'isset'; }\nif (array_key_exists('foo', $a)) { echo 'exists'; }\n</code></pre>\n\n<p><code>exists</code> will echo here, but <code>isset</code> will not since <code>isset(null) === false</code>.</p>\n\n<p><strong>Separation of concerns</strong></p>\n\n<p>showerhead explained the concept well, but I disagree with his execution a bit.</p>\n\n<p>As part of having only one responsibility, a function should have no inner depencies. What I mean by this is that a function that is not related to direct database interaction should not even have to know that a database exists. (Obviously at some point in your code, this will have to be broken, but it's more a general idea than a code-law.)</p>\n\n<p>In more technically, slightly more vague terms, if a function has any dependencies, they should be provided to a function rather than a function finding those dependencies itself. (\"dependency injection\" is typically what this is called.)</p>\n\n<p>I would consider rewriting your code like:</p>\n\n<pre><code>function output(array $recordsA, array $recordsB, $authorized, $module)\n{\n\n if($authorized)\n {\n include('/path/to/' . $module . '.php');\n }\n\n echo \"<ul>\"\n\n foreach ($recordsA as $record) {\n echo \"<li>\" . htmlspecialchars($row['description']) . \"</li>\";\n }\n\n echo \"</ul><br><ul>\";\n\n foreach ($recordsB as $record) {\n $status = ($authorized) ? htmlspecialchars($record['status']) : 'N/A';\n $description = htmlspecialchars($record['description']);\n echo \"<li>{$description} ({$status})</li>\";\n }\n\n echo \"</ul>\";\n\n}\n</code></pre>\n\n<p>Then the usage of the function would be:</p>\n\n<pre><code>$recordsAQuery = mysql_query(\"...\");\n$recordsA = array();\nwhile ($row = mysql_fetch_assoc($recordsAQuery)) {\n $recordsA[] = $row;\n}\n\n$recordsBQuery = mysql_query(\"...\");\n...\n\n$module = ...;\n\noutput($recordsA, $recordsB, is_authorized(), $module);\n</code></pre>\n\n<p>I would also be tempted to abstract yet more. Specifically, the database stuff could be abstracted away a bit more depending on how carried away one was.</p>\n\n<pre><code>function queryAndFetchAll($query, $conn = null)\n{\n $res = mysql_query($query);\n if (!$res) {\n throw new Exception(\"mysql_query failed. Query: [{$query}]. Error: [\" . mysql_error($conn) . \"]\");\n }\n $records = array();\n while ($row = mysql_fetch_assoc($res)) {\n $records[] = $row;\n }\n return $records;\n}\n\n$recordsA = queryAndFetchAll(\"SELECT ...\");\n$recordsB = queryAndFetchAll(\"SELECT ...\");\n</code></pre>\n\n<p>Note that I would name recordsA and recordsB something more descriptive. (I also might consider breaking this function into two functions.)</p>\n\n<p>And, depending on what exactly the module file is doing, I might try to abstract that out of the function.</p>\n\n<hr>\n\n<p>On a side note, the PDOStatement is Iterable, so you can pass it and the function can use it silently as an array.</p>\n\n<p>If you're not familiar with PDO this probably won't have much meaning, but hopefully the gist is there:</p>\n\n<pre><code>$recAStmt = $db->prepare(\"SELECT * FROM main WHERE id > ?\");\n$recAStmt->execute(array($id));\n$recBstmt = ...;\noutput($recAStmt, $recBStmt, ...);\n</code></pre>\n\n<p><strong>output</strong></p>\n\n<p>What is being output? I would consider naming this something like <code>renderStatuses</code>. (Though if you were to rename it render*, I would expect it to return content instead of echoing.)</p>\n\n<p><strong>echo vs return</strong></p>\n\n<p>That brings me to my next point :).</p>\n\n<p>I avoid outputting to the client except for in my main view code. What if for some reason you want to store this code to a variable instead of echoing it immediately? If you want to echo immediately, it's easy enough to do <code>echo f();</code>, but storing and then echoing is quite a pain. (<code>ob_start(); f(); $f = ob_get_flush();</code>) This does tend to make functions take a bit longer to write, but it's typically worth it.</p>\n\n<p><strong>SELECT *</strong></p>\n\n<p>This one is being pretty picky, however, I favor explicitly listing the column name. There's a tiny performance benefit (even if selecting all columns), but more so than that, I would rather my queries break in the future than my PHP code silently mess up.</p>\n\n<p>Consider if you decided to rename your status column. Your code would silently break. You'd start getting undefined index notices, and nothing would be output correctly.</p>\n\n<p>However, if you had selected all of the columns individually, the query would fail, and you'd likely notice the error a lot quicker.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T08:48:30.837",
"Id": "12926",
"ParentId": "12680",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "12926",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T04:44:13.587",
"Id": "12680",
"Score": "3",
"Tags": [
"php",
"mysql",
"security"
],
"Title": "Database output function"
}
|
12680
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.